untitled-pixi-live2d-engine 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,6 +2,8 @@
2
2
  typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("pixi.js"), require("@pixi/sound")) : typeof define === "function" && define.amd ? define(["exports", "pixi.js", "@pixi/sound"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory((global.PIXI = global.PIXI || {}, global.PIXI.live2d = global.PIXI.live2d || {}), global.PIXI, global.PIXI));
3
3
  })(this, (function(exports2, pixi_js, sound) {
4
4
  "use strict";var __defProp = Object.defineProperty;
5
+ var __defProps = Object.defineProperties;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
7
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
9
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -18,6 +20,7 @@ var __spreadValues = (a, b) => {
18
20
  }
19
21
  return a;
20
22
  };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
24
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
25
  var __async = (__this, __arguments, generator) => {
23
26
  return new Promise((resolve, reject) => {
@@ -105,7 +108,7 @@ var __async = (__this, __arguments, generator) => {
105
108
  preserveExpressionOnMotion: true,
106
109
  cubism: CubismFrameworkConfig
107
110
  };
108
- const VERSION = "1.0.2";
111
+ const VERSION = "1.2.0";
109
112
  const logger = {
110
113
  log(tag, ...messages) {
111
114
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -123,7 +126,7 @@ var __async = (__this, __arguments, generator) => {
123
126
  }
124
127
  }
125
128
  };
126
- function clamp(num, lower, upper) {
129
+ function clamp$1(num, lower, upper) {
127
130
  return num < lower ? lower : num > upper ? upper : num;
128
131
  }
129
132
  function rand(min, max) {
@@ -398,8 +401,8 @@ var __async = (__this, __arguments, generator) => {
398
401
  * @param instant - Should the focus position be instantly applied.
399
402
  */
400
403
  focus(x, y, instant = false) {
401
- this.targetX = clamp(x, -1, 1);
402
- this.targetY = clamp(y, -1, 1);
404
+ this.targetX = clamp$1(x, -1, 1);
405
+ this.targetY = clamp$1(y, -1, 1);
403
406
  if (instant) {
404
407
  this.x = this.targetX;
405
408
  this.y = this.targetY;
@@ -1916,6 +1919,68 @@ var __async = (__this, __arguments, generator) => {
1916
1919
  }
1917
1920
  }
1918
1921
  }
1922
+ const DEFAULT_LOD_SCALE_THRESHOLD = 0.5;
1923
+ const DEFAULT_LOD_TEXTURE_SIZE_THRESHOLD = 4096;
1924
+ function getTextureLODPlan({
1925
+ lod,
1926
+ effectiveScale,
1927
+ textureWidth,
1928
+ textureHeight,
1929
+ lodScaleThreshold,
1930
+ lodTextureSizeThreshold,
1931
+ lodMaxLevel
1932
+ }) {
1933
+ if (getTextureLODMode(lod) !== "single-auto") {
1934
+ return void 0;
1935
+ }
1936
+ if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) {
1937
+ return void 0;
1938
+ }
1939
+ const width = Math.floor(textureWidth);
1940
+ const height = Math.floor(textureHeight);
1941
+ if (width <= 1 || height <= 1) {
1942
+ return void 0;
1943
+ }
1944
+ const scaleThreshold = validPositive(lodScaleThreshold, DEFAULT_LOD_SCALE_THRESHOLD);
1945
+ if (effectiveScale >= scaleThreshold) {
1946
+ return void 0;
1947
+ }
1948
+ const textureSizeThreshold = validPositive(
1949
+ lodTextureSizeThreshold,
1950
+ DEFAULT_LOD_TEXTURE_SIZE_THRESHOLD
1951
+ );
1952
+ if (Math.max(width, height) < textureSizeThreshold) {
1953
+ return void 0;
1954
+ }
1955
+ const rawLevel = Math.round(Math.log2(1 / effectiveScale));
1956
+ const maxDimensionLevel = Math.max(1, Math.floor(Math.log2(Math.max(width, height))));
1957
+ const maxLevel = Math.min(maxDimensionLevel, validMaxLevel(lodMaxLevel, maxDimensionLevel));
1958
+ const level = clamp(Math.max(1, rawLevel), 1, maxLevel);
1959
+ const factor = __pow(2, level);
1960
+ return {
1961
+ level,
1962
+ width: Math.max(1, Math.round(width / factor)),
1963
+ height: Math.max(1, Math.round(height / factor))
1964
+ };
1965
+ }
1966
+ function getTextureLODMode(lod) {
1967
+ if (lod === false || lod === "single-auto") {
1968
+ return lod;
1969
+ }
1970
+ return "full";
1971
+ }
1972
+ function getTextureLODFilter(filter) {
1973
+ return filter === "nearest" ? "nearest" : "linear";
1974
+ }
1975
+ function validPositive(value, fallback) {
1976
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
1977
+ }
1978
+ function validMaxLevel(value, fallback) {
1979
+ return value !== void 0 && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
1980
+ }
1981
+ function clamp(value, min, max) {
1982
+ return Math.min(max, Math.max(min, value));
1983
+ }
1919
1984
  function createTexture(url, options = {}) {
1920
1985
  const config2 = pixi_js.loadTextures.config;
1921
1986
  const previousCrossOrigin = config2 == null ? void 0 : config2.crossOrigin;
@@ -1928,7 +1993,12 @@ var __async = (__this, __arguments, generator) => {
1928
1993
  config2.preferCreateImageBitmap = false;
1929
1994
  config2.preferWorkers = false;
1930
1995
  }
1931
- return pixi_js.Assets.load(url).catch((error) => {
1996
+ return pixi_js.Assets.load({
1997
+ src: url,
1998
+ data: {
1999
+ autoGenerateMipmaps: getTextureLODMode(options.lod) === "full"
2000
+ }
2001
+ }).catch((error) => {
1932
2002
  if (error instanceof Error) {
1933
2003
  throw error;
1934
2004
  }
@@ -2061,9 +2131,9 @@ var __async = (__this, __arguments, generator) => {
2061
2131
  const setupEssentials = (context, next) => __async(null, null, function* () {
2062
2132
  if (context.settings) {
2063
2133
  const live2DModel = context.live2dModel;
2064
- const textureOptions = {
2134
+ const textureOptions = __spreadValues({
2065
2135
  crossOrigin: context.options.crossOrigin
2066
- };
2136
+ }, context.options.textureOptions);
2067
2137
  if (context.settings instanceof CubismLegacyModelSettings) {
2068
2138
  textureOptions.preferCreateImageBitmap = false;
2069
2139
  }
@@ -2109,114 +2179,6 @@ var __async = (__this, __arguments, generator) => {
2109
2179
  }
2110
2180
  throw new TypeError("Missing settings.");
2111
2181
  });
2112
- const _ZipLoader = class _ZipLoader {
2113
- static unzip(reader, settings) {
2114
- return __async(this, null, function* () {
2115
- const filePaths = yield _ZipLoader.getFilePaths(reader);
2116
- const requiredFilePaths = [];
2117
- for (const definedFile of settings.getDefinedFiles()) {
2118
- const actualPath = decodeURI(resolveURL(settings.url, definedFile));
2119
- if (filePaths.includes(actualPath)) {
2120
- requiredFilePaths.push(actualPath);
2121
- }
2122
- }
2123
- const files = yield _ZipLoader.getFiles(reader, requiredFilePaths);
2124
- for (let i = 0; i < files.length; i++) {
2125
- const path = requiredFilePaths[i];
2126
- const file = files[i];
2127
- Object.defineProperty(file, "webkitRelativePath", {
2128
- value: path
2129
- });
2130
- }
2131
- return files;
2132
- });
2133
- }
2134
- static createSettings(reader) {
2135
- return __async(this, null, function* () {
2136
- const filePaths = yield _ZipLoader.getFilePaths(reader);
2137
- const settingsFilePath = filePaths.find(
2138
- (path) => path.endsWith("model.json") || path.endsWith("model3.json")
2139
- );
2140
- if (!settingsFilePath) {
2141
- throw new Error("Settings file not found");
2142
- }
2143
- const settingsText = yield _ZipLoader.readText(reader, settingsFilePath);
2144
- if (!settingsText) {
2145
- throw new Error("Empty settings file: " + settingsFilePath);
2146
- }
2147
- const settingsJSON = JSON.parse(settingsText);
2148
- settingsJSON.url = settingsFilePath;
2149
- const runtime = _ZipLoader.live2dFactory.findRuntime(settingsJSON);
2150
- if (!runtime) {
2151
- throw new Error("Unknown settings JSON");
2152
- }
2153
- return runtime.createModelSettings(settingsJSON);
2154
- });
2155
- }
2156
- static zipReader(data, url) {
2157
- return Promise.reject(new Error("Not implemented"));
2158
- }
2159
- static getFilePaths(reader) {
2160
- return Promise.reject(new Error("Not implemented"));
2161
- }
2162
- static getFiles(reader, paths) {
2163
- return Promise.reject(new Error("Not implemented"));
2164
- }
2165
- static readText(reader, path) {
2166
- return Promise.reject(new Error("Not implemented"));
2167
- }
2168
- static releaseReader(reader) {
2169
- }
2170
- };
2171
- // will be set by Live2DFactory
2172
- __publicField(_ZipLoader, "live2dFactory");
2173
- __publicField(_ZipLoader, "ZIP_PROTOCOL", "zip://");
2174
- __publicField(_ZipLoader, "uid", 0);
2175
- __publicField(_ZipLoader, "factory", (context, next) => __async(null, null, function* () {
2176
- const source = context.source;
2177
- let sourceURL;
2178
- let zipBlob;
2179
- let settings;
2180
- if (typeof source === "string" && (source.endsWith(".zip") || source.startsWith(_ZipLoader.ZIP_PROTOCOL))) {
2181
- if (source.startsWith(_ZipLoader.ZIP_PROTOCOL)) {
2182
- sourceURL = source.slice(_ZipLoader.ZIP_PROTOCOL.length);
2183
- } else {
2184
- sourceURL = source;
2185
- }
2186
- zipBlob = yield Live2DLoader.load({
2187
- url: sourceURL,
2188
- type: "blob",
2189
- target: context.live2dModel
2190
- });
2191
- } else if (Array.isArray(source) && source.length === 1 && source[0] instanceof File && source[0].name.endsWith(".zip")) {
2192
- zipBlob = source[0];
2193
- sourceURL = URL.createObjectURL(zipBlob);
2194
- settings = source.settings;
2195
- }
2196
- if (zipBlob) {
2197
- if (!zipBlob.size) {
2198
- throw new Error("Empty zip file");
2199
- }
2200
- const reader = yield _ZipLoader.zipReader(zipBlob, sourceURL);
2201
- if (!settings) {
2202
- settings = yield _ZipLoader.createSettings(reader);
2203
- }
2204
- settings._objectURL = _ZipLoader.ZIP_PROTOCOL + _ZipLoader.uid + "/" + settings.url;
2205
- const files = yield _ZipLoader.unzip(reader, settings);
2206
- files.settings = settings;
2207
- context.source = files;
2208
- if (sourceURL.startsWith("blob:")) {
2209
- context.live2dModel.once("modelLoaded", (internalModel) => {
2210
- internalModel.once("destroy", function() {
2211
- URL.revokeObjectURL(sourceURL);
2212
- });
2213
- });
2214
- }
2215
- _ZipLoader.releaseReader(reader);
2216
- }
2217
- return next();
2218
- }));
2219
- let ZipLoader = _ZipLoader;
2220
2182
  const _FileLoader = class _FileLoader {
2221
2183
  /**
2222
2184
  * Resolves the path of a resource file to the object URL.
@@ -2497,7 +2459,6 @@ var __async = (__this, __arguments, generator) => {
2497
2459
  * Middlewares to run through when setting up a Live2DModel.
2498
2460
  */
2499
2461
  __publicField(_Live2DFactory, "live2DModelMiddlewares", [
2500
- ZipLoader.factory,
2501
2462
  FileLoader.factory,
2502
2463
  urlToJSON,
2503
2464
  jsonToSettings,
@@ -2523,7 +2484,6 @@ var __async = (__this, __arguments, generator) => {
2523
2484
  return Live2DFactory.loadExpression(this, index);
2524
2485
  };
2525
2486
  FileLoader["live2dFactory"] = Live2DFactory;
2526
- ZipLoader["live2dFactory"] = Live2DFactory;
2527
2487
  const _Automator = class _Automator {
2528
2488
  constructor(model, {
2529
2489
  autoUpdate = true,
@@ -2677,10 +2637,17 @@ var __async = (__this, __arguments, generator) => {
2677
2637
  const tempWorldMatrix = new pixi_js.Matrix();
2678
2638
  const tempDrawableBounds = { x: 0, y: 0, width: 0, height: 0 };
2679
2639
  const tempModelBounds = new pixi_js.Bounds();
2640
+ let live2DPluginFallbackWarned = false;
2680
2641
  class Live2DPipe {
2681
2642
  constructor(renderer) {
2682
2643
  this.renderer = renderer;
2683
2644
  }
2645
+ addRenderable(model, instructionSet) {
2646
+ var _a, _b;
2647
+ const renderPipes = this.renderer.renderPipes;
2648
+ (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
2649
+ instructionSet.add(model);
2650
+ }
2684
2651
  execute(model) {
2685
2652
  if (!model.visible || model.alpha <= 0) {
2686
2653
  return;
@@ -2689,15 +2656,86 @@ var __async = (__this, __arguments, generator) => {
2689
2656
  }
2690
2657
  updateRenderable() {
2691
2658
  }
2659
+ destroyRenderable() {
2660
+ }
2661
+ validateRenderable() {
2662
+ return false;
2663
+ }
2692
2664
  destroy() {
2693
2665
  }
2694
2666
  }
2667
+ __publicField(Live2DPipe, "extension", {
2668
+ type: [pixi_js.ExtensionType.WebGLPipes],
2669
+ name: "live2d"
2670
+ });
2671
+ const Live2DPlugin = Live2DPipe;
2695
2672
  function ensureLive2DPipe(renderer) {
2696
2673
  const r = renderer;
2697
2674
  if (!r.renderPipes.live2d) {
2675
+ if (!live2DPluginFallbackWarned) {
2676
+ live2DPluginFallbackWarned = true;
2677
+ console.warn(
2678
+ "[untitled-pixi-live2d-engine] Lazy Live2D render pipe registration is deprecated. Register Live2DPlugin explicitly with `extensions.add(Live2DPlugin)` before creating the Pixi renderer."
2679
+ );
2680
+ }
2698
2681
  r.renderPipes.live2d = new Live2DPipe(renderer);
2699
2682
  }
2700
2683
  }
2684
+ function getMatrixMaxScale(matrix) {
2685
+ return Math.max(Math.hypot(matrix.a, matrix.b), Math.hypot(matrix.c, matrix.d));
2686
+ }
2687
+ function isDrawableTextureResource(resource) {
2688
+ if (!resource || typeof resource !== "object") {
2689
+ return false;
2690
+ }
2691
+ const { width, height } = resource;
2692
+ return typeof width === "number" && width > 0 && typeof height === "number" && height > 0;
2693
+ }
2694
+ function createTextureLODTexture(sourceTexture, level, width, height, filter) {
2695
+ var _a, _b;
2696
+ const resource = sourceTexture.source.resource;
2697
+ if (!isDrawableTextureResource(resource)) {
2698
+ return void 0;
2699
+ }
2700
+ const canvas = pixi_js.DOMAdapter.get().createCanvas(width, height);
2701
+ const context = canvas.getContext("2d");
2702
+ if (!context) {
2703
+ return void 0;
2704
+ }
2705
+ try {
2706
+ context.clearRect(0, 0, width, height);
2707
+ context.imageSmoothingEnabled = filter !== "nearest";
2708
+ if ("imageSmoothingQuality" in context && filter !== "nearest") {
2709
+ context.imageSmoothingQuality = "high";
2710
+ }
2711
+ context.drawImage(
2712
+ resource,
2713
+ 0,
2714
+ 0,
2715
+ sourceTexture.source.pixelWidth,
2716
+ sourceTexture.source.pixelHeight,
2717
+ 0,
2718
+ 0,
2719
+ width,
2720
+ height
2721
+ );
2722
+ } catch (e) {
2723
+ return void 0;
2724
+ }
2725
+ const label = `${(_b = (_a = sourceTexture.label) != null ? _a : sourceTexture.source.label) != null ? _b : "Live2DTexture"} LOD ${level}`;
2726
+ return new pixi_js.Texture({
2727
+ label,
2728
+ source: new pixi_js.CanvasSource({
2729
+ resource: canvas,
2730
+ width,
2731
+ height,
2732
+ resolution: 1,
2733
+ scaleMode: getTextureLODFilter(filter),
2734
+ autoGenerateMipmaps: false,
2735
+ label
2736
+ })
2737
+ });
2738
+ }
2701
2739
  class Live2DModel extends pixi_js.Container {
2702
2740
  /**
2703
2741
  * Creates a new Live2DModel instance.
@@ -2721,6 +2759,9 @@ var __async = (__this, __arguments, generator) => {
2721
2759
  * @type {Texture[]}
2722
2760
  */
2723
2761
  __publicField(this, "textures", []);
2762
+ __publicField(this, "textureOptions");
2763
+ __publicField(this, "textureLODStates", []);
2764
+ __publicField(this, "textureLODFailures", []);
2724
2765
  /** @override
2725
2766
  * The Live2DTransform instance for this model.
2726
2767
  */
@@ -2777,15 +2818,25 @@ var __async = (__this, __arguments, generator) => {
2777
2818
  this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
2778
2819
  shouldUpdateTexture = true;
2779
2820
  }
2821
+ const { projectionMatrix, offset, worldTransformMatrix } = renderer.globalUniforms.globalUniformData;
2822
+ const adjustedWorld = tempWorldMatrix.copyFrom(worldTransformMatrix).append(this.groupTransform);
2823
+ const effectiveScale = getMatrixMaxScale(adjustedWorld) * renderer.resolution;
2780
2824
  for (let i = 0; i < this.textures.length; i++) {
2781
- const texture = this.textures[i];
2782
- const hasGlSource = Boolean(texture.source._gpuData[renderer.uid]);
2783
- if (shouldUpdateTexture || !hasGlSource) {
2784
- renderer.gl.pixelStorei(
2785
- WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,
2786
- this.internalModel.textureFlipY
2787
- );
2788
- renderer.texture.bind(texture, 0);
2825
+ const originalTexture = this.textures[i];
2826
+ let texture = this.resolveTextureForRender(i, originalTexture, effectiveScale);
2827
+ try {
2828
+ this.uploadTextureForRender(renderer, texture, shouldUpdateTexture);
2829
+ } catch (e) {
2830
+ if (texture === originalTexture) {
2831
+ throw new Error("Failed to upload Live2D texture.");
2832
+ }
2833
+ const state = this.textureLODStates[i];
2834
+ if ((state == null ? void 0 : state.texture) === texture) {
2835
+ this.markTextureLODFailure(i, originalTexture, state.level);
2836
+ this.destroyTextureLODState(i);
2837
+ }
2838
+ texture = originalTexture;
2839
+ this.uploadTextureForRender(renderer, texture, shouldUpdateTexture);
2789
2840
  }
2790
2841
  this.internalModel.bindTexture(i, renderer.texture.getGlSource(texture.source).texture);
2791
2842
  }
@@ -2802,8 +2853,6 @@ var __async = (__this, __arguments, generator) => {
2802
2853
  if (frameDelta) {
2803
2854
  this.internalModel.update(frameDelta, this.elapsedTime);
2804
2855
  }
2805
- const { projectionMatrix, offset } = renderer.globalUniforms.globalUniformData;
2806
- const adjustedWorld = tempWorldMatrix.copyFrom(this.worldTransform);
2807
2856
  adjustedWorld.tx -= (_a = offset == null ? void 0 : offset.x) != null ? _a : 0;
2808
2857
  adjustedWorld.ty -= (_b = offset == null ? void 0 : offset.y) != null ? _b : 0;
2809
2858
  const internalTransform = tempMatrix$1.copyFrom(projectionMatrix).append(adjustedWorld);
@@ -2826,6 +2875,7 @@ var __async = (__this, __arguments, generator) => {
2826
2875
  }
2827
2876
  }
2828
2877
  });
2878
+ this.textureOptions = options == null ? void 0 : options.textureOptions;
2829
2879
  this.anchor = new pixi_js.ObservablePoint(
2830
2880
  {
2831
2881
  _onUpdate: () => this.onAnchorChange()
@@ -2977,9 +3027,7 @@ var __async = (__this, __arguments, generator) => {
2977
3027
  ensureLive2DPipe(renderer);
2978
3028
  const renderPipes = renderer.renderPipes;
2979
3029
  const addRenderable = () => {
2980
- var _a2, _b2;
2981
- (_b2 = (_a2 = renderPipes.batch) == null ? void 0 : _a2.break) == null ? void 0 : _b2.call(_a2, instructionSet);
2982
- instructionSet.add(this);
3030
+ renderPipes.live2d.addRenderable(this, instructionSet);
2983
3031
  };
2984
3032
  const collectChildren = () => {
2985
3033
  const children = this.children;
@@ -3270,6 +3318,75 @@ var __async = (__this, __arguments, generator) => {
3270
3318
  this.deltaTime += dt;
3271
3319
  this.elapsedTime += dt;
3272
3320
  }
3321
+ resolveTextureForRender(index, texture, effectiveScale) {
3322
+ var _a;
3323
+ const plan = getTextureLODPlan(__spreadProps(__spreadValues({}, this.textureOptions), {
3324
+ effectiveScale,
3325
+ textureWidth: texture.source.pixelWidth,
3326
+ textureHeight: texture.source.pixelHeight
3327
+ }));
3328
+ if (!plan) {
3329
+ return texture;
3330
+ }
3331
+ const failure = this.textureLODFailures[index];
3332
+ if ((failure == null ? void 0 : failure.source) === texture && failure.levels.has(plan.level)) {
3333
+ return texture;
3334
+ }
3335
+ const existing = this.textureLODStates[index];
3336
+ if ((existing == null ? void 0 : existing.source) === texture && existing.level === plan.level && !existing.texture.destroyed) {
3337
+ return existing.texture;
3338
+ }
3339
+ this.destroyTextureLODState(index);
3340
+ const lodTexture = createTextureLODTexture(
3341
+ texture,
3342
+ plan.level,
3343
+ plan.width,
3344
+ plan.height,
3345
+ (_a = this.textureOptions) == null ? void 0 : _a.lodFilter
3346
+ );
3347
+ if (!lodTexture) {
3348
+ this.markTextureLODFailure(index, texture, plan.level);
3349
+ return texture;
3350
+ }
3351
+ this.textureLODStates[index] = {
3352
+ source: texture,
3353
+ level: plan.level,
3354
+ texture: lodTexture
3355
+ };
3356
+ return lodTexture;
3357
+ }
3358
+ markTextureLODFailure(index, texture, level) {
3359
+ let failure = this.textureLODFailures[index];
3360
+ if ((failure == null ? void 0 : failure.source) !== texture) {
3361
+ failure = { source: texture, levels: /* @__PURE__ */ new Set() };
3362
+ this.textureLODFailures[index] = failure;
3363
+ }
3364
+ failure.levels.add(level);
3365
+ }
3366
+ destroyTextureLODState(index) {
3367
+ const state = this.textureLODStates[index];
3368
+ if (!state) {
3369
+ return;
3370
+ }
3371
+ state.texture.destroy(true);
3372
+ this.textureLODStates[index] = void 0;
3373
+ }
3374
+ destroyTextureLODStates() {
3375
+ for (let i = 0; i < this.textureLODStates.length; i++) {
3376
+ this.destroyTextureLODState(i);
3377
+ }
3378
+ this.textureLODFailures.length = 0;
3379
+ }
3380
+ uploadTextureForRender(renderer, texture, shouldUpdateTexture) {
3381
+ const hasGlSource = Boolean(texture.source._gpuData[renderer.uid]);
3382
+ if (shouldUpdateTexture || !hasGlSource) {
3383
+ renderer.gl.pixelStorei(
3384
+ WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,
3385
+ this.internalModel.textureFlipY
3386
+ );
3387
+ renderer.texture.bind(texture, 0);
3388
+ }
3389
+ }
3273
3390
  /**
3274
3391
  * Destroys the model and all related resources. This takes the same options and also
3275
3392
  * behaves the same as `PIXI.Container#destroy`.
@@ -3284,6 +3401,7 @@ var __async = (__this, __arguments, generator) => {
3284
3401
  */
3285
3402
  destroy(options) {
3286
3403
  this.emit("destroy");
3404
+ this.destroyTextureLODStates();
3287
3405
  if (options == null ? void 0 : options.texture) {
3288
3406
  this.textures.forEach((texture) => texture.destroy(options.baseTexture));
3289
3407
  }
@@ -3649,7 +3767,7 @@ var __async = (__this, __arguments, generator) => {
3649
3767
  this.rightParam = coreModel.getParamIndex("PARAM_EYE_R_OPEN");
3650
3768
  }
3651
3769
  setEyeParams(value) {
3652
- this.eyeParamValue = clamp(value, 0, 1);
3770
+ this.eyeParamValue = clamp$1(value, 0, 1);
3653
3771
  this.coreModel.setParamFloat(this.leftParam, this.eyeParamValue);
3654
3772
  this.coreModel.setParamFloat(this.rightParam, this.eyeParamValue);
3655
3773
  }
@@ -3739,6 +3857,12 @@ var __async = (__this, __arguments, generator) => {
3739
3857
  { breathDepth: 1, lipSyncGain: 1.5, lipSyncWeight: 0.4 },
3740
3858
  options
3741
3859
  );
3860
+ if ((options == null ? void 0 : options.useHighPrecisionMask) !== void 0 && options.useHighPrecisionMask !== false) {
3861
+ logger.warn(
3862
+ "CubismLegacyInternalModel",
3863
+ "`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."
3864
+ );
3865
+ }
3742
3866
  this.motionManager = new CubismLegacyMotionManager(this);
3743
3867
  this.parallelMotionManager = [];
3744
3868
  this.eyeBlink = new Live2DEyeBlink(coreModel);
@@ -3876,7 +4000,7 @@ var __async = (__this, __arguments, generator) => {
3876
4000
  const max_ = 1;
3877
4001
  const min_ = value > 0 ? 0.1 : 0;
3878
4002
  value = Math.pow(value, 1.15);
3879
- value = clamp(value, min_, max_);
4003
+ value = clamp$1(value, min_, max_);
3880
4004
  for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) {
3881
4005
  this.coreModel.addToParamFloat(
3882
4006
  this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]),
@@ -4116,7 +4240,7 @@ var __async = (__this, __arguments, generator) => {
4116
4240
  );
4117
4241
  if (visibleIndex >= 0) {
4118
4242
  const originalOpacity = model.getPartsOpacity(partsGroup[visibleIndex].partsIndex);
4119
- visibleOpacity = clamp(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4243
+ visibleOpacity = clamp$1(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4120
4244
  } else {
4121
4245
  visibleIndex = 0;
4122
4246
  visibleOpacity = 1;
@@ -12026,6 +12150,12 @@ var __async = (__this, __arguments, generator) => {
12026
12150
  const tempMatrix = new CubismMatrix44();
12027
12151
  const DEFAULT_MASKS_PER_RENDER_TEXTURE = 36;
12028
12152
  const MASKS_PER_RENDER_TEXTURE = 32;
12153
+ const HIGH_PRECISION_MASK_UNIQUE_MASK_SET_THRESHOLD = 16;
12154
+ const HIGH_PRECISION_MASK_MASKED_DRAWABLE_THRESHOLD = 64;
12155
+ const HIGH_PRECISION_MASK_MAX_MASKS_PER_DRAWABLE_THRESHOLD = 3;
12156
+ const HIGH_PRECISION_MASK_MASKED_VERTEX_THRESHOLD = 4096;
12157
+ const HIGH_PRECISION_MASK_VERTEX_RATIO_THRESHOLD = 0.5;
12158
+ const HIGH_PRECISION_MASK_VERTEX_RATIO_DRAWABLE_THRESHOLD = 24;
12029
12159
  function getRequiredMaskRenderTextureCount(model) {
12030
12160
  var _a;
12031
12161
  if (!model.isUsingMasking()) {
@@ -12048,6 +12178,51 @@ var __async = (__this, __arguments, generator) => {
12048
12178
  }
12049
12179
  return Math.ceil(clippingContextCount / MASKS_PER_RENDER_TEXTURE);
12050
12180
  }
12181
+ function getMaskProfile(model) {
12182
+ var _a, _b;
12183
+ const maskCounts = model.getDrawableMaskCounts();
12184
+ const masks = model.getDrawableMasks();
12185
+ const uniqueMaskSets = /* @__PURE__ */ new Set();
12186
+ const drawableCount = model.getDrawableCount();
12187
+ let maskedDrawableCount = 0;
12188
+ let maxMasksPerDrawable = 0;
12189
+ let maskedVertexCount = 0;
12190
+ let totalVertexCount = 0;
12191
+ for (let i = 0; i < drawableCount; i++) {
12192
+ const vertexCount = model.getDrawableVertexCount(i);
12193
+ const maskCount = (_a = maskCounts[i]) != null ? _a : 0;
12194
+ totalVertexCount += vertexCount;
12195
+ if (maskCount <= 0) {
12196
+ continue;
12197
+ }
12198
+ maskedDrawableCount++;
12199
+ maskedVertexCount += vertexCount;
12200
+ maxMasksPerDrawable = Math.max(maxMasksPerDrawable, maskCount);
12201
+ const maskSet = Array.from((_b = masks[i]) != null ? _b : []).slice(0, maskCount).sort((a, b) => a - b).join(",");
12202
+ uniqueMaskSets.add(maskSet);
12203
+ }
12204
+ return {
12205
+ maskedDrawableCount,
12206
+ uniqueMaskSetCount: uniqueMaskSets.size,
12207
+ maxMasksPerDrawable,
12208
+ maskedVertexCount,
12209
+ totalVertexCount
12210
+ };
12211
+ }
12212
+ function shouldUseHighPrecisionMask(model) {
12213
+ if (!model.isUsingMasking()) {
12214
+ return false;
12215
+ }
12216
+ const profile = getMaskProfile(model);
12217
+ const maskedVertexRatio = profile.totalVertexCount > 0 ? profile.maskedVertexCount / profile.totalVertexCount : 0;
12218
+ return profile.uniqueMaskSetCount > HIGH_PRECISION_MASK_UNIQUE_MASK_SET_THRESHOLD || profile.maskedDrawableCount > HIGH_PRECISION_MASK_MASKED_DRAWABLE_THRESHOLD || profile.maxMasksPerDrawable >= HIGH_PRECISION_MASK_MAX_MASKS_PER_DRAWABLE_THRESHOLD || profile.maskedVertexCount > HIGH_PRECISION_MASK_MASKED_VERTEX_THRESHOLD || maskedVertexRatio >= HIGH_PRECISION_MASK_VERTEX_RATIO_THRESHOLD && profile.maskedDrawableCount > HIGH_PRECISION_MASK_VERTEX_RATIO_DRAWABLE_THRESHOLD;
12219
+ }
12220
+ function resolveHighPrecisionMaskOption(model, option) {
12221
+ if (typeof option === "boolean") {
12222
+ return option;
12223
+ }
12224
+ return shouldUseHighPrecisionMask(model);
12225
+ }
12051
12226
  class CubismInternalModel extends InternalModel {
12052
12227
  constructor(coreModel, settings, options) {
12053
12228
  super();
@@ -12148,6 +12323,9 @@ var __async = (__this, __arguments, generator) => {
12148
12323
  breathParams.pushBack(new BreathParameterData(this.idParamBreath, 0, 0.5, 3.2345, 0.5));
12149
12324
  this.breath.setParameters(breathParams);
12150
12325
  this.renderer.initialize(this.coreModel, getRequiredMaskRenderTextureCount(this.coreModel));
12326
+ this.renderer.useHighPrecisionMask(
12327
+ resolveHighPrecisionMaskOption(this.coreModel, this.options.useHighPrecisionMask)
12328
+ );
12151
12329
  this.renderer.setIsPremultipliedAlpha(true);
12152
12330
  }
12153
12331
  getIdSafe(id) {
@@ -12246,7 +12424,7 @@ var __async = (__this, __arguments, generator) => {
12246
12424
  value = Math.pow(value, 1.15);
12247
12425
  const min_ = value > 0 ? 0.1 : 0;
12248
12426
  const max_ = 1;
12249
- value = clamp(value, min_, max_);
12427
+ value = clamp$1(value, min_, max_);
12250
12428
  this.motionManager.lipSyncIds.forEach((lipSyncId) => {
12251
12429
  model.addParameterValueById(this.getIdSafe(lipSyncId), value, this.options.lipSyncWeight);
12252
12430
  });
@@ -16506,6 +16684,7 @@ var __async = (__this, __arguments, generator) => {
16506
16684
  exports2.Live2DLoader = Live2DLoader;
16507
16685
  exports2.Live2DModel = Live2DModel;
16508
16686
  exports2.Live2DPhysics = Live2DPhysics;
16687
+ exports2.Live2DPlugin = Live2DPlugin;
16509
16688
  exports2.Live2DPose = Live2DPose;
16510
16689
  exports2.Live2DTransform = Live2DTransform;
16511
16690
  exports2.MBToByte = MBToByte;
@@ -16518,9 +16697,8 @@ var __async = (__this, __arguments, generator) => {
16518
16697
  exports2.VERSION = VERSION;
16519
16698
  exports2.VOLUME = VOLUME;
16520
16699
  exports2.XHRLoader = XHRLoader;
16521
- exports2.ZipLoader = ZipLoader;
16522
16700
  exports2.applyMixins = applyMixins;
16523
- exports2.clamp = clamp;
16701
+ exports2.clamp = clamp$1;
16524
16702
  exports2.config = config;
16525
16703
  exports2.configureCubismSDK = configureCubismSDK;
16526
16704
  exports2.copyArray = copyArray;