@needle-tools/three-mesh-effects 0.2.2 → 0.3.1

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.
Files changed (100) hide show
  1. package/CHANGELOG.md +28 -6
  2. package/README.md +76 -1
  3. package/SKILL.md +9 -1
  4. package/build/box-impostor-runtime.js +1298 -0
  5. package/build/box-impostor-runtime.js.map +7 -0
  6. package/build/deformation-runtime.js +85 -31
  7. package/build/deformation-runtime.js.map +4 -4
  8. package/build/hull-effects.js +60 -28
  9. package/build/hull-effects.js.map +3 -3
  10. package/build/impostor-runtime.js +235 -116
  11. package/build/impostor-runtime.js.map +4 -4
  12. package/build/index.js +4 -0
  13. package/build/index.js.map +2 -2
  14. package/build/internal/box-impostor/box-impostor-display-settings.js +50 -0
  15. package/build/internal/box-impostor/box-impostor-display-settings.js.map +7 -0
  16. package/build/internal/box-impostor/box-impostor-display.js +1005 -0
  17. package/build/internal/box-impostor/box-impostor-display.js.map +7 -0
  18. package/build/internal/box-impostor/box-impostor-face-axes.js +15 -0
  19. package/build/internal/box-impostor/box-impostor-face-axes.js.map +7 -0
  20. package/build/internal/box-impostor/box-impostor-faces.js +125 -0
  21. package/build/internal/box-impostor/box-impostor-faces.js.map +7 -0
  22. package/build/internal/box-impostor/box-impostor-geometry.js +230 -0
  23. package/build/internal/box-impostor/box-impostor-geometry.js.map +7 -0
  24. package/build/internal/box-impostor/box-impostor-material.js +964 -0
  25. package/build/internal/box-impostor/box-impostor-material.js.map +7 -0
  26. package/build/internal/box-impostor/box-impostor-metadata.js +108 -0
  27. package/build/internal/box-impostor/box-impostor-metadata.js.map +7 -0
  28. package/build/internal/box-impostor/box-impostor-projection.js +256 -0
  29. package/build/internal/box-impostor/box-impostor-projection.js.map +7 -0
  30. package/build/internal/box-impostor/box-impostor-runtime.js +1252 -0
  31. package/build/internal/box-impostor/box-impostor-runtime.js.map +7 -0
  32. package/build/internal/box-impostor/box-impostor-surface-search.js +21 -0
  33. package/build/internal/box-impostor/box-impostor-surface-search.js.map +7 -0
  34. package/build/internal/deformation/cloth-surface.js +23 -17
  35. package/build/internal/deformation/cloth-surface.js.map +3 -3
  36. package/build/internal/deformation/fur-surface.js +55 -12
  37. package/build/internal/deformation/fur-surface.js.map +3 -3
  38. package/build/internal/deformation/pin-cloth.js +7 -2
  39. package/build/internal/deformation/pin-cloth.js.map +2 -2
  40. package/build/internal/deformation/rig-runtime.js +85 -31
  41. package/build/internal/deformation/rig-runtime.js.map +4 -4
  42. package/build/internal/impostor/impostor-node-material.js +235 -116
  43. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  44. package/build/internal/rendering/hull-effect-runtime.js +59 -27
  45. package/build/internal/rendering/hull-effect-runtime.js.map +3 -3
  46. package/build/internal/rendering/texture-slot.js +26 -0
  47. package/build/internal/rendering/texture-slot.js.map +7 -0
  48. package/build/internal/rendering/wireframe.js +41 -9
  49. package/build/internal/rendering/wireframe.js.map +2 -2
  50. package/build/internal/rendering/wrap-preview.js +59 -27
  51. package/build/internal/rendering/wrap-preview.js.map +3 -3
  52. package/build/types/box-impostor/box-impostor-display-settings.d.ts +30 -0
  53. package/build/types/box-impostor/box-impostor-display-settings.js +1 -0
  54. package/build/types/box-impostor/box-impostor-display.d.ts +5 -0
  55. package/build/types/box-impostor/box-impostor-display.js +1 -0
  56. package/build/types/box-impostor/box-impostor-face-axes.d.ts +5 -0
  57. package/build/types/box-impostor/box-impostor-face-axes.js +1 -0
  58. package/build/types/box-impostor/box-impostor-faces.d.ts +11 -0
  59. package/build/types/box-impostor/box-impostor-faces.js +1 -0
  60. package/build/types/box-impostor/box-impostor-geometry.d.ts +5 -0
  61. package/build/types/box-impostor/box-impostor-geometry.js +1 -0
  62. package/build/types/box-impostor/box-impostor-material.d.ts +10 -0
  63. package/build/types/box-impostor/box-impostor-material.js +1 -0
  64. package/build/types/box-impostor/box-impostor-metadata.d.ts +31 -0
  65. package/build/types/box-impostor/box-impostor-metadata.js +1 -0
  66. package/build/types/box-impostor/box-impostor-projection.d.ts +19 -0
  67. package/build/types/box-impostor/box-impostor-projection.js +1 -0
  68. package/build/types/box-impostor/box-impostor-runtime.d.ts +25 -0
  69. package/build/types/box-impostor/box-impostor-runtime.js +1 -0
  70. package/build/types/box-impostor/box-impostor-surface-search.d.ts +13 -0
  71. package/build/types/box-impostor/box-impostor-surface-search.js +1 -0
  72. package/build/types/deformation/cloth-surface.d.ts +1 -0
  73. package/build/types/deformation/pin-cloth.d.ts +1 -0
  74. package/build/types/public/box-impostor-runtime.d.ts +6 -0
  75. package/build/types/public/box-impostor-runtime.js +1 -0
  76. package/build/types/public/hull-effects.d.ts +1 -0
  77. package/build/types/public/index.d.ts +1 -1
  78. package/build/types/rendering/texture-slot.d.ts +10 -0
  79. package/build/types/rendering/texture-slot.js +1 -0
  80. package/build/types/rendering/wireframe.d.ts +2 -2
  81. package/package.json +27 -6
  82. package/src/box-impostor/box-impostor-display-settings.js +54 -0
  83. package/src/box-impostor/box-impostor-display.js +38 -0
  84. package/src/box-impostor/box-impostor-face-axes.js +11 -0
  85. package/src/box-impostor/box-impostor-faces.js +118 -0
  86. package/src/box-impostor/box-impostor-geometry.js +140 -0
  87. package/src/box-impostor/box-impostor-material.js +721 -0
  88. package/src/box-impostor/box-impostor-metadata.js +122 -0
  89. package/src/box-impostor/box-impostor-projection.js +287 -0
  90. package/src/box-impostor/box-impostor-runtime.js +122 -0
  91. package/src/box-impostor/box-impostor-surface-search.js +11 -0
  92. package/src/deformation/cloth-surface.ts +28 -17
  93. package/src/deformation/fur-surface.ts +22 -12
  94. package/src/deformation/pin-cloth.ts +9 -3
  95. package/src/impostor/impostor-node-material.js +238 -150
  96. package/src/public/box-impostor-runtime.js +14 -0
  97. package/src/public/hull-effects.js +1 -0
  98. package/src/public/index.js +5 -1
  99. package/src/rendering/texture-slot.js +27 -0
  100. package/src/rendering/wireframe.js +51 -13
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/deformation/fur-surface.ts"],
4
- "sourcesContent": ["import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';\nimport { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';\nimport { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';\nimport type { RigDescriptor } from './rig-extension.js';\n\ninterface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }\n\n/** Optional GPU detail for a portable skinned GLB. Nothing is written into its\n * fallback material or geometry, and the variant is absent without Fur pins. */\nexport class FurSurface {\n readonly surfaces: Surface[] = [];\n private height: Texture | null = null;\n private clock = uniform(0);\n private wind = uniform(0);\n\n constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {\n const depth = new Map<Object3D, number>();\n descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));\n descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {\n const index = descriptor.joints.findIndex(joint => joint.node === influence.node);\n const pin = descriptor.pins[index];\n return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);\n }, 0)));\n scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');\n if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;\n if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;\n const values = new Float32Array(indices.count);\n for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {\n values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);\n }\n if (!values.some(value => value > 1e-5)) return;\n const modified = geometry.clone();\n modified.setAttribute('furDepth', new BufferAttribute(values, 1));\n const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };\n object.geometry = modified;\n this.surfaces.push(surface);\n });\n this.rebuild();\n }\n\n setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }\n update(seconds: number, windStrength: number) {\n this.clock.value += Math.max(0, Math.min(seconds, .1));\n this.wind.value = windStrength;\n }\n /** GLTFExporter must only see standard portable materials and attributes. */\n setPortable(portable: boolean) {\n for (const surface of this.surfaces) {\n surface.mesh.geometry = portable ? surface.geometry : surface.modified;\n surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];\n }\n }\n dispose() {\n this.setPortable(true);\n for (const surface of this.surfaces) {\n surface.modified.dispose(); surface.mesh.geometry = surface.geometry;\n for (const variant of surface.variants) variant.dispose();\n }\n this.surfaces.length = 0;\n }\n private rebuild() {\n for (const surface of this.surfaces) {\n const sources = Array.isArray(surface.material) ? surface.material : [surface.material];\n const variants = sources.map(source => this.material(source as MeshStandardMaterial));\n this.setPortable(true);\n for (const old of surface.variants) old.dispose();\n surface.variants = variants;\n }\n this.setPortable(false);\n }\n private material(source: MeshStandardMaterial) {\n const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();\n material.copy(source);\n material.name = `${source.name || 'Material'} \u00B7 Fur texture motion`;\n const coordinates = uv();\n const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;\n if (!signal) return material;\n const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);\n const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;\n const dimensions = signal.image as { width?: number; height?: number } | undefined;\n const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));\n const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));\n const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(.5);\n const raised = mix(.65, 1.35, height);\n const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));\n const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));\n // A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and\n // opacity aligned. The field follows the skinned surface and can shimmer\n // with wind; height modulates movement rather than drawing synthetic hair.\n const shift = movement.add(gust).mul(depth).mul(raised)\n .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');\n const sample = (map: Texture) => {\n const node = texture(map, uv(map.channel).add(shift));\n node.updateMatrix = true;\n return node;\n };\n const base = source.map ? sample(source.map) : vec4(1);\n material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));\n if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;\n if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap).xyz,\n vec2(source.normalScale.x, source.normalScale.y));\n material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);\n material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);\n if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));\n if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(\n source.emissive.r * source.emissiveIntensity,\n source.emissive.g * source.emissiveIntensity,\n source.emissive.b * source.emissiveIntensity));\n material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };\n return material;\n }\n}\n\n/** Convert the current skin displacement into a local UV offset. The metric\n * inversion avoids assuming that U/V align with world X/Y or have equal scale. */\nfunction projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {\n const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();\n const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();\n const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));\n const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));\n const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);\n const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);\n const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);\n const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);\n const u = movement.dot(dPosDu), v = movement.dot(dPosDv);\n return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));\n}\n"],
5
- "mappings": ";;;AAAA,SAAS,iBAAiB,sBAAsB,sBAAsB,mBAAoF;AAC1J,SAAS,0BAA0B,gCAA2C;AAC9E,SAAS,WAAW,OAAO,KAAK,WAAW,eAAe,SAAS,SAAS,IAAI,SAAS,MAAM,MAAM,YAAY;AAO1G,IAAM,aAAN,MAAiB;AAAA,EACb,WAAsB,CAAC;AAAA,EACxB,SAAyB;AAAA,EACzB,QAAQ,QAAQ,CAAC;AAAA,EACjB,OAAO,QAAQ,CAAC;AAAA,EAExB,YAAY,OAAiB,YAA2B,OAA4B,SAA8B;AAChH,UAAM,QAAQ,oBAAI,IAAsB;AACxC,eAAW,KAAK,QAAQ,CAAC,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,GAAG,IAAI,MAAO,IAAI,YAAY,MAAM,CAAC,CAAC;AAC3F,eAAW,SAAS,QAAQ,CAAC,QAAQ,MAAM,MAAM,IAAI,QAAQ,CAAC,GAAG,OAAO,WAAW,OAAO,CAAC,KAAK,cAAc;AAC5G,YAAM,QAAQ,WAAW,OAAO,UAAU,WAAS,MAAM,SA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,IAAI,MAAM,CAAC,CAAC;AACjE,QAAM,OAAO,YAAY,IAAI,EAAE,IAAI,KAAK,EAAE,IAAI,YAAY,SAAS,CAAC,EAAE,OAAO,IAAI,CAAC,CAAC;AACnF,QAAM,SAAS,OAAO,IAAI,MAAM,CAAC,EAAE,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC,EAAE,IAAI,IAAI;AACpE,QAAM,SAAS,OAAO,IAAI,MAAM,CAAC,EAAE,IAAI,OAAO,IAAI,MAAM,CAAC,CAAC,EAAE,IAAI,IAAI;AACpE,QAAM,KAAK,OAAO,IAAI,MAAM,GAAG,KAAK,OAAO,IAAI,MAAM,GAAG,WAAW,OAAO,IAAI,MAAM;AACpF,QAAM,SAAS,GAAG,IAAI,EAAE,EAAE,IAAI,SAAS,IAAI,QAAQ,CAAC,EAAE,IAAI,KAAK;AAC/D,QAAM,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,SAAS,IAAI,MAAM;AACvD,SAAO,KAAK,GAAG,IAAI,CAAC,EAAE,IAAI,SAAS,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,IAAI,SAAS,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,CAAC;AACpG;",
3
+ "sources": ["../../../src/deformation/fur-surface.ts", "../../../src/rendering/texture-slot.js"],
4
+ "sourcesContent": ["import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, Vector2, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';\nimport { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';\nimport { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';\nimport { bindTextureSlot } from '../rendering/texture-slot.js';\nimport type { RigDescriptor } from './rig-extension.js';\n\ninterface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }\n\n/** Optional GPU detail for a portable skinned GLB. Nothing is written into its\n * fallback material or geometry, and the variant is absent without Fur pins. */\nexport class FurSurface {\n readonly surfaces: Surface[] = [];\n private height: Texture | null = null;\n private clock = uniform(0);\n private wind = uniform(0);\n\n constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {\n const depth = new Map<Object3D, number>();\n descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));\n descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {\n const index = descriptor.joints.findIndex(joint => joint.node === influence.node);\n const pin = descriptor.pins[index];\n return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);\n }, 0)));\n scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');\n if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;\n if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;\n const values = new Float32Array(indices.count);\n for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {\n values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);\n }\n if (!values.some(value => value > 1e-5)) return;\n const modified = geometry.clone();\n modified.setAttribute('furDepth', new BufferAttribute(values, 1));\n const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };\n object.geometry = modified;\n this.surfaces.push(surface);\n });\n this.rebuild();\n }\n\n setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }\n update(seconds: number, windStrength: number) {\n this.clock.value += Math.max(0, Math.min(seconds, .1));\n this.wind.value = windStrength;\n }\n /** GLTFExporter must only see standard portable materials and attributes. */\n setPortable(portable: boolean) {\n for (const surface of this.surfaces) {\n surface.mesh.geometry = portable ? surface.geometry : surface.modified;\n surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];\n }\n }\n dispose() {\n this.setPortable(true);\n for (const surface of this.surfaces) {\n surface.modified.dispose(); surface.mesh.geometry = surface.geometry;\n for (const variant of surface.variants) variant.dispose();\n }\n this.surfaces.length = 0;\n }\n private rebuild() {\n for (const surface of this.surfaces) {\n const sources = Array.isArray(surface.material) ? surface.material : [surface.material];\n const variants = sources.map(source => this.material(source as MeshStandardMaterial));\n this.setPortable(true);\n for (const old of surface.variants) old.dispose();\n surface.variants = variants;\n }\n this.setPortable(false);\n }\n private material(source: MeshStandardMaterial) {\n const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();\n material.copy(source);\n material.name = `${source.name || 'Material'} \u00B7 Fur texture motion`;\n const coordinates = uv();\n const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;\n if (!signal) return material;\n const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);\n const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;\n const signalSlot = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap'].find(slot => Reflect.get(source, slot) === signal) ?? 'furHeightMap';\n const pixel = uniform(new Vector2());\n const updatePixel = (map: Texture) => {\n const dimensions = map.image as { width?: number; height?: number } | undefined;\n pixel.value.set(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));\n };\n updatePixel(signal);\n const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));\n const heightNode = this.height ? texture(this.height, uv(this.height.channel)) : null;\n if (heightNode && this.height) bindTextureSlot(material, 'furHeightMap', this.height,\n [heightNode], value => { this.height = value; if (signalSlot === 'furHeightMap') updatePixel(value); });\n const height = heightNode ? heightNode.r : float(.5);\n const raised = mix(.65, 1.35, height);\n const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));\n const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));\n // A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and\n // opacity aligned. The field follows the skinned surface and can shimmer\n // with wind; height modulates movement rather than drawing synthetic hair.\n const shift = movement.add(gust).mul(depth).mul(raised)\n .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');\n const sample = (map: Texture, slot: string) => {\n const node = texture(map, uv(map.channel).add(shift));\n node.updateMatrix = true;\n bindTextureSlot(material, slot, map, [node], value => { Reflect.set(source, slot, value); if (signalSlot === slot) updatePixel(value); });\n return node;\n };\n const base = source.map ? sample(source.map, 'map') : vec4(1);\n material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));\n if (source.alphaMap) material.opacityNode = sample(source.alphaMap, 'alphaMap').g;\n if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap, 'normalMap').xyz,\n vec2(source.normalScale.x, source.normalScale.y));\n material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap, 'roughnessMap').g.mul(source.roughness) : float(source.roughness);\n material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap, 'metalnessMap').b.mul(source.metalness) : float(source.metalness);\n if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap, 'aoMap').r).mul(source.aoMapIntensity));\n if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap, 'emissiveMap').rgb.mul(vec3(\n source.emissive.r * source.emissiveIntensity,\n source.emissive.g * source.emissiveIntensity,\n source.emissive.b * source.emissiveIntensity));\n material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };\n return material;\n }\n}\n\n/** Convert the current skin displacement into a local UV offset. The metric\n * inversion avoids assuming that U/V align with world X/Y or have equal scale. */\nfunction projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {\n const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();\n const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();\n const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));\n const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));\n const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);\n const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);\n const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);\n const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);\n const u = movement.dot(dPosDu), v = movement.dot(dPosDv);\n return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));\n}\n", "// @ts-check\n\n/** Keep material-slot texture replacement connected to the shader nodes.\n * @param {import('three').Material} material\n * @param {string} slot\n * @param {import('three').Texture} initial\n * @param {{value: import('three').Texture}[]} nodes\n * @param {((value: import('three').Texture) => void)=} onChange\n */\nexport function bindTextureSlot(material, slot, initial, nodes, onChange) {\n let current = initial;\n Object.defineProperty(material, slot, {\n configurable: true, enumerable: true,\n get: () => current,\n set: (/** @type {import('three').Texture} */ value) => {\n value.channel = current.channel;\n value.offset = current.offset;\n value.repeat = current.repeat;\n value.center = current.center;\n value.rotation = current.rotation;\n current = value;\n for (const node of nodes) node.value = value;\n onChange?.(value);\n material.needsUpdate = true;\n },\n });\n}\n"],
5
+ "mappings": ";;;AAAA,SAAS,iBAAiB,sBAAsB,sBAAsB,aAAa,eAAgF;AACnK,SAAS,0BAA0B,gCAA2C;AAC9E,SAAS,WAAW,OAAO,KAAK,WAAW,eAAe,SAAS,SAAS,IAAI,SAAS,MAAM,MAAM,YAAY;;;ACO1G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
84
84
  windTime = 0;
85
+ accumulator = 0;
85
86
  reset() {
86
87
  this.particles.clear();
87
88
  this.layout = "";
88
89
  this.windTime = 0;
90
+ this.accumulator = 0;
89
91
  }
90
92
  step(pins, parents, seconds, links, colliders = [], windStrength = 0) {
91
93
  const cloth = pins.filter((p) => p.cloth && !p.guide);
@@ -103,7 +105,10 @@ var PinCloth = class {
103
105
  const position = new Vector32().fromArray(pin.pose.position);
104
106
  this.particles.set(pin.id, { position, previous: position.clone() });
105
107
  }
106
- const dt = Math.min(Math.max(seconds, 0), 0.05), steps = Math.max(1, Math.ceil(dt / (1 / 60))), h = dt / steps;
108
+ const h = 1 / 60;
109
+ this.accumulator += Math.min(Math.max(seconds, 0), 0.05);
110
+ const steps = Math.floor((this.accumulator + 1e-12) / h);
111
+ this.accumulator = Math.max(0, this.accumulator - steps * h);
107
112
  const scale = Math.max(1e-4, ...links.map((link) => link.length));
108
113
  let maxRadius = 0;
109
114
  for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);
@@ -130,7 +135,7 @@ var PinCloth = class {
130
135
  } else for (const collider of colliders) search(collider);
131
136
  return found;
132
137
  };
133
- for (let substep = 0; substep < steps && dt > 0; substep++) {
138
+ for (let substep = 0; substep < steps; substep++) {
134
139
  this.windTime += h;
135
140
  for (const pin of cloth) {
136
141
  const particle = this.particles.get(pin.id);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/deformation/pin-cloth.ts", "../../../src/deformation/wind.ts", "../../../src/deformation/motion-settings.ts"],
4
- "sourcesContent": ["import { Quaternion, Vector3 } from 'three';\nimport type { PinRecord, Point } from './pin-types.js';\nimport type { PinParents, HierarchyEdge } from './pin-types.js';\nimport { windAcceleration } from './wind.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\n\nexport type ClothLink = { a: string; b: string; length: number };\nexport type ClothCollider = { position: Point; radius: number; driver?: string };\n\n/** Connect authored cloth controls along the occupied-volume geodesic, not\n * across the shortest line through empty space. The tree is a coarse fabric\n * constraint network; the ordinary skin remains its portable GLB fallback. */\nexport function clothLinks(pins: readonly PinRecord[], parents: PinParents, edges: readonly HierarchyEdge[] = [], components?: ReadonlyMap<string, number>): ClothLink[] {\n const cloth = pins.filter(p => p.cloth && !p.guide), byId = new Map(pins.map(p => [p.id, p]));\n const result: ClothLink[] = [], seen = new Set<string>();\n const add = (a: string, b: string) => {\n if (a === b || !byId.has(a) || !byId.has(b)) return;\n const key = [a, b].sort().join('\\0'); if (seen.has(key)) return;\n seen.add(key); result.push({ a, b, length: new Vector3().fromArray(byId.get(a)!.rest).distanceTo(new Vector3().fromArray(byId.get(b)!.rest)) });\n };\n for (const pin of cloth) {\n let parent = parents.get(pin.id);\n const visited = new Set<string>();\n while (parent && byId.get(parent)?.guide && !visited.has(parent)) { visited.add(parent); parent = parents.get(parent); }\n if (parent) add(pin.id, parent);\n }\n // A topology hierarchy may root a sheet at one of its free corners. Cloth\n // still needs body attachments there; otherwise the entire sheet falls as\n // one unconstrained pair or chain despite nearby non-cloth controls.\n for (const pin of cloth) {\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (parent && !parent.cloth && !parent.guide) continue;\n const anchors = edges.filter(edge => (edge.from === pin.id || edge.to === pin.id) &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.cloth &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.guide &&\n Number.isFinite(edge.geodesic ?? edge.cost));\n const same = anchors.filter(edge => !components || components.get(pin.id) === components.get(edge.from === pin.id ? edge.to : edge.from));\n const best = (same.length ? same : anchors).sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost))[0];\n if (best) add(pin.id, best.from === pin.id ? best.to : best.from);\n }\n const candidates = edges.filter(e => cloth.some(p => p.id === e.from) && cloth.some(p => p.id === e.to) && Number.isFinite(e.geodesic ?? e.cost)\n && (!components || components.get(e.from) === components.get(e.to)))\n .sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost));\n const root = new Map(cloth.map(p => [p.id, p.id]));\n const find = (id: string): string => { const parent = root.get(id)!; if (parent === id) return id; const top = find(parent); root.set(id, top); return top; };\n for (const edge of candidates) {\n const a = find(edge.from), b = find(edge.to); if (a === b) continue;\n root.set(a, b); add(edge.from, edge.to);\n }\n return result;\n}\n\n/** Small, fixed-step Verlet graph. The editor passes deformed voxel centers;\n * the GLB loader passes the same collider proxy driven by its joint graph. */\nexport class PinCloth {\n private particles = new Map<string, { position: Vector3; previous: Vector3 }>();\n private layout = '';\n private windTime = 0;\n reset() { this.particles.clear(); this.layout = ''; this.windTime = 0; }\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, links: readonly ClothLink[], colliders: readonly ClothCollider[] = [], windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n const cloth = pins.filter(p => p.cloth && !p.guide);\n if (!cloth.length) { this.reset(); return { pins, active: false }; }\n const layout = JSON.stringify([cloth.map(p => [p.id, p.rest]), links]);\n if (layout !== this.layout) { this.reset(); this.layout = layout; }\n const byId = new Map(pins.map(p => [p.id, p]));\n for (const pin of cloth) if (!this.particles.has(pin.id)) {\n const position = new Vector3().fromArray(pin.pose.position);\n this.particles.set(pin.id, { position, previous: position.clone() });\n }\n const dt = Math.min(Math.max(seconds, 0), .05), steps = Math.max(1, Math.ceil(dt / (1 / 60))), h = dt / steps;\n const scale = Math.max(1e-4, ...links.map(link => link.length));\n // A sampled voxel shell can contain thousands of spheres. Bin it once\n // per frame, then refresh each particle's nearby set after integration so\n // a fast-moving cloth point cannot retain last frame's collision region.\n let maxRadius = 0;\n for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);\n const cell = Math.max(1e-4, scale * 2 + maxRadius);\n const spatial = cloth.length > 4 && colliders.length > 128;\n const bins = new Map<string, ClothCollider[]>();\n const key = (x: number, y: number, z: number) => `${x},${y},${z}`;\n if (spatial) for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n const candidates = (position: Vector3) => {\n const found: ClothCollider[] = [];\n const search = (collider: ClothCollider) => {\n const p = collider.position, dx = position.x - p[0], dy = position.y - p[1], dz = position.z - p[2], reach = collider.radius + scale * 2;\n if (dx * dx + dy * dy + dz * dz < reach * reach) found.push(collider);\n };\n if (spatial) {\n const x = Math.floor(position.x / cell), y = Math.floor(position.y / cell), z = Math.floor(position.z / cell);\n for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++)\n for (const collider of bins.get(key(x + dx, y + dy, z + dz)) ?? []) search(collider);\n } else for (const collider of colliders) search(collider);\n return found;\n };\n for (let substep = 0; substep < steps && dt > 0; substep++) {\n this.windTime += h;\n for (const pin of cloth) {\n const particle = this.particles.get(pin.id)!;\n const motion = pin.motion ?? DEFAULT_MOTION;\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * scale * h * h;\n if (windStrength > 0 && motion.strength > 0) particle.position.addScaledVector(windAcceleration(this.windTime, windStrength, scale, particle.position.toArray()), motion.strength * h * h);\n // Pins are sparse controls, not free particles. A soft return to their\n // authored positions keeps broad sheets from drifting indefinitely.\n particle.position.lerp(new Vector3().fromArray(pin.pose.position), 1 - Math.exp(-2 * Math.PI * motion.frequency * h));\n }\n const nearby = new Map(cloth.map(pin => [pin.id, candidates(this.particles.get(pin.id)!.position)]));\n for (let iteration = 0; iteration < 6; iteration++) {\n for (const link of links) {\n const a = this.particles.get(link.a), b = this.particles.get(link.b);\n const pa = a?.position ?? new Vector3().fromArray(byId.get(link.a)?.pose.position ?? [0, 0, 0]);\n const pb = b?.position ?? new Vector3().fromArray(byId.get(link.b)?.pose.position ?? [0, 0, 0]);\n const delta = pa.clone().sub(pb), distance = delta.length(); if (distance < 1e-8) continue;\n const correction = delta.multiplyScalar((distance - link.length) / distance);\n if (a && b) { a.position.addScaledVector(correction, -.5); b.position.addScaledVector(correction, .5); }\n else if (a) a.position.sub(correction); else if (b) b.position.add(correction);\n }\n for (const [id, particle] of this.particles) for (const collider of nearby.get(id) ?? []) {\n const center = collider.position, dx = particle.position.x - center[0], dy = particle.position.y - center[1], dz = particle.position.z - center[2];\n const squared = dx * dx + dy * dy + dz * dz;\n if (squared >= collider.radius * collider.radius) continue;\n if (squared < 1e-16) particle.position.set(center[0], center[1] + collider.radius, center[2]);\n else {\n const factor = collider.radius / Math.sqrt(squared);\n particle.position.set(center[0] + dx * factor, center[1] + dy * factor, center[2] + dz * factor);\n }\n }\n }\n }\n let active = false;\n const result = pins.map(pin => {\n const particle = this.particles.get(pin.id); if (!particle) return pin;\n const target = new Vector3().fromArray(pin.pose.position), offset = particle.position.clone().sub(target);\n const velocity = particle.position.clone().sub(particle.previous);\n if (offset.lengthSq() > scale * scale * 1e-10 || velocity.lengthSq() > scale * scale * 1e-10) active = true;\n const parent = byId.get(parents.get(pin.id) ?? '');\n const rotation = parent ? new Quaternion().setFromUnitVectors(\n target.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize(),\n particle.position.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize()) : new Quaternion();\n return { ...pin, pose: { ...pin.pose, position: particle.position.toArray() as Point,\n rotation: rotation.multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize().toArray() as [number, number, number, number] } };\n });\n return { pins: active ? result : pins, active };\n }\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n"],
5
- "mappings": ";;;AAAA,SAAS,YAAY,WAAAA,gBAAe;;;ACApC,SAAS,eAAe;AAEjB,IAAM,oBAAoB;AAI1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';\nimport type { PinParents, HierarchyEdge } from './pin-types.js';\nimport { windAcceleration } from './wind.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\n\nexport type ClothLink = { a: string; b: string; length: number };\nexport type ClothCollider = { position: Point; radius: number; driver?: string };\n\n/** Connect authored cloth controls along the occupied-volume geodesic, not\n * across the shortest line through empty space. The tree is a coarse fabric\n * constraint network; the ordinary skin remains its portable GLB fallback. */\nexport function clothLinks(pins: readonly PinRecord[], parents: PinParents, edges: readonly HierarchyEdge[] = [], components?: ReadonlyMap<string, number>): ClothLink[] {\n const cloth = pins.filter(p => p.cloth && !p.guide), byId = new Map(pins.map(p => [p.id, p]));\n const result: ClothLink[] = [], seen = new Set<string>();\n const add = (a: string, b: string) => {\n if (a === b || !byId.has(a) || !byId.has(b)) return;\n const key = [a, b].sort().join('\\0'); if (seen.has(key)) return;\n seen.add(key); result.push({ a, b, length: new Vector3().fromArray(byId.get(a)!.rest).distanceTo(new Vector3().fromArray(byId.get(b)!.rest)) });\n };\n for (const pin of cloth) {\n let parent = parents.get(pin.id);\n const visited = new Set<string>();\n while (parent && byId.get(parent)?.guide && !visited.has(parent)) { visited.add(parent); parent = parents.get(parent); }\n if (parent) add(pin.id, parent);\n }\n // A topology hierarchy may root a sheet at one of its free corners. Cloth\n // still needs body attachments there; otherwise the entire sheet falls as\n // one unconstrained pair or chain despite nearby non-cloth controls.\n for (const pin of cloth) {\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (parent && !parent.cloth && !parent.guide) continue;\n const anchors = edges.filter(edge => (edge.from === pin.id || edge.to === pin.id) &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.cloth &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.guide &&\n Number.isFinite(edge.geodesic ?? edge.cost));\n const same = anchors.filter(edge => !components || components.get(pin.id) === components.get(edge.from === pin.id ? edge.to : edge.from));\n const best = (same.length ? same : anchors).sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost))[0];\n if (best) add(pin.id, best.from === pin.id ? best.to : best.from);\n }\n const candidates = edges.filter(e => cloth.some(p => p.id === e.from) && cloth.some(p => p.id === e.to) && Number.isFinite(e.geodesic ?? e.cost)\n && (!components || components.get(e.from) === components.get(e.to)))\n .sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost));\n const root = new Map(cloth.map(p => [p.id, p.id]));\n const find = (id: string): string => { const parent = root.get(id)!; if (parent === id) return id; const top = find(parent); root.set(id, top); return top; };\n for (const edge of candidates) {\n const a = find(edge.from), b = find(edge.to); if (a === b) continue;\n root.set(a, b); add(edge.from, edge.to);\n }\n return result;\n}\n\n/** Small, fixed-step Verlet graph. The editor passes deformed voxel centers;\n * the GLB loader passes the same collider proxy driven by its joint graph. */\nexport class PinCloth {\n private particles = new Map<string, { position: Vector3; previous: Vector3 }>();\n private layout = '';\n private windTime = 0;\n private accumulator = 0;\n reset() { this.particles.clear(); this.layout = ''; this.windTime = 0; this.accumulator = 0; }\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, links: readonly ClothLink[], colliders: readonly ClothCollider[] = [], windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n const cloth = pins.filter(p => p.cloth && !p.guide);\n if (!cloth.length) { this.reset(); return { pins, active: false }; }\n const layout = JSON.stringify([cloth.map(p => [p.id, p.rest]), links]);\n if (layout !== this.layout) { this.reset(); this.layout = layout; }\n const byId = new Map(pins.map(p => [p.id, p]));\n for (const pin of cloth) if (!this.particles.has(pin.id)) {\n const position = new Vector3().fromArray(pin.pose.position);\n this.particles.set(pin.id, { position, previous: position.clone() });\n }\n // Verlet stores displacement per step. Changing the step with render\n // timing changes its velocity and keeps a calm sheet moving.\n const h = 1 / 60;\n this.accumulator += Math.min(Math.max(seconds, 0), .05);\n const steps = Math.floor((this.accumulator + 1e-12) / h);\n this.accumulator = Math.max(0, this.accumulator - steps * h);\n const scale = Math.max(1e-4, ...links.map(link => link.length));\n // A sampled voxel shell can contain thousands of spheres. Bin it once\n // per frame, then refresh each particle's nearby set after integration so\n // a fast-moving cloth point cannot retain last frame's collision region.\n let maxRadius = 0;\n for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);\n const cell = Math.max(1e-4, scale * 2 + maxRadius);\n const spatial = cloth.length > 4 && colliders.length > 128;\n const bins = new Map<string, ClothCollider[]>();\n const key = (x: number, y: number, z: number) => `${x},${y},${z}`;\n if (spatial) for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n const candidates = (position: Vector3) => {\n const found: ClothCollider[] = [];\n const search = (collider: ClothCollider) => {\n const p = collider.position, dx = position.x - p[0], dy = position.y - p[1], dz = position.z - p[2], reach = collider.radius + scale * 2;\n if (dx * dx + dy * dy + dz * dz < reach * reach) found.push(collider);\n };\n if (spatial) {\n const x = Math.floor(position.x / cell), y = Math.floor(position.y / cell), z = Math.floor(position.z / cell);\n for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++)\n for (const collider of bins.get(key(x + dx, y + dy, z + dz)) ?? []) search(collider);\n } else for (const collider of colliders) search(collider);\n return found;\n };\n for (let substep = 0; substep < steps; substep++) {\n this.windTime += h;\n for (const pin of cloth) {\n const particle = this.particles.get(pin.id)!;\n const motion = pin.motion ?? DEFAULT_MOTION;\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * scale * h * h;\n if (windStrength > 0 && motion.strength > 0) particle.position.addScaledVector(windAcceleration(this.windTime, windStrength, scale, particle.position.toArray()), motion.strength * h * h);\n // Pins are sparse controls, not free particles. A soft return to their\n // authored positions keeps broad sheets from drifting indefinitely.\n particle.position.lerp(new Vector3().fromArray(pin.pose.position), 1 - Math.exp(-2 * Math.PI * motion.frequency * h));\n }\n const nearby = new Map(cloth.map(pin => [pin.id, candidates(this.particles.get(pin.id)!.position)]));\n for (let iteration = 0; iteration < 6; iteration++) {\n for (const link of links) {\n const a = this.particles.get(link.a), b = this.particles.get(link.b);\n const pa = a?.position ?? new Vector3().fromArray(byId.get(link.a)?.pose.position ?? [0, 0, 0]);\n const pb = b?.position ?? new Vector3().fromArray(byId.get(link.b)?.pose.position ?? [0, 0, 0]);\n const delta = pa.clone().sub(pb), distance = delta.length(); if (distance < 1e-8) continue;\n const correction = delta.multiplyScalar((distance - link.length) / distance);\n if (a && b) { a.position.addScaledVector(correction, -.5); b.position.addScaledVector(correction, .5); }\n else if (a) a.position.sub(correction); else if (b) b.position.add(correction);\n }\n for (const [id, particle] of this.particles) for (const collider of nearby.get(id) ?? []) {\n const center = collider.position, dx = particle.position.x - center[0], dy = particle.position.y - center[1], dz = particle.position.z - center[2];\n const squared = dx * dx + dy * dy + dz * dz;\n if (squared >= collider.radius * collider.radius) continue;\n if (squared < 1e-16) particle.position.set(center[0], center[1] + collider.radius, center[2]);\n else {\n const factor = collider.radius / Math.sqrt(squared);\n particle.position.set(center[0] + dx * factor, center[1] + dy * factor, center[2] + dz * factor);\n }\n }\n }\n }\n let active = false;\n const result = pins.map(pin => {\n const particle = this.particles.get(pin.id); if (!particle) return pin;\n const target = new Vector3().fromArray(pin.pose.position), offset = particle.position.clone().sub(target);\n const velocity = particle.position.clone().sub(particle.previous);\n if (offset.lengthSq() > scale * scale * 1e-10 || velocity.lengthSq() > scale * scale * 1e-10) active = true;\n const parent = byId.get(parents.get(pin.id) ?? '');\n const rotation = parent ? new Quaternion().setFromUnitVectors(\n target.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize(),\n particle.position.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize()) : new Quaternion();\n return { ...pin, pose: { ...pin.pose, position: particle.position.toArray() as Point,\n rotation: rotation.multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize().toArray() as [number, number, number, number] } };\n });\n return { pins: active ? result : pins, active };\n }\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n"],
5
+ "mappings": ";;;AAAA,SAAS,YAAY,WAAAA,gBAAe;;;ACApC,SAAS,eAAe;AAEjB,IAAM,oBAAoB;AAI1B,SAAS,YAAY,UAAkB;AAC5C,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,mBAAmB,QAAQ,CAAC;AAC/D,QAAM,QAAQ,UAAU,IAAI,QAAQ,QAAQ,OAAM,WAAW,QAAQ,MAAM,UAAU,QAAQ,MAAM,gBAAgB,QAAQ,MAAM,SAAS;AAC1I,SAAO;AAAA,IACL;AAAA,IACA,MAAM,KAAK,QAAQ,SAAS,MAAK,QAAQ;AAAA,IACzC,aAAa,IAAI,QAAQ;AAAA,IACzB,MAAM,OAAM,OAAM;AAAA,IAClB,WAAW,OAAM,OAAM;AAAA,IACvB,UAAU,OAAM,OAAM;AAAA,EACxB;AACF;AAKO,SAAS,iBAAiB,SAAiB,UAAkB,OAAe,UAA6B;AAC9G,MAAI,YAAY,EAAG,QAAO,IAAI,QAAQ;AACtC,QAAM,OAAO,KAAK,IAAI,MAAM,KAAK;AACjC,QAAM,UAAU,YAAY,QAAQ;AAIpC,QAAM,QAAQ,SAAS,CAAC,IAAI,MAAM,WAAW,SAAS,CAAC,IAAI,OAAM,SAAS,CAAC,IAAI,QAAO;AACtF,QAAM,OAAO,UAAU,QAAQ,WAAW,QAAQ;AAClD,QAAM,OAAO,WAAW,QAAQ,WAAW,OAAO,QAAQ,MAAM,UAAU;AAC1E,QAAM,OAAO,KAAK,IAAI,KAAI,IAAI,QAAQ,QAAQ,MAAK,KAAK,IAAI,IAAI,IAAI,MAAK,KAAK,IAAI,OAAO,GA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,MAAC,IAAI,IAAI,WAAW;AAC7G,aAAO,EAAE,GAAG,KAAK,MAAM;AAAA,QAAE,GAAG,IAAI;AAAA,QAAM,UAAU,SAAS,SAAS,QAAQ;AAAA,QACxE,UAAU,SAAS,SAAS,IAAI,WAAW,EAAE,UAAU,IAAI,KAAK,QAAQ,CAAC,EAAE,UAAU,EAAE,QAAQ;AAAA,MAAsC,EAAE;AAAA,IAC3I,CAAC;AACD,WAAO,EAAE,MAAM,SAAS,SAAS,MAAM,OAAO;AAAA,EAChD;AACF;",
6
6
  "names": ["Vector3", "Vector3"]
7
7
  }
@@ -1081,10 +1081,12 @@ var PinCloth = class {
1081
1081
  particles = /* @__PURE__ */ new Map();
1082
1082
  layout = "";
1083
1083
  windTime = 0;
1084
+ accumulator = 0;
1084
1085
  reset() {
1085
1086
  this.particles.clear();
1086
1087
  this.layout = "";
1087
1088
  this.windTime = 0;
1089
+ this.accumulator = 0;
1088
1090
  }
1089
1091
  step(pins, parents, seconds, links, colliders = [], windStrength = 0) {
1090
1092
  const cloth = pins.filter((p) => p.cloth && !p.guide);
@@ -1102,7 +1104,10 @@ var PinCloth = class {
1102
1104
  const position = new Vector35().fromArray(pin.pose.position);
1103
1105
  this.particles.set(pin.id, { position, previous: position.clone() });
1104
1106
  }
1105
- const dt = Math.min(Math.max(seconds, 0), 0.05), steps = Math.max(1, Math.ceil(dt / (1 / 60))), h = dt / steps;
1107
+ const h = 1 / 60;
1108
+ this.accumulator += Math.min(Math.max(seconds, 0), 0.05);
1109
+ const steps = Math.floor((this.accumulator + 1e-12) / h);
1110
+ this.accumulator = Math.max(0, this.accumulator - steps * h);
1106
1111
  const scale = Math.max(1e-4, ...links.map((link) => link.length));
1107
1112
  let maxRadius = 0;
1108
1113
  for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);
@@ -1129,7 +1134,7 @@ var PinCloth = class {
1129
1134
  } else for (const collider of colliders) search(collider);
1130
1135
  return found;
1131
1136
  };
1132
- for (let substep = 0; substep < steps && dt > 0; substep++) {
1137
+ for (let substep = 0; substep < steps; substep++) {
1133
1138
  this.windTime += h;
1134
1139
  for (const pin of cloth) {
1135
1140
  const particle = this.particles.get(pin.id);
@@ -1254,6 +1259,7 @@ var ClothSurface = class {
1254
1259
  edges;
1255
1260
  scale;
1256
1261
  time = 0;
1262
+ accumulator = 0;
1257
1263
  constructor(restVertices, indices, pins) {
1258
1264
  const vertexCount = restVertices.length / 3;
1259
1265
  const min = new Vector36(Infinity, Infinity, Infinity), max = new Vector36(-Infinity, -Infinity, -Infinity);
@@ -1335,6 +1341,7 @@ var ClothSurface = class {
1335
1341
  }
1336
1342
  reset() {
1337
1343
  this.time = 0;
1344
+ this.accumulator = 0;
1338
1345
  for (const particle of this.particles) particle.position.copy(particle.base), particle.previous.copy(particle.base);
1339
1346
  }
1340
1347
  step(baseVertices, seconds, windStrength, colliders = [], motion = DEFAULT_MOTION) {
@@ -1351,7 +1358,10 @@ var ClothSurface = class {
1351
1358
  particle.previous.add(delta);
1352
1359
  particle.base.copy(base[i]);
1353
1360
  }
1354
- const dt = Math.min(Math.max(seconds, 0), 0.05), steps = Math.max(1, Math.ceil(dt * 60)), h = dt / steps;
1361
+ const h = 1 / 60;
1362
+ this.accumulator += Math.min(Math.max(seconds, 0), 0.05);
1363
+ const steps = Math.floor((this.accumulator + 1e-12) / h);
1364
+ this.accumulator = Math.max(0, this.accumulator - steps * h);
1355
1365
  const profile = windProfile(windStrength), pressureScale = profile.load ? 0.025 * profile.surfaceLoad / profile.load : 0;
1356
1366
  const radius = Math.max(1e-4, ...colliders.map((collider) => collider.radius));
1357
1367
  const cell = radius * 2;
@@ -1363,7 +1373,7 @@ var ClothSurface = class {
1363
1373
  bin.push(collider);
1364
1374
  bins.set(id, bin);
1365
1375
  }
1366
- for (let step = 0; step < steps && h > 0; step++) {
1376
+ for (let step = 0; step < steps; step++) {
1367
1377
  this.time += h;
1368
1378
  const force = Array.from({ length: count }, () => new Vector36());
1369
1379
  const area = new Float32Array(count);
@@ -1410,23 +1420,24 @@ var ClothSurface = class {
1410
1420
  }
1411
1421
  if (colliders.length) for (const particle of this.particles) {
1412
1422
  if (particle.share < 0.35) continue;
1413
- const p = particle.position, px = p.x / cell, py = p.y / cell, pz = p.z / cell;
1414
- const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);
1415
- const sx = px - x < 0.5 ? -1 : 1, sy = py - y < 0.5 ? -1 : 1, sz = pz - z < 0.5 ? -1 : 1;
1416
- let chosen, penetration = 0;
1417
- for (let iz = 0; iz < 2; iz++) for (let iy = 0; iy < 2; iy++) for (let ix = 0; ix < 2; ix++) {
1418
- for (const collider of bins.get(key(x + ix * sx, y + iy * sy, z + iz * sz)) ?? []) {
1419
- const center = collider.position, bx = particle.base.x - center[0], by = particle.base.y - center[1], bz = particle.base.z - center[2];
1420
- if (bx * bx + by * by + bz * bz < collider.radius * collider.radius * 1.04) continue;
1421
- const vx = p.x - center[0], vy = p.y - center[1], vz = p.z - center[2];
1422
- const depth = collider.radius - Math.hypot(vx, vy, vz);
1423
- if (depth > penetration) {
1424
- penetration = depth;
1425
- chosen = collider;
1423
+ for (let contact = 0; contact < 8; contact++) {
1424
+ const p = particle.position, px = p.x / cell, py = p.y / cell, pz = p.z / cell;
1425
+ const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);
1426
+ const sx = px - x < 0.5 ? -1 : 1, sy = py - y < 0.5 ? -1 : 1, sz = pz - z < 0.5 ? -1 : 1;
1427
+ let chosen, penetration = 0;
1428
+ for (let iz = 0; iz < 2; iz++) for (let iy = 0; iy < 2; iy++) for (let ix = 0; ix < 2; ix++) {
1429
+ for (const collider of bins.get(key(x + ix * sx, y + iy * sy, z + iz * sz)) ?? []) {
1430
+ const center2 = collider.position, bx = particle.base.x - center2[0], by = particle.base.y - center2[1], bz = particle.base.z - center2[2];
1431
+ if (bx * bx + by * by + bz * bz < collider.radius * collider.radius * 1.04) continue;
1432
+ const vx = p.x - center2[0], vy = p.y - center2[1], vz = p.z - center2[2];
1433
+ const depth = collider.radius - Math.hypot(vx, vy, vz);
1434
+ if (depth > penetration) {
1435
+ penetration = depth;
1436
+ chosen = collider;
1437
+ }
1426
1438
  }
1427
1439
  }
1428
- }
1429
- if (chosen) {
1440
+ if (!chosen || penetration < this.scale * 1e-7) break;
1430
1441
  const center = chosen.position, delta = p.clone().sub(new Vector36().fromArray(center));
1431
1442
  if (delta.lengthSq() < 1e-12) delta.copy(particle.base).sub(new Vector36().fromArray(center));
1432
1443
  p.copy(new Vector36().fromArray(center).add(delta.setLength(chosen.radius)));
@@ -1480,9 +1491,32 @@ function driveRig(pins, reference, drivers) {
1480
1491
  }
1481
1492
 
1482
1493
  // src/deformation/fur-surface.ts
1483
- import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh } from "three";
1494
+ import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, Vector2 } from "three";
1484
1495
  import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";
1485
1496
  import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from "three/tsl";
1497
+
1498
+ // src/rendering/texture-slot.js
1499
+ function bindTextureSlot(material, slot, initial, nodes, onChange) {
1500
+ let current = initial;
1501
+ Object.defineProperty(material, slot, {
1502
+ configurable: true,
1503
+ enumerable: true,
1504
+ get: () => current,
1505
+ set: (value) => {
1506
+ value.channel = current.channel;
1507
+ value.offset = current.offset;
1508
+ value.repeat = current.repeat;
1509
+ value.center = current.center;
1510
+ value.rotation = current.rotation;
1511
+ current = value;
1512
+ for (const node of nodes) node.value = value;
1513
+ onChange?.(value);
1514
+ material.needsUpdate = true;
1515
+ }
1516
+ });
1517
+ }
1518
+
1519
+ // src/deformation/fur-surface.ts
1486
1520
  var FurSurface = class {
1487
1521
  surfaces = [];
1488
1522
  height = null;
@@ -1559,30 +1593,50 @@ var FurSurface = class {
1559
1593
  if (!signal) return material;
1560
1594
  const depth = attribute("furDepth", "float").mul(5).clamp(0, 1);
1561
1595
  const skinnedDelta = varying(positionLocal.sub(attribute("position", "vec3")), "furSkinDelta");
1562
- const dimensions = signal.image;
1563
- const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
1596
+ const signalSlot = ["map", "normalMap", "roughnessMap", "metalnessMap", "emissiveMap", "aoMap", "alphaMap"].find((slot) => Reflect.get(source, slot) === signal) ?? "furHeightMap";
1597
+ const pixel = uniform(new Vector2());
1598
+ const updatePixel = (map) => {
1599
+ const dimensions = map.image;
1600
+ pixel.value.set(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
1601
+ };
1602
+ updatePixel(signal);
1564
1603
  const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
1565
- const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(0.5);
1604
+ const heightNode = this.height ? texture(this.height, uv(this.height.channel)) : null;
1605
+ if (heightNode && this.height) bindTextureSlot(
1606
+ material,
1607
+ "furHeightMap",
1608
+ this.height,
1609
+ [heightNode],
1610
+ (value) => {
1611
+ this.height = value;
1612
+ if (signalSlot === "furHeightMap") updatePixel(value);
1613
+ }
1614
+ );
1615
+ const height = heightNode ? heightNode.r : float(0.5);
1566
1616
  const raised = mix(0.65, 1.35, height);
1567
1617
  const phase = coordinates.dot(vec2(31, 43)).add(height.sub(0.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
1568
1618
  const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(0.65));
1569
1619
  const shift = movement.add(gust).mul(depth).mul(raised).clamp(pixel.mul(-2), pixel.mul(2)).toVar("furTextureShift");
1570
- const sample = (map) => {
1620
+ const sample = (map, slot) => {
1571
1621
  const node = texture(map, uv(map.channel).add(shift));
1572
1622
  node.updateMatrix = true;
1623
+ bindTextureSlot(material, slot, map, [node], (value) => {
1624
+ Reflect.set(source, slot, value);
1625
+ if (signalSlot === slot) updatePixel(value);
1626
+ });
1573
1627
  return node;
1574
1628
  };
1575
- const base = source.map ? sample(source.map) : vec4(1);
1629
+ const base = source.map ? sample(source.map, "map") : vec4(1);
1576
1630
  material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
1577
- if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
1631
+ if (source.alphaMap) material.opacityNode = sample(source.alphaMap, "alphaMap").g;
1578
1632
  if (source.normalMap) material.normalNode = normalMap(
1579
- sample(source.normalMap).xyz,
1633
+ sample(source.normalMap, "normalMap").xyz,
1580
1634
  vec2(source.normalScale.x, source.normalScale.y)
1581
1635
  );
1582
- material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
1583
- material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
1584
- if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
1585
- if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
1636
+ material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap, "roughnessMap").g.mul(source.roughness) : float(source.roughness);
1637
+ material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap, "metalnessMap").b.mul(source.metalness) : float(source.metalness);
1638
+ if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap, "aoMap").r).mul(source.aoMapIntensity));
1639
+ if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap, "emissiveMap").rgb.mul(vec3(
1586
1640
  source.emissive.r * source.emissiveIntensity,
1587
1641
  source.emissive.g * source.emissiveIntensity,
1588
1642
  source.emissive.b * source.emissiveIntensity