@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/README.md +48 -1
- package/audio.d.ts +84 -0
- package/audio.js +453 -0
- package/esm/audio.js +449 -0
- package/esm/geometry.js +137 -0
- package/esm/index.js +3 -0
- package/esm/player.js +193 -0
- package/esm/scene.js +168 -0
- package/geometry.d.ts +6 -0
- package/geometry.js +143 -0
- package/index.d.ts +5 -0
- package/index.js +9 -1
- package/package.json +10 -2
- package/player.d.ts +58 -0
- package/player.js +197 -0
- package/scene.d.ts +10 -0
- package/scene.js +172 -0
package/esm/audio.js
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
export const DEFAULT_AUDIO_BANDS = Object.freeze({
|
|
2
|
+
bass: Object.freeze([20, 250]),
|
|
3
|
+
mid: Object.freeze([250, 2000]),
|
|
4
|
+
treble: Object.freeze([2000, 16000]),
|
|
5
|
+
});
|
|
6
|
+
export const DEFAULT_AUDIO_FEATURE_PORTS = Object.freeze([
|
|
7
|
+
'loudness', 'bass', 'mid', 'treble', 'onset', 'travel',
|
|
8
|
+
]);
|
|
9
|
+
function clampUnit(value) {
|
|
10
|
+
if (!Number.isFinite(value))
|
|
11
|
+
return 0;
|
|
12
|
+
return Math.max(0, Math.min(1, value));
|
|
13
|
+
}
|
|
14
|
+
function createAudioContext(provided) {
|
|
15
|
+
if (provided)
|
|
16
|
+
return { context: provided };
|
|
17
|
+
const AudioCtx = globalThis.AudioContext
|
|
18
|
+
?? globalThis.webkitAudioContext;
|
|
19
|
+
if (!AudioCtx)
|
|
20
|
+
throw new Error('Web Audio AudioContext is not available in this environment');
|
|
21
|
+
const context = new AudioCtx();
|
|
22
|
+
return { context, owned: context };
|
|
23
|
+
}
|
|
24
|
+
function configureAnalyser(context, options) {
|
|
25
|
+
const analyser = context.createAnalyser();
|
|
26
|
+
if (options.fftSize !== undefined)
|
|
27
|
+
analyser.fftSize = options.fftSize;
|
|
28
|
+
if (options.smoothingTimeConstant !== undefined) {
|
|
29
|
+
analyser.smoothingTimeConstant = options.smoothingTimeConstant;
|
|
30
|
+
}
|
|
31
|
+
return analyser;
|
|
32
|
+
}
|
|
33
|
+
function validateBands(bands) {
|
|
34
|
+
const entries = Object.entries(bands);
|
|
35
|
+
for (const [name, range] of entries) {
|
|
36
|
+
if (!name || name === 'loudness' || name === 'onset' || name === 'travel') {
|
|
37
|
+
throw new RangeError('Invalid audio band name: ' + name);
|
|
38
|
+
}
|
|
39
|
+
if (!Array.isArray(range) || range.length !== 2 || !Number.isFinite(range[0]) || !Number.isFinite(range[1]) || range[0] < 0 || range[0] >= range[1]) {
|
|
40
|
+
throw new RangeError('Invalid frequency band range for ' + name);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return entries;
|
|
44
|
+
}
|
|
45
|
+
export class WebAudioChannelSource {
|
|
46
|
+
ports;
|
|
47
|
+
analyser;
|
|
48
|
+
context;
|
|
49
|
+
bands;
|
|
50
|
+
sampleRateOverride;
|
|
51
|
+
onsetGain;
|
|
52
|
+
smoothing;
|
|
53
|
+
freqData;
|
|
54
|
+
prevSpectrum;
|
|
55
|
+
floatTimeData;
|
|
56
|
+
byteTimeData;
|
|
57
|
+
ownedContext;
|
|
58
|
+
cleanup;
|
|
59
|
+
starter;
|
|
60
|
+
hasPrevious = false;
|
|
61
|
+
prevTimestamp;
|
|
62
|
+
prevValues;
|
|
63
|
+
travel = 0;
|
|
64
|
+
recording;
|
|
65
|
+
recordedFrames = new Map();
|
|
66
|
+
disposed = false;
|
|
67
|
+
constructor(analyser, options = {}) {
|
|
68
|
+
if (!analyser || typeof analyser.getByteFrequencyData !== 'function') {
|
|
69
|
+
throw new TypeError('An AnalyserNode-compatible analyser is required');
|
|
70
|
+
}
|
|
71
|
+
if (!Number.isInteger(analyser.frequencyBinCount) || analyser.frequencyBinCount <= 0) {
|
|
72
|
+
throw new RangeError('Analyser frequencyBinCount must be a positive integer');
|
|
73
|
+
}
|
|
74
|
+
const smoothing = options.smoothing ?? 0;
|
|
75
|
+
if (!Number.isFinite(smoothing) || smoothing < 0 || smoothing >= 1) {
|
|
76
|
+
throw new RangeError('Smoothing must be in [0, 1)');
|
|
77
|
+
}
|
|
78
|
+
const onsetGain = options.onsetGain ?? 4;
|
|
79
|
+
if (!Number.isFinite(onsetGain) || onsetGain <= 0) {
|
|
80
|
+
throw new RangeError('onsetGain must be finite and positive');
|
|
81
|
+
}
|
|
82
|
+
if (options.sampleRate !== undefined && (!Number.isFinite(options.sampleRate) || options.sampleRate <= 0)) {
|
|
83
|
+
throw new RangeError('sampleRate must be finite and positive');
|
|
84
|
+
}
|
|
85
|
+
this.analyser = analyser;
|
|
86
|
+
this.context = options.audioContext;
|
|
87
|
+
this.ownedContext = options.ownedContext;
|
|
88
|
+
this.cleanup = options.cleanup;
|
|
89
|
+
this.starter = options.starter;
|
|
90
|
+
this.sampleRateOverride = options.sampleRate;
|
|
91
|
+
this.onsetGain = onsetGain;
|
|
92
|
+
this.smoothing = smoothing;
|
|
93
|
+
this.recording = options.record ?? false;
|
|
94
|
+
const bandMap = options.bands ?? DEFAULT_AUDIO_BANDS;
|
|
95
|
+
this.bands = validateBands(bandMap);
|
|
96
|
+
this.ports = Object.freeze(['loudness', ...this.bands.map(([name]) => name), 'onset', 'travel']);
|
|
97
|
+
this.freqData = new Uint8Array(analyser.frequencyBinCount);
|
|
98
|
+
this.prevSpectrum = new Float32Array(analyser.frequencyBinCount);
|
|
99
|
+
const timeSize = Math.max(1, analyser.fftSize || analyser.frequencyBinCount * 2);
|
|
100
|
+
if (typeof analyser.getFloatTimeDomainData === 'function') {
|
|
101
|
+
this.floatTimeData = new Float32Array(timeSize);
|
|
102
|
+
}
|
|
103
|
+
else if (typeof analyser.getByteTimeDomainData === 'function') {
|
|
104
|
+
this.byteTimeData = new Uint8Array(timeSize);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
static fromMediaElement(element, options = {}) {
|
|
108
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
109
|
+
const monitor = options.monitor ?? true;
|
|
110
|
+
const analyser = configureAnalyser(context, options);
|
|
111
|
+
const node = context.createMediaElementSource(element);
|
|
112
|
+
node.connect(analyser);
|
|
113
|
+
if (monitor)
|
|
114
|
+
analyser.connect(context.destination);
|
|
115
|
+
const restoreOutput = () => {
|
|
116
|
+
try {
|
|
117
|
+
node.disconnect();
|
|
118
|
+
}
|
|
119
|
+
catch { /* ignore */ }
|
|
120
|
+
try {
|
|
121
|
+
analyser.disconnect();
|
|
122
|
+
}
|
|
123
|
+
catch { /* ignore */ }
|
|
124
|
+
if (!owned && monitor) {
|
|
125
|
+
try {
|
|
126
|
+
node.connect(context.destination);
|
|
127
|
+
}
|
|
128
|
+
catch { /* ignore */ }
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
try {
|
|
132
|
+
return new WebAudioChannelSource(analyser, {
|
|
133
|
+
...options,
|
|
134
|
+
audioContext: context,
|
|
135
|
+
ownedContext: owned,
|
|
136
|
+
starter: () => { void element.play(); },
|
|
137
|
+
cleanup: restoreOutput,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
restoreOutput();
|
|
142
|
+
if (owned)
|
|
143
|
+
void owned.close();
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
static fromAudioBuffer(buffer, options = {}) {
|
|
148
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
149
|
+
return WebAudioChannelSource.connectBuffer(buffer, context, owned, options);
|
|
150
|
+
}
|
|
151
|
+
static connectBuffer(buffer, context, owned, options) {
|
|
152
|
+
const analyser = configureAnalyser(context, options);
|
|
153
|
+
const source = context.createBufferSource();
|
|
154
|
+
source.buffer = buffer;
|
|
155
|
+
source.loop = options.loop ?? false;
|
|
156
|
+
source.connect(analyser);
|
|
157
|
+
if (options.monitor ?? true)
|
|
158
|
+
analyser.connect(context.destination);
|
|
159
|
+
let started = false;
|
|
160
|
+
const startBuffer = (when, offset) => {
|
|
161
|
+
if (started)
|
|
162
|
+
return;
|
|
163
|
+
started = true;
|
|
164
|
+
source.start(when, offset);
|
|
165
|
+
};
|
|
166
|
+
const disconnect = () => {
|
|
167
|
+
if (started) {
|
|
168
|
+
try {
|
|
169
|
+
source.stop();
|
|
170
|
+
}
|
|
171
|
+
catch { /* ignore */ }
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
source.disconnect();
|
|
175
|
+
}
|
|
176
|
+
catch { /* ignore */ }
|
|
177
|
+
try {
|
|
178
|
+
analyser.disconnect();
|
|
179
|
+
}
|
|
180
|
+
catch { /* ignore */ }
|
|
181
|
+
};
|
|
182
|
+
try {
|
|
183
|
+
const channel = new WebAudioChannelSource(analyser, {
|
|
184
|
+
...options,
|
|
185
|
+
audioContext: context,
|
|
186
|
+
ownedContext: owned,
|
|
187
|
+
starter: startBuffer,
|
|
188
|
+
cleanup: disconnect,
|
|
189
|
+
});
|
|
190
|
+
if (options.autoplay)
|
|
191
|
+
channel.start();
|
|
192
|
+
return channel;
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
disconnect();
|
|
196
|
+
if (owned)
|
|
197
|
+
void owned.close();
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
static async fromFile(file, options = {}) {
|
|
202
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
203
|
+
try {
|
|
204
|
+
let bytes;
|
|
205
|
+
if (typeof file === 'string') {
|
|
206
|
+
const response = await fetch(file);
|
|
207
|
+
if (!response.ok)
|
|
208
|
+
throw new Error(`Failed to fetch audio file (${response.status}): ${file}`);
|
|
209
|
+
bytes = await response.arrayBuffer();
|
|
210
|
+
}
|
|
211
|
+
else if (file instanceof ArrayBuffer) {
|
|
212
|
+
bytes = file.slice(0);
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
bytes = await file.arrayBuffer();
|
|
216
|
+
}
|
|
217
|
+
const buffer = await context.decodeAudioData(bytes);
|
|
218
|
+
return WebAudioChannelSource.connectBuffer(buffer, context, owned, options);
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
if (owned)
|
|
222
|
+
void owned.close();
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
static fromMediaStream(stream, options = {}) {
|
|
227
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
228
|
+
const analyser = configureAnalyser(context, options);
|
|
229
|
+
const node = context.createMediaStreamSource(stream);
|
|
230
|
+
node.connect(analyser);
|
|
231
|
+
if (options.monitor ?? false)
|
|
232
|
+
analyser.connect(context.destination);
|
|
233
|
+
return new WebAudioChannelSource(analyser, {
|
|
234
|
+
...options,
|
|
235
|
+
audioContext: context,
|
|
236
|
+
ownedContext: owned,
|
|
237
|
+
cleanup: () => {
|
|
238
|
+
try {
|
|
239
|
+
node.disconnect();
|
|
240
|
+
}
|
|
241
|
+
catch { /* ignore */ }
|
|
242
|
+
try {
|
|
243
|
+
analyser.disconnect();
|
|
244
|
+
}
|
|
245
|
+
catch { /* ignore */ }
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
static async fromMicrophone(options = {}) {
|
|
250
|
+
const mediaDevices = globalThis.navigator?.mediaDevices;
|
|
251
|
+
if (!mediaDevices || typeof mediaDevices.getUserMedia !== 'function') {
|
|
252
|
+
throw new Error('Microphone capture (navigator.mediaDevices.getUserMedia) is not available');
|
|
253
|
+
}
|
|
254
|
+
const stream = await mediaDevices.getUserMedia({ audio: options.constraints ?? true });
|
|
255
|
+
let owned;
|
|
256
|
+
let node;
|
|
257
|
+
let analyser;
|
|
258
|
+
try {
|
|
259
|
+
const ctx = createAudioContext(options.audioContext);
|
|
260
|
+
owned = ctx.owned;
|
|
261
|
+
analyser = configureAnalyser(ctx.context, options);
|
|
262
|
+
node = ctx.context.createMediaStreamSource(stream);
|
|
263
|
+
node.connect(analyser);
|
|
264
|
+
if (options.monitor ?? false)
|
|
265
|
+
analyser.connect(ctx.context.destination);
|
|
266
|
+
const connectedNode = node;
|
|
267
|
+
const connectedAnalyser = analyser;
|
|
268
|
+
return new WebAudioChannelSource(connectedAnalyser, {
|
|
269
|
+
...options,
|
|
270
|
+
audioContext: ctx.context,
|
|
271
|
+
ownedContext: owned,
|
|
272
|
+
cleanup: () => {
|
|
273
|
+
try {
|
|
274
|
+
connectedNode.disconnect();
|
|
275
|
+
}
|
|
276
|
+
catch { /* ignore */ }
|
|
277
|
+
try {
|
|
278
|
+
connectedAnalyser.disconnect();
|
|
279
|
+
}
|
|
280
|
+
catch { /* ignore */ }
|
|
281
|
+
for (const track of stream.getTracks())
|
|
282
|
+
track.stop();
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
try {
|
|
288
|
+
node?.disconnect();
|
|
289
|
+
}
|
|
290
|
+
catch { /* ignore */ }
|
|
291
|
+
try {
|
|
292
|
+
analyser?.disconnect();
|
|
293
|
+
}
|
|
294
|
+
catch { /* ignore */ }
|
|
295
|
+
for (const track of stream.getTracks())
|
|
296
|
+
track.stop();
|
|
297
|
+
if (owned)
|
|
298
|
+
void owned.close();
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
async resume() {
|
|
303
|
+
this.assertActive();
|
|
304
|
+
if (this.context && this.context.state === 'suspended') {
|
|
305
|
+
await this.context.resume();
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
start(when, offset) {
|
|
309
|
+
this.assertActive();
|
|
310
|
+
this.starter?.(when, offset);
|
|
311
|
+
}
|
|
312
|
+
startRecording() {
|
|
313
|
+
this.recording = true;
|
|
314
|
+
}
|
|
315
|
+
stopRecording() {
|
|
316
|
+
this.recording = false;
|
|
317
|
+
}
|
|
318
|
+
reset() {
|
|
319
|
+
this.hasPrevious = false;
|
|
320
|
+
this.prevTimestamp = undefined;
|
|
321
|
+
this.prevValues = undefined;
|
|
322
|
+
this.travel = 0;
|
|
323
|
+
this.prevSpectrum.fill(0);
|
|
324
|
+
this.recordedFrames.clear();
|
|
325
|
+
}
|
|
326
|
+
sample(frame = 0, time) {
|
|
327
|
+
this.assertActive();
|
|
328
|
+
this.analyser.getByteFrequencyData(this.freqData);
|
|
329
|
+
const binCount = this.freqData.length;
|
|
330
|
+
const sampleRate = this.sampleRateOverride ?? this.analyser.context?.sampleRate ?? 48000;
|
|
331
|
+
const nyquist = sampleRate / 2;
|
|
332
|
+
const hzPerBin = nyquist / binCount;
|
|
333
|
+
const rawValues = {};
|
|
334
|
+
for (const [name, [lowHz, highHz]] of this.bands) {
|
|
335
|
+
const startBin = Math.max(0, Math.min(binCount - 1, Math.ceil(lowHz / hzPerBin)));
|
|
336
|
+
const rawEnd = highHz / hzPerBin;
|
|
337
|
+
const endBin = Math.max(startBin, Math.min(binCount - 1, Number.isInteger(rawEnd) ? rawEnd - 1 : Math.floor(rawEnd)));
|
|
338
|
+
let sumSq = 0;
|
|
339
|
+
for (let i = startBin; i <= endBin; i++) {
|
|
340
|
+
const m = this.freqData[i] / 255;
|
|
341
|
+
sumSq += m * m;
|
|
342
|
+
}
|
|
343
|
+
rawValues[name] = clampUnit(Math.sqrt(sumSq / (endBin - startBin + 1)));
|
|
344
|
+
}
|
|
345
|
+
let loudness = 0;
|
|
346
|
+
if (this.floatTimeData && this.analyser.getFloatTimeDomainData) {
|
|
347
|
+
this.analyser.getFloatTimeDomainData(this.floatTimeData);
|
|
348
|
+
let sumSq = 0;
|
|
349
|
+
for (let i = 0; i < this.floatTimeData.length; i++) {
|
|
350
|
+
const v = this.floatTimeData[i];
|
|
351
|
+
sumSq += v * v;
|
|
352
|
+
}
|
|
353
|
+
loudness = clampUnit(Math.sqrt(sumSq / this.floatTimeData.length));
|
|
354
|
+
}
|
|
355
|
+
else if (this.byteTimeData && this.analyser.getByteTimeDomainData) {
|
|
356
|
+
this.analyser.getByteTimeDomainData(this.byteTimeData);
|
|
357
|
+
let sumSq = 0;
|
|
358
|
+
for (let i = 0; i < this.byteTimeData.length; i++) {
|
|
359
|
+
const v = (this.byteTimeData[i] - 128) / 128;
|
|
360
|
+
sumSq += v * v;
|
|
361
|
+
}
|
|
362
|
+
loudness = clampUnit(Math.sqrt(sumSq / this.byteTimeData.length));
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
let sumSq = 0;
|
|
366
|
+
for (let i = 0; i < binCount; i++) {
|
|
367
|
+
const m = this.freqData[i] / 255;
|
|
368
|
+
sumSq += m * m;
|
|
369
|
+
}
|
|
370
|
+
loudness = clampUnit(Math.sqrt(sumSq / binCount));
|
|
371
|
+
}
|
|
372
|
+
rawValues.loudness = loudness;
|
|
373
|
+
let fluxSum = 0;
|
|
374
|
+
for (let i = 0; i < binCount; i++) {
|
|
375
|
+
const current = this.freqData[i] / 255;
|
|
376
|
+
if (this.hasPrevious) {
|
|
377
|
+
const diff = current - this.prevSpectrum[i];
|
|
378
|
+
if (diff > 0)
|
|
379
|
+
fluxSum += diff;
|
|
380
|
+
}
|
|
381
|
+
this.prevSpectrum[i] = current;
|
|
382
|
+
}
|
|
383
|
+
rawValues.onset = this.hasPrevious ? clampUnit((fluxSum / binCount) * this.onsetGain) : 0;
|
|
384
|
+
this.hasPrevious = true;
|
|
385
|
+
const timestamp = time !== undefined && Number.isFinite(time)
|
|
386
|
+
? time
|
|
387
|
+
: this.analyser.context?.currentTime ?? 0;
|
|
388
|
+
const dt = this.prevTimestamp !== undefined ? Math.max(0, timestamp - this.prevTimestamp) : 0;
|
|
389
|
+
this.prevTimestamp = timestamp;
|
|
390
|
+
this.travel += loudness * dt;
|
|
391
|
+
rawValues.travel = this.travel;
|
|
392
|
+
const values = {};
|
|
393
|
+
for (const port of this.ports) {
|
|
394
|
+
const raw = rawValues[port];
|
|
395
|
+
if (port === 'travel' || this.smoothing === 0 || !this.prevValues) {
|
|
396
|
+
values[port] = raw;
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
values[port] = this.prevValues[port] * this.smoothing + raw * (1 - this.smoothing);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
this.prevValues = values;
|
|
403
|
+
if (this.recording && Number.isSafeInteger(frame) && frame >= 0 && !this.recordedFrames.has(frame)) {
|
|
404
|
+
this.recordedFrames.set(frame, { ...values });
|
|
405
|
+
}
|
|
406
|
+
return { timestamp, values };
|
|
407
|
+
}
|
|
408
|
+
toChannelTable(sampleRate = 30) {
|
|
409
|
+
if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
|
|
410
|
+
throw new RangeError('Channel table sampleRate must be finite and positive');
|
|
411
|
+
}
|
|
412
|
+
if (!this.recordedFrames.size)
|
|
413
|
+
throw new Error('No recorded audio samples to export');
|
|
414
|
+
let maxFrame = 0;
|
|
415
|
+
for (const frame of this.recordedFrames.keys()) {
|
|
416
|
+
if (frame > maxFrame)
|
|
417
|
+
maxFrame = frame;
|
|
418
|
+
}
|
|
419
|
+
const channels = {};
|
|
420
|
+
for (const port of this.ports)
|
|
421
|
+
channels[port] = [];
|
|
422
|
+
let last;
|
|
423
|
+
for (let f = 0; f <= maxFrame; f++) {
|
|
424
|
+
const entry = this.recordedFrames.get(f) ?? last;
|
|
425
|
+
if (entry)
|
|
426
|
+
last = entry;
|
|
427
|
+
for (const port of this.ports)
|
|
428
|
+
channels[port].push(entry ? entry[port] : 0);
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
sampleRate,
|
|
432
|
+
boundary: 'clamp',
|
|
433
|
+
interpolation: 'linear',
|
|
434
|
+
channels,
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
dispose() {
|
|
438
|
+
if (this.disposed)
|
|
439
|
+
return;
|
|
440
|
+
this.disposed = true;
|
|
441
|
+
this.cleanup?.();
|
|
442
|
+
if (this.ownedContext)
|
|
443
|
+
void this.ownedContext.close();
|
|
444
|
+
}
|
|
445
|
+
assertActive() {
|
|
446
|
+
if (this.disposed)
|
|
447
|
+
throw new Error('WebAudioChannelSource has been disposed');
|
|
448
|
+
}
|
|
449
|
+
}
|
package/esm/geometry.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { BoxGeometry, BufferGeometry, CircleGeometry, Group, Mesh, 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
|
+
}
|
|
65
|
+
function numbers(value, count) {
|
|
66
|
+
return Array.isArray(value) && value.length === count && Array.from(value).every(Number.isFinite);
|
|
67
|
+
}
|
|
68
|
+
export function disposeProceduralGeometry(root) {
|
|
69
|
+
root.traverse(object => {
|
|
70
|
+
if (object instanceof Mesh)
|
|
71
|
+
object.geometry.dispose();
|
|
72
|
+
});
|
|
73
|
+
root.clear();
|
|
74
|
+
}
|
|
75
|
+
export function updateProceduralGeometry(root, descriptor, material) {
|
|
76
|
+
const ancestors = new Set();
|
|
77
|
+
function updateChildren(group, descriptors) {
|
|
78
|
+
const previous = [...group.children];
|
|
79
|
+
const next = [];
|
|
80
|
+
for (const child of descriptors) {
|
|
81
|
+
const object = update(previous[next.length], child);
|
|
82
|
+
if (object)
|
|
83
|
+
next.push(object);
|
|
84
|
+
}
|
|
85
|
+
if (previous.length === next.length && previous.every((object, i) => object === next[i]))
|
|
86
|
+
return;
|
|
87
|
+
group.clear();
|
|
88
|
+
for (let i = 0; i < previous.length; i++) {
|
|
89
|
+
if (previous[i] !== next[i])
|
|
90
|
+
disposeProceduralGeometry(previous[i]);
|
|
91
|
+
}
|
|
92
|
+
for (const object of next)
|
|
93
|
+
group.add(object);
|
|
94
|
+
}
|
|
95
|
+
function update(previous, value) {
|
|
96
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || ancestors.has(value))
|
|
97
|
+
return;
|
|
98
|
+
const { kind, primitive, args, geometry, geometries, translate, scale } = value;
|
|
99
|
+
if (primitive === 'box' && numbers(args, 3)) {
|
|
100
|
+
const [width, height, depth] = args;
|
|
101
|
+
if (previous instanceof Mesh && previous.geometry instanceof BoxGeometry) {
|
|
102
|
+
const p = previous.geometry.parameters;
|
|
103
|
+
if (p.width === width && p.height === height && p.depth === depth)
|
|
104
|
+
return previous;
|
|
105
|
+
}
|
|
106
|
+
return new Mesh(new BoxGeometry(width, height, depth), material);
|
|
107
|
+
}
|
|
108
|
+
if (primitive === 'sphere' && numbers(args, 3)) {
|
|
109
|
+
const [radius, , detail] = args;
|
|
110
|
+
const widthSegments = segments(detail, 3), heightSegments = segments(detail / 2, 2);
|
|
111
|
+
if (previous instanceof Mesh && previous.geometry instanceof SphereGeometry) {
|
|
112
|
+
const p = previous.geometry.parameters;
|
|
113
|
+
if (p.radius === radius && p.widthSegments === widthSegments && p.heightSegments === heightSegments)
|
|
114
|
+
return previous;
|
|
115
|
+
}
|
|
116
|
+
return new Mesh(new SphereGeometry(radius, widthSegments, heightSegments), material);
|
|
117
|
+
}
|
|
118
|
+
const transform = kind === 'transform' && numbers(translate, 3) && numbers(scale, 3);
|
|
119
|
+
const merge = kind === 'merge' && Array.isArray(geometries);
|
|
120
|
+
if (!transform && !merge)
|
|
121
|
+
return;
|
|
122
|
+
const group = previous instanceof Group ? previous : new Group();
|
|
123
|
+
if (transform) {
|
|
124
|
+
group.position.fromArray(translate);
|
|
125
|
+
group.scale.fromArray(scale);
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
group.position.set(0, 0, 0);
|
|
129
|
+
group.scale.setScalar(1);
|
|
130
|
+
}
|
|
131
|
+
ancestors.add(value);
|
|
132
|
+
updateChildren(group, transform ? [geometry] : geometries);
|
|
133
|
+
ancestors.delete(value);
|
|
134
|
+
return group;
|
|
135
|
+
}
|
|
136
|
+
updateChildren(root, [descriptor]);
|
|
137
|
+
}
|
package/esm/index.js
CHANGED