@webxr-jp/mtoon-atlas 0.3.2 → 0.5.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/README.md CHANGED
@@ -156,6 +156,28 @@ void main() {
156
156
  }
157
157
  ```
158
158
 
159
+ ## WebGPURenderer で使う
160
+
161
+ `MToonAtlasMaterial` は GLSL の `ShaderMaterial` なので WebGLRenderer 専用です。
162
+ WebGPURenderer では、TSL で書いた `MToonAtlasNodeMaterial` を `@webxr-jp/mtoon-atlas/nodes` から読み込んで使います。
163
+ WebGPU バックエンドと WebGL2 バックエンド(WebGPU 非対応環境での自動フォールバック)のどちらでも描画できます。
164
+
165
+ ```typescript
166
+ import { MToonAtlasLoaderPlugin } from '@webxr-jp/mtoon-atlas'
167
+ import { MToonAtlasNodeMaterial } from '@webxr-jp/mtoon-atlas/nodes'
168
+
169
+ loader.register(
170
+ (parser) => new MToonAtlasLoaderPlugin(parser, { materialType: MToonAtlasNodeMaterial }),
171
+ )
172
+ ```
173
+
174
+ - 必要な three のバージョンは他と同じ(r181 以上)です。`three/webgpu` と `three/tsl` を使います
175
+ - コンストラクタ・`setParameterTexture()`・`isOutline`・`outlineWidthMode`・`createOutlineMaterial()` は `MToonAtlasMaterial` と同じです
176
+ - 描画結果は `MToonAtlasMaterial` に合わせてあります。影は光の色ではなくシェーディング係数に掛かり、影の中は shadeColor になります。ただし点光源・スポットライトの影だけは three の既定どおり光の色に掛かります
177
+ - `MToonAtlasExporterPlugin` はどちらのマテリアルも書き出せます
178
+ - デバッグモード(`setDebugMode`)は未対応です
179
+ - マテリアルごとにシェーダーを構築します(同じ構成のマテリアル間でもシェーダーを共有しません)
180
+
159
181
  ## KTX2 トランスコーダーの配信元
160
182
 
161
183
  KTX2 テクスチャの読み込みには Basis Universal のトランスコーダー
@@ -194,6 +216,23 @@ import { MToonAtlasLoaderPlugin } from '@webxr-jp/mtoon-atlas'
194
216
  loader.register((parser) => new MToonAtlasLoaderPlugin(parser, { ktx2Loader }))
195
217
  ```
196
218
 
219
+ ### WebGPURenderer で描画する場合
220
+
221
+ 対応する圧縮形式(ASTC / BC / ETC2 など)の判定は、既定では一時的に作る WebGLRenderer で行います。
222
+ WebGPU と WebGL では使える形式が異なることがあるため、WebGPURenderer で描画するアプリでは描画に使うレンダラーで判定させてください。
223
+
224
+ ```typescript
225
+ import { setKtx2Renderer } from '@webxr-jp/mtoon-atlas'
226
+ import { WebGPURenderer } from 'three/webgpu'
227
+
228
+ const renderer = new WebGPURenderer()
229
+ await renderer.init() // init() 前のレンダラーでは判定できない
230
+ setKtx2Renderer(renderer) // VRM を読み込む前に一度呼ぶ
231
+ ```
232
+
233
+ プラグイン単位で指定する場合は `new MToonAtlasLoaderPlugin(parser, { ktx2Renderer: renderer })` とします。
234
+ 判定に失敗した場合(init() 前など)は警告を出し、従来どおり WebGL で判定します。
235
+
197
236
  ### プラグイン単位でパスを指定する
198
237
 
199
238
  ```typescript
package/dist/index.cjs CHANGED
@@ -28,24 +28,34 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
33
  DEFAULT_KTX2_TRANSCODER_PATH: () => DEFAULT_KTX2_TRANSCODER_PATH,
34
+ DEFAULT_PARAMETER_LAYOUT: () => DEFAULT_PARAMETER_LAYOUT,
35
+ DEFAULT_TEXELS_PER_SLOT: () => DEFAULT_TEXELS_PER_SLOT,
36
+ MAX_PARAMETER_UBO_BYTES: () => MAX_PARAMETER_UBO_BYTES,
34
37
  MTOON_ATLAS_EXTENSION_NAME: () => MTOON_ATLAS_EXTENSION_NAME,
35
38
  MTOON_TRANSPARENT_RENDER_ORDER: () => MTOON_TRANSPARENT_RENDER_ORDER,
36
39
  MTOON_TRANSPARENT_ZWRITE_RENDER_ORDER: () => MTOON_TRANSPARENT_ZWRITE_RENDER_ORDER,
37
40
  MToonAtlasExporterPlugin: () => MToonAtlasExporterPlugin,
38
41
  MToonAtlasLoaderPlugin: () => MToonAtlasLoaderPlugin,
39
42
  MToonAtlasMaterial: () => MToonAtlasMaterial,
43
+ PARAMETER_UBO_BUCKET_SLOTS: () => PARAMETER_UBO_BUCKET_SLOTS,
40
44
  applyAtlasTextureColorSpace: () => applyAtlasTextureColorSpace,
41
45
  clearKtx2LoaderCache: () => clearKtx2LoaderCache,
46
+ createPaddedParameterBuffer: () => createPaddedParameterBuffer,
47
+ extractParameterBufferFromTexture: () => extractParameterBufferFromTexture,
48
+ getKtx2Renderer: () => getKtx2Renderer,
42
49
  getKtx2TranscoderPath: () => getKtx2TranscoderPath,
43
50
  getMToonRenderOrder: () => getMToonRenderOrder,
51
+ getMaxParameterUBOSlots: () => getMaxParameterUBOSlots,
44
52
  rememberKtx2Source: () => rememberKtx2Source,
45
53
  resolveKtx2Loader: () => resolveKtx2Loader,
54
+ resolveParameterBucketSlots: () => resolveParameterBucketSlots,
55
+ setKtx2Renderer: () => setKtx2Renderer,
46
56
  setKtx2TranscoderPath: () => setKtx2TranscoderPath
47
57
  });
48
- module.exports = __toCommonJS(index_exports);
58
+ module.exports = __toCommonJS(src_exports);
49
59
 
50
60
  // src/MToonAtlasMaterial.ts
51
61
  var THREE = __toESM(require("three"), 1);
@@ -162,6 +172,9 @@ var MToonAtlasMaterial = class _MToonAtlasMaterial extends THREE.ShaderMaterial
162
172
  }
163
173
  ]);
164
174
  if (parameters) {
175
+ if (parameters.name !== void 0) {
176
+ this.name = parameters.name;
177
+ }
165
178
  if (parameters.color !== void 0) {
166
179
  this.uniforms.litFactor.value.set(parameters.color);
167
180
  }
@@ -513,6 +526,101 @@ var MToonAtlasMaterial = class _MToonAtlasMaterial extends THREE.ShaderMaterial
513
526
  }
514
527
  };
515
528
 
529
+ // src/types.ts
530
+ var DEFAULT_PARAMETER_LAYOUT = [
531
+ { id: "baseColor", texel: 0, channels: ["r", "g", "b"] },
532
+ { id: "opacity", texel: 0, channels: ["a"] },
533
+ { id: "shadeColor", texel: 1, channels: ["r", "g", "b"] },
534
+ { id: "shadingShiftTextureScale", texel: 1, channels: ["a"] },
535
+ { id: "emissiveColor", texel: 2, channels: ["r", "g", "b"] },
536
+ { id: "emissiveIntensity", texel: 2, channels: ["a"] },
537
+ { id: "matcapColor", texel: 3, channels: ["r", "g", "b"] },
538
+ { id: "outlineWidth", texel: 3, channels: ["a"] },
539
+ { id: "outlineColor", texel: 4, channels: ["r", "g", "b"] },
540
+ { id: "outlineLightingMix", texel: 4, channels: ["a"] },
541
+ { id: "parametricRimColor", texel: 5, channels: ["r", "g", "b"] },
542
+ { id: "parametricRimLift", texel: 5, channels: ["a"] },
543
+ { id: "parametricRimFresnelPower", texel: 6, channels: ["r"] },
544
+ { id: "shadingToony", texel: 6, channels: ["g"] },
545
+ { id: "rimLightingMix", texel: 6, channels: ["b"] },
546
+ { id: "uvAnimationRotation", texel: 6, channels: ["a"] },
547
+ { id: "normalScale", texel: 7, channels: ["r", "g"] },
548
+ { id: "uvAnimationScrollX", texel: 7, channels: ["b"] },
549
+ { id: "uvAnimationScrollY", texel: 7, channels: ["a"] },
550
+ { id: "shadingShift", texel: 8, channels: ["r"] }
551
+ ];
552
+
553
+ // src/parameter-buffer.ts
554
+ var MAX_PARAMETER_UBO_BYTES = 16384;
555
+ var DEFAULT_TEXELS_PER_SLOT = 9;
556
+ var BYTES_PER_VEC4 = 16;
557
+ var PARAMETER_UBO_BUCKET_SLOTS = [8, 16, 32, 64, 112];
558
+ function getMaxParameterUBOSlots(texelsPerSlot = DEFAULT_TEXELS_PER_SLOT) {
559
+ if (!Number.isInteger(texelsPerSlot) || texelsPerSlot <= 0) {
560
+ throw new RangeError(`texelsPerSlot \u306F\u6B63\u306E\u6574\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF08\u53D7\u3051\u53D6\u3063\u305F\u5024: ${texelsPerSlot}\uFF09`);
561
+ }
562
+ return Math.floor(MAX_PARAMETER_UBO_BYTES / (texelsPerSlot * BYTES_PER_VEC4));
563
+ }
564
+ function resolveParameterBucketSlots(slotCount, texelsPerSlot = DEFAULT_TEXELS_PER_SLOT) {
565
+ if (!Number.isInteger(slotCount) || slotCount < 0) {
566
+ throw new RangeError(`slotCount \u306F 0 \u4EE5\u4E0A\u306E\u6574\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF08\u53D7\u3051\u53D6\u3063\u305F\u5024: ${slotCount}\uFF09`);
567
+ }
568
+ const maxSlots = getMaxParameterUBOSlots(texelsPerSlot);
569
+ if (slotCount > maxSlots) {
570
+ throw new RangeError(
571
+ `\u30DE\u30C6\u30EA\u30A2\u30EB\u30B9\u30ED\u30C3\u30C8\u6570 (${slotCount}) \u304C UBO \u4E0A\u9650 (${maxSlots} \u30B9\u30ED\u30C3\u30C8 / ${MAX_PARAMETER_UBO_BYTES} bytes, texelsPerSlot=${texelsPerSlot}) \u3092\u8D85\u3048\u3066\u3044\u307E\u3059`
572
+ );
573
+ }
574
+ const effectiveSlots = Math.max(1, slotCount);
575
+ for (const bucket of PARAMETER_UBO_BUCKET_SLOTS) {
576
+ if (effectiveSlots <= bucket && bucket <= maxSlots) {
577
+ return bucket;
578
+ }
579
+ }
580
+ return maxSlots;
581
+ }
582
+ function createPaddedParameterBuffer(data, slotCount, texelsPerSlot = DEFAULT_TEXELS_PER_SLOT) {
583
+ const bucketSlots = resolveParameterBucketSlots(slotCount, texelsPerSlot);
584
+ const paddedLength = bucketSlots * texelsPerSlot * 4;
585
+ const buffer = new Float32Array(paddedLength);
586
+ const copyLength = Math.min(data.length, slotCount * texelsPerSlot * 4, paddedLength);
587
+ if (copyLength > 0) {
588
+ buffer.set(data.subarray(0, copyLength), 0);
589
+ }
590
+ return { buffer, bucketSlots };
591
+ }
592
+ function extractParameterBufferFromTexture(descriptor) {
593
+ const { texture, slotCount, texelsPerSlot, semantics, atlasedTextures } = descriptor;
594
+ const expectedLength = Math.max(0, slotCount * texelsPerSlot * 4);
595
+ const image = texture.image;
596
+ const raw = image?.data;
597
+ let data;
598
+ if (raw instanceof Float32Array) {
599
+ data = raw;
600
+ } else if (raw instanceof Uint16Array) {
601
+ data = new Float32Array(raw.length);
602
+ for (let i = 0; i < raw.length; i++) {
603
+ data[i] = raw[i] / 65535;
604
+ }
605
+ } else if (raw instanceof Uint8Array || raw instanceof Uint8ClampedArray) {
606
+ data = new Float32Array(raw.length);
607
+ for (let i = 0; i < raw.length; i++) {
608
+ data[i] = raw[i] / 255;
609
+ }
610
+ } else if (raw) {
611
+ data = Float32Array.from(raw);
612
+ } else {
613
+ data = new Float32Array(expectedLength);
614
+ }
615
+ return {
616
+ data,
617
+ slotCount,
618
+ texelsPerSlot,
619
+ semantics,
620
+ atlasedTextures
621
+ };
622
+ }
623
+
516
624
  // src/extensions/MToonAtlasLoaderPlugin.ts
517
625
  var import_three2 = require("three");
518
626
  var import_fast_png = require("fast-png");
@@ -553,14 +661,56 @@ function normalizeTranscoderPath(path) {
553
661
  }
554
662
  var defaultTranscoderPath = DEFAULT_KTX2_TRANSCODER_PATH;
555
663
  var loaderCache = /* @__PURE__ */ new Map();
664
+ var rendererLoaderCache = /* @__PURE__ */ new WeakMap();
665
+ var rendererLoaders = /* @__PURE__ */ new Set();
666
+ var defaultRenderer = null;
556
667
  function setKtx2TranscoderPath(path) {
557
668
  defaultTranscoderPath = normalizeTranscoderPath(path);
558
669
  }
559
670
  function getKtx2TranscoderPath() {
560
671
  return defaultTranscoderPath;
561
672
  }
562
- function resolveKtx2Loader(transcoderPath) {
673
+ function setKtx2Renderer(renderer) {
674
+ defaultRenderer = renderer;
675
+ }
676
+ function getKtx2Renderer() {
677
+ return defaultRenderer;
678
+ }
679
+ function resolveLoaderForRenderer(path, renderer) {
680
+ let byPath = rendererLoaderCache.get(renderer);
681
+ const cached = byPath?.get(path);
682
+ if (cached) {
683
+ return cached;
684
+ }
685
+ const loader = new import_KTX2Loader.KTX2Loader();
686
+ loader.setTranscoderPath(path);
687
+ try {
688
+ loader.detectSupport(renderer);
689
+ } catch (error) {
690
+ console.warn(
691
+ "MToonAtlasLoaderPlugin: \u6307\u5B9A\u3055\u308C\u305F\u30EC\u30F3\u30C0\u30E9\u30FC\u3067 KTX2 \u306E\u5BFE\u5FDC\u5F62\u5F0F\u3092\u5224\u5B9A\u3067\u304D\u306A\u3044\u305F\u3081\u3001WebGL \u3067\u5224\u5B9A\u3057\u307E\u3059\uFF08WebGPURenderer \u306F await renderer.init() \u6E08\u307F\u3067\u3042\u308B\u3053\u3068\uFF09:",
692
+ error
693
+ );
694
+ loader.dispose();
695
+ return null;
696
+ }
697
+ if (!byPath) {
698
+ byPath = /* @__PURE__ */ new Map();
699
+ rendererLoaderCache.set(renderer, byPath);
700
+ }
701
+ byPath.set(path, loader);
702
+ rendererLoaders.add(loader);
703
+ return loader;
704
+ }
705
+ function resolveKtx2Loader(transcoderPath, renderer) {
563
706
  const path = transcoderPath === void 0 ? defaultTranscoderPath : normalizeTranscoderPath(transcoderPath);
707
+ const supportRenderer = renderer ?? defaultRenderer;
708
+ if (supportRenderer) {
709
+ const loader = resolveLoaderForRenderer(path, supportRenderer);
710
+ if (loader) {
711
+ return loader;
712
+ }
713
+ }
564
714
  const cached = loaderCache.get(path);
565
715
  if (cached) {
566
716
  return cached;
@@ -568,7 +718,7 @@ function resolveKtx2Loader(transcoderPath) {
568
718
  if (typeof document === "undefined" || typeof WebGLRenderingContext === "undefined") {
569
719
  return null;
570
720
  }
571
- let renderer;
721
+ let tempRenderer;
572
722
  try {
573
723
  const canvas = document.createElement("canvas");
574
724
  const gl = canvas.getContext("webgl2");
@@ -576,17 +726,17 @@ function resolveKtx2Loader(transcoderPath) {
576
726
  console.warn("MToonAtlasLoaderPlugin: WebGL2\u304C\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093");
577
727
  return null;
578
728
  }
579
- renderer = new import_three.WebGLRenderer({ canvas, context: gl });
729
+ tempRenderer = new import_three.WebGLRenderer({ canvas, context: gl });
580
730
  const loader = new import_KTX2Loader.KTX2Loader();
581
731
  loader.setTranscoderPath(path);
582
- loader.detectSupport(renderer);
732
+ loader.detectSupport(tempRenderer);
583
733
  loaderCache.set(path, loader);
584
734
  return loader;
585
735
  } catch (error) {
586
736
  console.warn("MToonAtlasLoaderPlugin: KTX2Loader\u306E\u521D\u671F\u5316\u306B\u5931\u6557:", error);
587
737
  return null;
588
738
  } finally {
589
- renderer?.dispose();
739
+ tempRenderer?.dispose();
590
740
  }
591
741
  }
592
742
  function clearKtx2LoaderCache() {
@@ -594,6 +744,11 @@ function clearKtx2LoaderCache() {
594
744
  loader.dispose();
595
745
  }
596
746
  loaderCache.clear();
747
+ for (const loader of rendererLoaders) {
748
+ loader.dispose();
749
+ }
750
+ rendererLoaders.clear();
751
+ rendererLoaderCache = /* @__PURE__ */ new WeakMap();
597
752
  }
598
753
 
599
754
  // src/extensions/types.ts
@@ -616,13 +771,15 @@ var MToonAtlasLoaderPlugin = class {
616
771
  this.parser = parser;
617
772
  this.injectedKtx2Loader = options.ktx2Loader;
618
773
  this.ktx2TranscoderPath = options.ktx2TranscoderPath;
774
+ this.materialType = options.materialType ?? MToonAtlasMaterial;
775
+ this.ktx2Renderer = options.ktx2Renderer;
619
776
  }
620
777
  /**
621
778
  * このプラグインが使う KTX2Loader を取得する
622
779
  * 注入されたインスタンス > 指定パス > アプリ全体の既定値 の順に解決する
623
780
  */
624
781
  getKtx2Loader() {
625
- return this.injectedKtx2Loader ?? resolveKtx2Loader(this.ktx2TranscoderPath);
782
+ return this.injectedKtx2Loader ?? resolveKtx2Loader(this.ktx2TranscoderPath, this.ktx2Renderer);
626
783
  }
627
784
  /**
628
785
  * 再エクスポート用に元の KTX2 バイナリの複製を取得する(画像単位でメモ化)
@@ -668,18 +825,18 @@ var MToonAtlasLoaderPlugin = class {
668
825
  gltf.scene.traverse((object) => {
669
826
  if (!(object instanceof import_three2.Mesh)) return;
670
827
  const material = Array.isArray(object.material) ? object.material[0] : object.material;
671
- if (!(material instanceof MToonAtlasMaterial)) return;
828
+ if (!material || !("isMToonAtlasMaterial" in material)) return;
672
829
  if (!material.transparent) return;
673
830
  object.renderOrder = getMToonRenderOrder(material);
674
831
  });
675
832
  return null;
676
833
  }
677
834
  /**
678
- * パラメータテクスチャを16bit精度で読み込む
835
+ * パラメータ画像を16bit精度でデコードして生 Float32Array として読み込む
679
836
  * GLTFLoaderのloadTextureはImageBitmap経由で8bitに変換されるため、
680
837
  * 直接PNGデータを取得してfast-pngでデコードする
681
838
  */
682
- async _loadParameterTexture16bit(textureIndex) {
839
+ async _loadParameterData16bit(textureIndex) {
683
840
  const json = this.parser.json;
684
841
  if (textureIndex < 0 || textureIndex >= json.textures.length) {
685
842
  throw new Error(`MToonAtlasLoaderPlugin: Invalid texture index: ${textureIndex}`);
@@ -746,7 +903,14 @@ var MToonAtlasLoaderPlugin = class {
746
903
  }
747
904
  }
748
905
  }
749
- const texture = new import_three2.DataTexture(floatData, width, height, import_three2.RGBAFormat, import_three2.FloatType);
906
+ return { data: floatData, width, height };
907
+ }
908
+ /**
909
+ * パラメータテクスチャを16bit精度で読み込む(GLSL 版向け)
910
+ */
911
+ async _loadParameterTexture16bit(textureIndex) {
912
+ const { data, width, height } = await this._loadParameterData16bit(textureIndex);
913
+ const texture = new import_three2.DataTexture(data, width, height, import_three2.RGBAFormat, import_three2.FloatType);
750
914
  texture.flipY = false;
751
915
  texture.colorSpace = import_three2.NoColorSpace;
752
916
  texture.minFilter = import_three2.NearestFilter;
@@ -856,13 +1020,23 @@ var MToonAtlasLoaderPlugin = class {
856
1020
  }
857
1021
  }
858
1022
  };
1023
+ const prefersBuffer = this.materialType.prefersParameterBuffer === true;
1024
+ let parameterData = null;
859
1025
  let parameterTexture = null;
860
1026
  if (extension.parameterTexture && extension.parameterTexture.index >= 0) {
861
- pending.push(
862
- this._loadParameterTexture16bit(extension.parameterTexture.index).then((tex) => {
863
- parameterTexture = tex;
864
- })
865
- );
1027
+ if (prefersBuffer) {
1028
+ pending.push(
1029
+ this._loadParameterData16bit(extension.parameterTexture.index).then(({ data }) => {
1030
+ parameterData = data;
1031
+ })
1032
+ );
1033
+ } else {
1034
+ pending.push(
1035
+ this._loadParameterTexture16bit(extension.parameterTexture.index).then((tex) => {
1036
+ parameterTexture = tex;
1037
+ })
1038
+ );
1039
+ }
866
1040
  }
867
1041
  if (extension.atlasedTextures) {
868
1042
  for (const [key, value] of Object.entries(extension.atlasedTextures)) {
@@ -870,28 +1044,47 @@ var MToonAtlasLoaderPlugin = class {
870
1044
  }
871
1045
  }
872
1046
  await Promise.all(pending);
873
- if (!parameterTexture) {
874
- const dummyData = new Float32Array(4).fill(0);
875
- parameterTexture = new import_three2.DataTexture(dummyData, 1, 1, import_three2.RGBAFormat, import_three2.FloatType);
876
- parameterTexture.flipY = false;
877
- parameterTexture.colorSpace = import_three2.NoColorSpace;
878
- parameterTexture.minFilter = import_three2.NearestFilter;
879
- parameterTexture.magFilter = import_three2.NearestFilter;
880
- parameterTexture.needsUpdate = true;
881
- }
882
1047
  const slotAttributeName = extension.slotAttributeName.toLowerCase();
883
- const material = new MToonAtlasMaterial({
884
- parameterTexture: {
885
- texture: parameterTexture,
886
- slotCount: extension.parameterTexture.slotCount,
887
- texelsPerSlot: extension.parameterTexture.texelsPerSlot,
888
- atlasedTextures
889
- },
890
- slotAttribute: {
891
- name: slotAttributeName
892
- },
893
- name: materialDef.name
894
- });
1048
+ const slotCount = extension.parameterTexture?.slotCount ?? 0;
1049
+ const texelsPerSlot = extension.parameterTexture?.texelsPerSlot ?? 9;
1050
+ let material;
1051
+ if (prefersBuffer) {
1052
+ const data = parameterData ?? new Float32Array(Math.max(1, slotCount) * texelsPerSlot * 4);
1053
+ material = new this.materialType({
1054
+ parameterBuffer: {
1055
+ data,
1056
+ slotCount,
1057
+ texelsPerSlot,
1058
+ atlasedTextures
1059
+ },
1060
+ slotAttribute: {
1061
+ name: slotAttributeName
1062
+ },
1063
+ name: materialDef.name
1064
+ });
1065
+ } else {
1066
+ if (!parameterTexture) {
1067
+ const dummyData = new Float32Array(4).fill(0);
1068
+ parameterTexture = new import_three2.DataTexture(dummyData, 1, 1, import_three2.RGBAFormat, import_three2.FloatType);
1069
+ parameterTexture.flipY = false;
1070
+ parameterTexture.colorSpace = import_three2.NoColorSpace;
1071
+ parameterTexture.minFilter = import_three2.NearestFilter;
1072
+ parameterTexture.magFilter = import_three2.NearestFilter;
1073
+ parameterTexture.needsUpdate = true;
1074
+ }
1075
+ material = new this.materialType({
1076
+ parameterTexture: {
1077
+ texture: parameterTexture,
1078
+ slotCount,
1079
+ texelsPerSlot,
1080
+ atlasedTextures
1081
+ },
1082
+ slotAttribute: {
1083
+ name: slotAttributeName
1084
+ },
1085
+ name: materialDef.name
1086
+ });
1087
+ }
895
1088
  if (materialDef.doubleSided) {
896
1089
  material.side = import_three2.DoubleSide;
897
1090
  } else {
@@ -937,7 +1130,27 @@ var MToonAtlasExporterPlugin = class {
937
1130
  // オブジェクト参照ではキャッシュできない。
938
1131
  // キーの選び方は processTextureWithCache のコメントを参照
939
1132
  this.textureCache = /* @__PURE__ */ new Map();
1133
+ // パラメータバッファ(Float32Array参照)からインデックスへのキャッシュ(重複登録防止)
1134
+ // 本体とアウトライン(clone)は同一の parameterBuffer.data を参照するため、1回だけ書き出す
1135
+ this.parameterBufferCache = /* @__PURE__ */ new Map();
940
1136
  this.writer = writer;
1137
+ this.skipStandardMaterialProcessing();
1138
+ }
1139
+ /**
1140
+ * アトラスマテリアルを GLTFExporter 標準のマテリアル変換から外す
1141
+ *
1142
+ * 標準の変換は MeshStandardMaterial 前提で `material.color` などを読む。
1143
+ * GLSL 版は ShaderMaterial として警告付きで null になるだけだが、
1144
+ * TSL 版(NodeMaterial)は color を持たないため例外で書き出しが止まる。
1145
+ * どちらも afterParse で自前のマテリアル定義に差し替えるので、ここで null を返す
1146
+ */
1147
+ skipStandardMaterialProcessing() {
1148
+ const original = this.writer.processMaterialAsync?.bind(this.writer);
1149
+ if (!original) return;
1150
+ this.writer.processMaterialAsync = async (material) => {
1151
+ if (material && "isMToonAtlasMaterial" in material) return null;
1152
+ return original(material);
1153
+ };
941
1154
  }
942
1155
  /**
943
1156
  * テクスチャ圧縮オプションを設定
@@ -957,6 +1170,7 @@ var MToonAtlasExporterPlugin = class {
957
1170
  this.textureIndices.clear();
958
1171
  this.pendingTextureIndices.clear();
959
1172
  this.textureCache.clear();
1173
+ this.parameterBufferCache.clear();
960
1174
  const roots = Array.isArray(input) ? input : [input];
961
1175
  for (const root of roots) {
962
1176
  root.traverse((obj) => {
@@ -1054,12 +1268,16 @@ var MToonAtlasExporterPlugin = class {
1054
1268
  parameterTextureIndex: null,
1055
1269
  atlasedTextureIndices: {}
1056
1270
  };
1057
- if (material.parameterTexture?.texture) {
1271
+ if (material.parameterBuffer) {
1272
+ pendingIndices.parameterTextureIndex = this.processParameterBufferWithCache(
1273
+ material.parameterBuffer
1274
+ );
1275
+ } else if (material.parameterTexture?.texture) {
1058
1276
  pendingIndices.parameterTextureIndex = this.processParameterTextureWithCache(
1059
1277
  material.parameterTexture.texture
1060
1278
  );
1061
1279
  }
1062
- const atlasedTextures = material.parameterTexture?.atlasedTextures;
1280
+ const atlasedTextures = material.parameterBuffer?.atlasedTextures ?? material.parameterTexture?.atlasedTextures;
1063
1281
  if (atlasedTextures) {
1064
1282
  for (const [key, texture] of Object.entries(atlasedTextures)) {
1065
1283
  if (texture) {
@@ -1090,6 +1308,24 @@ var MToonAtlasExporterPlugin = class {
1090
1308
  pendingIndices.resolvePromise = resolveAllPromise;
1091
1309
  this.writer.pending.push(resolveAllPromise);
1092
1310
  }
1311
+ /**
1312
+ * パラメータバッファをキャッシュ付きで処理
1313
+ * 同じ Float32Array 参照は 1 回だけ処理される
1314
+ */
1315
+ processParameterBufferWithCache(descriptor) {
1316
+ const cached = this.parameterBufferCache.get(descriptor.data);
1317
+ if (cached) {
1318
+ return cached;
1319
+ }
1320
+ const promise = this.processParameterData(
1321
+ descriptor.data,
1322
+ descriptor.texelsPerSlot,
1323
+ descriptor.slotCount,
1324
+ "parameterTexture"
1325
+ );
1326
+ this.parameterBufferCache.set(descriptor.data, promise);
1327
+ return promise;
1328
+ }
1093
1329
  /**
1094
1330
  * パラメータテクスチャをキャッシュ付きで処理
1095
1331
  * 同じUUIDのテクスチャは1回だけ処理される
@@ -1133,6 +1369,18 @@ var MToonAtlasExporterPlugin = class {
1133
1369
  * 生のRGBAデータから直接PNGを生成してBINチャンクに格納
1134
1370
  */
1135
1371
  processParameterTexture(texture) {
1372
+ const image = texture.image;
1373
+ return this.processParameterData(
1374
+ image?.data,
1375
+ image?.width ?? 0,
1376
+ image?.height ?? 0,
1377
+ texture.name || "parameterTexture"
1378
+ );
1379
+ }
1380
+ /**
1381
+ * パラメータ配列(Float32Array / Uint8Array 等)を 16bit PNG として BIN チャンクへ書き込む
1382
+ */
1383
+ processParameterData(srcData, width, height, name) {
1136
1384
  const json = this.writer.json;
1137
1385
  json.textures = json.textures || [];
1138
1386
  json.images = json.images || [];
@@ -1155,7 +1403,7 @@ var MToonAtlasExporterPlugin = class {
1155
1403
  }
1156
1404
  const imageIndex = json.images.length;
1157
1405
  const imageDef = {
1158
- name: texture.name || "parameterTexture",
1406
+ name,
1159
1407
  mimeType: "image/png"
1160
1408
  };
1161
1409
  json.images.push(imageDef);
@@ -1163,21 +1411,19 @@ var MToonAtlasExporterPlugin = class {
1163
1411
  json.textures.push({
1164
1412
  sampler: nearestSamplerIndex,
1165
1413
  source: imageIndex,
1166
- name: texture.name || "parameterTexture"
1414
+ name
1167
1415
  });
1168
- const image = texture.image;
1169
- if (image?.data && image.width && image.height) {
1170
- const srcData = image.data;
1416
+ if (srcData && width > 0 && height > 0) {
1171
1417
  const isFloatData = srcData instanceof Float32Array || srcData.constructor?.name === "Float32Array";
1172
- const pixelCount = image.width * image.height * 4;
1418
+ const pixelCount = width * height * 4;
1173
1419
  const uint16Data = new Uint16Array(pixelCount);
1174
1420
  for (let i = 0; i < pixelCount; i++) {
1175
- const value = srcData[i];
1421
+ const value = srcData[i] ?? 0;
1176
1422
  uint16Data[i] = isFloatData ? Math.round(Math.min(1, Math.max(0, value)) * 65535) : value * 257;
1177
1423
  }
1178
1424
  const pngData = (0, import_fast_png2.encode)({
1179
- width: image.width,
1180
- height: image.height,
1425
+ width,
1426
+ height,
1181
1427
  depth: 16,
1182
1428
  channels: 4,
1183
1429
  data: uint16Data
@@ -1731,12 +1977,13 @@ var MToonAtlasExporterPlugin = class {
1731
1977
  */
1732
1978
  createMaterialDef(material) {
1733
1979
  const indices = this.textureIndices.get(material);
1980
+ const parameterMeta = material.parameterBuffer ?? material.parameterTexture;
1734
1981
  const extension = {
1735
1982
  version: "1.0",
1736
1983
  parameterTexture: {
1737
1984
  index: indices?.parameterTextureIndex ?? -1,
1738
- texelsPerSlot: material.parameterTexture?.texelsPerSlot ?? 9,
1739
- slotCount: material.parameterTexture?.slotCount ?? 0
1985
+ texelsPerSlot: parameterMeta?.texelsPerSlot ?? 9,
1986
+ slotCount: parameterMeta?.slotCount ?? 0
1740
1987
  },
1741
1988
  slotAttributeName: "_MTOON_MATERIAL_SLOT",
1742
1989
  atlasedTextures: {}
@@ -1850,18 +2097,28 @@ var MToonAtlasExporterPlugin = class {
1850
2097
  // Annotate the CommonJS export names for ESM import in node:
1851
2098
  0 && (module.exports = {
1852
2099
  DEFAULT_KTX2_TRANSCODER_PATH,
2100
+ DEFAULT_PARAMETER_LAYOUT,
2101
+ DEFAULT_TEXELS_PER_SLOT,
2102
+ MAX_PARAMETER_UBO_BYTES,
1853
2103
  MTOON_ATLAS_EXTENSION_NAME,
1854
2104
  MTOON_TRANSPARENT_RENDER_ORDER,
1855
2105
  MTOON_TRANSPARENT_ZWRITE_RENDER_ORDER,
1856
2106
  MToonAtlasExporterPlugin,
1857
2107
  MToonAtlasLoaderPlugin,
1858
2108
  MToonAtlasMaterial,
2109
+ PARAMETER_UBO_BUCKET_SLOTS,
1859
2110
  applyAtlasTextureColorSpace,
1860
2111
  clearKtx2LoaderCache,
2112
+ createPaddedParameterBuffer,
2113
+ extractParameterBufferFromTexture,
2114
+ getKtx2Renderer,
1861
2115
  getKtx2TranscoderPath,
1862
2116
  getMToonRenderOrder,
2117
+ getMaxParameterUBOSlots,
1863
2118
  rememberKtx2Source,
1864
2119
  resolveKtx2Loader,
2120
+ resolveParameterBucketSlots,
2121
+ setKtx2Renderer,
1865
2122
  setKtx2TranscoderPath
1866
2123
  });
1867
2124
  //# sourceMappingURL=index.cjs.map