untitled-pixi-live2d-engine 1.0.2 → 1.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.
@@ -1,6 +1,23 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
2
7
  var __pow = Math.pow;
3
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
4
21
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
22
  var __async = (__this, __arguments, generator) => {
6
23
  return new Promise((resolve, reject) => {
@@ -22,7 +39,7 @@ var __async = (__this, __arguments, generator) => {
22
39
  step((generator = generator.apply(__this, __arguments)).next());
23
40
  });
24
41
  };
25
- import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, Container, ObservablePoint, WebGLRenderer } from "pixi.js";
42
+ import { EventEmitter, Matrix, loadTextures, Assets, Ticker, Transform, Point, Bounds, Container, ObservablePoint, WebGLRenderer, DOMAdapter, Texture, CanvasSource } from "pixi.js";
26
43
  import { sound, Sound, webaudio } from "@pixi/sound";
27
44
  const LOGICAL_WIDTH = 2;
28
45
  const LOGICAL_HEIGHT = 2;
@@ -89,7 +106,7 @@ const config = {
89
106
  preserveExpressionOnMotion: true,
90
107
  cubism: CubismFrameworkConfig
91
108
  };
92
- const VERSION = "1.0.2";
109
+ const VERSION = "1.1.0";
93
110
  const logger = {
94
111
  log(tag, ...messages) {
95
112
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -107,7 +124,7 @@ const logger = {
107
124
  }
108
125
  }
109
126
  };
110
- function clamp(num, lower, upper) {
127
+ function clamp$1(num, lower, upper) {
111
128
  return num < lower ? lower : num > upper ? upper : num;
112
129
  }
113
130
  function rand(min, max) {
@@ -382,8 +399,8 @@ class FocusController {
382
399
  * @param instant - Should the focus position be instantly applied.
383
400
  */
384
401
  focus(x, y, instant = false) {
385
- this.targetX = clamp(x, -1, 1);
386
- this.targetY = clamp(y, -1, 1);
402
+ this.targetX = clamp$1(x, -1, 1);
403
+ this.targetY = clamp$1(y, -1, 1);
387
404
  if (instant) {
388
405
  this.x = this.targetX;
389
406
  this.y = this.targetY;
@@ -1900,6 +1917,68 @@ class CubismLegacyModelSettings extends ModelSettings {
1900
1917
  }
1901
1918
  }
1902
1919
  }
1920
+ const DEFAULT_LOD_SCALE_THRESHOLD = 0.5;
1921
+ const DEFAULT_LOD_TEXTURE_SIZE_THRESHOLD = 4096;
1922
+ function getTextureLODPlan({
1923
+ lod,
1924
+ effectiveScale,
1925
+ textureWidth,
1926
+ textureHeight,
1927
+ lodScaleThreshold,
1928
+ lodTextureSizeThreshold,
1929
+ lodMaxLevel
1930
+ }) {
1931
+ if (getTextureLODMode(lod) !== "single-auto") {
1932
+ return void 0;
1933
+ }
1934
+ if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) {
1935
+ return void 0;
1936
+ }
1937
+ const width = Math.floor(textureWidth);
1938
+ const height = Math.floor(textureHeight);
1939
+ if (width <= 1 || height <= 1) {
1940
+ return void 0;
1941
+ }
1942
+ const scaleThreshold = validPositive(lodScaleThreshold, DEFAULT_LOD_SCALE_THRESHOLD);
1943
+ if (effectiveScale >= scaleThreshold) {
1944
+ return void 0;
1945
+ }
1946
+ const textureSizeThreshold = validPositive(
1947
+ lodTextureSizeThreshold,
1948
+ DEFAULT_LOD_TEXTURE_SIZE_THRESHOLD
1949
+ );
1950
+ if (Math.max(width, height) < textureSizeThreshold) {
1951
+ return void 0;
1952
+ }
1953
+ const rawLevel = Math.round(Math.log2(1 / effectiveScale));
1954
+ const maxDimensionLevel = Math.max(1, Math.floor(Math.log2(Math.max(width, height))));
1955
+ const maxLevel = Math.min(maxDimensionLevel, validMaxLevel(lodMaxLevel, maxDimensionLevel));
1956
+ const level = clamp(Math.max(1, rawLevel), 1, maxLevel);
1957
+ const factor = __pow(2, level);
1958
+ return {
1959
+ level,
1960
+ width: Math.max(1, Math.round(width / factor)),
1961
+ height: Math.max(1, Math.round(height / factor))
1962
+ };
1963
+ }
1964
+ function getTextureLODMode(lod) {
1965
+ if (lod === false || lod === "single-auto") {
1966
+ return lod;
1967
+ }
1968
+ return "full";
1969
+ }
1970
+ function getTextureLODFilter(filter) {
1971
+ return filter === "nearest" ? "nearest" : "linear";
1972
+ }
1973
+ function validPositive(value, fallback) {
1974
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
1975
+ }
1976
+ function validMaxLevel(value, fallback) {
1977
+ return value !== void 0 && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
1978
+ }
1979
+ function clamp(value, min, max) {
1980
+ return Math.min(max, Math.max(min, value));
1981
+ }
1903
1982
  function createTexture(url, options = {}) {
1904
1983
  const config2 = loadTextures.config;
1905
1984
  const previousCrossOrigin = config2 == null ? void 0 : config2.crossOrigin;
@@ -1912,7 +1991,12 @@ function createTexture(url, options = {}) {
1912
1991
  config2.preferCreateImageBitmap = false;
1913
1992
  config2.preferWorkers = false;
1914
1993
  }
1915
- return Assets.load(url).catch((error) => {
1994
+ return Assets.load({
1995
+ src: url,
1996
+ data: {
1997
+ autoGenerateMipmaps: getTextureLODMode(options.lod) === "full"
1998
+ }
1999
+ }).catch((error) => {
1916
2000
  if (error instanceof Error) {
1917
2001
  throw error;
1918
2002
  }
@@ -2045,9 +2129,9 @@ const setupOptionals = (context, next) => __async(null, null, function* () {
2045
2129
  const setupEssentials = (context, next) => __async(null, null, function* () {
2046
2130
  if (context.settings) {
2047
2131
  const live2DModel = context.live2dModel;
2048
- const textureOptions = {
2132
+ const textureOptions = __spreadValues({
2049
2133
  crossOrigin: context.options.crossOrigin
2050
- };
2134
+ }, context.options.textureOptions);
2051
2135
  if (context.settings instanceof CubismLegacyModelSettings) {
2052
2136
  textureOptions.preferCreateImageBitmap = false;
2053
2137
  }
@@ -2682,6 +2766,61 @@ function ensureLive2DPipe(renderer) {
2682
2766
  r.renderPipes.live2d = new Live2DPipe(renderer);
2683
2767
  }
2684
2768
  }
2769
+ function getMatrixMaxScale(matrix) {
2770
+ return Math.max(Math.hypot(matrix.a, matrix.b), Math.hypot(matrix.c, matrix.d));
2771
+ }
2772
+ function isDrawableTextureResource(resource) {
2773
+ if (!resource || typeof resource !== "object") {
2774
+ return false;
2775
+ }
2776
+ const { width, height } = resource;
2777
+ return typeof width === "number" && width > 0 && typeof height === "number" && height > 0;
2778
+ }
2779
+ function createTextureLODTexture(sourceTexture, level, width, height, filter) {
2780
+ var _a, _b;
2781
+ const resource = sourceTexture.source.resource;
2782
+ if (!isDrawableTextureResource(resource)) {
2783
+ return void 0;
2784
+ }
2785
+ const canvas = DOMAdapter.get().createCanvas(width, height);
2786
+ const context = canvas.getContext("2d");
2787
+ if (!context) {
2788
+ return void 0;
2789
+ }
2790
+ try {
2791
+ context.clearRect(0, 0, width, height);
2792
+ context.imageSmoothingEnabled = filter !== "nearest";
2793
+ if ("imageSmoothingQuality" in context && filter !== "nearest") {
2794
+ context.imageSmoothingQuality = "high";
2795
+ }
2796
+ context.drawImage(
2797
+ resource,
2798
+ 0,
2799
+ 0,
2800
+ sourceTexture.source.pixelWidth,
2801
+ sourceTexture.source.pixelHeight,
2802
+ 0,
2803
+ 0,
2804
+ width,
2805
+ height
2806
+ );
2807
+ } catch (e) {
2808
+ return void 0;
2809
+ }
2810
+ const label = `${(_b = (_a = sourceTexture.label) != null ? _a : sourceTexture.source.label) != null ? _b : "Live2DTexture"} LOD ${level}`;
2811
+ return new Texture({
2812
+ label,
2813
+ source: new CanvasSource({
2814
+ resource: canvas,
2815
+ width,
2816
+ height,
2817
+ resolution: 1,
2818
+ scaleMode: getTextureLODFilter(filter),
2819
+ autoGenerateMipmaps: false,
2820
+ label
2821
+ })
2822
+ });
2823
+ }
2685
2824
  class Live2DModel extends Container {
2686
2825
  /**
2687
2826
  * Creates a new Live2DModel instance.
@@ -2705,6 +2844,9 @@ class Live2DModel extends Container {
2705
2844
  * @type {Texture[]}
2706
2845
  */
2707
2846
  __publicField(this, "textures", []);
2847
+ __publicField(this, "textureOptions");
2848
+ __publicField(this, "textureLODStates", []);
2849
+ __publicField(this, "textureLODFailures", []);
2708
2850
  /** @override
2709
2851
  * The Live2DTransform instance for this model.
2710
2852
  */
@@ -2761,15 +2903,25 @@ class Live2DModel extends Container {
2761
2903
  this.internalModel.updateWebGLContext(renderer.gl, this.generateUID());
2762
2904
  shouldUpdateTexture = true;
2763
2905
  }
2906
+ const { projectionMatrix, offset, worldTransformMatrix } = renderer.globalUniforms.globalUniformData;
2907
+ const adjustedWorld = tempWorldMatrix.copyFrom(worldTransformMatrix).append(this.groupTransform);
2908
+ const effectiveScale = getMatrixMaxScale(adjustedWorld) * renderer.resolution;
2764
2909
  for (let i = 0; i < this.textures.length; i++) {
2765
- const texture = this.textures[i];
2766
- const hasGlSource = Boolean(texture.source._gpuData[renderer.uid]);
2767
- if (shouldUpdateTexture || !hasGlSource) {
2768
- renderer.gl.pixelStorei(
2769
- WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,
2770
- this.internalModel.textureFlipY
2771
- );
2772
- renderer.texture.bind(texture, 0);
2910
+ const originalTexture = this.textures[i];
2911
+ let texture = this.resolveTextureForRender(i, originalTexture, effectiveScale);
2912
+ try {
2913
+ this.uploadTextureForRender(renderer, texture, shouldUpdateTexture);
2914
+ } catch (e) {
2915
+ if (texture === originalTexture) {
2916
+ throw new Error("Failed to upload Live2D texture.");
2917
+ }
2918
+ const state = this.textureLODStates[i];
2919
+ if ((state == null ? void 0 : state.texture) === texture) {
2920
+ this.markTextureLODFailure(i, originalTexture, state.level);
2921
+ this.destroyTextureLODState(i);
2922
+ }
2923
+ texture = originalTexture;
2924
+ this.uploadTextureForRender(renderer, texture, shouldUpdateTexture);
2773
2925
  }
2774
2926
  this.internalModel.bindTexture(i, renderer.texture.getGlSource(texture.source).texture);
2775
2927
  }
@@ -2786,8 +2938,6 @@ class Live2DModel extends Container {
2786
2938
  if (frameDelta) {
2787
2939
  this.internalModel.update(frameDelta, this.elapsedTime);
2788
2940
  }
2789
- const { projectionMatrix, offset } = renderer.globalUniforms.globalUniformData;
2790
- const adjustedWorld = tempWorldMatrix.copyFrom(this.worldTransform);
2791
2941
  adjustedWorld.tx -= (_a = offset == null ? void 0 : offset.x) != null ? _a : 0;
2792
2942
  adjustedWorld.ty -= (_b = offset == null ? void 0 : offset.y) != null ? _b : 0;
2793
2943
  const internalTransform = tempMatrix.copyFrom(projectionMatrix).append(adjustedWorld);
@@ -2810,6 +2960,7 @@ class Live2DModel extends Container {
2810
2960
  }
2811
2961
  }
2812
2962
  });
2963
+ this.textureOptions = options == null ? void 0 : options.textureOptions;
2813
2964
  this.anchor = new ObservablePoint(
2814
2965
  {
2815
2966
  _onUpdate: () => this.onAnchorChange()
@@ -3254,6 +3405,75 @@ class Live2DModel extends Container {
3254
3405
  this.deltaTime += dt;
3255
3406
  this.elapsedTime += dt;
3256
3407
  }
3408
+ resolveTextureForRender(index, texture, effectiveScale) {
3409
+ var _a;
3410
+ const plan = getTextureLODPlan(__spreadProps(__spreadValues({}, this.textureOptions), {
3411
+ effectiveScale,
3412
+ textureWidth: texture.source.pixelWidth,
3413
+ textureHeight: texture.source.pixelHeight
3414
+ }));
3415
+ if (!plan) {
3416
+ return texture;
3417
+ }
3418
+ const failure = this.textureLODFailures[index];
3419
+ if ((failure == null ? void 0 : failure.source) === texture && failure.levels.has(plan.level)) {
3420
+ return texture;
3421
+ }
3422
+ const existing = this.textureLODStates[index];
3423
+ if ((existing == null ? void 0 : existing.source) === texture && existing.level === plan.level && !existing.texture.destroyed) {
3424
+ return existing.texture;
3425
+ }
3426
+ this.destroyTextureLODState(index);
3427
+ const lodTexture = createTextureLODTexture(
3428
+ texture,
3429
+ plan.level,
3430
+ plan.width,
3431
+ plan.height,
3432
+ (_a = this.textureOptions) == null ? void 0 : _a.lodFilter
3433
+ );
3434
+ if (!lodTexture) {
3435
+ this.markTextureLODFailure(index, texture, plan.level);
3436
+ return texture;
3437
+ }
3438
+ this.textureLODStates[index] = {
3439
+ source: texture,
3440
+ level: plan.level,
3441
+ texture: lodTexture
3442
+ };
3443
+ return lodTexture;
3444
+ }
3445
+ markTextureLODFailure(index, texture, level) {
3446
+ let failure = this.textureLODFailures[index];
3447
+ if ((failure == null ? void 0 : failure.source) !== texture) {
3448
+ failure = { source: texture, levels: /* @__PURE__ */ new Set() };
3449
+ this.textureLODFailures[index] = failure;
3450
+ }
3451
+ failure.levels.add(level);
3452
+ }
3453
+ destroyTextureLODState(index) {
3454
+ const state = this.textureLODStates[index];
3455
+ if (!state) {
3456
+ return;
3457
+ }
3458
+ state.texture.destroy(true);
3459
+ this.textureLODStates[index] = void 0;
3460
+ }
3461
+ destroyTextureLODStates() {
3462
+ for (let i = 0; i < this.textureLODStates.length; i++) {
3463
+ this.destroyTextureLODState(i);
3464
+ }
3465
+ this.textureLODFailures.length = 0;
3466
+ }
3467
+ uploadTextureForRender(renderer, texture, shouldUpdateTexture) {
3468
+ const hasGlSource = Boolean(texture.source._gpuData[renderer.uid]);
3469
+ if (shouldUpdateTexture || !hasGlSource) {
3470
+ renderer.gl.pixelStorei(
3471
+ WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,
3472
+ this.internalModel.textureFlipY
3473
+ );
3474
+ renderer.texture.bind(texture, 0);
3475
+ }
3476
+ }
3257
3477
  /**
3258
3478
  * Destroys the model and all related resources. This takes the same options and also
3259
3479
  * behaves the same as `PIXI.Container#destroy`.
@@ -3268,6 +3488,7 @@ class Live2DModel extends Container {
3268
3488
  */
3269
3489
  destroy(options) {
3270
3490
  this.emit("destroy");
3491
+ this.destroyTextureLODStates();
3271
3492
  if (options == null ? void 0 : options.texture) {
3272
3493
  this.textures.forEach((texture) => texture.destroy(options.baseTexture));
3273
3494
  }
@@ -3633,7 +3854,7 @@ class Live2DEyeBlink {
3633
3854
  this.rightParam = coreModel.getParamIndex("PARAM_EYE_R_OPEN");
3634
3855
  }
3635
3856
  setEyeParams(value) {
3636
- this.eyeParamValue = clamp(value, 0, 1);
3857
+ this.eyeParamValue = clamp$1(value, 0, 1);
3637
3858
  this.coreModel.setParamFloat(this.leftParam, this.eyeParamValue);
3638
3859
  this.coreModel.setParamFloat(this.rightParam, this.eyeParamValue);
3639
3860
  }
@@ -3723,6 +3944,12 @@ class CubismLegacyInternalModel extends InternalModel {
3723
3944
  { breathDepth: 1, lipSyncGain: 1.5, lipSyncWeight: 0.4 },
3724
3945
  options
3725
3946
  );
3947
+ if ((options == null ? void 0 : options.useHighPrecisionMask) !== void 0 && options.useHighPrecisionMask !== false) {
3948
+ logger.warn(
3949
+ "CubismLegacyInternalModel",
3950
+ "`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."
3951
+ );
3952
+ }
3726
3953
  this.motionManager = new CubismLegacyMotionManager(this);
3727
3954
  this.parallelMotionManager = [];
3728
3955
  this.eyeBlink = new Live2DEyeBlink(coreModel);
@@ -3860,7 +4087,7 @@ class CubismLegacyInternalModel extends InternalModel {
3860
4087
  const max_ = 1;
3861
4088
  const min_ = value > 0 ? 0.1 : 0;
3862
4089
  value = Math.pow(value, 1.15);
3863
- value = clamp(value, min_, max_);
4090
+ value = clamp$1(value, min_, max_);
3864
4091
  for (let i = 0; i < this.motionManager.lipSyncIds.length; ++i) {
3865
4092
  this.coreModel.addToParamFloat(
3866
4093
  this.coreModel.getParamIndex(this.motionManager.lipSyncIds[i]),
@@ -4100,7 +4327,7 @@ class Live2DPose {
4100
4327
  );
4101
4328
  if (visibleIndex >= 0) {
4102
4329
  const originalOpacity = model.getPartsOpacity(partsGroup[visibleIndex].partsIndex);
4103
- visibleOpacity = clamp(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4330
+ visibleOpacity = clamp$1(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
4104
4331
  } else {
4105
4332
  visibleIndex = 0;
4106
4333
  visibleOpacity = 1;
@@ -4221,7 +4448,7 @@ export {
4221
4448
  XHRLoader,
4222
4449
  ZipLoader,
4223
4450
  applyMixins,
4224
- clamp,
4451
+ clamp$1 as clamp,
4225
4452
  config,
4226
4453
  copyArray,
4227
4454
  copyProperty,