@hackbuild/live2d 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,903 @@
1
+ var HackbuildLive2d = (function(exports) {
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ // src/core.ts
4
+ /**
5
+ * The Live2D Cubism Core: Live2D's own runtime for .moc3 models, under the
6
+ * Live2D Proprietary Software License. This library never bundles or copies
7
+ * it; {@link loadCubismCore} adds Live2D's script from cubism.live2d.com to
8
+ * the page when a model is opened, and says whose licence applies. The types
9
+ * here cover the part of its JavaScript surface the renderer reads.
10
+ */
11
+ /** Where Live2D serves the Cubism Core for the web. */
12
+ const CUBISM_CORE_URL = "https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js";
13
+ /** The line a page shows the first time the core loads. */
14
+ const CUBISM_CORE_LICENCE = "live2d cubism core, under the live2d proprietary software license agreement (https://www.live2d.com/eula/live2d-proprietary-software-license-agreement_en.html). it loads from cubism.live2d.com and is not part of this library.";
15
+ /** A Live2D model the library cannot open, with the reason in words a page can show. */
16
+ var Live2DError = class extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "Live2DError";
20
+ }
21
+ };
22
+ let loading = null;
23
+ const coreOf = () => globalThis.Live2DCubismCore;
24
+ /** Adds Live2D's Cubism Core to the page once and resolves to it; a core already on the page is used as is. */
25
+ function loadCubismCore(o = {}) {
26
+ const have = coreOf();
27
+ if (have) return Promise.resolve(have);
28
+ if (loading) return loading;
29
+ if (typeof document === "undefined") return Promise.reject(new Live2DError("the cubism core loads into a page; there is no document here."));
30
+ loading = new Promise((resolve, reject) => {
31
+ const s = document.createElement("script");
32
+ s.src = o.url ?? "https://cubism.live2d.com/sdk-web/cubismcore/live2dcubismcore.min.js";
33
+ s.async = true;
34
+ s.onload = () => {
35
+ const core = coreOf();
36
+ if (core) {
37
+ o.onLicence?.(CUBISM_CORE_LICENCE);
38
+ resolve(core);
39
+ } else reject(new Live2DError("the cubism core script loaded but defined nothing."));
40
+ };
41
+ s.onerror = () => {
42
+ loading = null;
43
+ s.remove();
44
+ reject(new Live2DError("the cubism core did not load from cubism.live2d.com. check the connection; live2d models need it."));
45
+ };
46
+ document.head.append(s);
47
+ });
48
+ return loading;
49
+ }
50
+ /** The core's version as major.minor.patch, from its packed number. */
51
+ function coreVersion(core) {
52
+ const v = core.Version.csmGetVersion();
53
+ return `${v >>> 24 & 255}.${v >>> 16 & 255}.${v & 65535}`;
54
+ }
55
+ // src/files.ts
56
+ /**
57
+ * A Live2D model as files: a .model3.json and what it names (the .moc3,
58
+ * textures, motions, expressions, physics, pose), from a zip, a folder or a
59
+ * file list the user dropped, or from a URL. The zip reader is written from
60
+ * the published ZIP format: stored and deflated entries, deflate through the
61
+ * browser's DecompressionStream. A reference the files do not hold is listed
62
+ * in `missing`, and the model still opens.
63
+ */
64
+ const norm = (p) => p.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
65
+ /** Joins a reference onto the folder of the file that names it, resolving `..` and `.`. */
66
+ function joinPath(base, ref) {
67
+ const out = norm(base).split("/").slice(0, -1);
68
+ for (const part of norm(ref).split("/")) if (part === "..") out.pop();
69
+ else if (part && part !== ".") out.push(part);
70
+ return out.join("/");
71
+ }
72
+ /** Reads a zip into files: stored and deflated entries, by its central directory. */
73
+ async function readZip(buffer) {
74
+ const v = new DataView(buffer);
75
+ let eocd = -1;
76
+ for (let i = buffer.byteLength - 22; i >= Math.max(0, buffer.byteLength - 65557); i--) if (v.getUint32(i, true) === 101010256) {
77
+ eocd = i;
78
+ break;
79
+ }
80
+ if (eocd < 0) throw new Live2DError("this file is not a zip.");
81
+ const count = v.getUint16(eocd + 10, true);
82
+ let p = v.getUint32(eocd + 16, true);
83
+ const out = /* @__PURE__ */ new Map();
84
+ const dec = new TextDecoder();
85
+ for (let n = 0; n < count; n++) {
86
+ if (v.getUint32(p, true) !== 33639248) throw new Live2DError("the zip's directory is damaged.");
87
+ const method = v.getUint16(p + 10, true);
88
+ const size = v.getUint32(p + 20, true);
89
+ const nameLen = v.getUint16(p + 28, true);
90
+ const extraLen = v.getUint16(p + 30, true);
91
+ const commentLen = v.getUint16(p + 32, true);
92
+ const local = v.getUint32(p + 42, true);
93
+ const name = norm(dec.decode(new Uint8Array(buffer, p + 46, nameLen)));
94
+ p += 46 + nameLen + extraLen + commentLen;
95
+ if (name.endsWith("/") || name.startsWith("__MACOSX/")) continue;
96
+ const dataAt = local + 30 + v.getUint16(local + 26, true) + v.getUint16(local + 28, true);
97
+ const raw = new Uint8Array(buffer.slice(dataAt, dataAt + size));
98
+ if (method === 0) out.set(name, new Blob([raw]));
99
+ else if (method === 8) {
100
+ if (typeof DecompressionStream === "undefined") throw new Live2DError("this browser cannot unpack a deflated zip. unzip it and drop the folder.");
101
+ const stream = new Blob([raw]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
102
+ out.set(name, await new Response(stream).blob());
103
+ } else throw new Live2DError(`the zip uses compression method ${method}, which this reader does not unpack. unzip it and drop the folder.`);
104
+ }
105
+ return out;
106
+ }
107
+ /** Files from a drop or a picker: a zip is unpacked, a folder keeps its relative paths. */
108
+ async function filesFrom(list) {
109
+ const files = [...list];
110
+ if (files.length === 1 && /\.zip$/i.test(files[0].name)) return readZip(await files[0].arrayBuffer());
111
+ const out = /* @__PURE__ */ new Map();
112
+ for (const f of files) out.set(norm(f.webkitRelativePath || f.name), f);
113
+ return out;
114
+ }
115
+ /** The model settings file among the files: the .model3.json nearest the root. */
116
+ function findModel(files) {
117
+ const paths = [...files.keys()];
118
+ const m3 = paths.filter((p) => /\.model3\.json$/i.test(p)).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length);
119
+ if (m3[0]) return m3[0];
120
+ if (paths.some((p) => /\.moc$/i.test(p)) || paths.some((p) => /(^|\/)[^/]*\.model\.json$/i.test(p))) throw new Live2DError("this is a cubism 2 model (.moc). this library opens cubism 3 and later models (.moc3).");
121
+ if (paths.some((p) => /\.moc3$/i.test(p))) throw new Live2DError("there is a .moc3 but no .model3.json that names its textures. add the .model3.json.");
122
+ throw new Live2DError("no live2d model here: drop a zip or a folder holding a .model3.json.");
123
+ }
124
+ async function json(b) {
125
+ if (!b) return null;
126
+ try {
127
+ return JSON.parse(await b.text());
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+ /** A model from dropped files: the settings, every file it names that is present, and the rest in `missing`. */
133
+ async function modelFromFiles(files, path = findModel(files)) {
134
+ const settings = await json(files.get(path));
135
+ if (!settings?.FileReferences?.Moc) throw new Live2DError(`${path} is not a model3 settings file: it names no moc.`);
136
+ return assemble(settings, path, (ref) => files.get(joinPath(path, ref)));
137
+ }
138
+ /** A model by the URL of its .model3.json; every file it names is fetched beside it. */
139
+ async function modelFromUrl(url, f = globalThis.fetch.bind(globalThis)) {
140
+ const here = globalThis.location?.href;
141
+ let abs;
142
+ try {
143
+ abs = new URL(url, here).href;
144
+ } catch {
145
+ throw new Live2DError(`${url} is not a url this page can resolve.`);
146
+ }
147
+ url = abs;
148
+ const res = await f(url);
149
+ if (!res.ok) throw new Live2DError(`the model settings at ${url} answered ${res.status}.`);
150
+ const settings = await res.json();
151
+ if (!settings?.FileReferences?.Moc) throw new Live2DError(`${url} is not a model3 settings file: it names no moc.`);
152
+ const blobs = /* @__PURE__ */ new Map();
153
+ const refs = refsOf(settings);
154
+ await Promise.all(refs.map(async (ref) => {
155
+ try {
156
+ const r = await f(new URL(ref, url).href);
157
+ blobs.set(ref, r.ok ? await r.blob() : void 0);
158
+ } catch {
159
+ blobs.set(ref, void 0);
160
+ }
161
+ }));
162
+ return assemble(settings, new URL(url).pathname, (ref) => blobs.get(ref));
163
+ }
164
+ function refsOf(s) {
165
+ const r = s.FileReferences;
166
+ return [
167
+ r.Moc,
168
+ ...r.Textures,
169
+ ...r.Physics ? [r.Physics] : [],
170
+ ...r.Pose ? [r.Pose] : [],
171
+ ...(r.Expressions ?? []).map((e) => e.File),
172
+ ...Object.values(r.Motions ?? {}).flat().map((m) => m.File)
173
+ ];
174
+ }
175
+ async function assemble(settings, path, get) {
176
+ const r = settings.FileReferences;
177
+ const missing = [];
178
+ const need = (ref) => {
179
+ const b = get(ref);
180
+ if (!b) missing.push(ref);
181
+ return b;
182
+ };
183
+ const moc = need(r.Moc);
184
+ if (!moc) throw new Live2DError(`the moc ${r.Moc} that the settings name is missing.`);
185
+ const textures = [];
186
+ for (const t of r.Textures) {
187
+ const b = need(t);
188
+ if (!b) throw new Live2DError(`the texture ${t} that the settings name is missing.`);
189
+ textures.push(b);
190
+ }
191
+ const motions = [];
192
+ for (const [group, list] of Object.entries(r.Motions ?? {})) for (const [index, m] of list.entries()) {
193
+ const ref = {
194
+ group,
195
+ index,
196
+ file: m.File,
197
+ json: await json(need(m.File))
198
+ };
199
+ if (m.FadeInTime !== void 0) ref.fadeIn = m.FadeInTime;
200
+ if (m.FadeOutTime !== void 0) ref.fadeOut = m.FadeOutTime;
201
+ motions.push(ref);
202
+ }
203
+ const expressions = [];
204
+ for (const e of r.Expressions ?? []) {
205
+ const j = await json(need(e.File));
206
+ if (j) expressions.push({
207
+ name: e.Name,
208
+ json: j
209
+ });
210
+ }
211
+ return {
212
+ name: norm(path).split("/").pop().replace(/\.model3\.json$/i, ""),
213
+ settings,
214
+ moc: await moc.arrayBuffer(),
215
+ textures,
216
+ motions,
217
+ expressions,
218
+ pose: r.Pose ? await json(need(r.Pose)) : null,
219
+ physics: r.Physics ? await json(need(r.Physics)) : null,
220
+ missing
221
+ };
222
+ }
223
+ // src/motion.ts
224
+ /** Parses a .motion3.json; fades default to the motion's own, then the model's entry, then 1 s and 1 s. */
225
+ function parseMotion(json, o = {}) {
226
+ const j = json ?? {};
227
+ const meta = j.Meta ?? {};
228
+ const curves = [];
229
+ for (const c of j.Curves ?? []) {
230
+ const s = c.Segments ?? [];
231
+ if (s.length < 2) continue;
232
+ const segs = [];
233
+ let i = 2;
234
+ let lastT = s[0];
235
+ let lastV = s[1];
236
+ while (i < s.length) {
237
+ const type = s[i];
238
+ const n = type === 1 ? 6 : 2;
239
+ const pts = s.slice(i + 1, i + 1 + n);
240
+ if (pts.length < n) break;
241
+ segs.push({
242
+ type,
243
+ p: [
244
+ lastT,
245
+ lastV,
246
+ ...pts
247
+ ]
248
+ });
249
+ lastT = pts[n - 2];
250
+ lastV = pts[n - 1];
251
+ i += 1 + n;
252
+ }
253
+ curves.push({
254
+ target: c.Target ?? "Parameter",
255
+ id: String(c.Id ?? ""),
256
+ fadeIn: typeof c.FadeInTime === "number" && c.FadeInTime >= 0 ? c.FadeInTime : null,
257
+ fadeOut: typeof c.FadeOutTime === "number" && c.FadeOutTime >= 0 ? c.FadeOutTime : null,
258
+ t0: s[0],
259
+ v0: s[1],
260
+ segs
261
+ });
262
+ }
263
+ const num = (v, d) => typeof v === "number" && v >= 0 ? v : d;
264
+ return {
265
+ duration: num(meta.Duration, 0),
266
+ loop: meta.Loop === true,
267
+ fadeIn: num(meta.FadeInTime, o.fadeIn ?? 1),
268
+ fadeOut: num(meta.FadeOutTime, o.fadeOut ?? 1),
269
+ restricted: meta.AreBeziersRestricted === true,
270
+ curves
271
+ };
272
+ }
273
+ const lerp = (a, b, t) => a + (b - a) * t;
274
+ function bez(a, b, c, d, s) {
275
+ const ab = lerp(a, b, s), bc = lerp(b, c, s), cd = lerp(c, d, s);
276
+ return lerp(lerp(ab, bc, s), lerp(bc, cd, s), s);
277
+ }
278
+ /** A curve's value at time t (seconds); before its first point the first value, after its last the last. */
279
+ function curveValue(c, t, restricted = false) {
280
+ if (!c.segs.length || t <= c.t0) return c.v0;
281
+ for (const s of c.segs) {
282
+ const p = s.p;
283
+ const t0 = p[0], v0 = p[1];
284
+ const t1 = p[p.length - 2], v1 = p[p.length - 1];
285
+ if (t > t1) continue;
286
+ const x = t1 > t0 ? (t - t0) / (t1 - t0) : 1;
287
+ if (s.type === 0) return lerp(v0, v1, x);
288
+ if (s.type === 2) return t < t1 ? v0 : v1;
289
+ if (s.type === 3) return t > t0 ? v1 : v0;
290
+ const [, , c1t, c1v, c2t, c2v] = p;
291
+ if (restricted) return bez(v0, c1v, c2v, v1, x);
292
+ let lo = 0, hi = 1, sp = x;
293
+ for (let k = 0; k < 24; k++) {
294
+ sp = (lo + hi) / 2;
295
+ if (bez(t0, c1t, c2t, t1, sp) < t) lo = sp;
296
+ else hi = sp;
297
+ }
298
+ return bez(v0, c1v, c2v, v1, sp);
299
+ }
300
+ const last = c.segs[c.segs.length - 1].p;
301
+ return last[last.length - 1];
302
+ }
303
+ /** Cubism's fade curve: a half cosine from 0 to 1. */
304
+ const ease = (x) => x <= 0 ? 0 : x >= 1 ? 1 : .5 - .5 * Math.cos(x * Math.PI);
305
+ /**
306
+ * Samples a motion `elapsed` seconds after it started, with an overall weight;
307
+ * `outAt` is when its fade out began (seconds after start), or null.
308
+ */
309
+ function sampleMotion(m, elapsed, weight = 1, outAt = null) {
310
+ const t = m.loop && m.duration > 0 ? elapsed % m.duration : Math.min(elapsed, m.duration || elapsed);
311
+ const fadeIn = (f) => f > 0 ? ease(elapsed / f) : 1;
312
+ const fadeOut = (f) => outAt === null ? 1 : f > 0 ? 1 - ease((elapsed - outAt) / f) : 0;
313
+ const base = weight * fadeIn(m.fadeIn) * fadeOut(m.fadeOut);
314
+ const out = {
315
+ params: /* @__PURE__ */ new Map(),
316
+ parts: /* @__PURE__ */ new Map(),
317
+ groups: /* @__PURE__ */ new Map()
318
+ };
319
+ for (const c of m.curves) {
320
+ const v = curveValue(c, t, m.restricted);
321
+ if (c.target === "Parameter") {
322
+ const w = c.fadeIn === null && c.fadeOut === null ? base : weight * fadeIn(c.fadeIn ?? m.fadeIn) * fadeOut(c.fadeOut ?? m.fadeOut);
323
+ out.params.set(c.id, {
324
+ value: v,
325
+ weight: w
326
+ });
327
+ } else if (c.target === "PartOpacity") out.parts.set(c.id, v);
328
+ else out.groups.set(c.id, v);
329
+ }
330
+ return out;
331
+ }
332
+ /** Parses a .exp3.json; fades default to 1 s. */
333
+ function parseExpression(json) {
334
+ const j = json ?? {};
335
+ const num = (v, d) => typeof v === "number" && v >= 0 ? v : d;
336
+ return {
337
+ fadeIn: num(j.FadeInTime, 1),
338
+ fadeOut: num(j.FadeOutTime, 1),
339
+ params: (j.Parameters ?? []).map((p) => ({
340
+ id: String(p.Id),
341
+ value: Number(p.Value ?? 0),
342
+ blend: p.Blend === "Multiply" || p.Blend === "Overwrite" ? p.Blend : "Add"
343
+ }))
344
+ };
345
+ }
346
+ /** One parameter value with an expression applied at weight w. */
347
+ function blendExpression(current, p, w) {
348
+ if (p.blend === "Add") return current + p.value * w;
349
+ if (p.blend === "Multiply") return current * (1 + (p.value - 1) * w);
350
+ return current * (1 - w) + p.value * w;
351
+ }
352
+ /**
353
+ * An eye blink in the rhythm people blink: open, then about every 2 to 6 s a
354
+ * close of 0.1 s, a hold of 0.05 s and an open of 0.15 s (inferred from
355
+ * blink studies). Returns the eye openness, 1 open to 0 shut. `rng` is 0 to 1.
356
+ */
357
+ var Blinker = class {
358
+ rng;
359
+ next;
360
+ start = -1;
361
+ constructor(rng, now = 0) {
362
+ this.rng = rng;
363
+ this.next = now + 2 + rng() * 4;
364
+ }
365
+ open(now) {
366
+ if (this.start < 0 && now >= this.next) this.start = now;
367
+ if (this.start < 0) return 1;
368
+ const t = now - this.start;
369
+ if (t < .1) return 1 - t / .1;
370
+ if (t < .15) return 0;
371
+ if (t < .3) return (t - .15) / .15;
372
+ this.start = -1;
373
+ this.next = now + 2 + this.rng() * 4;
374
+ return 1;
375
+ }
376
+ };
377
+ // src/render.ts
378
+ const VS = `attribute vec2 a_pos;
379
+ attribute vec2 a_uv;
380
+ uniform mat3 u_m;
381
+ varying vec2 v_uv;
382
+ void main() {
383
+ vec3 p = u_m * vec3(a_pos, 1.0);
384
+ gl_Position = vec4(p.xy, 0.0, 1.0);
385
+ v_uv = vec2(a_uv.x, 1.0 - a_uv.y);
386
+ }`;
387
+ const FS = `precision mediump float;
388
+ varying vec2 v_uv;
389
+ uniform sampler2D u_tex;
390
+ uniform float u_opacity;
391
+ uniform vec4 u_mul;
392
+ uniform vec4 u_scr;
393
+ uniform float u_mask;
394
+ void main() {
395
+ vec4 c = texture2D(u_tex, v_uv);
396
+ if (u_mask > 0.5) { if (c.a < 0.5) discard; gl_FragColor = vec4(0.0); return; }
397
+ vec3 rgb = c.a > 0.0 ? c.rgb / c.a : vec3(0.0);
398
+ rgb *= u_mul.rgb;
399
+ rgb = rgb + u_scr.rgb - rgb * u_scr.rgb;
400
+ float a = c.a * u_opacity;
401
+ gl_FragColor = vec4(rgb * a, a);
402
+ }`;
403
+ /** Draws one Cubism model into a WebGL context that has a stencil buffer. */
404
+ var Renderer = class {
405
+ gl;
406
+ core;
407
+ model;
408
+ prog;
409
+ pos;
410
+ uv;
411
+ idx;
412
+ tex = [];
413
+ loc = {};
414
+ aPos;
415
+ aUv;
416
+ order = [];
417
+ constructor(gl, core, model) {
418
+ this.gl = gl;
419
+ this.core = core;
420
+ this.model = model;
421
+ const sh = (type, src) => {
422
+ const s = gl.createShader(type);
423
+ gl.shaderSource(s, src);
424
+ gl.compileShader(s);
425
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(`live2d shader: ${gl.getShaderInfoLog(s)}`);
426
+ return s;
427
+ };
428
+ this.prog = gl.createProgram();
429
+ gl.attachShader(this.prog, sh(gl.VERTEX_SHADER, VS));
430
+ gl.attachShader(this.prog, sh(gl.FRAGMENT_SHADER, FS));
431
+ gl.linkProgram(this.prog);
432
+ if (!gl.getProgramParameter(this.prog, gl.LINK_STATUS)) throw new Error(`live2d program: ${gl.getProgramInfoLog(this.prog)}`);
433
+ for (const n of [
434
+ "u_m",
435
+ "u_tex",
436
+ "u_opacity",
437
+ "u_mul",
438
+ "u_scr",
439
+ "u_mask"
440
+ ]) this.loc[n] = gl.getUniformLocation(this.prog, n);
441
+ this.aPos = gl.getAttribLocation(this.prog, "a_pos");
442
+ this.aUv = gl.getAttribLocation(this.prog, "a_uv");
443
+ this.pos = gl.createBuffer();
444
+ this.uv = gl.createBuffer();
445
+ this.idx = gl.createBuffer();
446
+ }
447
+ /** Uploads the model's textures, premultiplied, with mipmaps. */
448
+ async textures(images) {
449
+ const gl = this.gl;
450
+ for (const b of images) {
451
+ const bmp = await createImageBitmap(b, {
452
+ premultiplyAlpha: "premultiply",
453
+ colorSpaceConversion: "none"
454
+ });
455
+ const t = gl.createTexture();
456
+ gl.bindTexture(gl.TEXTURE_2D, t);
457
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bmp);
458
+ gl.generateMipmap(gl.TEXTURE_2D);
459
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
460
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
461
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
462
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
463
+ bmp.close();
464
+ this.tex.push(t);
465
+ }
466
+ }
467
+ mesh(i) {
468
+ const gl = this.gl, d = this.model.drawables;
469
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.pos);
470
+ gl.bufferData(gl.ARRAY_BUFFER, d.vertexPositions[i], gl.DYNAMIC_DRAW);
471
+ gl.enableVertexAttribArray(this.aPos);
472
+ gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, 0, 0);
473
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.uv);
474
+ gl.bufferData(gl.ARRAY_BUFFER, d.vertexUvs[i], gl.DYNAMIC_DRAW);
475
+ gl.enableVertexAttribArray(this.aUv);
476
+ gl.vertexAttribPointer(this.aUv, 2, gl.FLOAT, false, 0, 0);
477
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.idx);
478
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, d.indices[i], gl.DYNAMIC_DRAW);
479
+ gl.activeTexture(gl.TEXTURE0);
480
+ gl.bindTexture(gl.TEXTURE_2D, this.tex[d.textureIndices[i]] ?? null);
481
+ gl.drawElements(gl.TRIANGLES, d.indexCounts[i], gl.UNSIGNED_SHORT, 0);
482
+ }
483
+ /** Draws the model with the matrix; the caller has run `model.update()`. */
484
+ draw(m) {
485
+ const gl = this.gl, d = this.model.drawables, U = this.core.Utils;
486
+ gl.useProgram(this.prog);
487
+ gl.uniformMatrix3fv(this.loc.u_m, false, m);
488
+ gl.uniform1i(this.loc.u_tex, 0);
489
+ gl.disable(gl.CULL_FACE);
490
+ gl.disable(gl.DEPTH_TEST);
491
+ gl.enable(gl.BLEND);
492
+ if (this.order.length !== d.count) this.order = Array.from({ length: d.count }, (_, i) => i);
493
+ this.order.sort((a, b) => d.renderOrders[a] - d.renderOrders[b]);
494
+ const visible = (i) => U.hasIsVisibleBit(d.dynamicFlags[i]) && d.opacities[i] > .001;
495
+ for (const i of this.order) {
496
+ if (!visible(i) || d.indexCounts[i] === 0) continue;
497
+ const masks = d.maskCounts[i] > 0 ? d.masks[i] : null;
498
+ if (masks) {
499
+ gl.enable(gl.STENCIL_TEST);
500
+ gl.clear(gl.STENCIL_BUFFER_BIT);
501
+ gl.stencilFunc(gl.ALWAYS, 1, 255);
502
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
503
+ gl.colorMask(false, false, false, false);
504
+ gl.uniform1f(this.loc.u_mask, 1);
505
+ for (let k = 0; k < d.maskCounts[i]; k++) {
506
+ const mi = masks[k];
507
+ if (mi >= 0 && d.indexCounts[mi] > 0) this.mesh(mi);
508
+ }
509
+ gl.colorMask(true, true, true, true);
510
+ gl.uniform1f(this.loc.u_mask, 0);
511
+ gl.stencilFunc(U.hasIsInvertedMaskBit(d.constantFlags[i]) ? gl.NOTEQUAL : gl.EQUAL, 1, 255);
512
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
513
+ } else gl.disable(gl.STENCIL_TEST);
514
+ const f = d.constantFlags[i];
515
+ if (U.hasBlendAdditiveBit(f)) gl.blendFunc(gl.ONE, gl.ONE);
516
+ else if (U.hasBlendMultiplicativeBit(f)) gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA);
517
+ else gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
518
+ gl.uniform1f(this.loc.u_opacity, d.opacities[i]);
519
+ const mc = d.multiplyColors, sc = d.screenColors;
520
+ gl.uniform4f(this.loc.u_mul, mc ? mc[i * 4] : 1, mc ? mc[i * 4 + 1] : 1, mc ? mc[i * 4 + 2] : 1, 1);
521
+ gl.uniform4f(this.loc.u_scr, sc ? sc[i * 4] : 0, sc ? sc[i * 4 + 1] : 0, sc ? sc[i * 4 + 2] : 0, 1);
522
+ this.mesh(i);
523
+ }
524
+ gl.disable(gl.STENCIL_TEST);
525
+ }
526
+ dispose() {
527
+ const gl = this.gl;
528
+ for (const t of this.tex) gl.deleteTexture(t);
529
+ gl.deleteBuffer(this.pos);
530
+ gl.deleteBuffer(this.uv);
531
+ gl.deleteBuffer(this.idx);
532
+ gl.deleteProgram(this.prog);
533
+ }
534
+ };
535
+ /** The bounds of the model's visible vertices, in model units. */
536
+ function modelBounds(model, core) {
537
+ const d = model.drawables;
538
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
539
+ for (let i = 0; i < d.count; i++) {
540
+ if (!core.Utils.hasIsVisibleBit(d.dynamicFlags[i]) || d.opacities[i] <= .001) continue;
541
+ const v = d.vertexPositions[i];
542
+ for (let k = 0; k < v.length; k += 2) {
543
+ const x = v[k], y = v[k + 1];
544
+ if (x < minX) minX = x;
545
+ if (x > maxX) maxX = x;
546
+ if (y < minY) minY = y;
547
+ if (y > maxY) maxY = y;
548
+ }
549
+ }
550
+ if (!Number.isFinite(minX)) {
551
+ const c = model.canvasinfo, w = c.CanvasWidth / c.PixelsPerUnit, h = c.CanvasHeight / c.PixelsPerUnit;
552
+ return {
553
+ minX: -w / 2,
554
+ minY: -h / 2,
555
+ maxX: w / 2,
556
+ maxY: h / 2
557
+ };
558
+ }
559
+ return {
560
+ minX,
561
+ minY,
562
+ maxX,
563
+ maxY
564
+ };
565
+ }
566
+ /** A matrix fitting a box of model units into a canvas of w by h pixels, keeping the aspect, with a margin. */
567
+ function fitMatrix(box, w, h, margin = .04) {
568
+ const bw = box.maxX - box.minX, bh = box.maxY - box.minY;
569
+ const sy = Math.min(2 * (1 - margin) / bh, 2 * (1 - margin) / bw * (w / h));
570
+ const sx = sy * (h / w);
571
+ const cx = (box.minX + box.maxX) / 2, cy = (box.minY + box.maxY) / 2;
572
+ return new Float32Array([
573
+ sx,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ sy,
578
+ 0,
579
+ -cx * sx,
580
+ -cy * sy,
581
+ 1
582
+ ]);
583
+ }
584
+ // src/model.ts
585
+ /**
586
+ * A Live2D model on a canvas: the Cubism Core reads the .moc3, and this
587
+ * library plays its motions and expressions, blinks, breathes, turns toward
588
+ * a point, moves the mouth from a level, and draws it. Each frame starts
589
+ * from the parameters' defaults, then motions (crossfaded), the expression,
590
+ * the blink, breath, look and mouth, then any value set by hand, clamped to
591
+ * each parameter's range. Physics (.physics3.json) is not run.
592
+ */
593
+ function seeded(seed = 12139) {
594
+ let a = seed >>> 0;
595
+ return () => {
596
+ a = a + 1831565813 >>> 0;
597
+ let t = a;
598
+ t = Math.imul(t ^ t >>> 15, t | 1);
599
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
600
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
601
+ };
602
+ }
603
+ const BREATH = [
604
+ [
605
+ "ParamAngleX",
606
+ 0,
607
+ 15,
608
+ 6.5345
609
+ ],
610
+ [
611
+ "ParamAngleY",
612
+ 0,
613
+ 8,
614
+ 3.5345
615
+ ],
616
+ [
617
+ "ParamAngleZ",
618
+ 0,
619
+ 10,
620
+ 5.5345
621
+ ],
622
+ [
623
+ "ParamBodyAngleX",
624
+ 0,
625
+ 4,
626
+ 15.5345
627
+ ],
628
+ [
629
+ "ParamBreath",
630
+ .5,
631
+ .5,
632
+ 3.2345
633
+ ]
634
+ ];
635
+ /** Opens a model source on a canvas and starts it. */
636
+ async function createLive2D(canvas, source, o = {}) {
637
+ const gl = canvas.getContext("webgl", {
638
+ stencil: true,
639
+ premultipliedAlpha: true,
640
+ alpha: true,
641
+ antialias: true
642
+ });
643
+ if (!gl) throw new Live2DError("this browser gives no webgl here. live2d models draw with webgl.");
644
+ const core = o.core ?? await loadCubismCore(o);
645
+ const consistent = core.Moc.hasMocConsistency;
646
+ if (consistent && !consistent(source.moc)) throw new Live2DError(`the cubism core ${coreVersion(core)} could not check ${source.name}.moc3: it is damaged or newer than the core.`);
647
+ const moc = core.Moc.fromArrayBuffer(source.moc);
648
+ if (!moc) throw new Live2DError(`the cubism core ${coreVersion(core)} could not read ${source.name}.moc3: it may be newer than the core.`);
649
+ const made = core.Model.fromMoc(moc);
650
+ if (!made) throw new Live2DError(`the cubism core could not make a model from ${source.name}.moc3.`);
651
+ const model = made;
652
+ const renderer = new Renderer(gl, core, model);
653
+ await renderer.textures(source.textures);
654
+ const P = model.parameters;
655
+ const index = new Map(P.ids.map((id, i) => [id, i]));
656
+ const defaults = Float32Array.from(P.defaultValues);
657
+ const has = (id) => index.has(id);
658
+ const group = (name) => source.settings.Groups?.find((g) => g.Name === name)?.Ids.filter(has) ?? [];
659
+ const eyes = group("EyeBlink").length ? group("EyeBlink") : ["ParamEyeLOpen", "ParamEyeROpen"].filter(has);
660
+ const lips = group("LipSync").length ? group("LipSync") : ["ParamMouthOpenY"].filter(has);
661
+ const motions = /* @__PURE__ */ new Map();
662
+ for (const m of source.motions) {
663
+ if (!m.json) continue;
664
+ const list = motions.get(m.group) ?? [];
665
+ list.push(parseMotion(m.json, {
666
+ ...m.fadeIn !== void 0 ? { fadeIn: m.fadeIn } : {},
667
+ ...m.fadeOut !== void 0 ? { fadeOut: m.fadeOut } : {}
668
+ }));
669
+ motions.set(m.group, list);
670
+ }
671
+ const expressions = new Map(source.expressions.map((e) => [e.name, parseExpression(e.json)]));
672
+ const idleGroup = [...motions.keys()].find((g) => /idle/i.test(g)) ?? null;
673
+ const partIndex = new Map(model.parts.ids.map((id, i) => [id, i]));
674
+ const poseGroups = (source.pose?.Groups ?? []).map((g) => g.map((p) => partIndex.get(p.Id)).filter((i) => i !== void 0)).filter((g) => g.length > 1);
675
+ const shown = poseGroups.map((g) => g[0]);
676
+ const rng = o.rng ?? seeded();
677
+ const auto = o.autoplay !== false;
678
+ const blink = new Blinker(rng);
679
+ const holds = /* @__PURE__ */ new Map();
680
+ let now = 0;
681
+ let cur = null;
682
+ let prev = null;
683
+ let exp = null;
684
+ let expOut = null;
685
+ let mouthOpen = 0;
686
+ const lookAt = {
687
+ x: 0,
688
+ y: 0,
689
+ sx: 0,
690
+ sy: 0
691
+ };
692
+ let frameMode = o.frame ?? "full";
693
+ let matrix = null;
694
+ let box = null;
695
+ const add = (id, v) => {
696
+ const i = index.get(id);
697
+ if (i !== void 0) P.values[i] += v;
698
+ };
699
+ function play(group, i) {
700
+ const list = motions.get(group);
701
+ if (!list?.length) return false;
702
+ const m = list[i ?? Math.floor(rng() * list.length)] ?? list[0];
703
+ if (cur) prev = {
704
+ ...cur,
705
+ outAt: cur.outAt ?? now - cur.start
706
+ };
707
+ cur = {
708
+ m,
709
+ start: now,
710
+ outAt: null
711
+ };
712
+ return true;
713
+ }
714
+ function step(dt) {
715
+ now += dt;
716
+ P.values.set(defaults);
717
+ if (auto && !cur && idleGroup) play(idleGroup);
718
+ if (cur && !cur.m.loop && cur.outAt === null && now - cur.start >= Math.max(cur.m.duration - cur.m.fadeOut, 0)) cur.outAt = now - cur.start;
719
+ if (cur && cur.outAt !== null && now - cur.start - cur.outAt >= cur.m.fadeOut) {
720
+ prev = null;
721
+ cur = null;
722
+ if (auto && idleGroup) play(idleGroup);
723
+ }
724
+ if (prev && prev.outAt !== null && now - prev.start - prev.outAt >= prev.m.fadeOut) prev = null;
725
+ let eyeFactor = 1;
726
+ let lipFactor = 1;
727
+ for (const p of [prev, cur]) {
728
+ if (!p) continue;
729
+ const f = sampleMotion(p.m, now - p.start, 1, p.outAt);
730
+ for (const [id, { value, weight }] of f.params) {
731
+ const k = index.get(id);
732
+ if (k !== void 0) P.values[k] = P.values[k] * (1 - weight) + value * weight;
733
+ }
734
+ for (const [id, v] of f.parts) {
735
+ const k = partIndex.get(id);
736
+ if (k === void 0) continue;
737
+ model.parts.opacities[k] = v;
738
+ poseGroups.forEach((g, gi) => {
739
+ if (g.includes(k) && v > .5) shown[gi] = k;
740
+ });
741
+ }
742
+ if (f.groups.has("EyeBlink")) eyeFactor = f.groups.get("EyeBlink");
743
+ if (f.groups.has("LipSync")) lipFactor = f.groups.get("LipSync");
744
+ }
745
+ poseGroups.forEach((g, gi) => {
746
+ for (const k of g) model.parts.opacities[k] = k === shown[gi] ? 1 : 0;
747
+ });
748
+ for (const [x, w] of [[expOut, -1], [exp, 1]]) {
749
+ if (!x) continue;
750
+ const t = now - x.start;
751
+ const weight = w > 0 ? ease(x.e.fadeIn > 0 ? t / x.e.fadeIn : 1) : 1 - ease(x.e.fadeOut > 0 ? t / x.e.fadeOut : 1);
752
+ if (w < 0 && weight <= 0) {
753
+ expOut = null;
754
+ continue;
755
+ }
756
+ for (const p of x.e.params) {
757
+ const k = index.get(p.id);
758
+ if (k !== void 0) P.values[k] = blendExpression(P.values[k], p, weight);
759
+ }
760
+ }
761
+ if (auto) {
762
+ const open = blink.open(now);
763
+ for (const id of eyes) {
764
+ const k = index.get(id);
765
+ P.values[k] = P.values[k] * (1 - (1 - open) * eyeFactor);
766
+ }
767
+ for (const [id, off, peak, cycle] of BREATH) add(id, (off + peak * Math.sin(2 * Math.PI * now / cycle)) * .5);
768
+ }
769
+ const k = 1 - Math.exp(-dt * 8);
770
+ lookAt.sx += (lookAt.x - lookAt.sx) * k;
771
+ lookAt.sy += (lookAt.y - lookAt.sy) * k;
772
+ add("ParamAngleX", lookAt.sx * 30);
773
+ add("ParamAngleY", lookAt.sy * 30);
774
+ add("ParamAngleZ", lookAt.sx * lookAt.sy * -30);
775
+ add("ParamBodyAngleX", lookAt.sx * 10);
776
+ add("ParamEyeBallX", lookAt.sx);
777
+ add("ParamEyeBallY", lookAt.sy);
778
+ for (const id of lips) add(id, mouthOpen * .8 * lipFactor);
779
+ for (const [i, v] of holds) P.values[i] = v;
780
+ for (let i = 0; i < P.count; i++) P.values[i] = Math.min(P.maximumValues[i], Math.max(P.minimumValues[i], P.values[i]));
781
+ model.update();
782
+ }
783
+ function sizeCanvas() {
784
+ const dpr = Math.min(2, globalThis.devicePixelRatio || 1);
785
+ const w = Math.max(1, Math.round((canvas.clientWidth || canvas.width) * dpr));
786
+ const h = Math.max(1, Math.round((canvas.clientHeight || canvas.height) * dpr));
787
+ if (canvas.width !== w || canvas.height !== h) {
788
+ canvas.width = w;
789
+ canvas.height = h;
790
+ }
791
+ matrix = null;
792
+ }
793
+ function draw() {
794
+ if (!box) box = modelBounds(model, core);
795
+ if (!matrix) matrix = fitMatrix(frameMode === "bust" ? {
796
+ ...box,
797
+ minY: box.maxY - (box.maxY - box.minY) * .5
798
+ } : box, canvas.width, canvas.height);
799
+ gl.viewport(0, 0, canvas.width, canvas.height);
800
+ gl.clearColor(0, 0, 0, 0);
801
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
802
+ renderer.draw(matrix);
803
+ model.drawables.resetDynamicFlags();
804
+ }
805
+ sizeCanvas();
806
+ step(0);
807
+ draw();
808
+ let raf = 0;
809
+ let last = 0;
810
+ let gone = false;
811
+ const tick = (t) => {
812
+ if (gone) return;
813
+ const dt = last ? Math.min(.1, (t - last) / 1e3) : 1 / 60;
814
+ last = t;
815
+ step(dt);
816
+ draw();
817
+ raf = requestAnimationFrame(tick);
818
+ };
819
+ if (o.loop !== false && typeof requestAnimationFrame === "function") raf = requestAnimationFrame(tick);
820
+ const groups = {};
821
+ for (const [g, l] of motions) groups[g] = l.length;
822
+ return {
823
+ name: source.name,
824
+ coreVersion: coreVersion(core),
825
+ expressions: [...expressions.keys()],
826
+ motions: groups,
827
+ parameters: [...P.ids],
828
+ missing: [...source.missing],
829
+ expression(name) {
830
+ if (name === null) {
831
+ if (exp) expOut = {
832
+ e: exp.e,
833
+ start: now
834
+ };
835
+ exp = null;
836
+ return true;
837
+ }
838
+ const e = expressions.get(name);
839
+ if (!e) return false;
840
+ if (exp) expOut = {
841
+ e: exp.e,
842
+ start: now
843
+ };
844
+ exp = {
845
+ e,
846
+ start: now
847
+ };
848
+ return true;
849
+ },
850
+ motion: play,
851
+ mouth(v) {
852
+ mouthOpen = Math.min(1, Math.max(0, v));
853
+ },
854
+ look(x, y) {
855
+ lookAt.x = Math.min(1, Math.max(-1, x));
856
+ lookAt.y = Math.min(1, Math.max(-1, y));
857
+ },
858
+ set(id, v) {
859
+ const i = index.get(id);
860
+ if (i === void 0) return;
861
+ if (v === null) holds.delete(i);
862
+ else holds.set(i, v);
863
+ },
864
+ frame(mode) {
865
+ frameMode = mode;
866
+ matrix = null;
867
+ },
868
+ resize: sizeCanvas,
869
+ update(dt) {
870
+ step(dt);
871
+ draw();
872
+ },
873
+ dispose() {
874
+ gone = true;
875
+ cancelAnimationFrame(raf);
876
+ renderer.dispose();
877
+ model.release();
878
+ }
879
+ };
880
+ }
881
+ exports.Blinker = Blinker;
882
+ exports.CUBISM_CORE_LICENCE = CUBISM_CORE_LICENCE;
883
+ exports.CUBISM_CORE_URL = CUBISM_CORE_URL;
884
+ exports.Live2DError = Live2DError;
885
+ exports.blendExpression = blendExpression;
886
+ exports.coreVersion = coreVersion;
887
+ exports.createLive2D = createLive2D;
888
+ exports.curveValue = curveValue;
889
+ exports.ease = ease;
890
+ exports.filesFrom = filesFrom;
891
+ exports.findModel = findModel;
892
+ exports.fitMatrix = fitMatrix;
893
+ exports.joinPath = joinPath;
894
+ exports.loadCubismCore = loadCubismCore;
895
+ exports.modelBounds = modelBounds;
896
+ exports.modelFromFiles = modelFromFiles;
897
+ exports.modelFromUrl = modelFromUrl;
898
+ exports.parseExpression = parseExpression;
899
+ exports.parseMotion = parseMotion;
900
+ exports.readZip = readZip;
901
+ exports.sampleMotion = sampleMotion;
902
+ return exports;
903
+ })({});