@npcify/web 0.1.1 → 0.1.3

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.
Files changed (3) hide show
  1. package/README.md +6 -6
  2. package/dist/index.js +1100 -742
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,250 +1,3 @@
1
- // ../ts-shared/src/body-occlusion.ts
2
- var BODY_TRIANGLE_MASK_MAX_BYTES = 16 * 1024 * 1024;
3
-
4
- // ../ts-shared/src/avatar-editor.ts
5
- var AVATAR_BODY_MORPHS = [
6
- // Torso
7
- {
8
- name: "breastSize",
9
- label: "Breast Size",
10
- category: "Torso",
11
- min: 0,
12
- max: 1,
13
- default: 0
14
- },
15
- {
16
- name: "waistWidth",
17
- label: "Waist Width",
18
- category: "Torso",
19
- min: 0,
20
- max: 1,
21
- default: 0
22
- },
23
- {
24
- name: "hipWidth",
25
- label: "Hip Width",
26
- category: "Torso",
27
- min: 0,
28
- max: 1,
29
- default: 0
30
- },
31
- {
32
- name: "bellySize",
33
- label: "Belly Size",
34
- category: "Torso",
35
- min: 0,
36
- max: 1,
37
- default: 0
38
- },
39
- {
40
- name: "buttSize",
41
- label: "Butt Size",
42
- category: "Torso",
43
- min: 0,
44
- max: 1,
45
- default: 0
46
- },
47
- {
48
- name: "chestWidth",
49
- label: "Chest Width",
50
- category: "Torso",
51
- min: 0,
52
- max: 1,
53
- default: 0
54
- },
55
- {
56
- name: "torsoLength",
57
- label: "Torso Length",
58
- category: "Torso",
59
- min: 0,
60
- max: 1,
61
- default: 0
62
- },
63
- // Upper Body
64
- {
65
- name: "shoulderBreadth",
66
- label: "Shoulder Breadth",
67
- category: "Upper Body",
68
- min: 0,
69
- max: 1,
70
- default: 0
71
- },
72
- {
73
- name: "neckThickness",
74
- label: "Neck Thickness",
75
- category: "Upper Body",
76
- min: 0,
77
- max: 1,
78
- default: 0
79
- },
80
- // Limbs
81
- {
82
- name: "armThickness",
83
- label: "Arm Thickness",
84
- category: "Limbs",
85
- min: 0,
86
- max: 1,
87
- default: 0
88
- },
89
- {
90
- name: "forearmThickness",
91
- label: "Forearm Thickness",
92
- category: "Limbs",
93
- min: 0,
94
- max: 1,
95
- default: 0
96
- },
97
- {
98
- name: "handSize",
99
- label: "Hand Size",
100
- category: "Limbs",
101
- min: 0,
102
- max: 1,
103
- default: 0
104
- },
105
- // Legs
106
- {
107
- name: "upperThighFat",
108
- label: "Upper Thigh",
109
- category: "Legs",
110
- min: 0,
111
- max: 1,
112
- default: 0
113
- },
114
- {
115
- name: "lowerThighFat",
116
- label: "Lower Thigh",
117
- category: "Legs",
118
- min: 0,
119
- max: 1,
120
- default: 0
121
- },
122
- {
123
- name: "calfSize",
124
- label: "Calf Size",
125
- category: "Legs",
126
- min: 0,
127
- max: 1,
128
- default: 0
129
- },
130
- {
131
- name: "footSize",
132
- label: "Foot Size",
133
- category: "Legs",
134
- min: 0,
135
- max: 1,
136
- default: 0
137
- }
138
- ];
139
- var AVATAR_DEFAULT_SKIN_COLOR = "#FFE0BD";
140
- var AVATAR_FACE_MORPHS = [
141
- // Face
142
- {
143
- name: "faceWidth",
144
- label: "Face Width",
145
- category: "Face",
146
- min: 0,
147
- max: 1,
148
- default: 0
149
- },
150
- {
151
- name: "jawWidth",
152
- label: "Jaw Width",
153
- category: "Face",
154
- min: 0,
155
- max: 1,
156
- default: 0
157
- },
158
- {
159
- name: "chinLength",
160
- label: "Chin Length",
161
- category: "Face",
162
- min: 0,
163
- max: 1,
164
- default: 0
165
- },
166
- {
167
- name: "cheekFullness",
168
- label: "Cheek Fullness",
169
- category: "Face",
170
- min: 0,
171
- max: 1,
172
- default: 0
173
- },
174
- // Eyes
175
- {
176
- name: "eyeSize",
177
- label: "Eye Size",
178
- category: "Eyes",
179
- min: 0,
180
- max: 1,
181
- default: 0
182
- },
183
- {
184
- name: "eyeSpacing",
185
- label: "Eye Spacing",
186
- category: "Eyes",
187
- min: 0,
188
- max: 1,
189
- default: 0
190
- },
191
- {
192
- name: "eyeAngle",
193
- label: "Eye Angle",
194
- category: "Eyes",
195
- min: 0,
196
- max: 1,
197
- default: 0
198
- },
199
- // Nose
200
- {
201
- name: "noseSize",
202
- label: "Nose Size",
203
- category: "Nose",
204
- min: 0,
205
- max: 1,
206
- default: 0
207
- },
208
- {
209
- name: "noseHeight",
210
- label: "Nose Height",
211
- category: "Nose",
212
- min: 0,
213
- max: 1,
214
- default: 0
215
- },
216
- // Mouth
217
- {
218
- name: "mouthSize",
219
- label: "Mouth Size",
220
- category: "Mouth",
221
- min: 0,
222
- max: 1,
223
- default: 0
224
- },
225
- {
226
- name: "lipThickness",
227
- label: "Lip Thickness",
228
- category: "Mouth",
229
- min: 0,
230
- max: 1,
231
- default: 0
232
- },
233
- // Ears
234
- {
235
- name: "earSize",
236
- label: "Ear Size",
237
- category: "Ears",
238
- min: 0,
239
- max: 1,
240
- default: 0
241
- }
242
- ];
243
- var AVATAR_ALL_MORPHS = [
244
- ...AVATAR_BODY_MORPHS,
245
- ...AVATAR_FACE_MORPHS
246
- ];
247
-
248
1
  // ../ts-shared/src/llm.ts
249
2
  var STAGING_PROTOCOL_VERSION = 1;
250
3
 
@@ -256,22 +9,8 @@ var MAXIMUM_PLAYBACK_DURATION_SECONDS = 10 * 60;
256
9
  var TTS_PROVIDERS = ["11labs"];
257
10
  var DEFAULT_TTS_PROVIDER = TTS_PROVIDERS[0];
258
11
 
259
- // ../ts-shared/src/avatar-generation-options.ts
260
- var DEFAULT_AVATAR_BASE_MODEL_ID = "npcify-female";
261
-
262
- // ../ts-shared/src/avatar-generation-catalog.ts
263
- var LEGACY_AVATAR_GENERATION_BASE = {
264
- id: DEFAULT_AVATAR_BASE_MODEL_ID,
265
- label: "Female",
266
- gender: "female",
267
- baseModelVersion: "legacy",
268
- catalogVersion: "legacy",
269
- catalogFingerprint: `sha256:${"0".repeat(64)}`,
270
- manifestKey: "avatar-generation/manifest.json",
271
- previewObjectKey: "avatar-generation/base/female.vrm",
272
- morphs: [...AVATAR_ALL_MORPHS],
273
- skinColor: { default: AVATAR_DEFAULT_SKIN_COLOR, colorizable: true }
274
- };
12
+ // ../ts-shared/src/body-occlusion.ts
13
+ var BODY_TRIANGLE_MASK_MAX_BYTES = 16 * 1024 * 1024;
275
14
 
276
15
  // ../ts-shared/src/baked-conversation.ts
277
16
  var BAKED_CONVERSATION_VERSION = 1;
@@ -3456,360 +3195,287 @@ var LazyAnimations = class {
3456
3195
  };
3457
3196
 
3458
3197
  // ../../clients/web-client/src/api/info.ts
3459
- import { VRMLoaderPlugin, VRMUtils } from "@pixiv/three-vrm";
3460
- import {
3461
- VRMAnimationLoaderPlugin
3462
- } from "@pixiv/three-vrm-animation";
3463
- import { LoadingManager } from "three";
3464
- import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
3465
- var GLB_HEADER_MAGIC = 1179937895;
3466
- var GLB_CHUNK_TYPE_JSON = 1313821514;
3467
- var textDecoder = new TextDecoder();
3468
- var isRecord2 = function(value) {
3469
- return typeof value === "object" && value !== null;
3470
- };
3471
- var resolveResourceUrl = function(url, baseUrl) {
3472
- try {
3473
- return new URL(url, baseUrl).toString();
3474
- } catch {
3475
- return url;
3198
+ import { VRMLoaderPlugin as VRMLoaderPlugin2, VRMUtils as VRMUtils4 } from "@pixiv/three-vrm";
3199
+
3200
+ // ../vrm-renderer/src/scene.ts
3201
+ import { Clock, PerspectiveCamera, Scene, WebGLRenderer } from "three";
3202
+ import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
3203
+
3204
+ // ../vrm-renderer/src/texture-cache.ts
3205
+ import { Source, Texture } from "three";
3206
+ var rendererReleases = /* @__PURE__ */ new WeakMap();
3207
+ var releaseRendererTextureCache = function(renderer) {
3208
+ for (const release of rendererReleases.get(renderer) ?? []) {
3209
+ release();
3476
3210
  }
3211
+ rendererReleases.delete(renderer);
3477
3212
  };
3478
- var parseContentLength = function(response) {
3479
- if (response.headers.get("content-encoding")) {
3480
- return null;
3481
- }
3482
- const header = response.headers.get("content-length");
3483
- if (!header) {
3484
- return null;
3213
+ var uploadOptions = function(texture) {
3214
+ return {
3215
+ wrapS: texture.wrapS,
3216
+ wrapT: texture.wrapT,
3217
+ magFilter: texture.magFilter,
3218
+ minFilter: texture.minFilter,
3219
+ anisotropy: texture.anisotropy,
3220
+ internalFormat: texture.internalFormat,
3221
+ format: texture.format,
3222
+ type: texture.type,
3223
+ generateMipmaps: texture.generateMipmaps,
3224
+ premultiplyAlpha: texture.premultiplyAlpha,
3225
+ flipY: texture.flipY,
3226
+ unpackAlignment: texture.unpackAlignment,
3227
+ colorSpace: texture.colorSpace
3228
+ };
3229
+ };
3230
+ var VrmTextureCache = class {
3231
+ entries = /* @__PURE__ */ new Map();
3232
+ bytes = 0;
3233
+ hits = 0;
3234
+ misses = 0;
3235
+ maxBytes;
3236
+ maxEntries;
3237
+ variants = /* @__PURE__ */ new WeakMap();
3238
+ constructor(options = {}) {
3239
+ if (Object.values(options).some(
3240
+ (value) => value !== void 0 && !Number.isFinite(value)
3241
+ )) {
3242
+ throw new Error("Texture cache limits must be finite");
3243
+ }
3244
+ this.maxBytes = Math.max(0, options.maxBytes ?? 64 * 1024 * 1024);
3245
+ this.maxEntries = Math.max(0, options.maxEntries ?? 64);
3485
3246
  }
3486
- const parsed = Number(header);
3487
- if (!Number.isFinite(parsed) || parsed <= 0) {
3488
- return null;
3247
+ getStats() {
3248
+ let idleBytes = 0;
3249
+ for (const entry of this.entries.values()) {
3250
+ if (entry.refs === 0) {
3251
+ idleBytes += this.retainedBytes(entry);
3252
+ }
3253
+ }
3254
+ return {
3255
+ entries: this.entries.size,
3256
+ bytes: this.bytes,
3257
+ idleBytes,
3258
+ hits: this.hits,
3259
+ misses: this.misses
3260
+ };
3489
3261
  }
3490
- return parsed;
3491
- };
3492
- var parseGltfJson = function(data) {
3493
- if (data.byteLength < 12) {
3494
- return { json: null, jsonText: null, isBinary: false };
3262
+ clear() {
3263
+ for (const entry of this.entries.values()) {
3264
+ this.evict(entry);
3265
+ }
3495
3266
  }
3496
- const view = new DataView(data);
3497
- const magic = view.getUint32(0, true);
3498
- if (magic === GLB_HEADER_MAGIC) {
3499
- let offset = 12;
3500
- while (offset + 8 <= view.byteLength) {
3501
- const chunkLength = view.getUint32(offset, true);
3502
- const chunkType = view.getUint32(offset + 4, true);
3503
- offset += 8;
3504
- if (chunkType === GLB_CHUNK_TYPE_JSON) {
3505
- const chunkData = new Uint8Array(data, offset, chunkLength);
3506
- const jsonText2 = textDecoder.decode(chunkData);
3507
- try {
3508
- const json = JSON.parse(jsonText2);
3509
- return { json, jsonText: jsonText2, isBinary: true };
3510
- } catch {
3511
- return { json: null, jsonText: jsonText2, isBinary: true };
3267
+ async acquire(key, decode2) {
3268
+ let entry = this.entries.get(key);
3269
+ if (entry) {
3270
+ this.hits += 1;
3271
+ this.entries.delete(key);
3272
+ this.entries.set(key, entry);
3273
+ } else {
3274
+ this.misses += 1;
3275
+ entry = {
3276
+ key,
3277
+ source: new Source(null),
3278
+ refs: 0,
3279
+ retained: true,
3280
+ closed: false,
3281
+ bytes: 0,
3282
+ anchors: /* @__PURE__ */ new Map(),
3283
+ rendererReleases: /* @__PURE__ */ new Map(),
3284
+ ready: Promise.resolve().then(decode2)
3285
+ };
3286
+ this.entries.set(key, entry);
3287
+ const created = entry;
3288
+ entry.ready = entry.ready.then((image) => {
3289
+ created.source.data = image;
3290
+ created.source.needsUpdate = true;
3291
+ created.bytes = Math.max(1, image.width * image.height * 4);
3292
+ if (created.retained) {
3293
+ this.bytes += created.bytes;
3512
3294
  }
3513
- }
3514
- offset += chunkLength;
3295
+ this.closeUnused(created);
3296
+ return image;
3297
+ }).catch((error) => {
3298
+ this.evict(created);
3299
+ throw error;
3300
+ });
3301
+ }
3302
+ entry.refs += 1;
3303
+ const acquired = entry;
3304
+ try {
3305
+ const image = await acquired.ready;
3306
+ let released = false;
3307
+ return {
3308
+ image,
3309
+ source: acquired.source,
3310
+ release: () => {
3311
+ if (!released) {
3312
+ released = true;
3313
+ this.unref(acquired);
3314
+ }
3315
+ },
3316
+ adopt: (texture) => {
3317
+ acquired.refs += 1;
3318
+ texture.source = acquired.source;
3319
+ const dispose = () => {
3320
+ texture.removeEventListener("dispose", dispose);
3321
+ this.unref(acquired);
3322
+ };
3323
+ texture.addEventListener("dispose", dispose);
3324
+ },
3325
+ retainGpu: (renderer, texture) => this.retainGpu(acquired, renderer, texture)
3326
+ };
3327
+ } catch (error) {
3328
+ this.unref(acquired);
3329
+ throw error;
3515
3330
  }
3516
- return { json: null, jsonText: null, isBinary: true };
3517
3331
  }
3518
- const jsonText = textDecoder.decode(new Uint8Array(data));
3519
- try {
3520
- const json = JSON.parse(jsonText);
3521
- return { json, jsonText, isBinary: false };
3522
- } catch {
3523
- return { json: null, jsonText, isBinary: false };
3332
+ /**
3333
+ * Drops one use. An image that becomes idle counts as the most recently
3334
+ * used one, and the idle limits apply again.
3335
+ */
3336
+ unref(entry) {
3337
+ entry.refs -= 1;
3338
+ if (entry.refs === 0 && this.entries.get(entry.key) === entry) {
3339
+ this.entries.delete(entry.key);
3340
+ this.entries.set(entry.key, entry);
3341
+ this.trim();
3342
+ }
3343
+ this.closeUnused(entry);
3524
3344
  }
3525
- };
3526
- var collectExternalResourceUrls = function(gltfJson, baseUrl) {
3527
- const urls = /* @__PURE__ */ new Set();
3528
- const addUri = function(uri) {
3529
- if (!uri) {
3345
+ retainGpu(entry, renderer, texture) {
3346
+ if (!entry.retained || texture.source !== entry.source) {
3530
3347
  return;
3531
3348
  }
3532
- if (uri.startsWith("data:") || uri.startsWith("blob:")) {
3533
- return;
3349
+ let anchors = entry.anchors.get(renderer);
3350
+ if (!anchors) {
3351
+ anchors = /* @__PURE__ */ new Map();
3352
+ entry.anchors.set(renderer, anchors);
3353
+ const release = () => {
3354
+ const textures = entry.anchors.get(renderer);
3355
+ if (textures) {
3356
+ for (const anchor2 of textures.values()) {
3357
+ anchor2.dispose();
3358
+ if (entry.retained) {
3359
+ this.bytes -= this.gpuBytes(entry, anchor2);
3360
+ }
3361
+ }
3362
+ entry.anchors.delete(renderer);
3363
+ }
3364
+ rendererReleases.get(renderer)?.delete(release);
3365
+ entry.rendererReleases.delete(renderer);
3366
+ };
3367
+ const releases = rendererReleases.get(renderer) ?? /* @__PURE__ */ new Set();
3368
+ releases.add(release);
3369
+ rendererReleases.set(renderer, releases);
3370
+ entry.rendererReleases.set(renderer, release);
3371
+ }
3372
+ let variant = this.variants.get(texture);
3373
+ if (!variant || variant.version !== texture.version) {
3374
+ const options = uploadOptions(texture);
3375
+ variant = {
3376
+ version: texture.version,
3377
+ key: JSON.stringify(options),
3378
+ options
3379
+ };
3380
+ this.variants.set(texture, variant);
3534
3381
  }
3535
- urls.add(resolveResourceUrl(uri, baseUrl));
3536
- };
3537
- const collectFrom = function(entries) {
3538
- if (!Array.isArray(entries)) {
3382
+ const { key } = variant;
3383
+ if (anchors.has(key)) {
3539
3384
  return;
3540
3385
  }
3541
- entries.forEach((entry) => {
3542
- if (!isRecord2(entry)) {
3543
- return;
3386
+ const anchor = new Texture(texture.image);
3387
+ Object.assign(anchor, variant.options);
3388
+ anchor.needsUpdate = true;
3389
+ anchor.source = texture.source;
3390
+ anchors.set(key, anchor);
3391
+ this.bytes += this.gpuBytes(entry, anchor);
3392
+ try {
3393
+ renderer.initTexture(anchor);
3394
+ } catch (error) {
3395
+ anchors.delete(key);
3396
+ this.bytes -= this.gpuBytes(entry, anchor);
3397
+ anchor.dispose();
3398
+ throw error;
3399
+ }
3400
+ if (entry.refs === 0) {
3401
+ this.trim();
3402
+ }
3403
+ }
3404
+ gpuBytes(entry, texture) {
3405
+ return Math.ceil(entry.bytes * (texture.generateMipmaps ? 4 / 3 : 1));
3406
+ }
3407
+ /** Decoded bytes plus the GPU uploads the cache keeps for the image. */
3408
+ retainedBytes(entry) {
3409
+ let total = entry.bytes;
3410
+ for (const anchors of entry.anchors.values()) {
3411
+ for (const anchor of anchors.values()) {
3412
+ total += this.gpuBytes(entry, anchor);
3544
3413
  }
3545
- const uri = entry.uri;
3546
- if (typeof uri !== "string") {
3414
+ }
3415
+ return total;
3416
+ }
3417
+ /**
3418
+ * Evicts the least recently used idle images until the idle ones fit the
3419
+ * limits. Evicting an image in use would free nothing: its live textures
3420
+ * keep the pixels and the GPU upload.
3421
+ */
3422
+ trim() {
3423
+ let idleEntries = 0;
3424
+ let idleBytes = 0;
3425
+ for (const entry of this.entries.values()) {
3426
+ if (entry.refs === 0) {
3427
+ idleEntries += 1;
3428
+ idleBytes += this.retainedBytes(entry);
3429
+ }
3430
+ }
3431
+ for (const entry of [...this.entries.values()]) {
3432
+ if (idleEntries <= this.maxEntries && idleBytes <= this.maxBytes) {
3547
3433
  return;
3548
3434
  }
3549
- addUri(uri);
3550
- });
3551
- };
3552
- collectFrom(gltfJson.buffers);
3553
- collectFrom(gltfJson.images);
3554
- return Array.from(urls);
3555
- };
3556
- var readResponseChunks = async function(response, resourceId, onProgress) {
3557
- const total = parseContentLength(response);
3558
- onProgress?.(resourceId, 0, total ?? 0);
3559
- if (!response.body) {
3560
- const buffer = await response.arrayBuffer();
3561
- const loaded2 = buffer.byteLength;
3562
- onProgress?.(resourceId, loaded2, total ?? loaded2);
3563
- return [new Uint8Array(buffer)];
3435
+ if (entry.refs === 0) {
3436
+ idleEntries -= 1;
3437
+ idleBytes -= this.retainedBytes(entry);
3438
+ this.evict(entry);
3439
+ }
3440
+ }
3564
3441
  }
3565
- const reader = response.body.getReader();
3566
- const chunks = [];
3567
- let loaded = 0;
3568
- while (true) {
3569
- const { done, value } = await reader.read();
3570
- if (done) {
3571
- break;
3442
+ evict(entry) {
3443
+ if (!entry.retained) {
3444
+ return;
3572
3445
  }
3573
- if (!value) {
3574
- continue;
3446
+ if (this.entries.get(entry.key) === entry) {
3447
+ this.entries.delete(entry.key);
3575
3448
  }
3576
- chunks.push(value);
3577
- loaded += value.length;
3578
- onProgress?.(resourceId, loaded, total ?? 0);
3579
- }
3580
- onProgress?.(resourceId, loaded, total ?? loaded);
3581
- return chunks;
3582
- };
3583
- var concatChunks = function(chunks) {
3584
- if (chunks.length === 0) {
3585
- return new Uint8Array();
3586
- }
3587
- if (chunks.length === 1) {
3588
- return chunks[0] ?? new Uint8Array();
3449
+ this.bytes -= entry.bytes;
3450
+ for (const release of entry.rendererReleases.values()) {
3451
+ release();
3452
+ }
3453
+ entry.anchors.clear();
3454
+ entry.retained = false;
3455
+ this.closeUnused(entry);
3589
3456
  }
3590
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
3591
- const combined = new Uint8Array(totalLength);
3592
- let offset = 0;
3593
- for (const chunk of chunks) {
3594
- combined.set(chunk, offset);
3595
- offset += chunk.length;
3457
+ closeUnused(entry) {
3458
+ if (!entry.retained && entry.refs === 0 && entry.source.data && !entry.closed) {
3459
+ entry.closed = true;
3460
+ const image = entry.source.data;
3461
+ if ("close" in image) {
3462
+ image.close();
3463
+ }
3464
+ }
3596
3465
  }
3597
- return combined;
3598
3466
  };
3599
- var toArrayBuffer = function(data) {
3600
- const buffer = new ArrayBuffer(data.byteLength);
3601
- new Uint8Array(buffer).set(data);
3602
- return buffer;
3603
- };
3604
- var fetchChunksWithProgress = async function(url, onProgress) {
3605
- const response = await fetch(url);
3606
- if (!response.ok) {
3607
- throw new Error(await response.text());
3608
- }
3609
- return await readResponseChunks(response, url, onProgress);
3610
- };
3611
- var fetchArrayBufferWithProgress = async function(url, onProgress) {
3612
- const chunks = await fetchChunksWithProgress(url, onProgress);
3613
- const combined = concatChunks(chunks);
3614
- return toArrayBuffer(combined);
3615
- };
3616
- var fetchBlobWithProgress = async function(url, onProgress) {
3617
- const chunks = await fetchChunksWithProgress(url, onProgress);
3618
- const combined = concatChunks(chunks);
3619
- return new Blob([toArrayBuffer(combined)]);
3620
- };
3621
- var loadGltfWithProgress = async function({
3622
- url,
3623
- onProgress,
3624
- configureLoader
3625
- }) {
3626
- const baseUrl = new URL(".", url).toString();
3627
- const buffer = await fetchArrayBufferWithProgress(url, onProgress);
3628
- const { json, jsonText, isBinary } = parseGltfJson(buffer);
3629
- const resourceUrls = json ? collectExternalResourceUrls(json, baseUrl) : [];
3630
- const resourceMap = /* @__PURE__ */ new Map();
3631
- if (resourceUrls.length > 0) {
3632
- const blobs = await Promise.all(
3633
- resourceUrls.map(async (resourceUrl) => {
3634
- const blob = await fetchBlobWithProgress(resourceUrl, onProgress);
3635
- return { resourceUrl, blob };
3636
- })
3637
- );
3638
- blobs.forEach(({ resourceUrl, blob }) => {
3639
- resourceMap.set(resourceUrl, URL.createObjectURL(blob));
3640
- });
3641
- }
3642
- const manager = new LoadingManager();
3643
- manager.setURLModifier((requestedUrl) => {
3644
- if (requestedUrl.startsWith("blob:") || requestedUrl.startsWith("data:")) {
3645
- return requestedUrl;
3646
- }
3647
- const resolved = resolveResourceUrl(requestedUrl, baseUrl);
3648
- return resourceMap.get(resolved) ?? resourceMap.get(requestedUrl) ?? requestedUrl;
3649
- });
3650
- const loader = new GLTFLoader(manager);
3651
- configureLoader?.(loader);
3652
- const parseInput = isBinary ? buffer : jsonText;
3653
- if (!parseInput) {
3654
- throw new Error("Failed to parse GLTF payload.");
3655
- }
3656
- try {
3657
- return await new Promise((resolve, reject) => {
3658
- loader.parse(parseInput, baseUrl, resolve, reject);
3659
- });
3660
- } finally {
3661
- resourceMap.forEach((blobUrl) => {
3662
- URL.revokeObjectURL(blobUrl);
3663
- });
3664
- }
3665
- };
3666
- var loadVrm = async ({
3667
- baseUrl,
3668
- characterId,
3669
- apiToken,
3670
- onProgress,
3671
- assetProfile
3672
- }) => {
3673
- const url = new URL(`/avatars/${characterId}/download-url`, baseUrl);
3674
- if (assetProfile && assetProfile !== "original") {
3675
- url.searchParams.set("assetProfile", assetProfile);
3676
- }
3677
- const res = await fetch(url.toString(), {
3678
- headers: buildAuthHeaders(apiToken, { allowEmpty: true }),
3679
- credentials: apiToken ? "omit" : "include"
3680
- });
3681
- if (!res.ok) {
3682
- throw new Error(await res.text());
3683
- }
3684
- const { url: vrmUrl } = await res.json();
3685
- const gltf = await loadGltfWithProgress({
3686
- url: vrmUrl,
3687
- onProgress,
3688
- configureLoader: (loader) => {
3689
- loader.register((parser) => new VRMLoaderPlugin(parser));
3690
- }
3691
- });
3692
- VRMUtils.removeUnnecessaryVertices(gltf.scene);
3693
- VRMUtils.combineSkeletons(gltf.scene);
3694
- return gltf.userData.vrm;
3695
- };
3696
- var loadVrma = async ({
3697
- baseUrl,
3698
- characterId,
3699
- animationId,
3700
- apiToken,
3701
- onProgress,
3702
- assetProfile
3703
- }) => {
3704
- const url = new URL(
3705
- `/avatars/${characterId}/animations/${animationId}/download-url`,
3706
- baseUrl
3707
- );
3708
- if (assetProfile && assetProfile !== "original") {
3709
- url.searchParams.set("assetProfile", assetProfile);
3710
- }
3711
- const res = await fetch(url.toString(), {
3712
- headers: buildAuthHeaders(apiToken, { allowEmpty: true }),
3713
- credentials: apiToken ? "omit" : "include"
3714
- });
3715
- if (!res.ok) {
3716
- throw new Error(await res.text());
3717
- }
3718
- const { url: vrmaUrl } = await res.json();
3719
- const gltf = await loadGltfWithProgress({
3720
- url: vrmaUrl,
3721
- onProgress,
3722
- configureLoader: (loader) => {
3723
- loader.register(
3724
- (parser) => new VRMAnimationLoaderPlugin(parser)
3725
- );
3726
- }
3727
- });
3728
- const animations = gltf.userData.vrmAnimations ?? gltf.userData.animations;
3729
- const animationList = Array.isArray(animations) ? animations : [];
3730
- if (animationList.length === 0) {
3731
- throw new Error(
3732
- `No animations found for character ${characterId} and animation ${animationId}`
3733
- );
3734
- }
3735
- const firstAnimation = animationList[0];
3736
- if (!firstAnimation) {
3737
- throw new Error(
3738
- `No animations found for character ${characterId} and animation ${animationId}`
3739
- );
3740
- }
3741
- return firstAnimation;
3742
- };
3743
- var getInfo = async ({
3744
- baseUrl,
3745
- characterId,
3746
- apiToken
3747
- }) => {
3748
- const url = new URL(`/avatars/${characterId}/info`, baseUrl);
3749
- const res = await fetch(url.toString(), {
3750
- headers: buildAuthHeaders(apiToken, { allowEmpty: true }),
3751
- credentials: apiToken ? "omit" : "include"
3752
- });
3753
- if (!res.ok) {
3754
- throw new Error(await res.text());
3755
- }
3756
- return await res.json();
3757
- };
3758
-
3759
- // ../../clients/web-client/src/asset-load-progress.ts
3760
- var createAssetProgressReporter = function(callback) {
3761
- if (!callback) {
3762
- const noop = () => {
3763
- };
3764
- return {
3765
- updateResource: noop
3766
- };
3767
- }
3768
- const resources = /* @__PURE__ */ new Map();
3769
- let lastProgress = -1;
3770
- let lastTotal = -1;
3771
- const updateResource = (resourceId, loaded, total) => {
3772
- const safeLoaded = Math.max(0, loaded);
3773
- const safeTotal = Math.max(0, total);
3774
- resources.set(resourceId, { loaded: safeLoaded, total: safeTotal });
3775
- let summedLoaded = 0;
3776
- let summedTotal = 0;
3777
- for (const resource of resources.values()) {
3778
- if (resource.total <= 0) {
3779
- continue;
3780
- }
3781
- summedLoaded += Math.min(resource.loaded, resource.total);
3782
- summedTotal += resource.total;
3783
- }
3784
- if (summedLoaded === lastProgress && summedTotal === lastTotal) {
3785
- return;
3786
- }
3787
- lastProgress = summedLoaded;
3788
- lastTotal = summedTotal;
3789
- callback({ progress: summedLoaded, total: summedTotal });
3790
- };
3791
- return { updateResource };
3792
- };
3793
-
3794
- // ../vrm-renderer/src/scene.ts
3795
- import {
3796
- Clock,
3797
- PerspectiveCamera,
3798
- Scene,
3799
- WebGLRenderer
3800
- } from "three";
3801
- import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
3802
-
3803
- // ../vrm-renderer/src/core/lighting.ts
3804
- import {
3805
- AmbientLight,
3806
- DirectionalLight,
3807
- NoToneMapping,
3808
- SRGBColorSpace
3809
- } from "three";
3810
- var AVATAR_COLOR_SETTINGS = {
3811
- toneMapping: NoToneMapping,
3812
- outputColorSpace: SRGBColorSpace
3467
+ var defaultVrmTextureCache = new VrmTextureCache();
3468
+
3469
+ // ../vrm-renderer/src/core/lighting.ts
3470
+ import {
3471
+ AmbientLight,
3472
+ DirectionalLight,
3473
+ NoToneMapping,
3474
+ SRGBColorSpace
3475
+ } from "three";
3476
+ var AVATAR_COLOR_SETTINGS = {
3477
+ toneMapping: NoToneMapping,
3478
+ outputColorSpace: SRGBColorSpace
3813
3479
  };
3814
3480
  var addAvatarLights = function(scene, {
3815
3481
  ambientIntensity = 0.7,
@@ -3838,8 +3504,8 @@ var CAMERA_PRESETS = {
3838
3504
  lookAt: [0, 1.4, 0]
3839
3505
  }
3840
3506
  };
3841
- var cameraCollisionRadius = function(near, verticalFovDegrees, aspect) {
3842
- const verticalHalf = Math.max(near, 1e-3) * Math.tan(MathUtils.degToRad(verticalFovDegrees) / 2);
3507
+ var cameraCollisionRadius = function(near2, verticalFovDegrees, aspect) {
3508
+ const verticalHalf = Math.max(near2, 1e-3) * Math.tan(MathUtils.degToRad(verticalFovDegrees) / 2);
3843
3509
  const horizontalHalf = verticalHalf * Math.max(aspect, 1e-3);
3844
3510
  return Math.max(0.06, Math.hypot(horizontalHalf, verticalHalf));
3845
3511
  };
@@ -4092,156 +3758,839 @@ var createSceneContext = function(options) {
4092
3758
  { cause }
4093
3759
  );
4094
3760
  }
4095
- const controls = new OrbitControls(intentCamera, canvas);
4096
- controls.enablePan = enablePan;
4097
- controls.enableDamping = enableDamping;
4098
- controls.enableZoom = enableZoom;
4099
- Object.assign(renderer, AVATAR_COLOR_SETTINGS);
4100
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
4101
- const clock = new Clock();
4102
- return {
4103
- scene,
4104
- camera,
4105
- intentCamera,
4106
- renderer,
4107
- controls,
4108
- clock,
4109
- collisionBackend: new NoopCameraCollisionBackend()
4110
- };
3761
+ const controls = new OrbitControls(intentCamera, canvas);
3762
+ controls.enablePan = enablePan;
3763
+ controls.enableDamping = enableDamping;
3764
+ controls.enableZoom = enableZoom;
3765
+ Object.assign(renderer, AVATAR_COLOR_SETTINGS);
3766
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
3767
+ const clock = new Clock();
3768
+ return {
3769
+ scene,
3770
+ camera,
3771
+ intentCamera,
3772
+ renderer,
3773
+ controls,
3774
+ clock,
3775
+ collisionBackend: new NoopCameraCollisionBackend()
3776
+ };
3777
+ };
3778
+ var resizeRenderer = function(ctx, width, height) {
3779
+ if (width <= 0 || height <= 0) {
3780
+ return;
3781
+ }
3782
+ ctx.camera.aspect = width / height;
3783
+ ctx.camera.updateProjectionMatrix();
3784
+ ctx.intentCamera.aspect = width / height;
3785
+ ctx.intentCamera.updateProjectionMatrix();
3786
+ ctx.renderer.setSize(width, height, false);
3787
+ };
3788
+ var setCameraCollisionBackend = function(ctx, backend) {
3789
+ ctx.collisionBackend = backend ?? new NoopCameraCollisionBackend();
3790
+ };
3791
+ var resolveSceneCamera = function(ctx, deltaSeconds) {
3792
+ ctx.collisionBackend.update();
3793
+ const result = ctx.collisionBackend.resolve({
3794
+ cameraRadius: cameraCollisionRadius(
3795
+ ctx.camera.near,
3796
+ ctx.camera.fov,
3797
+ ctx.camera.aspect
3798
+ ),
3799
+ deltaSeconds,
3800
+ desiredPosition: ctx.intentCamera.position,
3801
+ target: ctx.controls.target
3802
+ });
3803
+ ctx.camera.position.copy(result.position);
3804
+ ctx.camera.quaternion.copy(ctx.intentCamera.quaternion);
3805
+ ctx.camera.scale.copy(ctx.intentCamera.scale);
3806
+ ctx.camera.lookAt(ctx.controls.target);
3807
+ ctx.camera.updateMatrixWorld();
3808
+ };
3809
+ var disposeSceneContext = function(ctx) {
3810
+ ctx.controls.dispose();
3811
+ releaseRendererTextureCache(ctx.renderer);
3812
+ ctx.renderer.dispose();
3813
+ ctx.renderer.forceContextLoss();
3814
+ };
3815
+
3816
+ // ../vrm-renderer/src/preview-controller.ts
3817
+ import { VRMUtils as VRMUtils3 } from "@pixiv/three-vrm";
3818
+ import { Box3, GridHelper, Vector3 as Vector33 } from "three";
3819
+
3820
+ // ../vrm-renderer/src/loaders.ts
3821
+ import { VRMLoaderPlugin, VRMUtils } from "@pixiv/three-vrm";
3822
+ import { VRMAnimationLoaderPlugin } from "@pixiv/three-vrm-animation";
3823
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
3824
+
3825
+ // ../vrm-renderer/src/texture-cache-loader.ts
3826
+ import {
3827
+ Cache,
3828
+ ImageBitmapLoader,
3829
+ Texture as Texture2
3830
+ } from "three";
3831
+
3832
+ // ../vrm-renderer/src/texture-expressions.ts
3833
+ import {
3834
+ MToonMaterial,
3835
+ VRMExpressionTextureTransformBind
3836
+ } from "@pixiv/three-vrm";
3837
+
3838
+ // ../vrm-renderer/src/texture-expressions-shader.ts
3839
+ var sampleMap = "texture2D( map, mapUv )";
3840
+ var sampleShade = "texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv )";
3841
+ var mouthShader = `
3842
+ uniform float npcifyMouthWeights[6];
3843
+ uniform float npcifyMouthTexelWidth;
3844
+ vec4 npcifySampleMouth(sampler2D atlas, vec2 uv) {
3845
+ // Clamp inside the neutral column before adding each whole-cell offset.
3846
+ // Interpolating these offsets would slide the face across adjacent cells.
3847
+ uv.x = clamp(uv.x, 0.5 * npcifyMouthTexelWidth, 1.0 / 6.0 - 0.5 * npcifyMouthTexelWidth);
3848
+ vec4 color = vec4(0.0);
3849
+ ${Array.from(
3850
+ { length: 6 },
3851
+ (_, column) => `
3852
+ if (npcifyMouthWeights[${column}] > 0.0) {
3853
+ color += npcifyMouthWeights[${column}] * texture2D(atlas, uv + vec2(${column}.0 / 6.0, 0.0));
3854
+ }`
3855
+ ).join("\n")}
3856
+ return color;
3857
+ }
3858
+ `;
3859
+ var createMouthAtlasShader = function(material) {
3860
+ if (!material.fragmentShader.includes(sampleMap) || !material.fragmentShader.includes(sampleShade)) {
3861
+ return null;
3862
+ }
3863
+ const fragment = material.fragmentShader;
3864
+ const cacheKey = material.customProgramCacheKey;
3865
+ const weights = { value: new Float32Array([1, 0, 0, 0, 0, 0]) };
3866
+ const texel = { value: 1 / 4096 };
3867
+ const uniforms = material.uniforms;
3868
+ uniforms.npcifyMouthWeights = weights;
3869
+ uniforms.npcifyMouthTexelWidth = texel;
3870
+ material.fragmentShader = mouthShader + fragment.replace(sampleMap, "npcifySampleMouth( map, mapUv )").replace(
3871
+ sampleShade,
3872
+ "npcifySampleMouth( shadeMultiplyTexture, shadeMultiplyTextureUv )"
3873
+ );
3874
+ material.customProgramCacheKey = function() {
3875
+ return `${cacheKey.call(material)},npcify-mouth-atlas-v1`;
3876
+ };
3877
+ material.needsUpdate = true;
3878
+ return {
3879
+ update(values) {
3880
+ weights.value.set(values);
3881
+ const image = material.map?.image;
3882
+ if (image && typeof image === "object" && "width" in image && typeof image.width === "number" && image.width > 0) {
3883
+ texel.value = 1 / image.width;
3884
+ }
3885
+ },
3886
+ dispose() {
3887
+ material.fragmentShader = fragment;
3888
+ material.customProgramCacheKey = cacheKey;
3889
+ delete uniforms.npcifyMouthWeights;
3890
+ delete uniforms.npcifyMouthTexelWidth;
3891
+ }
3892
+ };
3893
+ };
3894
+
3895
+ // ../vrm-renderer/src/texture-expressions-pixels.ts
3896
+ import { DataTexture, Source as Source2, SRGBColorSpace as SRGBColorSpace2 } from "three";
3897
+ var rawImage = function(image) {
3898
+ if (!image || typeof image !== "object" || !("data" in image) || !("width" in image) || !("height" in image)) {
3899
+ return false;
3900
+ }
3901
+ return image.data instanceof Uint8Array && typeof image.width === "number" && typeof image.height === "number" && image.width >= 6 && image.height >= 7 && Number.isInteger(image.width) && Number.isInteger(image.height) && image.data.length === image.width * image.height * 4;
3902
+ };
3903
+ var linear = Float32Array.from({ length: 256 }, (_, value) => {
3904
+ const s = value / 255;
3905
+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
3906
+ });
3907
+ var srgb = Uint8Array.from({ length: 4097 }, (_, value) => {
3908
+ const s = value / 4096;
3909
+ return Math.round(
3910
+ 255 * (s <= 31308e-7 ? 12.92 * s : 1.055 * s ** (1 / 2.4) - 0.055)
3911
+ );
3912
+ });
3913
+ var PixelColumns = class {
3914
+ constructor(original) {
3915
+ this.original = original;
3916
+ }
3917
+ image = null;
3918
+ columns = [];
3919
+ previous = new Float32Array(6).fill(-1);
3920
+ source = new Source2({ data: new Uint8Array(4), width: 1, height: 1 });
3921
+ update(weights) {
3922
+ const image = this.original.image;
3923
+ if (!rawImage(image)) {
3924
+ return false;
3925
+ }
3926
+ const changed = image !== this.image;
3927
+ if (changed) {
3928
+ this.prepare(image);
3929
+ }
3930
+ if (!changed && weights.every(
3931
+ (value, column) => Math.abs(value - this.previous[column]) < 1e-5
3932
+ )) {
3933
+ return false;
3934
+ }
3935
+ this.previous.set(weights);
3936
+ const data = this.source.data.data;
3937
+ const active = Array.from(weights.entries()).filter(([, weight]) => weight > 0).map(([column, weight]) => ({ pixels: this.columns[column], weight }));
3938
+ const isSrgb = this.original.colorSpace === SRGBColorSpace2;
3939
+ for (let i = 0; i < data.length; i += 1) {
3940
+ let value = 0;
3941
+ for (let column = 0; column < active.length; column += 1) {
3942
+ const source = active[column];
3943
+ value += source.pixels[i] * source.weight;
3944
+ }
3945
+ data[i] = isSrgb && i % 4 !== 3 ? srgb[Math.max(0, Math.min(4096, Math.round(value * 4096)))] : Math.round(value * 255);
3946
+ }
3947
+ return true;
3948
+ }
3949
+ prepare(image) {
3950
+ this.image = image;
3951
+ const width = Math.max(1, Math.round(image.width / 6));
3952
+ const length = width * image.height * 4;
3953
+ this.source.data = {
3954
+ data: new Uint8Array(length),
3955
+ width,
3956
+ height: image.height
3957
+ };
3958
+ const isSrgb = this.original.colorSpace === SRGBColorSpace2;
3959
+ this.columns = Array.from({ length: 6 }, (_, column) => {
3960
+ const pixels = new Float32Array(length);
3961
+ for (let y = 0; y < image.height; y += 1) {
3962
+ for (let x = 0; x < width; x += 1) {
3963
+ const sample = ((x + 0.5) / width + column) * image.width / 6 - 0.5;
3964
+ const left = Math.max(
3965
+ 0,
3966
+ Math.min(image.width - 1, Math.floor(sample))
3967
+ );
3968
+ const right = Math.min(image.width - 1, left + 1);
3969
+ const mix = Math.max(0, sample - left);
3970
+ for (let channel = 0; channel < 4; channel += 1) {
3971
+ const a = image.data[(y * image.width + left) * 4 + channel];
3972
+ const b = image.data[(y * image.width + right) * 4 + channel];
3973
+ const convert = isSrgb && channel !== 3;
3974
+ const first = convert ? linear[a] : a / 255;
3975
+ const second = convert ? linear[b] : b / 255;
3976
+ pixels[(y * width + x) * 4 + channel] = first + (second - first) * mix;
3977
+ }
3978
+ }
3979
+ }
3980
+ return pixels;
3981
+ });
3982
+ }
3983
+ dispose() {
3984
+ this.columns = [];
3985
+ this.image = null;
3986
+ this.source.data = null;
3987
+ }
3988
+ };
3989
+ var createMouthAtlasPixels = function(material) {
3990
+ const properties = ["map", "shadeMultiplyTexture"];
3991
+ if (properties.some(
3992
+ (name) => material[name] && !rawImage(material[name].image)
3993
+ )) {
3994
+ return null;
3995
+ }
3996
+ const columns = /* @__PURE__ */ new Map();
3997
+ const textures = properties.flatMap((name) => {
3998
+ const original = material[name];
3999
+ if (!original) {
4000
+ return [];
4001
+ }
4002
+ let pixels = columns.get(original.colorSpace);
4003
+ if (!pixels) {
4004
+ pixels = new PixelColumns(original);
4005
+ columns.set(original.colorSpace, pixels);
4006
+ }
4007
+ const texture = new DataTexture();
4008
+ texture.copy(original);
4009
+ texture.source = pixels.source;
4010
+ texture.generateMipmaps = false;
4011
+ texture.minFilter = original.magFilter;
4012
+ material[name] = texture;
4013
+ return [{ name, original, texture, pixels }];
4014
+ });
4015
+ return {
4016
+ update(weights) {
4017
+ const changed = new Set(
4018
+ [...columns.values()].filter((pixels) => pixels.update(weights))
4019
+ );
4020
+ for (const { texture, pixels } of textures) {
4021
+ texture.repeat.x = 6;
4022
+ if (changed.has(pixels)) {
4023
+ texture.needsUpdate = true;
4024
+ }
4025
+ }
4026
+ },
4027
+ dispose() {
4028
+ for (const { name, original, texture } of textures) {
4029
+ material[name] = original;
4030
+ texture.dispose();
4031
+ original.dispose();
4032
+ }
4033
+ columns.forEach((pixels) => pixels.dispose());
4034
+ }
4035
+ };
4036
+ };
4037
+
4038
+ // ../vrm-renderer/src/texture-expressions.ts
4039
+ var MOUTHS = ["aa", "ih", "ou", "ee", "oh"];
4040
+ var installed = /* @__PURE__ */ new WeakSet();
4041
+ var near = function(a, b) {
4042
+ return Math.abs(a - b) < 1e-5;
4043
+ };
4044
+ var findAtlasBindings = function(vrm) {
4045
+ const bindings = [];
4046
+ for (const [index, name] of MOUTHS.entries()) {
4047
+ const expression = vrm.expressionManager?.getExpression(name);
4048
+ if (!expression?.isBinary || !expression.binds.length) {
4049
+ return [];
4050
+ }
4051
+ for (const bind of expression.binds) {
4052
+ if (!(bind instanceof VRMExpressionTextureTransformBind) || !(bind.material instanceof MToonMaterial) || !near(bind.offset.x, (index + 1) / 6) || !near(bind.offset.y, 0) || !near(bind.scale.x, 1) || !near(bind.scale.y, 1)) {
4053
+ return [];
4054
+ }
4055
+ bindings.push({ expression, bind, column: index + 1 });
4056
+ }
4057
+ }
4058
+ const materials = new Set(bindings.map(({ bind }) => bind.material));
4059
+ for (const material of materials) {
4060
+ if (new Set(
4061
+ bindings.filter(({ bind }) => bind.material === material).map(({ column }) => column)
4062
+ ).size !== 5) {
4063
+ return [];
4064
+ }
4065
+ const face = material;
4066
+ if (!face.map || face.shadeMultiplyTexture && face.shadeMultiplyTexture.image !== face.map.image) {
4067
+ return [];
4068
+ }
4069
+ for (const texture of [face.map, face.shadeMultiplyTexture]) {
4070
+ if (texture && (!near(texture.offset.x, 0) || !near(texture.offset.y, 0) || !near(texture.repeat.x, 1) || !near(texture.repeat.y, 1) || !near(texture.rotation, 0))) {
4071
+ return [];
4072
+ }
4073
+ }
4074
+ let hasBlinkRow = false;
4075
+ let rowDirection = 0;
4076
+ for (const expression of vrm.expressionManager.expressions) {
4077
+ if (MOUTHS.some((name) => name === expression.expressionName)) {
4078
+ continue;
4079
+ }
4080
+ for (const bind of expression.binds) {
4081
+ if (!(bind instanceof VRMExpressionTextureTransformBind) || bind.material !== material) {
4082
+ continue;
4083
+ }
4084
+ const row = Math.round(bind.offset.y * 7);
4085
+ if (!expression.isBinary || !near(bind.offset.x, 0) || !near(bind.offset.y, row / 7) || Math.abs(row) > 6 || row !== 0 && rowDirection !== 0 && Math.sign(row) !== rowDirection || !near(bind.scale.x, 1) || !near(bind.scale.y, 1)) {
4086
+ return [];
4087
+ }
4088
+ if (row !== 0) {
4089
+ rowDirection = Math.sign(row);
4090
+ }
4091
+ hasBlinkRow ||= expression.expressionName === "blink" && Math.abs(row) === 1;
4092
+ }
4093
+ }
4094
+ if (!hasBlinkRow) {
4095
+ return [];
4096
+ }
4097
+ }
4098
+ return bindings;
4099
+ };
4100
+ var enableTextureExpressionBlending = function(vrm, options = {}) {
4101
+ if (installed.has(vrm)) {
4102
+ return;
4103
+ }
4104
+ const bindings = findAtlasBindings(vrm);
4105
+ if (!bindings.length) {
4106
+ return;
4107
+ }
4108
+ const materials = [
4109
+ ...new Set(bindings.map(({ bind }) => bind.material))
4110
+ ];
4111
+ const outputs = materials.map(
4112
+ (material) => options.backend === "pixels" ? createMouthAtlasPixels(material) : createMouthAtlasShader(material)
4113
+ );
4114
+ if (outputs.some((output) => !output)) {
4115
+ outputs.forEach((output) => output?.dispose());
4116
+ return;
4117
+ }
4118
+ installed.add(vrm);
4119
+ for (const [index, material] of materials.entries()) {
4120
+ const output = outputs[index];
4121
+ const targets = new Float32Array(6);
4122
+ const weights = new Float32Array([1, 0, 0, 0, 0, 0]);
4123
+ for (const { expression, bind, column } of bindings) {
4124
+ if (bind.material !== material) {
4125
+ continue;
4126
+ }
4127
+ expression.isBinary = false;
4128
+ expression.deleteBind(bind);
4129
+ expression.addBind({
4130
+ clearAppliedWeight: () => {
4131
+ targets[column] = 0;
4132
+ },
4133
+ applyWeight: (weight) => {
4134
+ targets[column] = Number.isFinite(weight) ? Math.max(0, Math.min(1, weight)) : 0;
4135
+ }
4136
+ });
4137
+ }
4138
+ const originalUpdate = material.update;
4139
+ material.update = function(delta) {
4140
+ let total = 0;
4141
+ for (let column = 1; column < 6; column += 1) {
4142
+ total += targets[column];
4143
+ }
4144
+ targets[0] = Math.max(0, 1 - total);
4145
+ const scale = Math.max(1, total);
4146
+ let distance = 0;
4147
+ for (let column = 0; column < 6; column += 1) {
4148
+ targets[column] = targets[column] / scale;
4149
+ distance = Math.max(
4150
+ distance,
4151
+ Math.abs(targets[column] - weights[column])
4152
+ );
4153
+ }
4154
+ const step = Number.isFinite(delta) ? Math.max(0, delta) / 0.08 : 0;
4155
+ const factor = distance > 0 ? Math.min(1, step / distance) : 1;
4156
+ for (let column = 0; column < 6; column += 1) {
4157
+ weights[column] = weights[column] + (targets[column] - weights[column]) * factor;
4158
+ }
4159
+ output.update(weights);
4160
+ originalUpdate.call(material, delta);
4161
+ };
4162
+ const dispose = function() {
4163
+ material.removeEventListener("dispose", dispose);
4164
+ material.update = originalUpdate;
4165
+ output.dispose();
4166
+ };
4167
+ material.addEventListener("dispose", dispose);
4168
+ }
4169
+ };
4170
+
4171
+ // ../vrm-renderer/src/session.ts
4172
+ import { VRMUtils as VRMUtils2 } from "@pixiv/three-vrm";
4173
+ import { AnimationMixer, LoopOnce, LoopRepeat } from "three";
4174
+
4175
+ // ../vrm-renderer/src/animation.ts
4176
+ import {
4177
+ createVRMAnimationClip as createPixivVRMAnimationClip
4178
+ } from "@pixiv/three-vrm-animation";
4179
+ var NPCIFY_VRM_NORMALIZATION_ROOT_NAME = "NPCifyNormalizationRoot";
4180
+ var canonicalAnimationTargets = /* @__PURE__ */ new WeakMap();
4181
+ var isNpcifyNormalizedVrm = function(vrm) {
4182
+ return vrm.scene.children.some(
4183
+ (child) => child.name === NPCIFY_VRM_NORMALIZATION_ROOT_NAME
4184
+ );
4185
+ };
4186
+ var canonicalAnimationTarget = function(vrm) {
4187
+ if (vrm.meta.metaVersion !== "0" || !isNpcifyNormalizedVrm(vrm)) {
4188
+ return vrm;
4189
+ }
4190
+ const cached = canonicalAnimationTargets.get(vrm);
4191
+ if (cached) {
4192
+ return cached;
4193
+ }
4194
+ const target = new Proxy(vrm, {
4195
+ get(source, property, receiver) {
4196
+ if (property === "meta") {
4197
+ return { ...source.meta, metaVersion: "1" };
4198
+ }
4199
+ return Reflect.get(source, property, receiver);
4200
+ }
4201
+ });
4202
+ canonicalAnimationTargets.set(vrm, target);
4203
+ return target;
4204
+ };
4205
+ var createVRMAnimationClip = function(animation, vrm) {
4206
+ return createPixivVRMAnimationClip(animation, canonicalAnimationTarget(vrm));
4207
+ };
4208
+
4209
+ // ../vrm-renderer/src/session.ts
4210
+ var attachVrm = function(ctx, vrm) {
4211
+ ctx.scene.add(vrm.scene);
4212
+ setCameraCollisionBackend(
4213
+ ctx,
4214
+ new HumanoidCapsuleCollisionBackend(
4215
+ (name) => vrm.humanoid.getRawBoneNode(name)
4216
+ )
4217
+ );
4218
+ const mixer = new AnimationMixer(vrm.scene);
4219
+ return { vrm, mixer, activeAction: null, animationFrameId: null };
4220
+ };
4221
+ var detachVrm = function(ctx, session, options = {}) {
4222
+ stopRenderLoop(session);
4223
+ session.mixer.stopAllAction();
4224
+ if (session.vrm.scene.parent) {
4225
+ session.vrm.scene.parent.remove(session.vrm.scene);
4226
+ }
4227
+ setCameraCollisionBackend(ctx, null);
4228
+ session.mixer.uncacheRoot(session.vrm.scene);
4229
+ if (options.dispose) {
4230
+ disposeVrm(session.vrm);
4231
+ }
4232
+ };
4233
+ var disposeVrm = function(vrm) {
4234
+ disposeObject3D(vrm.scene);
4235
+ };
4236
+ var disposeObject3D = function(object) {
4237
+ VRMUtils2.deepDispose(object);
4238
+ };
4239
+ var stopRenderLoop = function(session) {
4240
+ if (session.animationFrameId === null) {
4241
+ return;
4242
+ }
4243
+ cancelAnimationFrame(session.animationFrameId);
4244
+ session.animationFrameId = null;
4245
+ };
4246
+ var setCameraView = function(ctx, position, lookAt) {
4247
+ ctx.camera.position.set(...position);
4248
+ ctx.camera.lookAt(...lookAt);
4249
+ ctx.intentCamera.position.set(...position);
4250
+ ctx.intentCamera.lookAt(...lookAt);
4251
+ ctx.controls.target.set(...lookAt);
4252
+ ctx.controls.update();
4253
+ resolveSceneCamera(ctx, 0);
4254
+ };
4255
+ var applyCameraPreset = function(ctx, preset) {
4256
+ const config = CAMERA_PRESETS[preset];
4257
+ setCameraView(ctx, config.position, config.lookAt);
4258
+ };
4259
+
4260
+ // ../../clients/web-client/src/api/info.ts
4261
+ import {
4262
+ VRMAnimationLoaderPlugin as VRMAnimationLoaderPlugin2
4263
+ } from "@pixiv/three-vrm-animation";
4264
+ import { LoadingManager } from "three";
4265
+ import { GLTFLoader as GLTFLoader2 } from "three/examples/jsm/loaders/GLTFLoader.js";
4266
+ var GLB_HEADER_MAGIC = 1179937895;
4267
+ var GLB_CHUNK_TYPE_JSON = 1313821514;
4268
+ var textDecoder = new TextDecoder();
4269
+ var isRecord2 = function(value) {
4270
+ return typeof value === "object" && value !== null;
4271
+ };
4272
+ var resolveResourceUrl = function(url, baseUrl) {
4273
+ try {
4274
+ return new URL(url, baseUrl).toString();
4275
+ } catch {
4276
+ return url;
4277
+ }
4278
+ };
4279
+ var parseContentLength = function(response) {
4280
+ if (response.headers.get("content-encoding")) {
4281
+ return null;
4282
+ }
4283
+ const header = response.headers.get("content-length");
4284
+ if (!header) {
4285
+ return null;
4286
+ }
4287
+ const parsed = Number(header);
4288
+ if (!Number.isFinite(parsed) || parsed <= 0) {
4289
+ return null;
4290
+ }
4291
+ return parsed;
4292
+ };
4293
+ var parseGltfJson = function(data) {
4294
+ if (data.byteLength < 12) {
4295
+ return { json: null, jsonText: null, isBinary: false };
4296
+ }
4297
+ const view = new DataView(data);
4298
+ const magic = view.getUint32(0, true);
4299
+ if (magic === GLB_HEADER_MAGIC) {
4300
+ let offset = 12;
4301
+ while (offset + 8 <= view.byteLength) {
4302
+ const chunkLength = view.getUint32(offset, true);
4303
+ const chunkType = view.getUint32(offset + 4, true);
4304
+ offset += 8;
4305
+ if (chunkType === GLB_CHUNK_TYPE_JSON) {
4306
+ const chunkData = new Uint8Array(data, offset, chunkLength);
4307
+ const jsonText2 = textDecoder.decode(chunkData);
4308
+ try {
4309
+ const json = JSON.parse(jsonText2);
4310
+ return { json, jsonText: jsonText2, isBinary: true };
4311
+ } catch {
4312
+ return { json: null, jsonText: jsonText2, isBinary: true };
4313
+ }
4314
+ }
4315
+ offset += chunkLength;
4316
+ }
4317
+ return { json: null, jsonText: null, isBinary: true };
4318
+ }
4319
+ const jsonText = textDecoder.decode(new Uint8Array(data));
4320
+ try {
4321
+ const json = JSON.parse(jsonText);
4322
+ return { json, jsonText, isBinary: false };
4323
+ } catch {
4324
+ return { json: null, jsonText, isBinary: false };
4325
+ }
4326
+ };
4327
+ var collectExternalResourceUrls = function(gltfJson, baseUrl) {
4328
+ const urls = /* @__PURE__ */ new Set();
4329
+ const addUri = function(uri) {
4330
+ if (!uri) {
4331
+ return;
4332
+ }
4333
+ if (uri.startsWith("data:") || uri.startsWith("blob:")) {
4334
+ return;
4335
+ }
4336
+ urls.add(resolveResourceUrl(uri, baseUrl));
4337
+ };
4338
+ const collectFrom = function(entries) {
4339
+ if (!Array.isArray(entries)) {
4340
+ return;
4341
+ }
4342
+ entries.forEach((entry) => {
4343
+ if (!isRecord2(entry)) {
4344
+ return;
4345
+ }
4346
+ const uri = entry.uri;
4347
+ if (typeof uri !== "string") {
4348
+ return;
4349
+ }
4350
+ addUri(uri);
4351
+ });
4352
+ };
4353
+ collectFrom(gltfJson.buffers);
4354
+ collectFrom(gltfJson.images);
4355
+ return Array.from(urls);
4356
+ };
4357
+ var readResponseChunks = async function(response, resourceId, onProgress) {
4358
+ const total = parseContentLength(response);
4359
+ onProgress?.(resourceId, 0, total ?? 0);
4360
+ if (!response.body) {
4361
+ const buffer = await response.arrayBuffer();
4362
+ const loaded2 = buffer.byteLength;
4363
+ onProgress?.(resourceId, loaded2, total ?? loaded2);
4364
+ return [new Uint8Array(buffer)];
4365
+ }
4366
+ const reader = response.body.getReader();
4367
+ const chunks = [];
4368
+ let loaded = 0;
4369
+ while (true) {
4370
+ const { done, value } = await reader.read();
4371
+ if (done) {
4372
+ break;
4373
+ }
4374
+ if (!value) {
4375
+ continue;
4376
+ }
4377
+ chunks.push(value);
4378
+ loaded += value.length;
4379
+ onProgress?.(resourceId, loaded, total ?? 0);
4380
+ }
4381
+ onProgress?.(resourceId, loaded, total ?? loaded);
4382
+ return chunks;
4383
+ };
4384
+ var concatChunks = function(chunks) {
4385
+ if (chunks.length === 0) {
4386
+ return new Uint8Array();
4387
+ }
4388
+ if (chunks.length === 1) {
4389
+ return chunks[0] ?? new Uint8Array();
4390
+ }
4391
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
4392
+ const combined = new Uint8Array(totalLength);
4393
+ let offset = 0;
4394
+ for (const chunk of chunks) {
4395
+ combined.set(chunk, offset);
4396
+ offset += chunk.length;
4397
+ }
4398
+ return combined;
4399
+ };
4400
+ var toArrayBuffer = function(data) {
4401
+ const buffer = new ArrayBuffer(data.byteLength);
4402
+ new Uint8Array(buffer).set(data);
4403
+ return buffer;
4404
+ };
4405
+ var fetchChunksWithProgress = async function(url, onProgress) {
4406
+ const response = await fetch(url);
4407
+ if (!response.ok) {
4408
+ throw new Error(await response.text());
4409
+ }
4410
+ return await readResponseChunks(response, url, onProgress);
4411
+ };
4412
+ var fetchArrayBufferWithProgress = async function(url, onProgress) {
4413
+ const chunks = await fetchChunksWithProgress(url, onProgress);
4414
+ const combined = concatChunks(chunks);
4415
+ return toArrayBuffer(combined);
4416
+ };
4417
+ var fetchBlobWithProgress = async function(url, onProgress) {
4418
+ const chunks = await fetchChunksWithProgress(url, onProgress);
4419
+ const combined = concatChunks(chunks);
4420
+ return new Blob([toArrayBuffer(combined)]);
4421
+ };
4422
+ var loadGltfWithProgress = async function({
4423
+ url,
4424
+ onProgress,
4425
+ configureLoader
4426
+ }) {
4427
+ const baseUrl = new URL(".", url).toString();
4428
+ const buffer = await fetchArrayBufferWithProgress(url, onProgress);
4429
+ const { json, jsonText, isBinary } = parseGltfJson(buffer);
4430
+ const resourceUrls = json ? collectExternalResourceUrls(json, baseUrl) : [];
4431
+ const resourceMap = /* @__PURE__ */ new Map();
4432
+ if (resourceUrls.length > 0) {
4433
+ const blobs = await Promise.all(
4434
+ resourceUrls.map(async (resourceUrl) => {
4435
+ const blob = await fetchBlobWithProgress(resourceUrl, onProgress);
4436
+ return { resourceUrl, blob };
4437
+ })
4438
+ );
4439
+ blobs.forEach(({ resourceUrl, blob }) => {
4440
+ resourceMap.set(resourceUrl, URL.createObjectURL(blob));
4441
+ });
4442
+ }
4443
+ const manager = new LoadingManager();
4444
+ manager.setURLModifier((requestedUrl) => {
4445
+ if (requestedUrl.startsWith("blob:") || requestedUrl.startsWith("data:")) {
4446
+ return requestedUrl;
4447
+ }
4448
+ const resolved = resolveResourceUrl(requestedUrl, baseUrl);
4449
+ return resourceMap.get(resolved) ?? resourceMap.get(requestedUrl) ?? requestedUrl;
4450
+ });
4451
+ const loader = new GLTFLoader2(manager);
4452
+ configureLoader?.(loader);
4453
+ const parseInput = isBinary ? buffer : jsonText;
4454
+ if (!parseInput) {
4455
+ throw new Error("Failed to parse GLTF payload.");
4456
+ }
4457
+ try {
4458
+ return await new Promise((resolve, reject) => {
4459
+ loader.parse(parseInput, baseUrl, resolve, reject);
4460
+ });
4461
+ } finally {
4462
+ resourceMap.forEach((blobUrl) => {
4463
+ URL.revokeObjectURL(blobUrl);
4464
+ });
4465
+ }
4111
4466
  };
4112
- var resizeRenderer = function(ctx, width, height) {
4113
- if (width <= 0 || height <= 0) {
4114
- return;
4467
+ var loadVrm = async ({
4468
+ baseUrl,
4469
+ characterId,
4470
+ apiToken,
4471
+ onProgress,
4472
+ assetProfile
4473
+ }) => {
4474
+ const url = new URL(`/avatars/${characterId}/download-url`, baseUrl);
4475
+ if (assetProfile && assetProfile !== "original") {
4476
+ url.searchParams.set("assetProfile", assetProfile);
4115
4477
  }
4116
- ctx.camera.aspect = width / height;
4117
- ctx.camera.updateProjectionMatrix();
4118
- ctx.intentCamera.aspect = width / height;
4119
- ctx.intentCamera.updateProjectionMatrix();
4120
- ctx.renderer.setSize(width, height, false);
4121
- };
4122
- var setCameraCollisionBackend = function(ctx, backend) {
4123
- ctx.collisionBackend = backend ?? new NoopCameraCollisionBackend();
4124
- };
4125
- var resolveSceneCamera = function(ctx, deltaSeconds) {
4126
- ctx.collisionBackend.update();
4127
- const result = ctx.collisionBackend.resolve({
4128
- cameraRadius: cameraCollisionRadius(
4129
- ctx.camera.near,
4130
- ctx.camera.fov,
4131
- ctx.camera.aspect
4132
- ),
4133
- deltaSeconds,
4134
- desiredPosition: ctx.intentCamera.position,
4135
- target: ctx.controls.target
4478
+ const res = await fetch(url.toString(), {
4479
+ headers: buildAuthHeaders(apiToken, { allowEmpty: true }),
4480
+ credentials: apiToken ? "omit" : "include"
4136
4481
  });
4137
- ctx.camera.position.copy(result.position);
4138
- ctx.camera.quaternion.copy(ctx.intentCamera.quaternion);
4139
- ctx.camera.scale.copy(ctx.intentCamera.scale);
4140
- ctx.camera.lookAt(ctx.controls.target);
4141
- ctx.camera.updateMatrixWorld();
4142
- };
4143
- var disposeSceneContext = function(ctx) {
4144
- ctx.controls.dispose();
4145
- ctx.renderer.dispose();
4146
- ctx.renderer.forceContextLoss();
4482
+ if (!res.ok) {
4483
+ throw new Error(await res.text());
4484
+ }
4485
+ const { url: vrmUrl } = await res.json();
4486
+ const gltf = await loadGltfWithProgress({
4487
+ url: vrmUrl,
4488
+ onProgress,
4489
+ configureLoader: (loader) => {
4490
+ loader.register((parser) => new VRMLoaderPlugin2(parser));
4491
+ }
4492
+ });
4493
+ VRMUtils4.removeUnnecessaryVertices(gltf.scene);
4494
+ VRMUtils4.combineSkeletons(gltf.scene);
4495
+ enableTextureExpressionBlending(gltf.userData.vrm);
4496
+ return gltf.userData.vrm;
4147
4497
  };
4148
-
4149
- // ../vrm-renderer/src/preview-controller.ts
4150
- import { VRMUtils as VRMUtils4 } from "@pixiv/three-vrm";
4151
- import { Box3, GridHelper, Vector3 as Vector33 } from "three";
4152
-
4153
- // ../vrm-renderer/src/loaders.ts
4154
- import { VRMLoaderPlugin as VRMLoaderPlugin2, VRMUtils as VRMUtils2 } from "@pixiv/three-vrm";
4155
- import { VRMAnimationLoaderPlugin as VRMAnimationLoaderPlugin2 } from "@pixiv/three-vrm-animation";
4156
- import { GLTFLoader as GLTFLoader2 } from "three/examples/jsm/loaders/GLTFLoader.js";
4157
-
4158
- // ../vrm-renderer/src/session.ts
4159
- import { VRMUtils as VRMUtils3 } from "@pixiv/three-vrm";
4160
- import { AnimationMixer, LoopOnce, LoopRepeat } from "three";
4161
-
4162
- // ../vrm-renderer/src/animation.ts
4163
- import {
4164
- createVRMAnimationClip as createPixivVRMAnimationClip
4165
- } from "@pixiv/three-vrm-animation";
4166
- var NPCIFY_VRM_NORMALIZATION_ROOT_NAME = "NPCifyNormalizationRoot";
4167
- var canonicalAnimationTargets = /* @__PURE__ */ new WeakMap();
4168
- var isNpcifyNormalizedVrm = function(vrm) {
4169
- return vrm.scene.children.some(
4170
- (child) => child.name === NPCIFY_VRM_NORMALIZATION_ROOT_NAME
4498
+ var loadVrma = async ({
4499
+ baseUrl,
4500
+ characterId,
4501
+ animationId,
4502
+ apiToken,
4503
+ onProgress,
4504
+ assetProfile
4505
+ }) => {
4506
+ const url = new URL(
4507
+ `/avatars/${characterId}/animations/${animationId}/download-url`,
4508
+ baseUrl
4171
4509
  );
4172
- };
4173
- var canonicalAnimationTarget = function(vrm) {
4174
- if (vrm.meta.metaVersion !== "0" || !isNpcifyNormalizedVrm(vrm)) {
4175
- return vrm;
4510
+ if (assetProfile && assetProfile !== "original") {
4511
+ url.searchParams.set("assetProfile", assetProfile);
4176
4512
  }
4177
- const cached = canonicalAnimationTargets.get(vrm);
4178
- if (cached) {
4179
- return cached;
4513
+ const res = await fetch(url.toString(), {
4514
+ headers: buildAuthHeaders(apiToken, { allowEmpty: true }),
4515
+ credentials: apiToken ? "omit" : "include"
4516
+ });
4517
+ if (!res.ok) {
4518
+ throw new Error(await res.text());
4180
4519
  }
4181
- const target = new Proxy(vrm, {
4182
- get(source, property, receiver) {
4183
- if (property === "meta") {
4184
- return { ...source.meta, metaVersion: "1" };
4185
- }
4186
- return Reflect.get(source, property, receiver);
4520
+ const { url: vrmaUrl } = await res.json();
4521
+ const gltf = await loadGltfWithProgress({
4522
+ url: vrmaUrl,
4523
+ onProgress,
4524
+ configureLoader: (loader) => {
4525
+ loader.register(
4526
+ (parser) => new VRMAnimationLoaderPlugin2(parser)
4527
+ );
4187
4528
  }
4188
4529
  });
4189
- canonicalAnimationTargets.set(vrm, target);
4190
- return target;
4191
- };
4192
- var createVRMAnimationClip = function(animation, vrm) {
4193
- return createPixivVRMAnimationClip(animation, canonicalAnimationTarget(vrm));
4194
- };
4195
-
4196
- // ../vrm-renderer/src/session.ts
4197
- var attachVrm = function(ctx, vrm) {
4198
- ctx.scene.add(vrm.scene);
4199
- setCameraCollisionBackend(
4200
- ctx,
4201
- new HumanoidCapsuleCollisionBackend(
4202
- (name) => vrm.humanoid.getRawBoneNode(name)
4203
- )
4204
- );
4205
- const mixer = new AnimationMixer(vrm.scene);
4206
- return { vrm, mixer, activeAction: null, animationFrameId: null };
4207
- };
4208
- var detachVrm = function(ctx, session, options = {}) {
4209
- stopRenderLoop(session);
4210
- session.mixer.stopAllAction();
4211
- if (session.vrm.scene.parent) {
4212
- session.vrm.scene.parent.remove(session.vrm.scene);
4530
+ const animations = gltf.userData.vrmAnimations ?? gltf.userData.animations;
4531
+ const animationList = Array.isArray(animations) ? animations : [];
4532
+ if (animationList.length === 0) {
4533
+ throw new Error(
4534
+ `No animations found for character ${characterId} and animation ${animationId}`
4535
+ );
4213
4536
  }
4214
- setCameraCollisionBackend(ctx, null);
4215
- session.mixer.uncacheRoot(session.vrm.scene);
4216
- if (options.dispose) {
4217
- disposeVrm(session.vrm);
4537
+ const firstAnimation = animationList[0];
4538
+ if (!firstAnimation) {
4539
+ throw new Error(
4540
+ `No animations found for character ${characterId} and animation ${animationId}`
4541
+ );
4218
4542
  }
4543
+ return firstAnimation;
4219
4544
  };
4220
- var disposeVrm = function(vrm) {
4221
- disposeObject3D(vrm.scene);
4222
- };
4223
- var disposeObject3D = function(object) {
4224
- VRMUtils3.deepDispose(object);
4225
- };
4226
- var stopRenderLoop = function(session) {
4227
- if (session.animationFrameId === null) {
4228
- return;
4545
+ var getInfo = async ({
4546
+ baseUrl,
4547
+ characterId,
4548
+ apiToken
4549
+ }) => {
4550
+ const url = new URL(`/avatars/${characterId}/info`, baseUrl);
4551
+ const res = await fetch(url.toString(), {
4552
+ headers: buildAuthHeaders(apiToken, { allowEmpty: true }),
4553
+ credentials: apiToken ? "omit" : "include"
4554
+ });
4555
+ if (!res.ok) {
4556
+ throw new Error(await res.text());
4229
4557
  }
4230
- cancelAnimationFrame(session.animationFrameId);
4231
- session.animationFrameId = null;
4232
- };
4233
- var setCameraView = function(ctx, position, lookAt) {
4234
- ctx.camera.position.set(...position);
4235
- ctx.camera.lookAt(...lookAt);
4236
- ctx.intentCamera.position.set(...position);
4237
- ctx.intentCamera.lookAt(...lookAt);
4238
- ctx.controls.target.set(...lookAt);
4239
- ctx.controls.update();
4240
- resolveSceneCamera(ctx, 0);
4558
+ return await res.json();
4241
4559
  };
4242
- var applyCameraPreset = function(ctx, preset) {
4243
- const config = CAMERA_PRESETS[preset];
4244
- setCameraView(ctx, config.position, config.lookAt);
4560
+
4561
+ // ../../clients/web-client/src/asset-load-progress.ts
4562
+ var createAssetProgressReporter = function(callback) {
4563
+ if (!callback) {
4564
+ const noop = () => {
4565
+ };
4566
+ return {
4567
+ updateResource: noop
4568
+ };
4569
+ }
4570
+ const resources = /* @__PURE__ */ new Map();
4571
+ let lastProgress = -1;
4572
+ let lastTotal = -1;
4573
+ const updateResource = (resourceId, loaded, total) => {
4574
+ const safeLoaded = Math.max(0, loaded);
4575
+ const safeTotal = Math.max(0, total);
4576
+ resources.set(resourceId, { loaded: safeLoaded, total: safeTotal });
4577
+ let summedLoaded = 0;
4578
+ let summedTotal = 0;
4579
+ for (const resource of resources.values()) {
4580
+ if (resource.total <= 0) {
4581
+ continue;
4582
+ }
4583
+ summedLoaded += Math.min(resource.loaded, resource.total);
4584
+ summedTotal += resource.total;
4585
+ }
4586
+ if (summedLoaded === lastProgress && summedTotal === lastTotal) {
4587
+ return;
4588
+ }
4589
+ lastProgress = summedLoaded;
4590
+ lastTotal = summedTotal;
4591
+ callback({ progress: summedLoaded, total: summedTotal });
4592
+ };
4593
+ return { updateResource };
4245
4594
  };
4246
4595
 
4247
4596
  // ../../clients/web-client/src/character/animation.ts
@@ -4310,7 +4659,8 @@ var AnimationController = class {
4310
4659
  }
4311
4660
  const config = this.configs.get(animationId) ?? defaultAnimationConfig;
4312
4661
  const action = this.mixer.clipAction(clip);
4313
- const loop = loopOverride ?? config.loop;
4662
+ const isIdleAnimation = animationId === this.idleAnimationId;
4663
+ const loop = isIdleAnimation || (loopOverride ?? config.loop);
4314
4664
  if (loop) {
4315
4665
  action.setLoop(LoopRepeat2, Infinity);
4316
4666
  action.clampWhenFinished = false;
@@ -4329,8 +4679,7 @@ var AnimationController = class {
4329
4679
  action.reset().play();
4330
4680
  }
4331
4681
  this.activeAction = action;
4332
- const isIdleAnimation = animationId === this.idleAnimationId;
4333
- if (!config.loop && !isIdleAnimation && this.idleAnimationId) {
4682
+ if (!loop && this.idleAnimationId) {
4334
4683
  this.pendingReturnToIdleAction = action;
4335
4684
  } else {
4336
4685
  this.pendingReturnToIdleAction = null;
@@ -4661,9 +5010,17 @@ var AudioPlayer = class {
4661
5010
  cleanupListeners();
4662
5011
  resolve();
4663
5012
  };
4664
- const onError = () => {
5013
+ const failPlayback = (error) => {
4665
5014
  cleanupListeners();
4666
- reject(new Error("Audio playback failed"));
5015
+ if (!options?.signal?.aborted) {
5016
+ element.pause();
5017
+ element.removeAttribute("src");
5018
+ element.load();
5019
+ }
5020
+ reject(error);
5021
+ };
5022
+ const onError = () => {
5023
+ failPlayback(new Error("Audio playback failed"));
4667
5024
  };
4668
5025
  const onAbort = () => {
4669
5026
  element.pause();
@@ -4674,10 +5031,7 @@ var AudioPlayer = class {
4674
5031
  element.addEventListener("ended", onEnded);
4675
5032
  element.addEventListener("error", onError);
4676
5033
  options?.signal?.addEventListener("abort", onAbort, { once: true });
4677
- void element.play().then(markStarted).catch((error) => {
4678
- cleanupListeners();
4679
- reject(error);
4680
- });
5034
+ void element.play().then(markStarted).catch(failPlayback);
4681
5035
  });
4682
5036
  } finally {
4683
5037
  options?.signal?.removeEventListener("abort", abortSource);
@@ -4765,7 +5119,7 @@ var AudioPlayer = class {
4765
5119
  return this.audioElement;
4766
5120
  }
4767
5121
  const element = document.createElement("audio");
4768
- element.autoplay = true;
5122
+ element.autoplay = false;
4769
5123
  element.setAttribute("playsinline", "true");
4770
5124
  element.preload = "auto";
4771
5125
  element.style.display = "none";
@@ -7117,6 +7471,10 @@ var StreamPlaybackController = class {
7117
7471
  this.flushOptions(state);
7118
7472
  return true;
7119
7473
  } catch (error) {
7474
+ if (this.states.get(params.stagingId) !== state || this.activePlayback?.stagingId !== params.stagingId) {
7475
+ this.recordPlaybackEvent(params, "cancelled", this.errorReason(error));
7476
+ return false;
7477
+ }
7120
7478
  if (isPlaybackCancelledError(error)) {
7121
7479
  this.recordPlaybackEvent(params, "cancelled", this.errorReason(error));
7122
7480
  return false;