@threepipe/webgi-plugins 0.6.4 → 0.8.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.
Files changed (127) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/LICENSE +133 -16
  3. package/README.md +29 -26
  4. package/THIRD_PARTY_NOTICES.md +243 -0
  5. package/dist/dependencies.txt +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +3907 -18
  8. package/dist/index.js.map +1 -1
  9. package/dist/index.mjs +3824 -18
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/passes/BilateralFilterPass.d.ts +1 -1
  12. package/dist/passes/BilateralFilterPass.d.ts.map +1 -1
  13. package/dist/plugins/buffer/VelocityBufferPlugin.d.ts.map +1 -1
  14. package/dist/plugins/extras/AdvancedGroundPlugin.d.ts +4 -3
  15. package/dist/plugins/extras/AdvancedGroundPlugin.d.ts.map +1 -1
  16. package/dist/plugins/extras/AnisotropyPlugin.d.ts +5 -4
  17. package/dist/plugins/extras/AnisotropyPlugin.d.ts.map +1 -1
  18. package/dist/plugins/extras/WatchHandsPlugin.d.ts +1 -1
  19. package/dist/plugins/extras/WatchHandsPlugin.d.ts.map +1 -1
  20. package/dist/plugins/index.d.ts +23 -23
  21. package/dist/plugins/postprocessing/BloomPlugin.d.ts.map +1 -1
  22. package/dist/plugins/postprocessing/DepthOfFieldPlugin.d.ts.map +1 -1
  23. package/dist/plugins/postprocessing/OutlinePlugin.d.ts +1 -1
  24. package/dist/plugins/postprocessing/OutlinePlugin.d.ts.map +1 -1
  25. package/dist/plugins/postprocessing/SSContactShadowsPlugin.d.ts.map +1 -1
  26. package/dist/plugins/postprocessing/SSGIPlugin.d.ts +3 -2
  27. package/dist/plugins/postprocessing/SSGIPlugin.d.ts.map +1 -1
  28. package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts +1 -1
  29. package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts.map +1 -1
  30. package/dist/plugins/postprocessing/TemporalAAPlugin.d.ts.map +1 -1
  31. package/dist/utils/FSShadowMaterial.d.ts.map +1 -1
  32. package/dist/utils/RandomizedDirectionalLight.d.ts.map +1 -1
  33. package/dist/utils/Reflector2.d.ts +4 -4
  34. package/dist/utils/Reflector2.d.ts.map +1 -1
  35. package/dist/utils/ShadowMapBaker.d.ts +1 -1
  36. package/dist/utils/ShadowMapBaker.d.ts.map +1 -1
  37. package/docs/.nojekyll +1 -0
  38. package/docs/assets/hierarchy.js +1 -0
  39. package/docs/assets/highlight.css +22 -0
  40. package/docs/assets/icons.js +18 -0
  41. package/docs/assets/icons.svg +1 -0
  42. package/docs/assets/main.js +60 -0
  43. package/docs/assets/navigation.js +1 -0
  44. package/docs/assets/search.js +1 -0
  45. package/docs/assets/style.css +1648 -0
  46. package/docs/classes/AdvancedGroundPlugin.html +736 -0
  47. package/docs/classes/AnisotropyPlugin.html +432 -0
  48. package/docs/classes/BloomPlugin.html +466 -0
  49. package/docs/classes/BloomPluginPass.html +323 -0
  50. package/docs/classes/DepthOfFieldPlugin.html +493 -0
  51. package/docs/classes/DepthOfFieldPluginPass.html +340 -0
  52. package/docs/classes/OutlinePlugin.html +696 -0
  53. package/docs/classes/OutlineRenderPass.html +252 -0
  54. package/docs/classes/SSContactShadowsPlugin.html +421 -0
  55. package/docs/classes/SSGIPlugin.html +488 -0
  56. package/docs/classes/SSGIPluginPass.html +404 -0
  57. package/docs/classes/SSReflectionPlugin.html +495 -0
  58. package/docs/classes/SSReflectionPluginPass.html +410 -0
  59. package/docs/classes/SSVelocityMaterial.html +110 -0
  60. package/docs/classes/TemporalAAPlugin.html +447 -0
  61. package/docs/classes/TemporalAAPluginPass.html +337 -0
  62. package/docs/classes/VelocityBufferPlugin.html +480 -0
  63. package/docs/classes/WatchHandsPlugin.html +443 -0
  64. package/docs/hierarchy.html +28 -0
  65. package/docs/index.html +38 -0
  66. package/docs/types/OutlinePluginPass.html +32 -0
  67. package/docs/types/OutlinePluginTarget.html +32 -0
  68. package/docs/types/SSGIPluginTarget.html +32 -0
  69. package/docs/types/SSReflectionPluginTarget.html +32 -0
  70. package/docs/types/VelocityBufferPluginPass.html +32 -0
  71. package/docs/types/VelocityBufferPluginTarget.html +32 -0
  72. package/docs/variables/anisotropyGLTFExtension.html +43 -0
  73. package/docs/variables/webgiPlugins.html +32 -0
  74. package/package.json +23 -22
  75. package/src/global.d.ts +27 -0
  76. package/src/index.ts +1 -0
  77. package/src/passes/BilateralFilterPass.ts +62 -0
  78. package/src/passes/shaders/ssaoBilateral.glsl +89 -0
  79. package/src/plugins/buffer/VelocityBufferPlugin.ts +270 -0
  80. package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.frag.glsl +46 -0
  81. package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.vert.glsl +51 -0
  82. package/src/plugins/buffer/shaders/VelocityBufferPlugin.unpack.glsl +8 -0
  83. package/src/plugins/extras/AdvancedGroundPlugin.ts +385 -0
  84. package/src/plugins/extras/AnisotropyPlugin.ts +519 -0
  85. package/src/plugins/extras/WatchHandsPlugin.ts +156 -0
  86. package/src/plugins/extras/shaders/anisotropyBsdf.glsl +64 -0
  87. package/src/plugins/extras/shaders/anisotropyTBN.glsl +35 -0
  88. package/src/plugins/index.ts +38 -0
  89. package/src/plugins/postprocessing/BloomPlugin.ts +377 -0
  90. package/src/plugins/postprocessing/DepthOfFieldPlugin.ts +470 -0
  91. package/src/plugins/postprocessing/OutlinePlugin.ts +476 -0
  92. package/src/plugins/postprocessing/SSContactShadowsPlugin.ts +374 -0
  93. package/src/plugins/postprocessing/SSGIPlugin.ts +597 -0
  94. package/src/plugins/postprocessing/SSReflectionPlugin.ts +563 -0
  95. package/src/plugins/postprocessing/TemporalAAPlugin.ts +301 -0
  96. package/src/plugins/postprocessing/shaders/dofBlurBox.glsl +46 -0
  97. package/src/plugins/postprocessing/shaders/dofCombine.glsl +68 -0
  98. package/src/plugins/postprocessing/shaders/dofComputeCoC.glsl +21 -0
  99. package/src/plugins/postprocessing/shaders/dofExpandCoC.glsl +56 -0
  100. package/src/plugins/postprocessing/shaders/dofPoissonBox.glsl +90 -0
  101. package/src/plugins/postprocessing/shaders/giPatch.glsl +53 -0
  102. package/src/plugins/postprocessing/shaders/hdrBloom.glsl +101 -0
  103. package/src/plugins/postprocessing/shaders/outline.glsl +60 -0
  104. package/src/plugins/postprocessing/shaders/outlineDepthFrag.glsl +22 -0
  105. package/src/plugins/postprocessing/shaders/outlineDepthVert.glsl +26 -0
  106. package/src/plugins/postprocessing/shaders/poissonDiskSamples.glsl +19 -0
  107. package/src/plugins/postprocessing/shaders/samplePointHelpers.glsl +3 -0
  108. package/src/plugins/postprocessing/shaders/ssrPatch.glsl +145 -0
  109. package/src/plugins/postprocessing/shaders/ssreflectionMain.glsl +69 -0
  110. package/src/plugins/postprocessing/shaders/ssrt.glsl +118 -0
  111. package/src/utils/FSShadowMaterial.ts +65 -0
  112. package/src/utils/RandomizedDirectionalLight.ts +288 -0
  113. package/src/utils/Reflector2.ts +309 -0
  114. package/src/utils/ShadowMapBaker.ts +527 -0
  115. package/src/utils/shaders/computeScreenSpaceVelocity.glsl +16 -0
  116. package/src/utils/shaders/getWorldPositionFromViewZ.glsl +9 -0
  117. package/src/utils/shaders/poissonDiskSamples.glsl +19 -0
  118. package/src/utils/shaders/reflectorSample.glsl +54 -0
  119. package/src/utils/shaders/seperableBlurShaderMasked.glsl +28 -0
  120. package/src/utils/shaders/seperableShadowBlur.glsl +21 -0
  121. package/src/utils/shaders/ssreflection.glsl +141 -0
  122. package/src/utils/shaders/ssrtao.glsl +275 -0
  123. package/src/utils/shaders/temporalaa.glsl +233 -0
  124. package/src/utils/shaders.ts +24 -0
  125. package/tsconfig.json +40 -44
  126. package/dist/version.d.ts +0 -2
  127. package/dist/version.d.ts.map +0 -1
@@ -0,0 +1,519 @@
1
+ import {
2
+ AssetManager,
3
+ AViewerPluginSync,
4
+ getTexelDecoding,
5
+ glsl,
6
+ GLTF,
7
+ GLTFLoaderPlugin,
8
+ GLTFParser,
9
+ GLTFWriter2,
10
+ IMaterial,
11
+ IObject3D,
12
+ IShaderPropertiesUpdater,
13
+ ITexture,
14
+ makeSamplerUi,
15
+ MaterialExtension,
16
+ Matrix3,
17
+ PhysicalMaterial,
18
+ serialize,
19
+ RenderManager,
20
+ shaderReplaceString,
21
+ SRGBColorSpace,
22
+ ThreeViewer,
23
+ uiFolderContainer,
24
+ UiObjectConfig,
25
+ uiToggle,
26
+ updateMaterialDefines
27
+ } from "threepipe";
28
+ import anisotropyBsdf from './shaders/anisotropyBsdf.glsl' // todo rename
29
+ import anisotropyTBN from './shaders/anisotropyTBN.glsl'
30
+
31
+ const ShaderChunk = RenderManager.ShaderChunk
32
+ // shaders similar to Filament: https://github.com/google/filament/tree/v1.12.0/shaders/src
33
+ // Filament, Apache License 2.0, Copyright (C) 2015 The Android Open Source Project
34
+
35
+ /**
36
+ * Anisotropy Plugin
37
+ * Adds a material extension to PhysicalMaterial to support anisotropy maps.
38
+ * Anisotropy is a directional material property that causes the material to reflect light differently depending on the direction of the surface. This is useful for materials like brushed metal, fabric, etc.
39
+ * This is a separate implementation than the anisotropy property in three.js which satisfies `KHR_materials_anisotropy` glTF extension. It includes some additional properties like support for both rotation and directional maps(like Blender), noise, interfacing with the progressive plugin etc.
40
+ *
41
+ * It also adds a UI to the material to edit the settings.
42
+ * It uses WEBGI_materials_anisotropy glTF extension to save the settings in glTF files.
43
+ * @category Plugins
44
+ */
45
+ @uiFolderContainer('Anisotropy (MatExt)')
46
+ export class AnisotropyPlugin extends AViewerPluginSync {
47
+ static readonly PluginType = 'AnisotropyPlugin'
48
+
49
+ @uiToggle('Enabled', (that: AnisotropyPlugin)=>({onChange: that.setDirty}))
50
+ @serialize() enabled = true
51
+
52
+ // todo add support for bicubic filtering?
53
+ // @uiToggle('Bicubic', (that: AnisotropyPlugin)=>({onChange: that.setDirty}))
54
+ // @matDefine('CUSTOM_BUMP_MAP_BICUBIC', undefined, true, AnisotropyPlugin.prototype.setDirty)
55
+ // @serialize() bicubicFiltering = true
56
+
57
+ private _defines: any = {
58
+ // ['ANISOTROPY_BICUBIC']: false,
59
+ }
60
+ private _uniforms: any = {
61
+ anisotropyFactor: {value: 1},
62
+ anisotropyNoise: {value: 1},
63
+ anisotropyDirection: {value: 1},
64
+ anisotropyDirectionMap: {value: null},
65
+ anisotropy2MapUvTransform: {value: new Matrix3()},
66
+ frameCount: {value: 0},
67
+ }
68
+
69
+ public enableAnisotropy(material: IMaterial, map?: ITexture, factor?: number, noise?: number, directionMode?: 'CONSTANT' | 'ROTATION' | 'DIRECTION'): boolean {
70
+ const ud = material?.userData
71
+ if (!ud) return false
72
+ if (ud._isAnisotropic === undefined) {
73
+ const meshes = material.appliedMeshes
74
+ let possible = true
75
+ if (meshes) for (const {geometry} of meshes) {
76
+ if (geometry && (!geometry.attributes.position || !geometry.attributes.normal || !geometry.attributes.uv)) {
77
+ possible = false
78
+ }
79
+ if (possible && geometry && !geometry.attributes.tangent) {
80
+ geometry.computeTangents()
81
+ }
82
+ }
83
+ if (!possible) {
84
+ return false
85
+ }
86
+ }
87
+ ud._isAnisotropic = true
88
+ ud._anisotropyFactor = factor ?? ud._anisotropyFactor ?? 1
89
+ ud._anisotropyNoise = noise ?? ud._anisotropyNoise ?? 0
90
+ ud._anisotropyDirection = /*direction ?? */ ud._anisotropyDirection ?? 1 // direction when map is not used
91
+ ud._anisotropyDirectionMode = directionMode ?? ud._anisotropyDirectionMode ?? 'DIRECTION'
92
+ ud._anisotropyDirectionMap = map ?? ud._anisotropyDirectionMap ?? null
93
+ if (material.setDirty) material.setDirty()
94
+ return true
95
+ }
96
+
97
+ readonly materialExtension: MaterialExtension = {
98
+ uuid: AnisotropyPlugin.PluginType,
99
+ priority: 10, // more than sscs(which is 5)
100
+ shaderExtender: (shader, material, _renderer) => {
101
+ if (this.isDisabled() || !material?.userData._isAnisotropic) return
102
+ const rotMap: ITexture | undefined | null = material.userData?._anisotropyDirectionMap
103
+
104
+ const bsdfs = glsl`
105
+ //#if ANISOTROPY_ENABLED
106
+ #include <randomHelpers>
107
+ #ifndef D_frameCount
108
+ #define D_frameCount
109
+ uniform float frameCount;
110
+ #endif
111
+ ${rotMap ? getTexelDecoding('anisotropyDirectionMap', rotMap?.colorSpace) : ''}\n
112
+ `
113
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#include <common>', bsdfs, {append: true})
114
+
115
+ // Because this frag is also patched in SSCS. todo set priority wrt sscs.
116
+ shader.fragmentShader = shader.fragmentShader.replace('#include <lights_fragment_begin>', ShaderChunk.lights_fragment_begin)
117
+
118
+ shader.fragmentShader = shaderReplaceString(
119
+ shaderReplaceString(shader.fragmentShader,
120
+ 'IncidentLight directLight;', anisotropyTBN, {prepend: true}),
121
+ 'RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight )',
122
+ 'RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight, anisotropicT, anisotropicB )', {replaceAll: true})
123
+
124
+ // eslint-disable-next-line @typescript-eslint/naming-convention
125
+ let lights_physical_pars_fragment = shaderReplaceString(ShaderChunk.lights_physical_pars_fragment,
126
+ 'void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {',
127
+ 'void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight, const in vec3 anisotropicT, const in vec3 anisotropicB ) {')
128
+ lights_physical_pars_fragment = shaderReplaceString(lights_physical_pars_fragment,
129
+ 'vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {',
130
+ anisotropyBsdf + '\n', {prepend: true})
131
+ lights_physical_pars_fragment = shaderReplaceString(lights_physical_pars_fragment,
132
+ 'BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material )',
133
+ 'BRDF_GGX_Anisotropy( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )')
134
+
135
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#include <lights_physical_pars_fragment>', lights_physical_pars_fragment)
136
+
137
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#include <normal_fragment_begin>', ShaderChunk.normal_fragment_begin)
138
+
139
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader,
140
+ '#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )',
141
+ '#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )')
142
+
143
+ // eslint-disable-next-line @typescript-eslint/naming-convention
144
+ let lights_fragment_maps = glsl`
145
+ #if defined( USE_ENVMAP )
146
+ vec3 anisotropyBentNormal = indirectAnisotropyBentNormal(geometryNormal, geometryViewDir, material.roughness, anisotropicT, anisotropicB);
147
+ #endif
148
+ ` + ShaderChunk.lights_fragment_maps
149
+ lights_fragment_maps = shaderReplaceString(lights_fragment_maps,
150
+ 'getIBLIrradiance( geometryNormal )',
151
+ 'getIBLIrradiance( anisotropyBentNormal )')
152
+ lights_fragment_maps = shaderReplaceString(lights_fragment_maps,
153
+ 'getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )',
154
+ 'getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )')
155
+
156
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#include <lights_fragment_maps>', lights_fragment_maps)
157
+
158
+ shader.vertexShader = shaderReplaceString(shader.vertexShader, '#include <uv_pars_vertex>',
159
+ `
160
+ #if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
161
+ varying vec2 vAnisotropy2MapUv;
162
+ uniform mat3 anisotropy2MapUvTransform;
163
+ #endif
164
+ `, {prepend: true},
165
+ )
166
+ shader.vertexShader = shaderReplaceString(shader.vertexShader, '#include <uv_vertex>',
167
+ `
168
+ #if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
169
+ vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;
170
+ #endif
171
+ `, {prepend: true},
172
+ )
173
+
174
+ if(!shader.defines) shader.defines = {}
175
+ shader.defines.USE_ANISOTROPY_BRDF = '' // for getting the brdf functions in shader
176
+ shader.defines.USE_UV = ''
177
+ shader.vertexTangents = true
178
+ },
179
+ onObjectRender: (object: IObject3D, material) => {
180
+ const userData = material.userData
181
+ if (!userData?._isAnisotropic) return
182
+ if (!object.isMesh || !object.geometry) return
183
+ if (!object.geometry.attributes.tangent) {
184
+ this._viewer?.console.error('AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.', object)
185
+ // throw new Error('AnisotropyPlugin: No tangents on the geometry')
186
+ // mesh.geometry.computeTangents() // tangents must be set before onBeforeRender call, otherwise it's not set in the program.
187
+ }
188
+ this._uniforms.anisotropyFactor.value = userData._anisotropyFactor ?? 1
189
+ this._uniforms.anisotropyNoise.value = userData._anisotropyNoise ?? 0
190
+ this._uniforms.anisotropyDirection.value = userData._anisotropyDirection ?? 1
191
+ const tex = userData._anisotropyDirectionMap?.isTexture ? userData._anisotropyDirectionMap : null
192
+ this._uniforms.anisotropyDirectionMap.value = tex
193
+ if (tex) {
194
+ tex.updateMatrix()
195
+ this._uniforms.anisotropy2MapUvTransform.value.copy(tex.matrix)
196
+ }
197
+ updateMaterialDefines({
198
+ ...this._defines,
199
+ ['ANISOTROPY_ENABLED']: +this.enabled,
200
+ // CONSTANT | ROTATION | DIRECTION
201
+ ['ANISOTROPY_TEX_MODE']: !tex ? 0 : userData._anisotropyDirectionMode === 'DIRECTION' ? 2 : userData._anisotropyDirectionMode === 'ROTATION' ? 1 : 0,
202
+ }, material)
203
+ },
204
+ extraUniforms: {
205
+ // ...this._uniforms, // done in constructor
206
+ },
207
+ computeCacheKey: material1 => {
208
+ return (this.enabled ? '1' : '0') + (material1.userData?._isAnisotropic ? '1' : '0') + material1.userData?._anisotropyDirectionMap?.uuid // todo: srgb ext + material1.userData?._anisotropyDirectionMap?.encoding
209
+ },
210
+ isCompatible: (material1: PhysicalMaterial) => material1.isPhysicalMaterial,
211
+ updaters: () =>
212
+ [
213
+ // this._viewer?.getPlugin(ProgressivePlugin),
214
+ // this._viewer?.scene.mainCamera,
215
+ this._viewer?.renderManager,
216
+ ] as IShaderPropertiesUpdater[],
217
+ getUiConfig: material => {
218
+ const viewer = this._viewer!
219
+ const enableAnisotropy = this.enableAnisotropy.bind(this)
220
+ const state = material.userData
221
+ const config: UiObjectConfig = {
222
+ type: 'folder',
223
+ label: 'Anisotropy',
224
+ onChange: (ev)=>{
225
+ if (!ev.config) return
226
+ this.setDirty()
227
+ },
228
+ children: [
229
+ {
230
+ type: 'checkbox',
231
+ label: 'Enabled',
232
+ get value() {
233
+ return state._isAnisotropic || false
234
+ },
235
+ set value(v) {
236
+ if (v === state._isAnisotropic) return
237
+ if (v) {
238
+ if (!enableAnisotropy(material))
239
+ viewer.dialog.alert('AnisotropyPlugin - One or more geometries cannot be made anisotropic.')
240
+ } else {
241
+ state._isAnisotropic = false
242
+ if (material.setDirty) material.setDirty()
243
+ }
244
+ config.uiRefresh?.(true, 'postFrame')
245
+ },
246
+ },
247
+ {
248
+ type: 'slider',
249
+ label: 'Factor',
250
+ bounds: [-2, 2],
251
+ hidden: () => !state._isAnisotropic,
252
+ property: [state, '_anisotropyFactor'],
253
+ // onChange: this.setDirty,
254
+ },
255
+ {
256
+ type: 'slider',
257
+ label: 'Noise',
258
+ bounds: [0, 2],
259
+ hidden: () => !state._isAnisotropic,
260
+ property: [state, '_anisotropyNoise'],
261
+ // onChange: this.setDirty,
262
+ },
263
+ {
264
+ type: 'dropdown',
265
+ label: 'Mode',
266
+ hidden: () => !state._isAnisotropic,
267
+ property: [state, '_anisotropyDirectionMode'],
268
+ children: ([
269
+ 'CONSTANT',
270
+ 'ROTATION',
271
+ 'DIRECTION',
272
+ ] as string[]).map(value => ({
273
+ label: value,
274
+ })),
275
+ onChange: ()=>{
276
+ if (material.setDirty) material.setDirty()
277
+ config.uiRefresh?.(true, 'postFrame')
278
+ },
279
+ },
280
+ {
281
+ type: 'slider',
282
+ label: 'Direction',
283
+ bounds: [0, 5],
284
+ hidden: () => state._anisotropyDirectionMode === 'CONSTANT' || !state._isAnisotropic,
285
+ property: [state, '_anisotropicDirection'],
286
+ // onChange: this.setDirty,
287
+ },
288
+ {
289
+ type: 'image',
290
+ label: 'Texture',
291
+ hidden: () => !state._isAnisotropic || state._anisotropyDirectionMode === 'CONSTANT',
292
+ property: [state, '_anisotropyDirectionMap'],
293
+ onChange: ()=>{
294
+ if (material.setDirty) material.setDirty()
295
+ },
296
+ },
297
+ makeSamplerUi(state as any, '_anisotropyDirectionMap', 'Sampler',() => !state._isAnisotropic || state._anisotropyDirectionMode === 'CONSTANT', ()=>material.setDirty && material.setDirty()),
298
+ ],
299
+ }
300
+ return config
301
+ },
302
+
303
+ // todo errors will be fixed on threepipe update
304
+ onMaterialUpdate: (material)=>{
305
+ if (!material.userData?._isAnisotropic) return
306
+ material.userData.__appliedMeshes?.forEach((m: any)=> this.tryComputeTangents(m, [material]))
307
+ },
308
+ onRegister: (material)=>{
309
+ if (!material.userData?._isAnisotropic) return
310
+ material.userData.__appliedMeshes?.forEach((m: any)=> this.tryComputeTangents(m, [material]))
311
+ },
312
+ onAddToMesh: (mesh: IObject3D)=>{
313
+ if(!mesh.isMesh) return
314
+ const m = mesh
315
+ const mats = Array.isArray(m.material) ? m.material : [m.material]
316
+ if (!mats.find(m1=>m1?.userData?._isAnisotropic)) return
317
+ this.tryComputeTangents(m, mats as any)
318
+ },
319
+ }
320
+
321
+ tryComputeTangents(m: IObject3D, mats: IMaterial[]) {
322
+ if (m.geometry && !m.geometry.attributes.tangent) {
323
+ let possible = true
324
+ if (!m.geometry.index || !m.geometry.attributes.position || !m.geometry.attributes.normal || !m.geometry.attributes.uv) {
325
+ possible = false
326
+ }
327
+ if (possible) m.geometry.computeTangents()
328
+ else mats.map(m1=>{
329
+ if (m1?.userData?._isAnisotropic) m1.userData._isAnisotropic = false
330
+ })
331
+ }
332
+ }
333
+
334
+ setDirty = (): void => {
335
+ this.materialExtension.setDirty?.()
336
+ this._viewer?.setDirty()
337
+ }
338
+
339
+ constructor() {
340
+ super()
341
+ Object.assign(this.materialExtension.extraUniforms!, this._uniforms)
342
+ }
343
+
344
+ onAdded(v: ThreeViewer) {
345
+ super.onAdded(v)
346
+ v.assetManager.materials.registerMaterialExtension(this.materialExtension)
347
+ v.assetManager.registerGltfExtension(anisotropyGLTFExtension)
348
+ }
349
+
350
+ onRemove(v: ThreeViewer) {
351
+ v.assetManager.materials?.unregisterMaterialExtension(this.materialExtension)
352
+ v.assetManager.unregisterGltfExtension(anisotropyGLTFExtension.name)
353
+ return super.onRemove(v)
354
+ }
355
+
356
+ // @uiButton('Enable Anisotropy (selected)', (that: AnisotropyPlugin)=>({hidden: ()=>!that._viewer?.getPlugin(PickingPlugin)}))
357
+ // makeSelectedAnisotropic = (): boolean => {
358
+ // const material = (this._viewer?.getPlugin(PickingPlugin)?.getSelectedObject() as any)?.material as IMaterial
359
+ // if (material?.assetType !== 'material') return false
360
+ // return this.enableAnisotropy(material)
361
+ // }
362
+
363
+ /**
364
+ * @deprecated use {@link anisotropyGLTFExtension}
365
+ */
366
+ public static readonly ANISOTROPY_GLTF_EXTENSION = 'WEBGI_materials_anisotropy'
367
+
368
+
369
+ /**
370
+ * @deprecated - use {@link enableAnisotropy} instead
371
+ * @param material
372
+ */
373
+ public makeAnisotropic(material: IMaterial): boolean {
374
+ return this.enableAnisotropy(material)
375
+ }
376
+ }
377
+
378
+ declare module 'threepipe' {
379
+ interface IMaterialUserData {
380
+ /**
381
+ * Is the material anisotropic
382
+ */
383
+ _isAnisotropic?: boolean
384
+ /**
385
+ * Anisotropy factor
386
+ */
387
+ _anisotropyFactor?: number
388
+ /**
389
+ * Anisotropy noise factor
390
+ */
391
+ _anisotropyNoise?: number
392
+ /**
393
+ * Anisotropy direction mode
394
+ */
395
+ _anisotropyDirectionMode?: 'CONSTANT' | 'ROTATION' | 'DIRECTION'
396
+ /**
397
+ * Anisotropy direction map, when mode is ROTATION or DIRECTION
398
+ */
399
+ _anisotropyDirectionMap?: ITexture | null
400
+ /**
401
+ * Direction when map is not used, when mode is CONSTANT
402
+ */
403
+ _anisotropyDirection?: number
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Anisotropy Materials Extension
409
+ *
410
+ * Specification: https://webgi.xyz/docs/gltf-extensions/WEBGI_materials_anisotropy.html
411
+ */
412
+
413
+ class GLTFMaterialsAnisotropyExtensionImport implements GLTFLoaderPlugin {
414
+ public name: string
415
+ public parser: GLTFParser
416
+
417
+ constructor(parser: GLTFParser) {
418
+
419
+ this.parser = parser
420
+ this.name = anisotropyGLTFExtension.name
421
+
422
+ }
423
+
424
+ async extendMaterialParams(materialIndex: number, materialParams: any) {
425
+
426
+ const parser = this.parser
427
+ const materialDef = parser.json.materials[materialIndex]
428
+
429
+ if (!materialDef.extensions || !materialDef.extensions[this.name]) {
430
+
431
+ return Promise.resolve()
432
+
433
+ }
434
+
435
+ const pending = []
436
+
437
+ const extension = materialDef.extensions[this.name]
438
+
439
+ if (!materialParams.userData) materialParams.userData = {}
440
+ materialParams.userData._isAnisotropic = true // single _ so that its saved when cloning( and tojson) but not when saving glb
441
+ materialParams.userData._anisotropyFactor = extension.anisotropyFactor ?? 0.0
442
+ materialParams.userData._anisotropyNoise = extension.anisotropyNoiseFactor ?? extension.anisotropyNoise ?? 0.
443
+
444
+ let {anisotropyDirectionMode, anisotropyDirection} = extension
445
+
446
+ // backwards compatibility. todo: make changes to blender plugin.
447
+ if (!anisotropyDirectionMode) anisotropyDirectionMode = extension.anisotropyTextureMode
448
+ if (!anisotropyDirection) anisotropyDirection = extension.anisotropyRotation
449
+
450
+ materialParams.userData._anisotropyDirectionMode = anisotropyDirectionMode && typeof anisotropyDirection?.index === 'number' ? anisotropyDirectionMode : 'CONSTANT'
451
+ if (anisotropyDirectionMode === 'ROTATION' || anisotropyDirectionMode === 'DIRECTION') {
452
+ pending.push(parser.assignTexture(materialParams.userData, '_anisotropyDirectionMap', anisotropyDirection).then((t: any) => {
453
+ // t.format = RGBFormat
454
+ t.colorSpace = SRGBColorSpace
455
+ }))
456
+ // pending.push(parser.assignTexture(materialParams, 'map', anisotropyDirection))
457
+ } else {
458
+ materialParams.userData._anisotropyDirection = anisotropyDirection ?? 0
459
+ }
460
+ return Promise.all(pending)
461
+ }
462
+
463
+ afterRoot(result: GLTF): Promise<void> | null {
464
+ result.scene?.traverse((object: any) => {
465
+ const mat = object.material?.userData?._isAnisotropic
466
+ if (!mat) return
467
+ const geom = object.geometry
468
+ if (!geom.attributes.tangent) {
469
+ geom.computeTangents()
470
+ geom.attributes.tangent.needsUpdate = true
471
+ }
472
+
473
+ })
474
+ return null
475
+ }
476
+
477
+ }
478
+
479
+
480
+ const glTFMaterialsAnisotropyExtensionExport = (w: GLTFWriter2)=> ({
481
+ writeMaterial: (material: any, materialDef: any) => {
482
+ if (!material.isMeshStandardMaterial || !material.userData._isAnisotropic) return
483
+
484
+ if ((material.userData._anisotropyFactor || 0) < 0.001) return // todo: is this correct?
485
+
486
+ materialDef.extensions = materialDef.extensions || {}
487
+
488
+ const extensionDef: any = {}
489
+
490
+ extensionDef.anisotropyFactor = material.userData._anisotropyFactor || 1.0
491
+ extensionDef.anisotropyNoiseFactor = material.userData._anisotropyNoise || 0.0
492
+ extensionDef.anisotropyDirectionMode = material.userData._anisotropyDirectionMode || 'CONSTANT'
493
+
494
+ if (w.checkEmptyMap(material.userData._anisotropyDirectionMap) && extensionDef.anisotropyDirectionMode !== 'CONSTANT') {
495
+
496
+ const anisotropyDirectionMapDef = {index: w.processTexture(material.userData._anisotropyDirectionMap)}
497
+ w.applyTextureTransform(anisotropyDirectionMapDef, material.userData._anisotropyDirectionMap)
498
+ extensionDef.anisotropyDirection = anisotropyDirectionMapDef
499
+
500
+ } else {
501
+
502
+ extensionDef.anisotropyDirectionMode = 'CONSTANT'
503
+ extensionDef.anisotropyDirection = material.userData._anisotropyDirection || 0.0
504
+
505
+ }
506
+
507
+ materialDef.extensions[ anisotropyGLTFExtension.name ] = extensionDef
508
+ w.extensionsUsed[ anisotropyGLTFExtension.name ] = true
509
+ },
510
+ })
511
+
512
+ export const anisotropyGLTFExtension = {
513
+ name: 'WEBGI_materials_anisotropy',
514
+ import: (p) => new GLTFMaterialsAnisotropyExtensionImport(p),
515
+ export: glTFMaterialsAnisotropyExtensionExport,
516
+ textures: {
517
+ anisotropyDirection: 'RGB',
518
+ },
519
+ } satisfies AssetManager['gltfExtensions'][number]
@@ -0,0 +1,156 @@
1
+ import {
2
+ AViewerPluginSync,
3
+ ISceneEventMap,
4
+ Object3D,
5
+ onChange, ProgressivePlugin,
6
+ serialize,
7
+ ThreeViewer,
8
+ uiButton,
9
+ uiDropdown,
10
+ uiFolderContainer,
11
+ uiInput,
12
+ uiSlider,
13
+ uiToggle
14
+ } from "threepipe"
15
+
16
+ @uiFolderContainer('Watch Hands Time')
17
+ export class WatchHandsPlugin extends AViewerPluginSync {
18
+ static readonly PluginType = 'WatchHandsPlugin'
19
+
20
+ @uiToggle()
21
+ @serialize()
22
+ enabled = true
23
+
24
+ dependencies = []
25
+
26
+ @uiDropdown(undefined, ['x', 'y', 'z'].map(label=>({label})))
27
+ @serialize()
28
+ axis: 'x'|'y'|'z' = 'y'
29
+
30
+ @uiToggle()
31
+ @serialize()
32
+ invertAxis = false
33
+
34
+ @uiToggle()
35
+ @serialize()
36
+ analog = true
37
+
38
+ @uiSlider(undefined, [0, 12], 0.001)
39
+ @serialize()
40
+ hourOffset = 0
41
+
42
+ @uiSlider(undefined, [0, 60], 0.001)
43
+ @serialize()
44
+ minuteOffset = 0
45
+
46
+ @uiSlider(undefined, [0, 60], 0.001)
47
+ @serialize()
48
+ secondOffset = 0
49
+
50
+ @uiInput()
51
+ @serialize()
52
+ hour = '.*hour.*'
53
+ @uiInput()
54
+ @serialize()
55
+ minute = '.*minute.*'
56
+ @uiInput()
57
+ @serialize()
58
+ second = '.*second.*'
59
+
60
+ @uiToggle()
61
+ @onChange('refresh')
62
+ @serialize()
63
+ regex = true
64
+
65
+ hands: {
66
+ type: 'hour' | 'minute' | 'second'
67
+ object: Object3D
68
+ }[] = []
69
+
70
+ onAdded(viewer: ThreeViewer): void {
71
+ super.onAdded(viewer)
72
+ viewer.scene.addEventListener('addSceneObject', this._addSceneObject)
73
+ viewer.addEventListener('preFrame', this._preFrame)
74
+ }
75
+ onRemove(viewer: ThreeViewer): void {
76
+ viewer.scene.removeEventListener('addSceneObject', this._addSceneObject)
77
+ viewer.removeEventListener('preFrame', this._preFrame)
78
+ super.onRemove(viewer)
79
+ }
80
+
81
+ private _lastEnabled = true
82
+ private _preFrame = () => {
83
+ if (!this.enabled) {
84
+ if (this._lastEnabled) {
85
+ this._lastEnabled = false
86
+ if (!this.hands.length) return
87
+ for (const h of this.hands) {
88
+ h.object.rotation.fromArray(h.object.userData.initRotation)
89
+ h.object.updateMatrixWorld()
90
+ }
91
+ this._viewer?.renderManager.resetShadows()
92
+ this._viewer?.setDirty()
93
+ }
94
+ return
95
+ }
96
+ this._lastEnabled = true
97
+ if (!this.hands.length) return
98
+
99
+ const d = this._viewer?.getPlugin<ProgressivePlugin>('ProgressivePlugin')?.postFrameConvergedRecordingDelta()
100
+ // if (d && d > 0) delta = d
101
+ if (d === 0) return // not converged yet.
102
+ // if d < 0: not recording, do nothing
103
+
104
+ // viewer.addEventListener('preFrame', () => {
105
+
106
+ // hand_hour - y 0-2*PI
107
+ // hand_minute - y 0-2*PI
108
+ // hand_second - y 3*PI-PI
109
+ const time = new Date()
110
+ const invert = this.invertAxis ? -1 : 1
111
+ const secondHandRotation = invert * (time.getSeconds() + (this.analog ? time.getMilliseconds() / 1000 : 0) - this.secondOffset) * (Math.PI * 2) / 60
112
+ const minuteHandRotation = invert * (time.getMinutes() - this.minuteOffset) * (Math.PI * 2) / 60 + secondHandRotation / 60
113
+ const hourHandRotation = invert * (time.getHours() - this.hourOffset) * (Math.PI * 2) / 12 + minuteHandRotation / 12
114
+
115
+ // every found hand counts, so a watch without a second hand (or a changed offset) updates too
116
+ const targetRotation = {second: secondHandRotation, minute: minuteHandRotation, hour: hourHandRotation}
117
+ if (this.hands.some(h=>Math.abs(targetRotation[h.type] - h.object.rotation[this.axis]) > 0.001)) {
118
+ for (const hand of this.hands) {
119
+ hand.object.rotation[this.axis] = targetRotation[hand.type]
120
+ }
121
+ this._viewer?.renderManager.resetShadows()
122
+ this._viewer?.setDirty()
123
+ }
124
+ // })
125
+ }
126
+
127
+ private _addSceneObject = async(e: ISceneEventMap['addSceneObject']): Promise<void> => {
128
+ if (!e.object) return
129
+ this.refresh()
130
+ }
131
+
132
+ @uiButton()
133
+ refresh() {
134
+ this.hands = []
135
+ this._viewer?.scene.modelRoot.traverse(o=>{
136
+ let isChild = false
137
+ o.traverseAncestors(oa=>{
138
+ if (isChild) return
139
+ if (this.hands.find(h=>h.object === oa)) isChild = true
140
+ })
141
+ if (isChild) return
142
+ if (o.name.match(this.regex ? new RegExp(this.hour) : this.hour)) {
143
+ if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray()
144
+ this.hands.push({type: 'hour', object: o})
145
+ }
146
+ if (o.name.match(this.regex ? new RegExp(this.minute) : this.minute)) {
147
+ if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray()
148
+ this.hands.push({type: 'minute', object: o})
149
+ }
150
+ if (o.name.match(this.regex ? new RegExp(this.second) : this.second)) {
151
+ if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray()
152
+ this.hands.push({type: 'second', object: o})
153
+ }
154
+ })
155
+ }
156
+ }