@webxr-jp/mtoon-atlas 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.
package/dist/index.js ADDED
@@ -0,0 +1,1635 @@
1
+ // src/MToonAtlasMaterial.ts
2
+ import * as THREE from "three";
3
+
4
+ // raw:./shaders/mtoon.vert
5
+ var mtoon_default = "// #define PHONG\n\nvarying vec3 vViewPosition;\n\n// MToonAtlasMaterial - \u30B9\u30ED\u30C3\u30C8\u5C5E\u6027\n// \u9802\u70B9\u3054\u3068\u306E\u30DE\u30C6\u30EA\u30A2\u30EB\u30B9\u30ED\u30C3\u30C8\u30A4\u30F3\u30C7\u30C3\u30AF\u30B9\uFF08\u30D1\u30E9\u30E1\u30FC\u30BF\u30C6\u30AF\u30B9\u30C1\u30E3\u304B\u3089\u30D1\u30E9\u30E1\u30FC\u30BF\u3092\u5FA9\u5143\u3059\u308B\u305F\u3081\u306B\u4F7F\u7528\uFF09\n// \u5C5E\u6027\u540D\u306FMToonAtlasMaterial.setSlotAttribute()\u3067\u52D5\u7684\u306B\u5909\u66F4\u53EF\u80FD\nattribute float mtoonMaterialSlot; // SLOT_ATTRIBUTE\nvarying float vMaterialSlot;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\n#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef MTOON_USE_UV\n varying vec2 vUv;\n\n // COMPAT: pre-r151 uses a common uvTransform\n #if THREE_VRM_THREE_REVISION < 151\n uniform mat3 uvTransform;\n #endif\n#endif\n\n// #include <uv2_pars_vertex>\n// COMAPT: pre-r151 uses uv2 for lightMap and aoMap\n#if THREE_VRM_THREE_REVISION < 151\n #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n uniform mat3 uv2Transform;\n #endif\n#endif\n\n// #include <displacementmap_pars_vertex>\n// #include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n uniform sampler2D outlineWidthMultiplyTexture;\n uniform mat3 outlineWidthMultiplyTextureUvTransform;\n#endif\n\nuniform float outlineWidthFactor;\n\nuniform sampler2D uParameterTexture;\nuniform vec2 uParameterTextureSize; // (texelsPerSlot, slotCount) = (width, height)\nuniform float uTexelsPerSlot;\n\nvec4 sampleParameter(float slotIndex, float texelIndex) {\n float y = (slotIndex + 0.5) / uParameterTextureSize.y;\n float x = (texelIndex + 0.5) / uParameterTextureSize.x;\n return texture2D(uParameterTexture, vec2(x, y));\n}\n\nvoid main() {\n vMaterialSlot = mtoonMaterialSlot;\n\n // Sample outlineWidthFactor from parameter texture\n // outlineWidth is at texel 3, channel a (index 3)\n vec4 param3 = sampleParameter(vMaterialSlot, 3.0);\n float outlineWidthFactor = param3.a;\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n // COMPAT: pre-r151 uses a common uvTransform\n #if THREE_VRM_THREE_REVISION >= 151\n vUv = uv;\n #else\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n #endif\n\n // #include <uv2_vertex>\n // COMAPT: pre-r151 uses uv2 for lightMap and aoMap\n #if THREE_VRM_THREE_REVISION < 151\n #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n #endif\n #endif\n\n #include <color_vertex>\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n\n // we need this to compute the outline properly\n objectNormal = normalize( objectNormal );\n\n #include <defaultnormal_vertex>\n\n #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #endif\n\n #include <begin_vertex>\n\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n // #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n\n vViewPosition = - mvPosition.xyz;\n\n #ifdef OUTLINE\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = outlineWidthFactor * worldNormalLength * objectNormal;\n\n #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy;\n float outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g;\n outlineOffset *= outlineTex;\n #endif\n\n #ifdef OUTLINE_WIDTH_SCREEN\n outlineOffset *= vViewPosition.z / projectionMatrix[ 1 ].y;\n #endif\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );\n\n gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic\n #endif\n\n #include <worldpos_vertex>\n // #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n\n}\n";
6
+
7
+ // raw:./shaders/mtoon.frag
8
+ var mtoon_default2 = "// #define PHONG\n\n// TODO: MToonAtlasMaterial - \u30D1\u30E9\u30E1\u30FC\u30BF\u30C6\u30AF\u30B9\u30C1\u30E3\u30B5\u30F3\u30D7\u30EA\u30F3\u30B0\nuniform sampler2D uParameterTexture;\nuniform vec2 uParameterTextureSize; // (texelsPerSlot, slotCount) = (width, height)\nuniform float uTexelsPerSlot;\nvarying float vMaterialSlot;\n\nvec4 sampleParameter(float slotIndex, float texelIndex) {\n float y = (slotIndex + 0.5) / uParameterTextureSize.y;\n float x = (texelIndex + 0.5) / uParameterTextureSize.x;\n return texture2D(uParameterTexture, vec2(x, y));\n}\n\nuniform vec3 litFactor;\n\nuniform float opacity;\n\nuniform vec3 shadeColorFactor;\n#ifdef USE_SHADEMULTIPLYTEXTURE\n uniform sampler2D shadeMultiplyTexture;\n uniform mat3 shadeMultiplyTextureUvTransform;\n#endif\n\nuniform float shadingShiftFactor;\nuniform float shadingToonyFactor;\n\n#ifdef USE_SHADINGSHIFTTEXTURE\n uniform sampler2D shadingShiftTexture;\n uniform mat3 shadingShiftTextureUvTransform;\n uniform float shadingShiftTextureScale;\n#endif\n\nuniform float giEqualizationFactor;\n\nuniform vec3 parametricRimColorFactor;\n#ifdef USE_RIMMULTIPLYTEXTURE\n uniform sampler2D rimMultiplyTexture;\n uniform mat3 rimMultiplyTextureUvTransform;\n#endif\nuniform float rimLightingMixFactor;\nuniform float parametricRimFresnelPowerFactor;\nuniform float parametricRimLiftFactor;\n\n#ifdef USE_MATCAPTEXTURE\n uniform vec3 matcapFactor;\n uniform sampler2D matcapTexture;\n uniform mat3 matcapTextureUvTransform;\n#endif\n\nuniform vec3 emissive;\nuniform float emissiveIntensity;\n\nuniform vec3 outlineColorFactor;\nuniform float outlineLightingMixFactor;\n\n#ifdef USE_UVANIMATIONMASKTEXTURE\n uniform sampler2D uvAnimationMaskTexture;\n uniform mat3 uvAnimationMaskTextureUvTransform;\n#endif\n\nuniform float uvAnimationScrollXOffset;\nuniform float uvAnimationScrollYOffset;\nuniform float uvAnimationRotationPhase;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n\n// #include <uv_pars_fragment>\n#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif\n\n// #include <uv2_pars_fragment>\n// COMAPT: pre-r151 uses uv2 for lightMap and aoMap\n#if THREE_VRM_THREE_REVISION < 151\n #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n #endif\n#endif\n\n#include <map_pars_fragment>\n\n#ifdef USE_MAP\n uniform mat3 mapUvTransform;\n#endif\n\n// #include <alphamap_pars_fragment>\n\n#include <alphatest_pars_fragment>\n\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapUvTransform;\n#endif\n\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n\n// #include <bsdfs>\n// COMPAT: pre-r151 doesn't have BRDF_Lambert in <common>\n#if THREE_VRM_THREE_REVISION < 151\n vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n }\n#endif\n\n#include <lights_pars_begin>\n\n#include <normal_pars_fragment>\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingShift;\n float shadingToony;\n};\n\nfloat linearstep( float a, float b, float t ) {\n return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 );\n}\n\n/**\n * Convert NdotL into toon shading factor using shadingShift and shadingToony\n */\nfloat getShading(\n const in float dotNL,\n const in float shadow,\n const in float shadingShift,\n const in float shadingToony\n) {\n float shading = dotNL;\n shading = shading + shadingShift;\n shading = linearstep( -1.0 + shadingToony, 1.0 - shadingToony, shading );\n shading *= shadow;\n return shading;\n}\n\n/**\n * Mix diffuseColor and shadeColor using shading factor and light color\n */\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float shading,\n in vec3 lightColor\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( shading * lightColor ) );\n #endif\n\n vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) );\n\n // The \"comment out if you want to PBR absolutely\" line\n #ifdef V0_COMPAT_SHADE\n col = min( col, material.diffuseColor );\n #endif\n\n return col;\n}\n\n// COMPAT: pre-r156 uses a struct GeometricContext\n#if THREE_VRM_THREE_REVISION >= 157\n void RE_Direct_MToon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {\n float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 );\n vec3 irradiance = directLight.color;\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n\n irradiance *= dotNL;\n\n float shading = getShading( dotNL, shadow, material.shadingShift, material.shadingToony );\n\n // toon shaded diffuse\n reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );\n }\n\n void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {\n // indirect diffuse will use diffuseColor, no shadeColor involved\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n }\n#else\n void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {\n float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 );\n vec3 irradiance = directLight.color;\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n\n irradiance *= dotNL;\n\n float shading = getShading( dotNL, shadow, material.shadingShift, material.shadingToony );\n\n // toon shaded diffuse\n reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );\n }\n\n void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {\n // indirect diffuse will use diffuseColor, no shadeColor involved\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n }\n#endif\n\n#define RE_Direct RE_Direct_MToon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon\n#define Material_LightProbeLOD( material ) (0)\n\n#include <shadowmap_pars_fragment>\n// #include <bumpmap_pars_fragment>\n\n// #include <normalmap_pars_fragment>\n#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform mat3 normalMapUvTransform;\n uniform vec2 normalScale;\n\n#endif\n\n// COMPAT: pre-r151\n// USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151\n#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )\n\n uniform mat3 normalMatrix;\n\n#endif\n\n// COMPAT: pre-r151\n// USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) )\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n // three-vrm specific change: it requires `uv` as an input in order to support uv scrolls\n\n // Temporary compat against shader change @ Three.js r126, r151\n #if THREE_VRM_THREE_REVISION >= 151\n\n mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = surf_norm;\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\n return mat3( T * scale, B * scale, N );\n\n }\n\n #else\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = normalize( surf_norm );\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n if ( length( T ) == 0.0 || length( B ) == 0.0 ) {\n return surf_norm;\n }\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\n }\n\n #endif\n\n#endif\n\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == post correction ==========================================================\nvoid postCorrection() {\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}\n\n// == main procedure ===========================================================\nvoid main() {\n // Sample parameters from texture\n vec4 param0 = sampleParameter(vMaterialSlot, 0.0);\n vec3 litFactor = param0.rgb;\n float opacity = param0.a;\n\n vec4 param1 = sampleParameter(vMaterialSlot, 1.0);\n vec3 shadeColorFactor = param1.rgb;\n float shadingShiftTextureScale = param1.a;\n\n vec4 param2 = sampleParameter(vMaterialSlot, 2.0);\n vec3 emissive = param2.rgb;\n float emissiveIntensity = param2.a;\n\n vec4 param3 = sampleParameter(vMaterialSlot, 3.0);\n vec3 matcapFactor = param3.rgb;\n float outlineWidthFactor = param3.a;\n\n vec4 param4 = sampleParameter(vMaterialSlot, 4.0);\n vec3 outlineColorFactor = param4.rgb;\n float outlineLightingMixFactor = param4.a;\n\n vec4 param5 = sampleParameter(vMaterialSlot, 5.0);\n vec3 parametricRimColorFactor = param5.rgb;\n float parametricRimLiftFactor = param5.a;\n\n vec4 param6 = sampleParameter(vMaterialSlot, 6.0);\n float parametricRimFresnelPowerFactor = param6.r;\n float shadingToonyFactor = param6.g;\n float rimLightingMixFactor = param6.b;\n float uvAnimationRotationPhase = param6.a;\n\n vec4 param7 = sampleParameter(vMaterialSlot, 7.0);\n vec2 normalScale = param7.rg;\n float uvAnimationScrollXOffset = param7.b;\n float uvAnimationScrollYOffset = param7.a;\n\n vec4 param8 = sampleParameter(vMaterialSlot, 8.0);\n // shadingShiftFactor \u306F 0\u301C1 \u3067\u4FDD\u5B58\u3055\u308C\u3066\u3044\u308B\u306E\u3067 -1\u301C1 \u306B\u5FA9\u5143\n float shadingShiftFactor = param8.r * 2.0 - 1.0;\n #include <clipping_planes_fragment>\n\n vec2 uv = vec2(0.5, 0.5);\n\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n uv = vUv;\n\n float uvAnimMask = 1.0;\n #ifdef USE_UVANIMATIONMASKTEXTURE\n vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy;\n uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b;\n #endif\n\n float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask );\n float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask );\n uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;\n uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask;\n #endif\n\n #ifdef DEBUG_UV\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n gl_FragColor = vec4( uv, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n vec4 diffuseColor = vec4( litFactor, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive * emissiveIntensity;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy;\n vec4 sampledDiffuseColor = texture2D( map, mapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n #endif\n diffuseColor *= sampledDiffuseColor;\n #endif\n\n // #include <color_fragment>\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n diffuseColor.rgb *= vColor;\n #endif\n\n // #include <alphamap_fragment>\n\n #include <alphatest_fragment>\n\n // #include <specularmap_fragment>\n\n // #include <normal_fragment_begin>\n float faceDirection = gl_FrontFacing ? 1.0 : -1.0;\n\n #ifdef FLAT_SHADED\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n #else\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal *= faceDirection;\n\n #endif\n\n #endif\n\n #ifdef USE_NORMALMAP\n\n vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;\n\n #endif\n\n #ifdef USE_NORMALMAP_TANGENTSPACE\n\n #ifdef USE_TANGENT\n\n mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\n #else\n\n mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv );\n\n #endif\n\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\n tbn[0] *= faceDirection;\n tbn[1] *= faceDirection;\n\n #endif\n\n #endif\n\n #ifdef USE_CLEARCOAT_NORMALMAP\n\n #ifdef USE_TANGENT\n\n mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\n #else\n\n mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\n #endif\n\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\n tbn2[0] *= faceDirection;\n tbn2[1] *= faceDirection;\n\n #endif\n\n #endif\n\n // non perturbed normal for clearcoat among others\n\n vec3 nonPerturbedNormal = normal;\n\n #ifdef OUTLINE\n normal *= -1.0;\n #endif\n\n // #include <normal_fragment_maps>\n\n // COMPAT: pre-r151\n // USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151\n #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )\n\n normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n #ifdef FLIP_SIDED\n\n normal = - normal;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * faceDirection;\n\n #endif\n\n normal = normalize( normalMatrix * normal );\n\n // COMPAT: pre-r151\n // USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151\n #elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP )\n\n vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n\n // COMPAT: pre-r151\n #if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT )\n\n normal = normalize( tbn * mapN );\n\n #else\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );\n\n #endif\n\n #endif\n\n // #include <emissivemap_fragment>\n #ifdef USE_EMISSIVEMAP\n vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy;\n totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb;\n #endif\n\n #ifdef DEBUG_NORMAL\n gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );\n return;\n #endif\n\n // \u30C7\u30D0\u30C3\u30B0: \u30B7\u30E3\u30C9\u30A6\u95A2\u9023\u306E\u5024\u3092\u53EF\u8996\u5316\n #ifdef DEBUG_SHADOW\n // \u30B7\u30E3\u30C9\u30A6\u30DE\u30C3\u30D7\u306E\u6709\u52B9\u72B6\u614B\u3092\u78BA\u8A8D\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n // DirectionalShadowCoord \u306E\u53EF\u8996\u5316\uFF08\u8D64\u7DD1\u30C1\u30E3\u30F3\u30CD\u30EB\uFF09\n vec4 shadowCoord = vDirectionalShadowCoord[ 0 ];\n gl_FragColor = vec4( shadowCoord.xy, 0.0, 1.0 );\n #else\n // \u30B7\u30E3\u30C9\u30A6\u30DE\u30C3\u30D7\u304C\u7121\u52B9\u306E\u5834\u5408\u306F\u9EC4\u8272\n gl_FragColor = vec4( 1.0, 1.0, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n #ifdef DEBUG_SHADOW_VALUE\n // \u5B9F\u969B\u306E\u30B7\u30E3\u30C9\u30A6\u5024\u3092\u53EF\u8996\u5316\uFF08\u767D=\u5F71\u306A\u3057\u3001\u9ED2=\u5F71\u3042\u308A\uFF09\n float debugShadow = 1.0;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow debugDirLightShadow = directionalLightShadows[ 0 ];\n #if THREE_VRM_THREE_REVISION >= 166\n debugShadow = getShadow( directionalShadowMap[ 0 ], debugDirLightShadow.shadowMapSize, debugDirLightShadow.shadowIntensity, debugDirLightShadow.shadowBias, debugDirLightShadow.shadowRadius, vDirectionalShadowCoord[ 0 ] );\n #else\n debugShadow = getShadow( directionalShadowMap[ 0 ], debugDirLightShadow.shadowMapSize, debugDirLightShadow.shadowBias, debugDirLightShadow.shadowRadius, vDirectionalShadowCoord[ 0 ] );\n #endif\n #endif\n gl_FragColor = vec4( vec3( debugShadow ), 1.0 );\n return;\n #endif\n\n #ifdef DEBUG_RECEIVE_SHADOW\n // receiveShadow \u30D5\u30E9\u30B0\u306E\u78BA\u8A8D\uFF08\u7DD1=\u6709\u52B9\u3001\u8D64=\u7121\u52B9\uFF09\n gl_FragColor = vec4( receiveShadow ? 0.0 : 1.0, receiveShadow ? 1.0 : 0.0, 0.0, 1.0 );\n return;\n #endif\n\n #ifdef DEBUG_LIGHT_DIR\n // \u30E9\u30A4\u30C8\u65B9\u5411\u306E\u53EF\u8996\u5316\n #if NUM_DIR_LIGHTS > 0\n vec3 lightDir = directionalLights[ 0 ].direction;\n gl_FragColor = vec4( 0.5 + 0.5 * lightDir, 1.0 );\n #else\n gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); // \u30DE\u30BC\u30F3\u30BF = \u30E9\u30A4\u30C8\u306A\u3057\n #endif\n return;\n #endif\n\n #ifdef DEBUG_DOT_NL\n // dotNL\uFF08\u6CD5\u7DDA\u3068\u30E9\u30A4\u30C8\u65B9\u5411\u306E\u5185\u7A4D\uFF09\u306E\u53EF\u8996\u5316\n #if NUM_DIR_LIGHTS > 0\n float debugDotNL = dot( normal, directionalLights[ 0 ].direction );\n // -1\u301C1 \u3092 0\u301C1 \u306B\u30DE\u30C3\u30D4\u30F3\u30B0\n gl_FragColor = vec4( vec3( 0.5 + 0.5 * debugDotNL ), 1.0 );\n #else\n gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );\n #endif\n return;\n #endif\n\n // -- MToon: lighting --------------------------------------------------------\n // accumulation\n // #include <lights_phong_fragment>\n MToonMaterial material;\n\n material.diffuseColor = diffuseColor.rgb;\n\n material.shadeColor = shadeColorFactor;\n #ifdef USE_SHADEMULTIPLYTEXTURE\n vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb;\n #endif\n\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n material.shadeColor.rgb *= vColor;\n #endif\n\n material.shadingShift = shadingShiftFactor;\n #ifdef USE_SHADINGSHIFTTEXTURE\n vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy;\n material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale;\n #endif\n\n material.shadingToony = shadingToonyFactor;\n\n #ifdef DEBUG_SHADING\n // MToon\u306E\u30B7\u30A7\u30FC\u30C7\u30A3\u30F3\u30B0\u7D50\u679C\u3092\u53EF\u8996\u5316\uFF08shadingShift/shadingToony\u9069\u7528\u5F8C\uFF09\n #if NUM_DIR_LIGHTS > 0\n float debugDotNL2 = clamp( dot( normal, directionalLights[ 0 ].direction ), -1.0, 1.0 );\n float debugShading = getShading( debugDotNL2, 1.0, material.shadingShift, material.shadingToony );\n gl_FragColor = vec4( vec3( debugShading ), 1.0 );\n #else\n gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );\n #endif\n return;\n #endif\n\n #ifdef DEBUG_SHADING_PARAMS\n // shadingShift \u3068 shadingToony \u306E\u5024\u3092\u53EF\u8996\u5316\n // R = shadingShift (-1\u301C1 \u3092 0\u301C1 \u306B), G = shadingToony (0\u301C1)\n // B = \u30D1\u30E9\u30E1\u30FC\u30BF\u30C6\u30AF\u30B9\u30C1\u30E3\u304B\u3089\u306E\u751F\u306EshadingToonyFactor\n gl_FragColor = vec4( 0.5 + 0.5 * material.shadingShift, material.shadingToony, shadingToonyFactor, 1.0 );\n return;\n #endif\n\n #ifdef DEBUG_PARAM_RAW\n // \u30D1\u30E9\u30E1\u30FC\u30BF\u30C6\u30AF\u30B9\u30C1\u30E3\u304B\u3089\u306E\u751F\u306E\u5024\u3092\u53EF\u8996\u5316\n // R = shadingShiftFactor (param8.r), G = shadingToonyFactor (param6.g)\n // B = vMaterialSlot / 10.0 (\u30B9\u30ED\u30C3\u30C8\u78BA\u8A8D\u7528)\n gl_FragColor = vec4( 0.5 + 0.5 * shadingShiftFactor, shadingToonyFactor, vMaterialSlot / 10.0, 1.0 );\n return;\n #endif\n\n #ifdef DEBUG_ALPHA\n // \u30A2\u30EB\u30D5\u30A1\u5024\u3092\u53EF\u8996\u5316\n // R = diffuseColor.a (\u30C6\u30AF\u30B9\u30C1\u30E3\u30A2\u30EB\u30D5\u30A1 * opacity)\n // G = opacity (\u30D1\u30E9\u30E1\u30FC\u30BF\u30C6\u30AF\u30B9\u30C1\u30E3\u304B\u3089\u306E\u5024)\n // B = sampledDiffuseColor.a (\u30C6\u30AF\u30B9\u30C1\u30E3\u306E\u30A2\u30EB\u30D5\u30A1\u306E\u307F\u3001USE_MAP\u306E\u5834\u5408)\n float texAlpha = 1.0;\n #ifdef USE_MAP\n texAlpha = texture2D( map, vUv ).a;\n #endif\n gl_FragColor = vec4( diffuseColor.a, opacity, texAlpha, 1.0 );\n return;\n #endif\n\n // #include <lights_fragment_begin>\n\n // MToon Specific changes:\n // Since we want to take shadows into account of shading instead of irradiance,\n // we had to modify the codes that multiplies the results of shadowmap into color of direct lights.\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n vec3 geometryPosition = - vViewPosition;\n vec3 geometryNormal = normal;\n vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n vec3 geometryClearcoatNormal;\n\n #ifdef USE_CLEARCOAT\n\n geometryClearcoatNormal = clearcoatNormal;\n\n #endif\n #else\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n #ifdef USE_CLEARCOAT\n\n geometry.clearcoatNormal = clearcoatNormal;\n\n #endif\n #endif\n\n IncidentLight directLight;\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float shadow;\n\n #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n pointLight = pointLights[ i ];\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n getPointLightInfo( pointLight, geometryPosition, directLight );\n #else\n getPointLightInfo( pointLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n // COMPAT: pre-r166\n // r166 introduced shadowIntensity\n #if THREE_VRM_THREE_REVISION >= 166\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #else\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n #endif\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );\n #else\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n SpotLight spotLight;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n spotLight = spotLights[ i ];\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n getSpotLightInfo( spotLight, geometryPosition, directLight );\n #else\n getSpotLightInfo( spotLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n // COMPAT: pre-r166\n // r166 introduced shadowIntensity\n #if THREE_VRM_THREE_REVISION >= 166\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #else\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n #endif\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );\n #else\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n directionalLight = directionalLights[ i ];\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n getDirectionalLightInfo( directionalLight, directLight );\n #else\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n // COMPAT: pre-r166\n // r166 introduced shadowIntensity\n #if THREE_VRM_THREE_REVISION >= 166\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #else\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n #endif\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );\n #else\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n // #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\n // RectAreaLight rectAreaLight;\n\n // #pragma unroll_loop_start\n // for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n // rectAreaLight = rectAreaLights[ i ];\n // RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\n // }\n // #pragma unroll_loop_end\n\n // #endif\n\n #if defined( RE_IndirectDiffuse )\n\n vec3 iblIrradiance = vec3( 0.0 );\n\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n // COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES\n #if THREE_VRM_THREE_REVISION >= 157\n #if defined( USE_LIGHT_PROBES )\n irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n #endif\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #endif\n\n #if ( NUM_HEMI_LIGHTS > 0 )\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n #else\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #endif\n\n // #if defined( RE_IndirectSpecular )\n\n // vec3 radiance = vec3( 0.0 );\n // vec3 clearcoatRadiance = vec3( 0.0 );\n\n // #endif\n\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n reflectedLight.directSpecular /= PI;\n #endif\n vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 );\n\n vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor );\n\n #ifdef USE_MATCAPTEXTURE\n {\n vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );\n vec3 y = cross( viewDir, x ); // guaranteed to be normalized\n vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );\n sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy;\n vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb;\n rim += matcapFactor * matcap;\n }\n #endif\n\n #ifdef USE_RIMMULTIPLYTEXTURE\n vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb;\n #endif\n\n col += rimMix * rim;\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n #if defined( OUTLINE )\n col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor );\n #endif\n\n #ifdef OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}\n";
9
+
10
+ // src/MToonAtlasMaterial.ts
11
+ var MToonAtlasMaterial = class _MToonAtlasMaterial extends THREE.ShaderMaterial {
12
+ /**
13
+ * コンストラクタ
14
+ *
15
+ * @param parameters オプション
16
+ */
17
+ constructor(parameters) {
18
+ super({
19
+ vertexShader: mtoon_default,
20
+ fragmentShader: mtoon_default2,
21
+ side: THREE.FrontSide,
22
+ alphaTest: 0,
23
+ fog: true,
24
+ lights: true,
25
+ clipping: true,
26
+ defines: {
27
+ THREE_VRM_THREE_REVISION: parseInt(THREE.REVISION).toString()
28
+ }
29
+ });
30
+ /**
31
+ * マテリアル識別フラグ
32
+ */
33
+ this.isMToonAtlasMaterial = true;
34
+ /**
35
+ * スロット属性設定
36
+ *
37
+ * @internal
38
+ */
39
+ this._slotAttribute = {
40
+ name: "mtoonMaterialSlot"
41
+ };
42
+ /**
43
+ * 現在のデバッグモード
44
+ *
45
+ * @internal
46
+ */
47
+ this._debugMode = "none";
48
+ /**
49
+ * アウトラインモードフラグ
50
+ *
51
+ * @internal
52
+ */
53
+ this._isOutline = false;
54
+ /**
55
+ * アウトライン幅モード
56
+ * - 'none': アウトラインなし
57
+ * - 'worldCoordinates': ワールド座標系での固定幅
58
+ * - 'screenCoordinates': スクリーン座標系での固定幅
59
+ *
60
+ * @internal
61
+ */
62
+ this._outlineWidthMode = "none";
63
+ this.uniforms = THREE.UniformsUtils.merge([
64
+ THREE.UniformsLib.common,
65
+ THREE.UniformsLib.lights,
66
+ {
67
+ // パラメータテクスチャ関連
68
+ uParameterTexture: { value: null },
69
+ uParameterTextureSize: { value: new THREE.Vector2(1, 1) },
70
+ uTexelsPerSlot: { value: 9 },
71
+ // アトラステクスチャ
72
+ map: { value: null },
73
+ shadeMultiplyTexture: { value: null },
74
+ shadingShiftTexture: { value: null },
75
+ normalMap: { value: null },
76
+ emissiveMap: { value: null },
77
+ matcapTexture: { value: null },
78
+ rimMultiplyTexture: { value: null },
79
+ uvAnimationMaskTexture: { value: null },
80
+ // MToon パラメータ
81
+ litFactor: { value: new THREE.Color(1, 1, 1) },
82
+ opacity: { value: 1 },
83
+ shadeColorFactor: { value: new THREE.Color(0.97, 0.97, 0.97) },
84
+ shadingShiftFactor: { value: 0 },
85
+ shadingToonyFactor: { value: 0.9 },
86
+ giEqualizationFactor: { value: 0.9 },
87
+ parametricRimColorFactor: { value: new THREE.Color(0, 0, 0) },
88
+ rimLightingMixFactor: { value: 0 },
89
+ parametricRimFresnelPowerFactor: { value: 5 },
90
+ parametricRimLiftFactor: { value: 0 },
91
+ matcapFactor: { value: new THREE.Color(1, 1, 1) },
92
+ emissive: { value: new THREE.Color(0, 0, 0) },
93
+ emissiveIntensity: { value: 0 },
94
+ outlineColorFactor: { value: new THREE.Color(0, 0, 0) },
95
+ outlineLightingMixFactor: { value: 1 },
96
+ uvAnimationScrollXOffset: { value: 0 },
97
+ uvAnimationScrollYOffset: { value: 0 },
98
+ uvAnimationRotationPhase: { value: 0 },
99
+ // UV Transform 行列
100
+ mapUvTransform: { value: new THREE.Matrix3() },
101
+ shadeMultiplyTextureUvTransform: { value: new THREE.Matrix3() },
102
+ shadingShiftTextureUvTransform: { value: new THREE.Matrix3() },
103
+ emissiveMapUvTransform: { value: new THREE.Matrix3() },
104
+ matcapTextureUvTransform: { value: new THREE.Matrix3() },
105
+ rimMultiplyTextureUvTransform: { value: new THREE.Matrix3() },
106
+ uvAnimationMaskTextureUvTransform: { value: new THREE.Matrix3() },
107
+ normalMapUvTransform: { value: new THREE.Matrix3() }
108
+ }
109
+ ]);
110
+ if (parameters) {
111
+ if (parameters.color !== void 0) {
112
+ this.uniforms.litFactor.value.set(parameters.color);
113
+ }
114
+ if (parameters.emissive !== void 0) {
115
+ this.uniforms.emissive.value.set(parameters.emissive);
116
+ }
117
+ if (parameters.emissiveIntensity !== void 0) {
118
+ this.uniforms.emissiveIntensity.value = parameters.emissiveIntensity;
119
+ }
120
+ }
121
+ if (parameters?.parameterTexture) {
122
+ this.setParameterTexture(parameters.parameterTexture);
123
+ }
124
+ if (parameters?.slotAttribute) {
125
+ this.setSlotAttribute(parameters.slotAttribute);
126
+ }
127
+ }
128
+ /**
129
+ * パラメータテクスチャを設定
130
+ *
131
+ * @param descriptor パラメータテクスチャディスクリプタ
132
+ * @returns this(チェーン可能)
133
+ */
134
+ setParameterTexture(descriptor) {
135
+ this._parameterTexture = descriptor ?? void 0;
136
+ if (descriptor) {
137
+ this.uniforms.uParameterTexture.value = descriptor.texture;
138
+ this.uniforms.uParameterTextureSize.value.set(
139
+ descriptor.texelsPerSlot,
140
+ descriptor.slotCount
141
+ );
142
+ this.uniforms.uTexelsPerSlot.value = descriptor.texelsPerSlot;
143
+ if (descriptor.atlasedTextures) {
144
+ this._setAtlasedTextures(descriptor.atlasedTextures);
145
+ }
146
+ } else {
147
+ this.uniforms.uParameterTexture.value = null;
148
+ this.uniforms.uParameterTextureSize.value.set(1, 1);
149
+ this.uniforms.uTexelsPerSlot.value = 9;
150
+ }
151
+ this._updateDefines();
152
+ return this;
153
+ }
154
+ /**
155
+ * Definesを更新
156
+ */
157
+ _updateDefines() {
158
+ if (!this.defines) return;
159
+ const uniforms = this.uniforms;
160
+ const setDefine = (name, condition) => {
161
+ if (condition) {
162
+ this.defines[name] = "";
163
+ } else {
164
+ delete this.defines[name];
165
+ }
166
+ };
167
+ setDefine("USE_MAP", !!uniforms.map.value);
168
+ setDefine("USE_SHADEMULTIPLYTEXTURE", !!uniforms.shadeMultiplyTexture.value);
169
+ setDefine("USE_SHADINGSHIFTTEXTURE", !!uniforms.shadingShiftTexture.value);
170
+ setDefine("USE_NORMALMAP", !!uniforms.normalMap.value);
171
+ setDefine("USE_EMISSIVEMAP", !!uniforms.emissiveMap.value);
172
+ setDefine("USE_MATCAPTEXTURE", !!uniforms.matcapTexture.value);
173
+ setDefine("USE_RIMMULTIPLYTEXTURE", !!uniforms.rimMultiplyTexture.value);
174
+ setDefine("USE_UVANIMATIONMASKTEXTURE", !!uniforms.uvAnimationMaskTexture.value);
175
+ const useUv = !!uniforms.map.value || !!uniforms.shadeMultiplyTexture.value || !!uniforms.shadingShiftTexture.value || !!uniforms.normalMap.value || !!uniforms.emissiveMap.value || !!uniforms.matcapTexture.value || !!uniforms.rimMultiplyTexture.value || !!uniforms.uvAnimationMaskTexture.value || this.uniforms.uvAnimationScrollXOffset.value !== 0 || this.uniforms.uvAnimationScrollYOffset.value !== 0 || this.uniforms.uvAnimationRotationPhase.value !== 0;
176
+ setDefine("MTOON_USE_UV", useUv);
177
+ setDefine("OUTLINE", this._isOutline);
178
+ setDefine("OUTLINE_WIDTH_SCREEN", this._isOutline && this._outlineWidthMode === "screenCoordinates");
179
+ this.needsUpdate = true;
180
+ }
181
+ /**
182
+ * スロット属性を設定
183
+ *
184
+ * シェーダー内の属性名を動的に変更します。
185
+ * GLTFLoaderはカスタム属性名を小文字に変換するため、
186
+ * ローダーで設定された属性名に合わせてシェーダーを更新します。
187
+ *
188
+ * @param config スロット属性設定
189
+ * @returns this(チェーン可能)
190
+ */
191
+ setSlotAttribute(config) {
192
+ const oldName = this._slotAttribute.name;
193
+ this._slotAttribute = config;
194
+ if (config.name !== oldName) {
195
+ this.vertexShader = this.vertexShader.replace(
196
+ /attribute float \w+;\s*\/\/ SLOT_ATTRIBUTE/g,
197
+ `attribute float ${config.name}; // SLOT_ATTRIBUTE`
198
+ );
199
+ this.vertexShader = this.vertexShader.replace(
200
+ /vMaterialSlot = \w+;/g,
201
+ `vMaterialSlot = ${config.name};`
202
+ );
203
+ this.needsUpdate = true;
204
+ }
205
+ return this;
206
+ }
207
+ /**
208
+ * パラメータテクスチャを取得
209
+ *
210
+ * @returns パラメータテクスチャディスクリプタ
211
+ */
212
+ get parameterTexture() {
213
+ return this._parameterTexture;
214
+ }
215
+ /**
216
+ * スロット属性を取得
217
+ *
218
+ * @returns スロット属性設定
219
+ */
220
+ get slotAttribute() {
221
+ return this._slotAttribute;
222
+ }
223
+ /**
224
+ * アトラス化テクスチャを設定
225
+ *
226
+ * @param atlases アトラス化テクスチャセット
227
+ * @internal
228
+ */
229
+ _setAtlasedTextures(atlases) {
230
+ if (atlases.baseColor) {
231
+ this.uniforms.map.value = atlases.baseColor;
232
+ }
233
+ if (atlases.shade) {
234
+ this.uniforms.shadeMultiplyTexture.value = atlases.shade;
235
+ }
236
+ if (atlases.shadingShift) {
237
+ this.uniforms.shadingShiftTexture.value = atlases.shadingShift;
238
+ }
239
+ if (atlases.normal) {
240
+ this.uniforms.normalMap.value = atlases.normal;
241
+ }
242
+ if (atlases.emissive) {
243
+ this.uniforms.emissiveMap.value = atlases.emissive;
244
+ }
245
+ if (atlases.matcap) {
246
+ this.uniforms.matcapTexture.value = atlases.matcap;
247
+ }
248
+ if (atlases.rim) {
249
+ this.uniforms.rimMultiplyTexture.value = atlases.rim;
250
+ }
251
+ if (atlases.uvAnimationMask) {
252
+ this.uniforms.uvAnimationMaskTexture.value = atlases.uvAnimationMask;
253
+ }
254
+ }
255
+ /**
256
+ * マテリアルをコピー
257
+ *
258
+ * @param source ソースマテリアル
259
+ * @returns this
260
+ */
261
+ copy(source) {
262
+ super.copy(source);
263
+ if (source._parameterTexture) {
264
+ this._parameterTexture = { ...source._parameterTexture };
265
+ this.setParameterTexture(this._parameterTexture);
266
+ }
267
+ this._slotAttribute = { ...source._slotAttribute };
268
+ this._isOutline = source._isOutline;
269
+ this._outlineWidthMode = source._outlineWidthMode;
270
+ this._updateDefines();
271
+ return this;
272
+ }
273
+ /**
274
+ * マテリアルをクローン
275
+ *
276
+ * @returns クローンされたマテリアル
277
+ */
278
+ clone() {
279
+ const cloned = new _MToonAtlasMaterial();
280
+ cloned.copy(this);
281
+ return cloned;
282
+ }
283
+ /**
284
+ * アウトラインモードを取得
285
+ *
286
+ * @returns アウトラインモードかどうか
287
+ */
288
+ get isOutline() {
289
+ return this._isOutline;
290
+ }
291
+ /**
292
+ * アウトラインモードを設定
293
+ *
294
+ * @param value アウトラインモードにするかどうか
295
+ */
296
+ set isOutline(value) {
297
+ if (this._isOutline === value) return;
298
+ this._isOutline = value;
299
+ this.side = value ? THREE.BackSide : THREE.FrontSide;
300
+ this._updateDefines();
301
+ }
302
+ /**
303
+ * アウトライン幅モードを取得
304
+ *
305
+ * @returns アウトライン幅モード
306
+ */
307
+ get outlineWidthMode() {
308
+ return this._outlineWidthMode;
309
+ }
310
+ /**
311
+ * アウトライン幅モードを設定
312
+ *
313
+ * @param value アウトライン幅モード
314
+ */
315
+ set outlineWidthMode(value) {
316
+ if (this._outlineWidthMode === value) return;
317
+ this._outlineWidthMode = value;
318
+ this._updateDefines();
319
+ }
320
+ /**
321
+ * アウトライン用マテリアルを作成
322
+ *
323
+ * このマテリアルをベースに、アウトライン描画用のマテリアルを生成します。
324
+ * 生成されたマテリアルは `isOutline = true` が設定され、
325
+ * `side = BackSide` で裏面を描画します。
326
+ *
327
+ * @param widthMode アウトライン幅モード(デフォルト: 'worldCoordinates')
328
+ * @returns アウトライン用マテリアル
329
+ *
330
+ * @example
331
+ * ```typescript
332
+ * const baseMaterial = new MToonAtlasMaterial()
333
+ * baseMaterial.setParameterTexture(descriptor)
334
+ *
335
+ * const outlineMaterial = baseMaterial.createOutlineMaterial()
336
+ * // outlineMaterial.isOutline === true
337
+ * // outlineMaterial.side === THREE.BackSide
338
+ * ```
339
+ */
340
+ createOutlineMaterial(widthMode = "worldCoordinates") {
341
+ const outlineMaterial = this.clone();
342
+ outlineMaterial._outlineWidthMode = widthMode;
343
+ outlineMaterial.isOutline = true;
344
+ outlineMaterial.polygonOffset = true;
345
+ outlineMaterial.polygonOffsetFactor = 1;
346
+ outlineMaterial.polygonOffsetUnits = 1;
347
+ return outlineMaterial;
348
+ }
349
+ /**
350
+ * フレーム更新(アニメーション対応)
351
+ *
352
+ * UV アニメーションやその他の時間依存パラメータを更新
353
+ *
354
+ * @param deltaTime フレーム経過時間(秒)
355
+ */
356
+ update(_deltaTime) {
357
+ if (this.uniforms.uvAnimationScrollXOffset && this.uniforms.uvAnimationScrollYOffset && this.uniforms.uvAnimationRotationPhase) {
358
+ const paramTexture = this._parameterTexture;
359
+ if (paramTexture) {
360
+ }
361
+ }
362
+ }
363
+ /**
364
+ * デバッグモードを設定
365
+ *
366
+ * シャドウの問題を調査するために、様々なパラメータを可視化できます。
367
+ *
368
+ * @param mode デバッグモード
369
+ * @returns this(チェーン可能)
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * // シャドウ値を可視化(白=影なし、黒=影あり)
374
+ * material.setDebugMode('shadowValue')
375
+ *
376
+ * // 通常描画に戻す
377
+ * material.setDebugMode('none')
378
+ * ```
379
+ */
380
+ setDebugMode(mode) {
381
+ this._debugMode = mode;
382
+ if (!this.defines) return this;
383
+ const debugDefines = [
384
+ "DEBUG_UV",
385
+ "DEBUG_NORMAL",
386
+ "DEBUG_SHADOW",
387
+ "DEBUG_SHADOW_VALUE",
388
+ "DEBUG_RECEIVE_SHADOW",
389
+ "DEBUG_LIGHT_DIR",
390
+ "DEBUG_DOT_NL",
391
+ "DEBUG_SHADING",
392
+ "DEBUG_SHADING_PARAMS",
393
+ "DEBUG_PARAM_RAW",
394
+ "DEBUG_LITSHADERATE",
395
+ "DEBUG_ALPHA"
396
+ ];
397
+ for (const define2 of debugDefines) {
398
+ delete this.defines[define2];
399
+ }
400
+ const modeToDefine = {
401
+ "none": null,
402
+ "uv": "DEBUG_UV",
403
+ "normal": "DEBUG_NORMAL",
404
+ "shadow": "DEBUG_SHADOW",
405
+ "shadowValue": "DEBUG_SHADOW_VALUE",
406
+ "receiveShadow": "DEBUG_RECEIVE_SHADOW",
407
+ "lightDir": "DEBUG_LIGHT_DIR",
408
+ "dotNL": "DEBUG_DOT_NL",
409
+ "shading": "DEBUG_SHADING",
410
+ "shadingParams": "DEBUG_SHADING_PARAMS",
411
+ "paramRaw": "DEBUG_PARAM_RAW",
412
+ "litShadeRate": "DEBUG_LITSHADERATE",
413
+ "alpha": "DEBUG_ALPHA"
414
+ };
415
+ const define = modeToDefine[mode];
416
+ if (define) {
417
+ this.defines[define] = "";
418
+ }
419
+ this.needsUpdate = true;
420
+ return this;
421
+ }
422
+ /**
423
+ * 現在のデバッグモードを取得
424
+ *
425
+ * @returns 現在のデバッグモード
426
+ */
427
+ get debugMode() {
428
+ return this._debugMode;
429
+ }
430
+ /**
431
+ * 利用可能なデバッグモードの一覧を取得
432
+ *
433
+ * @returns デバッグモードの配列
434
+ */
435
+ static getAvailableDebugModes() {
436
+ return [
437
+ "none",
438
+ "uv",
439
+ "normal",
440
+ "shadow",
441
+ "shadowValue",
442
+ "receiveShadow",
443
+ "lightDir",
444
+ "dotNL",
445
+ "shading",
446
+ "shadingParams",
447
+ "paramRaw",
448
+ "litShadeRate",
449
+ "alpha"
450
+ ];
451
+ }
452
+ };
453
+
454
+ // src/extensions/MToonAtlasLoaderPlugin.ts
455
+ import { SRGBColorSpace, NoColorSpace, DoubleSide, FrontSide as FrontSide2, NearestFilter, DataTexture, FloatType, RGBAFormat, LinearFilter, LinearMipmapLinearFilter, RepeatWrapping, WebGLRenderer } from "three";
456
+ import { decode as decodePng } from "fast-png";
457
+ import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";
458
+
459
+ // src/extensions/types.ts
460
+ var MTOON_ATLAS_EXTENSION_NAME = "XRIFT_mtoon_atlas";
461
+
462
+ // src/extensions/MToonAtlasLoaderPlugin.ts
463
+ var ktx2LoaderInstance = null;
464
+ function getKTX2Loader() {
465
+ if (ktx2LoaderInstance) {
466
+ return ktx2LoaderInstance;
467
+ }
468
+ if (typeof document === "undefined" || typeof WebGLRenderingContext === "undefined") {
469
+ return null;
470
+ }
471
+ try {
472
+ const canvas = document.createElement("canvas");
473
+ const gl = canvas.getContext("webgl2");
474
+ if (!gl) {
475
+ console.warn("MToonAtlasLoaderPlugin: WebGL2\u304C\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093");
476
+ return null;
477
+ }
478
+ const renderer = new WebGLRenderer({ canvas, context: gl });
479
+ ktx2LoaderInstance = new KTX2Loader();
480
+ ktx2LoaderInstance.setTranscoderPath(
481
+ "https://cdn.jsdelivr.net/npm/three@0.175.0/examples/jsm/libs/basis/"
482
+ );
483
+ ktx2LoaderInstance.detectSupport(renderer);
484
+ renderer.dispose();
485
+ return ktx2LoaderInstance;
486
+ } catch (error) {
487
+ console.warn("MToonAtlasLoaderPlugin: KTX2Loader\u306E\u521D\u671F\u5316\u306B\u5931\u6557:", error);
488
+ return null;
489
+ }
490
+ }
491
+ var MToonAtlasLoaderPlugin = class {
492
+ constructor(parser) {
493
+ this.name = MTOON_ATLAS_EXTENSION_NAME;
494
+ this.parser = parser;
495
+ }
496
+ loadMaterial(materialIndex) {
497
+ const materialDef = this.parser.json.materials[materialIndex];
498
+ if (!materialDef.extensions || !materialDef.extensions[MTOON_ATLAS_EXTENSION_NAME]) {
499
+ return null;
500
+ }
501
+ return this._loadMaterialAsync(materialIndex);
502
+ }
503
+ /**
504
+ * パラメータテクスチャを16bit精度で読み込む
505
+ * GLTFLoaderのloadTextureはImageBitmap経由で8bitに変換されるため、
506
+ * 直接PNGデータを取得してfast-pngでデコードする
507
+ */
508
+ async _loadParameterTexture16bit(textureIndex) {
509
+ const json = this.parser.json;
510
+ if (textureIndex < 0 || textureIndex >= json.textures.length) {
511
+ throw new Error(`MToonAtlasLoaderPlugin: Invalid texture index: ${textureIndex}`);
512
+ }
513
+ const textureDef = json.textures[textureIndex];
514
+ if (!textureDef) {
515
+ throw new Error(`MToonAtlasLoaderPlugin: Texture definition not found at index ${textureIndex}`);
516
+ }
517
+ const imageIndex = textureDef.source;
518
+ if (imageIndex === void 0 || imageIndex < 0 || imageIndex >= json.images.length) {
519
+ throw new Error(`MToonAtlasLoaderPlugin: Invalid image index: ${imageIndex} for texture ${textureIndex}`);
520
+ }
521
+ const imageDef = json.images[imageIndex];
522
+ let pngData;
523
+ if (imageDef.uri) {
524
+ if (imageDef.uri.startsWith("data:")) {
525
+ const base64 = imageDef.uri.split(",")[1];
526
+ const binary = atob(base64);
527
+ const bytes = new Uint8Array(binary.length);
528
+ for (let i = 0; i < binary.length; i++) {
529
+ bytes[i] = binary.charCodeAt(i);
530
+ }
531
+ pngData = bytes.buffer;
532
+ } else {
533
+ const response = await fetch(imageDef.uri);
534
+ pngData = await response.arrayBuffer();
535
+ }
536
+ } else if (imageDef.bufferView !== void 0) {
537
+ const bufferViewData = await this.parser.getDependency("bufferView", imageDef.bufferView);
538
+ pngData = bufferViewData;
539
+ } else {
540
+ throw new Error("MToonAtlasLoaderPlugin: Invalid image definition");
541
+ }
542
+ const decoded = decodePng(new Uint8Array(pngData));
543
+ const { width, height, depth, channels, data } = decoded;
544
+ const pixelCount = width * height * 4;
545
+ const floatData = new Float32Array(pixelCount);
546
+ if (depth === 16) {
547
+ const uint16Data = data;
548
+ if (channels === 4) {
549
+ for (let i = 0; i < pixelCount; i++) {
550
+ floatData[i] = uint16Data[i] / 65535;
551
+ }
552
+ } else if (channels === 3) {
553
+ for (let i = 0; i < width * height; i++) {
554
+ floatData[i * 4] = uint16Data[i * 3] / 65535;
555
+ floatData[i * 4 + 1] = uint16Data[i * 3 + 1] / 65535;
556
+ floatData[i * 4 + 2] = uint16Data[i * 3 + 2] / 65535;
557
+ floatData[i * 4 + 3] = 1;
558
+ }
559
+ }
560
+ } else {
561
+ const uint8Data = data;
562
+ if (channels === 4) {
563
+ for (let i = 0; i < pixelCount; i++) {
564
+ floatData[i] = uint8Data[i] / 255;
565
+ }
566
+ } else if (channels === 3) {
567
+ for (let i = 0; i < width * height; i++) {
568
+ floatData[i * 4] = uint8Data[i * 3] / 255;
569
+ floatData[i * 4 + 1] = uint8Data[i * 3 + 1] / 255;
570
+ floatData[i * 4 + 2] = uint8Data[i * 3 + 2] / 255;
571
+ floatData[i * 4 + 3] = 1;
572
+ }
573
+ }
574
+ }
575
+ const texture = new DataTexture(floatData, width, height, RGBAFormat, FloatType);
576
+ texture.flipY = false;
577
+ texture.colorSpace = NoColorSpace;
578
+ texture.minFilter = NearestFilter;
579
+ texture.magFilter = NearestFilter;
580
+ texture.needsUpdate = true;
581
+ return texture;
582
+ }
583
+ /**
584
+ * KTX2テクスチャを直接読み込む
585
+ * GLTFLoaderのloadTextureがKTX2を正しく処理できない場合のフォールバック
586
+ */
587
+ async _loadKtx2Texture(textureIndex) {
588
+ const json = this.parser.json;
589
+ const textureDef = json.textures?.[textureIndex];
590
+ if (!textureDef) {
591
+ console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3\u5B9A\u7FA9\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${textureIndex}`);
592
+ return null;
593
+ }
594
+ const ktx2Extension = textureDef.extensions?.KHR_texture_basisu;
595
+ const imageIndex = ktx2Extension?.source ?? textureDef.source;
596
+ if (imageIndex === void 0 || imageIndex < 0 || imageIndex >= json.images.length) {
597
+ console.warn(`MToonAtlasLoaderPlugin: \u7121\u52B9\u306A\u753B\u50CF\u30A4\u30F3\u30C7\u30C3\u30AF\u30B9: ${imageIndex}`);
598
+ return null;
599
+ }
600
+ const imageDef = json.images[imageIndex];
601
+ let ktx2Data;
602
+ try {
603
+ if (imageDef.uri) {
604
+ if (imageDef.uri.startsWith("data:")) {
605
+ const base64 = imageDef.uri.split(",")[1];
606
+ const binary = atob(base64);
607
+ const bytes = new Uint8Array(binary.length);
608
+ for (let i = 0; i < binary.length; i++) {
609
+ bytes[i] = binary.charCodeAt(i);
610
+ }
611
+ ktx2Data = bytes.buffer;
612
+ } else {
613
+ const response = await fetch(imageDef.uri);
614
+ ktx2Data = await response.arrayBuffer();
615
+ }
616
+ } else if (imageDef.bufferView !== void 0) {
617
+ ktx2Data = await this.parser.getDependency("bufferView", imageDef.bufferView);
618
+ } else {
619
+ console.warn("MToonAtlasLoaderPlugin: \u7121\u52B9\u306A\u753B\u50CF\u5B9A\u7FA9\uFF08uri/bufferView\u306A\u3057\uFF09");
620
+ return null;
621
+ }
622
+ const ktx2Loader = getKTX2Loader();
623
+ if (!ktx2Loader) {
624
+ console.warn("MToonAtlasLoaderPlugin: KTX2Loader\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093");
625
+ return null;
626
+ }
627
+ return new Promise((resolve, reject) => {
628
+ ktx2Loader.parse(
629
+ ktx2Data,
630
+ (texture) => {
631
+ texture.flipY = false;
632
+ texture.minFilter = LinearMipmapLinearFilter;
633
+ texture.magFilter = LinearFilter;
634
+ texture.wrapS = RepeatWrapping;
635
+ texture.wrapT = RepeatWrapping;
636
+ texture.needsUpdate = true;
637
+ resolve(texture);
638
+ },
639
+ (error) => {
640
+ reject(error);
641
+ }
642
+ );
643
+ });
644
+ } catch (error) {
645
+ console.warn(`MToonAtlasLoaderPlugin: KTX2\u30C6\u30AF\u30B9\u30C1\u30E3\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557: ${error}`);
646
+ return null;
647
+ }
648
+ }
649
+ async _loadMaterialAsync(materialIndex) {
650
+ const materialDef = this.parser.json.materials[materialIndex];
651
+ const extension = materialDef.extensions[MTOON_ATLAS_EXTENSION_NAME];
652
+ const pending = [];
653
+ const atlasedTextures = {};
654
+ const loadTexture = async (key, textureInfo) => {
655
+ if (textureInfo) {
656
+ try {
657
+ const textureDef = this.parser.json.textures?.[textureInfo.index];
658
+ const isKtx2 = textureDef?.extensions?.KHR_texture_basisu !== void 0;
659
+ let loadedTexture = null;
660
+ if (isKtx2) {
661
+ loadedTexture = await this._loadKtx2Texture(textureInfo.index);
662
+ } else {
663
+ loadedTexture = await this.parser.loadTexture(textureInfo.index);
664
+ }
665
+ if (!loadedTexture) {
666
+ console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureInfo.index}) \u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F`);
667
+ return;
668
+ }
669
+ const texture = loadedTexture.clone();
670
+ if ("source" in loadedTexture && loadedTexture.source) {
671
+ texture.source = loadedTexture.source;
672
+ }
673
+ texture.flipY = false;
674
+ const srgbTextures = ["baseColor", "shade", "emissive", "matcap", "rim"];
675
+ if (srgbTextures.includes(key)) {
676
+ texture.colorSpace = SRGBColorSpace;
677
+ } else {
678
+ texture.colorSpace = NoColorSpace;
679
+ }
680
+ atlasedTextures[key] = texture;
681
+ } catch (error) {
682
+ console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureInfo.index}) \u306E\u8AAD\u307F\u8FBC\u307F\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F:`, error);
683
+ }
684
+ }
685
+ };
686
+ let parameterTexture = null;
687
+ if (extension.parameterTexture && extension.parameterTexture.index >= 0) {
688
+ pending.push(
689
+ this._loadParameterTexture16bit(extension.parameterTexture.index).then((tex) => {
690
+ parameterTexture = tex;
691
+ })
692
+ );
693
+ }
694
+ if (extension.atlasedTextures) {
695
+ for (const [key, value] of Object.entries(extension.atlasedTextures)) {
696
+ pending.push(loadTexture(key, value));
697
+ }
698
+ }
699
+ await Promise.all(pending);
700
+ if (!parameterTexture) {
701
+ const dummyData = new Float32Array(4).fill(0);
702
+ parameterTexture = new DataTexture(dummyData, 1, 1, RGBAFormat, FloatType);
703
+ parameterTexture.flipY = false;
704
+ parameterTexture.colorSpace = NoColorSpace;
705
+ parameterTexture.minFilter = NearestFilter;
706
+ parameterTexture.magFilter = NearestFilter;
707
+ parameterTexture.needsUpdate = true;
708
+ }
709
+ const slotAttributeName = extension.slotAttributeName.toLowerCase();
710
+ const material = new MToonAtlasMaterial({
711
+ parameterTexture: {
712
+ texture: parameterTexture,
713
+ slotCount: extension.parameterTexture.slotCount,
714
+ texelsPerSlot: extension.parameterTexture.texelsPerSlot,
715
+ atlasedTextures
716
+ },
717
+ slotAttribute: {
718
+ name: slotAttributeName
719
+ },
720
+ name: materialDef.name
721
+ });
722
+ if (materialDef.doubleSided) {
723
+ material.side = DoubleSide;
724
+ } else {
725
+ material.side = FrontSide2;
726
+ }
727
+ if (materialDef.alphaMode === "BLEND") {
728
+ material.transparent = true;
729
+ material.depthWrite = false;
730
+ } else if (materialDef.alphaMode === "MASK") {
731
+ material.transparent = false;
732
+ material.alphaTest = materialDef.alphaCutoff ?? 0.5;
733
+ } else {
734
+ material.transparent = false;
735
+ }
736
+ if (materialDef.extras) {
737
+ material.userData = materialDef.extras;
738
+ }
739
+ if (extension.isOutline) {
740
+ material.isOutline = true;
741
+ }
742
+ if (extension.outlineWidthMode) {
743
+ material.outlineWidthMode = extension.outlineWidthMode;
744
+ }
745
+ return material;
746
+ }
747
+ };
748
+
749
+ // src/extensions/MToonAtlasExporterPlugin.ts
750
+ import { Mesh } from "three";
751
+ import { encode as encodePng16 } from "fast-png";
752
+ import { compressToKtx2 } from "@webxr-jp/texture-compression";
753
+ var MToonAtlasExporterPlugin = class {
754
+ constructor(writer) {
755
+ this.name = MTOON_ATLAS_EXTENSION_NAME;
756
+ // MToonAtlasMaterialを持つメッシュのマップ(SkinnedMeshと通常のMesh両方対応)
757
+ this.mtoonAtlasMeshes = /* @__PURE__ */ new Map();
758
+ // beforeParseで処理されたテクスチャインデックス(解決済み)
759
+ this.textureIndices = /* @__PURE__ */ new Map();
760
+ // beforeParseで処理中のテクスチャインデックス(Promise)
761
+ this.pendingTextureIndices = /* @__PURE__ */ new Map();
762
+ // テクスチャUUIDからインデックスへのキャッシュ(重複登録防止)
763
+ // Three.jsのShaderMaterial.copyがuniformsをディープクローンするため、
764
+ // オブジェクト参照ではなくUUIDでキャッシュする必要がある
765
+ this.textureCache = /* @__PURE__ */ new Map();
766
+ this.writer = writer;
767
+ }
768
+ /**
769
+ * テクスチャ圧縮オプションを設定
770
+ * 設定された場合、アトラステクスチャを KTX2 形式で圧縮してエクスポート
771
+ *
772
+ * @param options - 圧縮オプション
773
+ */
774
+ setTextureCompressionOptions(options) {
775
+ this.textureCompressionOptions = options;
776
+ }
777
+ /**
778
+ * beforeParseでシーン内のMToonAtlasMaterialを収集し、テクスチャを処理
779
+ * また、スロット属性名をGLTFExporterが正しい名前でエクスポートするようにリネーム
780
+ */
781
+ beforeParse(input) {
782
+ this.mtoonAtlasMeshes.clear();
783
+ this.textureIndices.clear();
784
+ this.pendingTextureIndices.clear();
785
+ this.textureCache.clear();
786
+ const roots = Array.isArray(input) ? input : [input];
787
+ for (const root of roots) {
788
+ root.traverse((obj) => {
789
+ if (obj instanceof Mesh) {
790
+ const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
791
+ const mtoonMaterials = [];
792
+ for (const material of materials) {
793
+ if (material && "isMToonAtlasMaterial" in material) {
794
+ mtoonMaterials.push(material);
795
+ }
796
+ }
797
+ if (mtoonMaterials.length > 0) {
798
+ this.mtoonAtlasMeshes.set(obj, mtoonMaterials);
799
+ const material = mtoonMaterials[0];
800
+ const originalAttrName = material.slotAttribute?.name || "mtoonMaterialSlot";
801
+ const targetAttrName = "mtoon_material_slot";
802
+ if (originalAttrName !== targetAttrName) {
803
+ const attr = obj.geometry.getAttribute(originalAttrName);
804
+ if (attr) {
805
+ obj.geometry.setAttribute(targetAttrName, attr);
806
+ }
807
+ }
808
+ for (const material2 of mtoonMaterials) {
809
+ if (!this.pendingTextureIndices.has(material2)) {
810
+ this.processTexturesForMaterial(material2);
811
+ }
812
+ }
813
+ }
814
+ }
815
+ });
816
+ }
817
+ this.optimizeMorphAttributeSharing(roots);
818
+ }
819
+ /**
820
+ * 属性データの重複を検出してアクセサを共有する最適化
821
+ *
822
+ * GLTFExporterには以下の問題がある:
823
+ * 1. morphTarget処理でattribute.clone()を毎回呼び出すため、キャッシュが効かない
824
+ * 2. 同一データを持つ異なる属性オブジェクトが別々にエクスポートされる
825
+ *
826
+ * この問題を回避するため、processAccessorをラップして
827
+ * データ内容のフィンガープリントでキャッシュを行う
828
+ */
829
+ optimizeMorphAttributeSharing(_roots) {
830
+ const fingerprintToAccessor = /* @__PURE__ */ new Map();
831
+ const getFingerprint = (attribute) => {
832
+ const array = attribute.array;
833
+ const byteLength = attribute.array.byteLength;
834
+ const itemSize = attribute.itemSize;
835
+ const count = attribute.count;
836
+ const normalized = attribute.normalized;
837
+ const len = array.length;
838
+ if (len === 0) return `${byteLength}:${itemSize}:${count}:${normalized}:`;
839
+ const sampleCount = Math.min(16, len);
840
+ const samples = [];
841
+ for (let i = 0; i < sampleCount && i < len; i++) {
842
+ samples.push(array[i]);
843
+ }
844
+ const midStart = Math.floor(len / 2) - Math.floor(sampleCount / 2);
845
+ for (let i = 0; i < sampleCount && midStart + i < len; i++) {
846
+ samples.push(array[Math.max(0, midStart + i)]);
847
+ }
848
+ const endStart = Math.max(0, len - sampleCount);
849
+ for (let i = 0; i < sampleCount && endStart + i < len; i++) {
850
+ samples.push(array[endStart + i]);
851
+ }
852
+ return `${byteLength}:${itemSize}:${count}:${normalized}:${samples.map((v) => v.toFixed(6)).join(",")}`;
853
+ };
854
+ const originalProcessAccessor = this.writer.processAccessor.bind(this.writer);
855
+ let cacheHits = 0;
856
+ let totalCalls = 0;
857
+ this.writer.processAccessor = (attribute, geometry, start, count) => {
858
+ totalCalls++;
859
+ const fingerprint = getFingerprint(attribute);
860
+ const cachedAccessor = fingerprintToAccessor.get(fingerprint);
861
+ if (cachedAccessor !== void 0) {
862
+ cacheHits++;
863
+ return cachedAccessor;
864
+ }
865
+ const accessorIndex = originalProcessAccessor(attribute, geometry, start, count);
866
+ fingerprintToAccessor.set(fingerprint, accessorIndex);
867
+ return accessorIndex;
868
+ };
869
+ const originalAfterParse = this.afterParse.bind(this);
870
+ this.afterParse = (input) => {
871
+ originalAfterParse(input);
872
+ console.log(`[MToonAtlasExporterPlugin] processAccessor cache: ${cacheHits}/${totalCalls} hits (${fingerprintToAccessor.size} unique)`);
873
+ };
874
+ }
875
+ /**
876
+ * マテリアルのテクスチャを処理してインデックスを保存
877
+ * 非同期でBINチャンクに書き込み、完了後にtextureIndicesに格納
878
+ */
879
+ processTexturesForMaterial(material) {
880
+ const pendingIndices = {
881
+ parameterTextureIndex: null,
882
+ atlasedTextureIndices: {}
883
+ };
884
+ if (material.parameterTexture?.texture) {
885
+ pendingIndices.parameterTextureIndex = this.processParameterTextureWithCache(
886
+ material.parameterTexture.texture
887
+ );
888
+ }
889
+ const atlasedTextures = material.parameterTexture?.atlasedTextures;
890
+ if (atlasedTextures) {
891
+ for (const [key, texture] of Object.entries(atlasedTextures)) {
892
+ if (texture) {
893
+ pendingIndices.atlasedTextureIndices[key] = this.processTextureWithCache(texture);
894
+ }
895
+ }
896
+ }
897
+ this.pendingTextureIndices.set(material, pendingIndices);
898
+ const allPromises = [];
899
+ if (pendingIndices.parameterTextureIndex) {
900
+ allPromises.push(pendingIndices.parameterTextureIndex.then(() => {
901
+ }));
902
+ }
903
+ for (const promise of Object.values(pendingIndices.atlasedTextureIndices)) {
904
+ allPromises.push(promise.then(() => {
905
+ }));
906
+ }
907
+ const resolveAllPromise = Promise.all(allPromises).then(async () => {
908
+ const resolvedIndices = {
909
+ parameterTextureIndex: pendingIndices.parameterTextureIndex ? await pendingIndices.parameterTextureIndex : -1,
910
+ atlasedTextureIndices: {}
911
+ };
912
+ for (const [key, promise] of Object.entries(pendingIndices.atlasedTextureIndices)) {
913
+ resolvedIndices.atlasedTextureIndices[key] = await promise;
914
+ }
915
+ this.textureIndices.set(material, resolvedIndices);
916
+ });
917
+ pendingIndices.resolvePromise = resolveAllPromise;
918
+ this.writer.pending.push(resolveAllPromise);
919
+ }
920
+ /**
921
+ * パラメータテクスチャをキャッシュ付きで処理
922
+ * 同じUUIDのテクスチャは1回だけ処理される
923
+ */
924
+ processParameterTextureWithCache(texture) {
925
+ const uuid = texture.uuid;
926
+ const cached = this.textureCache.get(uuid);
927
+ if (cached) {
928
+ return cached;
929
+ }
930
+ const promise = this.processParameterTexture(texture);
931
+ this.textureCache.set(uuid, promise);
932
+ return promise;
933
+ }
934
+ /**
935
+ * 通常テクスチャをキャッシュ付きで処理
936
+ * 同じUUIDのテクスチャは1回だけ処理される
937
+ */
938
+ processTextureWithCache(texture) {
939
+ const uuid = texture.uuid;
940
+ const cached = this.textureCache.get(uuid);
941
+ if (cached) {
942
+ return cached;
943
+ }
944
+ const promise = this.processTextureWithFallback(texture);
945
+ this.textureCache.set(uuid, promise);
946
+ return promise;
947
+ }
948
+ /**
949
+ * パラメータテクスチャを処理(BINチャンクに書き込み)
950
+ * Canvas 2DのPremultiplied Alpha問題を回避するため、
951
+ * 生のRGBAデータから直接PNGを生成してBINチャンクに格納
952
+ */
953
+ processParameterTexture(texture) {
954
+ const json = this.writer.json;
955
+ json.textures = json.textures || [];
956
+ json.images = json.images || [];
957
+ json.samplers = json.samplers || [];
958
+ let nearestSamplerIndex = json.samplers.findIndex(
959
+ (s) => s.magFilter === 9728 && s.minFilter === 9728
960
+ );
961
+ if (nearestSamplerIndex === -1) {
962
+ nearestSamplerIndex = json.samplers.length;
963
+ json.samplers.push({
964
+ magFilter: 9728,
965
+ // NEAREST
966
+ minFilter: 9728,
967
+ // NEAREST
968
+ wrapS: 33071,
969
+ // CLAMP_TO_EDGE
970
+ wrapT: 33071
971
+ // CLAMP_TO_EDGE
972
+ });
973
+ }
974
+ const imageIndex = json.images.length;
975
+ const imageDef = {
976
+ name: texture.name || "parameterTexture",
977
+ mimeType: "image/png"
978
+ };
979
+ json.images.push(imageDef);
980
+ const textureIndex = json.textures.length;
981
+ json.textures.push({
982
+ sampler: nearestSamplerIndex,
983
+ source: imageIndex,
984
+ name: texture.name || "parameterTexture"
985
+ });
986
+ const image = texture.image;
987
+ if (image?.data && image.width && image.height) {
988
+ const srcData = image.data;
989
+ const isFloatData = srcData instanceof Float32Array || srcData.constructor?.name === "Float32Array";
990
+ const pixelCount = image.width * image.height * 4;
991
+ const uint16Data = new Uint16Array(pixelCount);
992
+ for (let i = 0; i < pixelCount; i++) {
993
+ const value = srcData[i];
994
+ uint16Data[i] = isFloatData ? Math.round(Math.min(1, Math.max(0, value)) * 65535) : value * 257;
995
+ }
996
+ const pngData = encodePng16({
997
+ width: image.width,
998
+ height: image.height,
999
+ depth: 16,
1000
+ channels: 4,
1001
+ data: uint16Data
1002
+ });
1003
+ const blob = new Blob([pngData.buffer], { type: "image/png" });
1004
+ const bufferViewPromise = this.writer.processBufferViewImage(blob).then((bufferViewIndex) => {
1005
+ imageDef.bufferView = bufferViewIndex;
1006
+ return textureIndex;
1007
+ });
1008
+ this.writer.pending.push(bufferViewPromise.then(() => {
1009
+ }));
1010
+ return bufferViewPromise;
1011
+ } else {
1012
+ console.warn("MToonAtlasExporterPlugin: Parameter texture has no valid data");
1013
+ const placeholder = new Uint8Array([
1014
+ 137,
1015
+ 80,
1016
+ 78,
1017
+ 71,
1018
+ 13,
1019
+ 10,
1020
+ 26,
1021
+ 10,
1022
+ // PNG signature
1023
+ 0,
1024
+ 0,
1025
+ 0,
1026
+ 13,
1027
+ 73,
1028
+ 72,
1029
+ 68,
1030
+ 82,
1031
+ // IHDR chunk
1032
+ 0,
1033
+ 0,
1034
+ 0,
1035
+ 1,
1036
+ 0,
1037
+ 0,
1038
+ 0,
1039
+ 1,
1040
+ 8,
1041
+ 6,
1042
+ 0,
1043
+ 0,
1044
+ 0,
1045
+ 31,
1046
+ 21,
1047
+ 196,
1048
+ 137,
1049
+ 0,
1050
+ 0,
1051
+ 0,
1052
+ 10,
1053
+ 73,
1054
+ 68,
1055
+ 65,
1056
+ 84,
1057
+ 120,
1058
+ 156,
1059
+ 99,
1060
+ 0,
1061
+ 1,
1062
+ 0,
1063
+ 0,
1064
+ 5,
1065
+ 0,
1066
+ 1,
1067
+ 13,
1068
+ 10,
1069
+ 45,
1070
+ 180,
1071
+ 0,
1072
+ 0,
1073
+ 0,
1074
+ 0,
1075
+ 73,
1076
+ 69,
1077
+ 78,
1078
+ 68,
1079
+ 174,
1080
+ 66,
1081
+ 96,
1082
+ 130
1083
+ ]);
1084
+ const blob = new Blob([placeholder], { type: "image/png" });
1085
+ const bufferViewPromise = this.writer.processBufferViewImage(blob).then((bufferViewIndex) => {
1086
+ imageDef.bufferView = bufferViewIndex;
1087
+ return textureIndex;
1088
+ });
1089
+ this.writer.pending.push(bufferViewPromise.then(() => {
1090
+ }));
1091
+ return bufferViewPromise;
1092
+ }
1093
+ }
1094
+ /**
1095
+ * テクスチャを処理してBINチャンクに書き込む
1096
+ * @param texture - 処理するテクスチャ
1097
+ *
1098
+ * 注: writer.processTextureは使用しない。
1099
+ * GLTFExporter内部でテクスチャがキャッシュされないため、
1100
+ * 同じテクスチャオブジェクトでも毎回新しいエントリが作成されてしまう。
1101
+ * 代わりに手動でテクスチャを登録することで、キャッシュを正しく機能させる。
1102
+ */
1103
+ processTextureWithFallback(texture) {
1104
+ if (this.textureCompressionOptions) {
1105
+ return this.processTextureAsKtx2(texture);
1106
+ }
1107
+ return this.processTextureAsPng(texture);
1108
+ }
1109
+ /**
1110
+ * テクスチャを KTX2 形式で処理してBINチャンクに書き込む
1111
+ * @param texture - 処理するテクスチャ
1112
+ */
1113
+ processTextureAsKtx2(texture) {
1114
+ const json = this.writer.json;
1115
+ json.textures = json.textures || [];
1116
+ json.images = json.images || [];
1117
+ json.samplers = json.samplers || [];
1118
+ let linearSamplerIndex = json.samplers.findIndex(
1119
+ (s) => s.magFilter === 9729 && s.minFilter === 9987
1120
+ );
1121
+ if (linearSamplerIndex === -1) {
1122
+ linearSamplerIndex = json.samplers.length;
1123
+ json.samplers.push({
1124
+ magFilter: 9729,
1125
+ // LINEAR
1126
+ minFilter: 9987,
1127
+ // LINEAR_MIPMAP_LINEAR
1128
+ wrapS: 10497,
1129
+ // REPEAT
1130
+ wrapT: 10497
1131
+ // REPEAT
1132
+ });
1133
+ }
1134
+ const imageIndex = json.images.length;
1135
+ const imageDef = {
1136
+ name: texture.name || "texture",
1137
+ mimeType: "image/ktx2"
1138
+ };
1139
+ json.images.push(imageDef);
1140
+ const textureIndex = json.textures.length;
1141
+ json.textures.push({
1142
+ sampler: linearSamplerIndex,
1143
+ source: imageIndex,
1144
+ name: texture.name || "texture",
1145
+ extensions: {
1146
+ KHR_texture_basisu: {
1147
+ source: imageIndex
1148
+ }
1149
+ }
1150
+ });
1151
+ json.extensionsUsed = json.extensionsUsed || [];
1152
+ if (!json.extensionsUsed.includes("KHR_texture_basisu")) {
1153
+ json.extensionsUsed.push("KHR_texture_basisu");
1154
+ }
1155
+ const bufferViewPromise = this.compressTextureToKtx2(texture).then(async (ktx2Data) => {
1156
+ const arrayCopy = new Uint8Array(ktx2Data).buffer;
1157
+ const blob = new Blob([arrayCopy], { type: "image/ktx2" });
1158
+ const bufferViewIndex = await this.writer.processBufferViewImage(blob);
1159
+ imageDef.bufferView = bufferViewIndex;
1160
+ return textureIndex;
1161
+ });
1162
+ this.writer.pending.push(bufferViewPromise.then(() => {
1163
+ }));
1164
+ return bufferViewPromise;
1165
+ }
1166
+ /**
1167
+ * テクスチャを KTX2 バイナリに圧縮
1168
+ * @param texture - 処理するテクスチャ
1169
+ * @returns KTX2 バイナリデータ
1170
+ */
1171
+ async compressTextureToKtx2(texture) {
1172
+ const image = texture.image;
1173
+ if (!image) {
1174
+ throw new Error("\u30C6\u30AF\u30B9\u30C1\u30E3\u306B\u6709\u52B9\u306A\u753B\u50CF\u30C7\u30FC\u30BF\u304C\u3042\u308A\u307E\u305B\u3093");
1175
+ }
1176
+ const width = image.width;
1177
+ const height = image.height;
1178
+ if (!width || !height) {
1179
+ throw new Error("\u30C6\u30AF\u30B9\u30C1\u30E3\u306E\u753B\u50CF\u30B5\u30A4\u30BA\u304C\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093");
1180
+ }
1181
+ const rgbaData = await this.extractRgbaData(image);
1182
+ const pixelCount = width * height * 4;
1183
+ if (rgbaData.length !== pixelCount) {
1184
+ throw new Error(`\u753B\u50CF\u30C7\u30FC\u30BF\u30B5\u30A4\u30BA\u304C\u4E0D\u6B63: expected ${pixelCount}, got ${rgbaData.length}`);
1185
+ }
1186
+ const compressionOptions = {
1187
+ quality: this.textureCompressionOptions?.quality,
1188
+ compressionLevel: this.textureCompressionOptions?.compressionLevel,
1189
+ generateMipmaps: this.textureCompressionOptions?.generateMipmaps,
1190
+ supercompression: this.textureCompressionOptions?.supercompression
1191
+ };
1192
+ const result = await compressToKtx2(
1193
+ rgbaData,
1194
+ width,
1195
+ height,
1196
+ compressionOptions
1197
+ );
1198
+ if (result.isErr()) {
1199
+ throw new Error(`KTX2\u5727\u7E2E\u306B\u5931\u6557: ${result.error.message}`);
1200
+ }
1201
+ return result.value.data;
1202
+ }
1203
+ /**
1204
+ * 様々な画像形式からRGBAデータを抽出
1205
+ * @param image - 画像データ(DataTexture, HTMLImageElement, ImageBitmap, HTMLCanvasElement等)
1206
+ * @returns RGBA形式のUint8Array
1207
+ */
1208
+ async extractRgbaData(image) {
1209
+ if (image.data && image.width && image.height) {
1210
+ const srcData = image.data;
1211
+ const isFloatData = srcData instanceof Float32Array || srcData.constructor?.name === "Float32Array";
1212
+ const pixelCount = image.width * image.height * 4;
1213
+ if (isFloatData) {
1214
+ const rgbaData = new Uint8Array(pixelCount);
1215
+ for (let i = 0; i < pixelCount; i++) {
1216
+ rgbaData[i] = Math.round(Math.min(1, Math.max(0, srcData[i])) * 255);
1217
+ }
1218
+ return rgbaData;
1219
+ } else {
1220
+ return new Uint8Array(srcData);
1221
+ }
1222
+ }
1223
+ if (image instanceof HTMLCanvasElement) {
1224
+ const ctx = image.getContext("2d");
1225
+ if (ctx) {
1226
+ const imageData = ctx.getImageData(0, 0, image.width, image.height);
1227
+ return new Uint8Array(imageData.data);
1228
+ }
1229
+ }
1230
+ if (image instanceof HTMLImageElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
1231
+ const canvas = document.createElement("canvas");
1232
+ canvas.width = image.width;
1233
+ canvas.height = image.height;
1234
+ const ctx = canvas.getContext("2d");
1235
+ if (ctx) {
1236
+ ctx.drawImage(image, 0, 0);
1237
+ const imageData = ctx.getImageData(0, 0, image.width, image.height);
1238
+ return new Uint8Array(imageData.data);
1239
+ }
1240
+ }
1241
+ if (typeof image.toDataURL === "function") {
1242
+ return new Promise((resolve, reject) => {
1243
+ const dataUrl = image.toDataURL("image/png");
1244
+ const img = new Image();
1245
+ img.onload = () => {
1246
+ const canvas = document.createElement("canvas");
1247
+ canvas.width = img.width;
1248
+ canvas.height = img.height;
1249
+ const ctx = canvas.getContext("2d");
1250
+ if (ctx) {
1251
+ ctx.drawImage(img, 0, 0);
1252
+ const imageData = ctx.getImageData(0, 0, img.width, img.height);
1253
+ resolve(new Uint8Array(imageData.data));
1254
+ } else {
1255
+ reject(new Error("Canvas 2D context\u53D6\u5F97\u306B\u5931\u6557"));
1256
+ }
1257
+ };
1258
+ img.onerror = () => reject(new Error("\u753B\u50CF\u306E\u30ED\u30FC\u30C9\u306B\u5931\u6557"));
1259
+ img.src = dataUrl;
1260
+ });
1261
+ }
1262
+ throw new Error("\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u306A\u3044\u753B\u50CF\u5F62\u5F0F\u3067\u3059");
1263
+ }
1264
+ /**
1265
+ * テクスチャを PNG 形式で処理してBINチャンクに書き込む(従来の処理)
1266
+ * @param texture - 処理するテクスチャ
1267
+ */
1268
+ processTextureAsPng(texture) {
1269
+ const json = this.writer.json;
1270
+ json.textures = json.textures || [];
1271
+ json.images = json.images || [];
1272
+ json.samplers = json.samplers || [];
1273
+ let linearSamplerIndex = json.samplers.findIndex(
1274
+ (s) => s.magFilter === 9729 && s.minFilter === 9987
1275
+ );
1276
+ if (linearSamplerIndex === -1) {
1277
+ linearSamplerIndex = json.samplers.length;
1278
+ json.samplers.push({
1279
+ magFilter: 9729,
1280
+ // LINEAR
1281
+ minFilter: 9987,
1282
+ // LINEAR_MIPMAP_LINEAR
1283
+ wrapS: 10497,
1284
+ // REPEAT
1285
+ wrapT: 10497
1286
+ // REPEAT
1287
+ });
1288
+ }
1289
+ const imageIndex = json.images.length;
1290
+ const imageDef = {
1291
+ name: texture.name || "texture",
1292
+ mimeType: "image/png"
1293
+ };
1294
+ json.images.push(imageDef);
1295
+ const textureIndex = json.textures.length;
1296
+ json.textures.push({
1297
+ sampler: linearSamplerIndex,
1298
+ source: imageIndex,
1299
+ name: texture.name || "texture"
1300
+ });
1301
+ const image = texture.image;
1302
+ const blobPromise = this.imageToBlobAsync(image);
1303
+ const bufferViewPromise = blobPromise.then((blob) => this.writer.processBufferViewImage(blob)).then((bufferViewIndex) => {
1304
+ imageDef.bufferView = bufferViewIndex;
1305
+ return textureIndex;
1306
+ });
1307
+ this.writer.pending.push(bufferViewPromise.then(() => {
1308
+ }));
1309
+ return bufferViewPromise;
1310
+ }
1311
+ /**
1312
+ * 画像をBlobに変換する(非同期)
1313
+ */
1314
+ async imageToBlobAsync(image) {
1315
+ if (!image) {
1316
+ console.warn("MToonAtlasExporterPlugin: Texture has no image, using placeholder");
1317
+ return this.createPlaceholderBlob();
1318
+ }
1319
+ if (image instanceof HTMLCanvasElement) {
1320
+ return new Promise((resolve) => {
1321
+ image.toBlob((blob) => {
1322
+ resolve(blob || this.createPlaceholderBlob());
1323
+ }, "image/png");
1324
+ });
1325
+ }
1326
+ if (image instanceof ImageBitmap || image instanceof HTMLImageElement) {
1327
+ const canvas = document.createElement("canvas");
1328
+ canvas.width = image.width;
1329
+ canvas.height = image.height;
1330
+ const ctx = canvas.getContext("2d");
1331
+ if (ctx) {
1332
+ ctx.drawImage(image, 0, 0);
1333
+ return new Promise((resolve) => {
1334
+ canvas.toBlob((blob) => {
1335
+ resolve(blob || this.createPlaceholderBlob());
1336
+ }, "image/png");
1337
+ });
1338
+ }
1339
+ }
1340
+ if (image.data && image.width && image.height) {
1341
+ const canvas = document.createElement("canvas");
1342
+ canvas.width = image.width;
1343
+ canvas.height = image.height;
1344
+ const ctx = canvas.getContext("2d");
1345
+ if (ctx) {
1346
+ const srcData = image.data;
1347
+ const isFloatData = srcData instanceof Float32Array || srcData.constructor?.name === "Float32Array";
1348
+ const pixelCount = image.width * image.height * 4;
1349
+ const uint8Data = new Uint8ClampedArray(pixelCount);
1350
+ for (let i = 0; i < pixelCount; i++) {
1351
+ const value = srcData[i];
1352
+ uint8Data[i] = isFloatData ? Math.round(Math.min(1, Math.max(0, value)) * 255) : value;
1353
+ }
1354
+ const imageData = new ImageData(uint8Data, image.width, image.height);
1355
+ ctx.putImageData(imageData, 0, 0);
1356
+ return new Promise((resolve) => {
1357
+ canvas.toBlob((blob) => {
1358
+ resolve(blob || this.createPlaceholderBlob());
1359
+ }, "image/png");
1360
+ });
1361
+ }
1362
+ }
1363
+ if (typeof image.toDataURL === "function") {
1364
+ const dataUrl = image.toDataURL("image/png");
1365
+ const base64 = dataUrl.split(",")[1];
1366
+ const binary = atob(base64);
1367
+ const bytes = new Uint8Array(binary.length);
1368
+ for (let i = 0; i < binary.length; i++) {
1369
+ bytes[i] = binary.charCodeAt(i);
1370
+ }
1371
+ return new Blob([bytes], { type: "image/png" });
1372
+ }
1373
+ console.warn("MToonAtlasExporterPlugin: Could not convert texture image, using placeholder");
1374
+ return this.createPlaceholderBlob();
1375
+ }
1376
+ /**
1377
+ * 1x1透明プレースホルダーBlob作成
1378
+ */
1379
+ createPlaceholderBlob() {
1380
+ const placeholder = new Uint8Array([
1381
+ 137,
1382
+ 80,
1383
+ 78,
1384
+ 71,
1385
+ 13,
1386
+ 10,
1387
+ 26,
1388
+ 10,
1389
+ 0,
1390
+ 0,
1391
+ 0,
1392
+ 13,
1393
+ 73,
1394
+ 72,
1395
+ 68,
1396
+ 82,
1397
+ 0,
1398
+ 0,
1399
+ 0,
1400
+ 1,
1401
+ 0,
1402
+ 0,
1403
+ 0,
1404
+ 1,
1405
+ 8,
1406
+ 6,
1407
+ 0,
1408
+ 0,
1409
+ 0,
1410
+ 31,
1411
+ 21,
1412
+ 196,
1413
+ 137,
1414
+ 0,
1415
+ 0,
1416
+ 0,
1417
+ 10,
1418
+ 73,
1419
+ 68,
1420
+ 65,
1421
+ 84,
1422
+ 120,
1423
+ 156,
1424
+ 99,
1425
+ 0,
1426
+ 1,
1427
+ 0,
1428
+ 0,
1429
+ 5,
1430
+ 0,
1431
+ 1,
1432
+ 13,
1433
+ 10,
1434
+ 45,
1435
+ 180,
1436
+ 0,
1437
+ 0,
1438
+ 0,
1439
+ 0,
1440
+ 73,
1441
+ 69,
1442
+ 78,
1443
+ 68,
1444
+ 174,
1445
+ 66,
1446
+ 96,
1447
+ 130
1448
+ ]);
1449
+ return new Blob([placeholder], { type: "image/png" });
1450
+ }
1451
+ /**
1452
+ * afterParseでマテリアルとメッシュのプリミティブ属性をJSONに追加
1453
+ *
1454
+ * GLTFExporterはShaderMaterialをスキップするため、
1455
+ * ここで手動でマテリアル定義を追加します。
1456
+ *
1457
+ * 注: テクスチャ処理のPromiseはwriter.pendingに追加済みなので、
1458
+ * afterParse完了後にGLTFExporterがawait Promise.all(pending)で待機する。
1459
+ * マテリアル定義内のテクスチャインデックスは、pendingのPromise内で更新される。
1460
+ */
1461
+ afterParse(_input) {
1462
+ if (this.mtoonAtlasMeshes.size === 0) return;
1463
+ const json = this.writer.json;
1464
+ const materialIndexMap = /* @__PURE__ */ new Map();
1465
+ const materialDefMap = /* @__PURE__ */ new Map();
1466
+ for (const [mesh, materials] of this.mtoonAtlasMeshes) {
1467
+ for (const material of materials) {
1468
+ if (materialIndexMap.has(material)) continue;
1469
+ const materialDef = this.createMaterialDef(material);
1470
+ json.materials = json.materials || [];
1471
+ const materialIndex = json.materials.length;
1472
+ json.materials.push(materialDef);
1473
+ materialIndexMap.set(material, materialIndex);
1474
+ materialDefMap.set(material, materialDef);
1475
+ }
1476
+ this.updateMeshPrimitive(mesh, materials, materialIndexMap);
1477
+ }
1478
+ json.extensionsUsed = json.extensionsUsed || [];
1479
+ if (!json.extensionsUsed.includes(MTOON_ATLAS_EXTENSION_NAME)) {
1480
+ json.extensionsUsed.push(MTOON_ATLAS_EXTENSION_NAME);
1481
+ }
1482
+ const updateMaterialDefsPromise = this.waitForAllTextureIndices().then(() => {
1483
+ for (const [material, materialDef] of materialDefMap) {
1484
+ const indices = this.textureIndices.get(material);
1485
+ if (indices) {
1486
+ const extension = materialDef.extensions[MTOON_ATLAS_EXTENSION_NAME];
1487
+ if (extension.parameterTexture) {
1488
+ extension.parameterTexture.index = indices.parameterTextureIndex;
1489
+ }
1490
+ for (const [key, index] of Object.entries(indices.atlasedTextureIndices)) {
1491
+ extension.atlasedTextures[key] = { index };
1492
+ }
1493
+ }
1494
+ }
1495
+ });
1496
+ this.writer.pending.push(updateMaterialDefsPromise);
1497
+ }
1498
+ /**
1499
+ * 全てのテクスチャインデックスが解決され、textureIndicesに登録されるのを待つ
1500
+ */
1501
+ async waitForAllTextureIndices() {
1502
+ const allPromises = [];
1503
+ for (const pending of this.pendingTextureIndices.values()) {
1504
+ const resolvePromise = pending.resolvePromise;
1505
+ if (resolvePromise) {
1506
+ allPromises.push(resolvePromise);
1507
+ }
1508
+ }
1509
+ await Promise.all(allPromises);
1510
+ }
1511
+ /**
1512
+ * MToonAtlasMaterialからGLTFマテリアル定義を作成
1513
+ */
1514
+ createMaterialDef(material) {
1515
+ const indices = this.textureIndices.get(material);
1516
+ const extension = {
1517
+ version: "1.0",
1518
+ parameterTexture: {
1519
+ index: indices?.parameterTextureIndex ?? -1,
1520
+ texelsPerSlot: material.parameterTexture?.texelsPerSlot ?? 9,
1521
+ slotCount: material.parameterTexture?.slotCount ?? 0
1522
+ },
1523
+ slotAttributeName: "_MTOON_MATERIAL_SLOT",
1524
+ atlasedTextures: {}
1525
+ };
1526
+ if (material.isOutline) {
1527
+ extension.isOutline = true;
1528
+ }
1529
+ if (material.outlineWidthMode && material.outlineWidthMode !== "none") {
1530
+ extension.outlineWidthMode = material.outlineWidthMode;
1531
+ }
1532
+ if (indices?.atlasedTextureIndices) {
1533
+ for (const [key, index] of Object.entries(indices.atlasedTextureIndices)) {
1534
+ ;
1535
+ extension.atlasedTextures[key] = { index };
1536
+ }
1537
+ }
1538
+ const materialDef = {
1539
+ name: material.name || "MToonAtlasMaterial",
1540
+ pbrMetallicRoughness: {
1541
+ baseColorFactor: [1, 1, 1, 1],
1542
+ metallicFactor: 0,
1543
+ roughnessFactor: 1
1544
+ },
1545
+ doubleSided: material.side === 2,
1546
+ // THREE.DoubleSide
1547
+ extensions: {
1548
+ [MTOON_ATLAS_EXTENSION_NAME]: extension
1549
+ }
1550
+ };
1551
+ if (material.transparent) {
1552
+ materialDef.alphaMode = "BLEND";
1553
+ } else if (material.alphaTest > 0) {
1554
+ materialDef.alphaMode = "MASK";
1555
+ materialDef.alphaCutoff = material.alphaTest;
1556
+ }
1557
+ return materialDef;
1558
+ }
1559
+ /**
1560
+ * メッシュのプリミティブにマテリアルとスロット属性を設定
1561
+ */
1562
+ updateMeshPrimitive(mesh, materials, materialIndexMap) {
1563
+ const json = this.writer.json;
1564
+ const nodeIndex = this.writer.nodeMap?.get(mesh);
1565
+ if (nodeIndex === void 0) return;
1566
+ const nodeDef = json.nodes?.[nodeIndex];
1567
+ if (!nodeDef || nodeDef.mesh === void 0) return;
1568
+ const meshDef = json.meshes?.[nodeDef.mesh];
1569
+ if (!meshDef?.primitives) return;
1570
+ const material = materials[0];
1571
+ const materialIndex = materialIndexMap.get(material);
1572
+ if (materialIndex === void 0) return;
1573
+ for (const primitive of meshDef.primitives) {
1574
+ primitive.material = materialIndex;
1575
+ if (primitive.attributes["_MTOON_MATERIAL_SLOT"] === void 0) {
1576
+ const attributeName = "mtoon_material_slot";
1577
+ this.addSlotAttribute(primitive, mesh, attributeName);
1578
+ }
1579
+ }
1580
+ }
1581
+ /**
1582
+ * スロット属性をプリミティブに追加
1583
+ */
1584
+ addSlotAttribute(primitive, mesh, attributeName) {
1585
+ const attribute = mesh.geometry.getAttribute(attributeName);
1586
+ if (!attribute) return;
1587
+ if (typeof this.writer.processAccessor === "function") {
1588
+ try {
1589
+ const accessorIndex2 = this.writer.processAccessor(attribute, mesh.geometry);
1590
+ primitive.attributes["_MTOON_MATERIAL_SLOT"] = accessorIndex2;
1591
+ return;
1592
+ } catch {
1593
+ }
1594
+ }
1595
+ const json = this.writer.json;
1596
+ json.accessors = json.accessors || [];
1597
+ json.bufferViews = json.bufferViews || [];
1598
+ json.buffers = json.buffers || [];
1599
+ const array = attribute.array;
1600
+ const byteArray = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
1601
+ let binary = "";
1602
+ for (let i = 0; i < byteArray.length; i++) {
1603
+ binary += String.fromCharCode(byteArray[i]);
1604
+ }
1605
+ const base64 = btoa(binary);
1606
+ const dataUri = `data:application/octet-stream;base64,${base64}`;
1607
+ const bufferIndex = json.buffers.length;
1608
+ json.buffers.push({
1609
+ uri: dataUri,
1610
+ byteLength: byteArray.byteLength
1611
+ });
1612
+ const bufferViewIndex = json.bufferViews.length;
1613
+ json.bufferViews.push({
1614
+ buffer: bufferIndex,
1615
+ byteOffset: 0,
1616
+ byteLength: byteArray.byteLength
1617
+ });
1618
+ const accessorIndex = json.accessors.length;
1619
+ json.accessors.push({
1620
+ bufferView: bufferViewIndex,
1621
+ componentType: 5126,
1622
+ // FLOAT
1623
+ count: attribute.count,
1624
+ type: "SCALAR"
1625
+ });
1626
+ primitive.attributes["_MTOON_MATERIAL_SLOT"] = accessorIndex;
1627
+ }
1628
+ };
1629
+ export {
1630
+ MTOON_ATLAS_EXTENSION_NAME,
1631
+ MToonAtlasExporterPlugin,
1632
+ MToonAtlasLoaderPlugin,
1633
+ MToonAtlasMaterial
1634
+ };
1635
+ //# sourceMappingURL=index.js.map