threepipe
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

script.ts 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import {
  2. _testFinish,
  3. BaseGroundPlugin,
  4. BasicShadowMap,
  5. Color,
  6. DataUtils,
  7. DirectionalLight,
  8. IObject3D,
  9. LoadingScreenPlugin,
  10. MaterialExtension,
  11. ProgressivePlugin,
  12. ShaderChunk,
  13. shaderReplaceString,
  14. SSAAPlugin,
  15. ThreeViewer,
  16. Vector3,
  17. } from 'threepipe'
  18. import {TweakpaneUiPlugin} from '@threepipe/plugin-tweakpane'
  19. const hdris = [
  20. 'https://threejs.org/examples/textures/equirectangular/quarry_01_1k.hdr',
  21. 'https://threejs.org/examples/textures/equirectangular/spot1Lux.hdr',
  22. 'https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr',
  23. 'https://dist.pixotronics.com/webgi/assets/hdr/gem_2.hdr',
  24. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_04_1k.hdr',
  25. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_03_1k.hdr',
  26. 'https://threejs.org/examples/textures/equirectangular/pedestrian_overpass_1k.hdr',
  27. 'https://threejs.org/examples/textures/equirectangular/blouberg_sunrise_2_1k.hdr',
  28. 'https://threejs.org/examples/textures/equirectangular/royal_esplanade_1k.hdr',
  29. 'https://threejs.org/examples/textures/equirectangular/moonless_golf_1k.hdr',
  30. 'https://threejs.org/examples/textures/equirectangular/san_giuseppe_bridge_2k.hdr',
  31. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_06_1k.hdr',
  32. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_05_1k.hdr',
  33. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_02_1k.hdr',
  34. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_01_1k.hdr',
  35. ]
  36. async function init() {
  37. const viewer = new ThreeViewer({
  38. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  39. msaa: false,
  40. rgbm: false,
  41. plugins: [new ProgressivePlugin((window as any).TESTING ? 20 : 200), SSAAPlugin, LoadingScreenPlugin],
  42. dropzone: {
  43. addOptions: {
  44. disposeSceneObjects: true,
  45. autoSetEnvironment: true,
  46. autoSetBackground: true,
  47. },
  48. },
  49. })
  50. const directionalLight = createDirLight(viewer)
  51. viewer.materialManager.registerMaterialExtension(extension)
  52. viewer.renderManager.renderer.shadowMap.type = BasicShadowMap
  53. // extra check to ignore the sampling of shadow if intensity is 0
  54. ShaderChunk.lights_fragment_begin = shaderReplaceString(
  55. ShaderChunk.lights_fragment_begin,
  56. 'directLight.color *= ( directLight.visible && receiveShadow )',
  57. 'directLight.color *= ( directLight.visible && receiveShadow && length(directLight.color) > 0.001)',
  58. {replaceAll: true})
  59. const ground = viewer.addPluginSync(BaseGroundPlugin)
  60. ground.mesh!.castShadow = false
  61. ground.material!.roughness = 1
  62. ground.material!.metalness = 0
  63. const ui = viewer.addPluginSync(new TweakpaneUiPlugin(false))
  64. await viewer.load<IObject3D>('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  65. autoCenter: true,
  66. autoScale: true,
  67. })
  68. viewer.scene.envMapIntensity = 1
  69. await viewer.setEnvironmentMap(hdris[0], {
  70. setBackground: true,
  71. })
  72. ui.appendChild({
  73. type: 'dropdown',
  74. label: 'Environment Map',
  75. children: hdris.map((url)=>({
  76. label: url.split('/').pop()!.split('.').shift()!,
  77. value: url,
  78. })),
  79. value: hdris[0],
  80. onChange: async(ev)=>{
  81. console.log(ev.value)
  82. await viewer.setEnvironmentMap(ev.value, {
  83. setBackground: true,
  84. })
  85. refreshHist()
  86. },
  87. })
  88. let histogram2 = createHistogramFromImage(viewer.scene.environment?.image)
  89. function refreshHist() {
  90. histogram2 = createHistogramFromImage(viewer.scene.environment?.image)
  91. }
  92. viewer.addEventListener('postFrame', ()=>updateLight(viewer, directionalLight, histogram2))
  93. ui.setupPluginUi(BaseGroundPlugin)
  94. // const targetPreview = viewer.addPluginSync(new RenderTargetPreviewPlugin())
  95. // targetPreview.addTarget(()=>directionalLight.shadow.map, 'shadow')
  96. }
  97. const extension: MaterialExtension = {
  98. isCompatible: ()=> true,
  99. computeCacheKey: ()=> 'aomap1',
  100. shaderExtender(shader) {
  101. shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#include <aomap_fragment>', `
  102. #ifdef USE_AOMAP
  103. // reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture
  104. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  105. #else
  106. const int ii = 0;
  107. DirectionalLightShadow edls = directionalLightShadows[ ii ];
  108. float ambientOcclusion = getShadow( directionalShadowMap[ ii ], edls.shadowMapSize, edls.shadowBias, edls.shadowRadius, vDirectionalShadowCoord[ ii ] );
  109. #endif
  110. reflectedLight.indirectDiffuse *= ambientOcclusion;
  111. #if defined( USE_ENVMAP ) && defined( STANDARD )
  112. float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );
  113. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  114. #endif
  115. `)
  116. // shader.defines.USE_UV = ''
  117. },
  118. }
  119. function createDirLight(viewer: ThreeViewer) {
  120. const directionalLight = new DirectionalLight(0xffffff, 4)
  121. directionalLight.position.set(-2, -2, 2)
  122. directionalLight.lookAt(0, 0, 0)
  123. directionalLight.color.set(0xffffff)
  124. directionalLight.intensity = 0
  125. directionalLight.castShadow = true
  126. directionalLight.shadow.mapSize.setScalar(1024)
  127. directionalLight.shadow.camera.near = 0.1
  128. directionalLight.shadow.camera.far = 10
  129. directionalLight.shadow.camera.top = 2
  130. directionalLight.shadow.camera.bottom = -2
  131. directionalLight.shadow.camera.left = -2
  132. directionalLight.shadow.camera.right = 2
  133. viewer.scene.addObject(directionalLight, {addToRoot: true})
  134. // move to index 0 in parent.children, so that directionalLight always has index 0 in shader. required for material extension
  135. const parent = directionalLight.parent!
  136. const index = parent.children.indexOf(directionalLight)
  137. if (index > 0) {
  138. parent.children.splice(index, 1)
  139. parent.children.unshift(directionalLight)
  140. }
  141. return directionalLight
  142. }
  143. function updateLight(viewer: ThreeViewer, directionalLight: DirectionalLight, histogram: ReturnType<typeof createHistogramFromImage>) {
  144. if (viewer.renderManager.frameCount < 1) return
  145. // if (viewer.renderManager.frameCount > 2) return
  146. const bounds = viewer.scene.getBounds(false)
  147. const size = bounds.getSize(new Vector3()).length()
  148. const center = bounds.getCenter(new Vector3())
  149. const i = viewer.renderManager.frameCount <= 1 ? histogram.brightestI : histogram.sampleIndex()
  150. histogram.indexToColor(i, directionalLight)
  151. directionalLight.intensity = 0 // so it doesnt show in the scene
  152. histogram.indexToPosition(i, directionalLight.position).multiplyScalar(0.5 + size).add(center)
  153. directionalLight.lookAt(center)
  154. directionalLight.shadow.camera.near = Math.max(size / 100, 0.1)
  155. directionalLight.shadow.camera.far = size * 2.5
  156. directionalLight.shadow.camera.updateProjectionMatrix()
  157. viewer.renderManager.resetShadows()
  158. }
  159. function sampleRandom2(pow = 2) {
  160. return Math.max(0, Math.pow(Math.random(), pow) - 0.001)
  161. }
  162. function sampleRandom() {
  163. return Math.max(0, Math.random() - 0.001)
  164. }
  165. const maxIntensityClamp = 50
  166. const ignoreBottomBins = 1 // should be at-least 1 to ignore black pixels.
  167. const numBins = 100 // Number of bins in the histogram (configurable)
  168. const sampleRandPower = 1.25 // increase this to give more focus to higher intensity pixels. between 1 and 2
  169. const topHalf = true // todo if this is true, half the shadow in shader?
  170. function createHistogramFromImage(image: {data: Uint16Array, width: number, height: number}) {
  171. const histogram: number[][] = []
  172. let maxIntensity = -1
  173. let brightestI = 0
  174. // const maxIntensity1 = 65504
  175. for (let i = 0; i < image.data.length / 4; i++) {
  176. const r = DataUtils.fromHalfFloat(image.data[i * 4])
  177. const g = DataUtils.fromHalfFloat(image.data[i * 4 + 1])
  178. const b = DataUtils.fromHalfFloat(image.data[i * 4 + 2])
  179. const a = DataUtils.fromHalfFloat(image.data[i * 4 + 3])
  180. const intensity = a * Math.max(r, g, b) // Calculate intensity
  181. const binIndex = Math.floor(numBins * Math.max(0, Math.min(1 - 0.001, intensity / maxIntensityClamp))) // Calculate the bin index
  182. histogram[binIndex] ||= []
  183. histogram[binIndex].push(i)
  184. if (maxIntensity < intensity) {
  185. maxIntensity = intensity
  186. brightestI = i
  187. }
  188. if (topHalf && i > image.data.length / 8) break
  189. }
  190. histogram.reverse()
  191. const cdf = histogram.map((bin) => bin ? bin.length : 0)
  192. const maxW = numBins - 1 - ignoreBottomBins + 1
  193. cdf[0] = cdf[0] * maxW
  194. for (let i = 1; i < numBins; i++) {
  195. cdf[i] = cdf[i - 1] + (cdf[i] || 0) * (maxW - i) // *i for intensity of that bin
  196. }
  197. console.log(cdf)
  198. return {
  199. histogram, cdf,
  200. brightestI,
  201. maxIntensity,
  202. sampleIndex: ()=>{
  203. const max = cdf[cdf.length - 1]
  204. const r = sampleRandom2(sampleRandPower) * max
  205. const binIndex = cdf.findIndex((value) => value >= r)
  206. const bin = histogram[binIndex]
  207. const index = Math.floor(bin.length * sampleRandom())
  208. return bin[index]
  209. },
  210. indexToPosition: (i: number, position: Vector3)=>{
  211. // todo handle envMapRotation
  212. const {width, height} = image
  213. const x = i % width / width
  214. const y = 1 - Math.floor(i / width) / height
  215. const phi = Math.PI * (x * 2 - 1)
  216. const theta = Math.PI * 0.5 * (y * 2 - 1)
  217. return position.set(
  218. Math.cos(theta) * Math.cos(phi),
  219. Math.sin(theta),
  220. Math.cos(theta) * Math.sin(phi),
  221. )
  222. },
  223. indexToColor: (i: number, light: {color: Color, intensity: number})=>{
  224. // todo handle envMapIntensity
  225. const r = DataUtils.fromHalfFloat(image.data[i * 4])
  226. const g = DataUtils.fromHalfFloat(image.data[i * 4 + 1])
  227. const b = DataUtils.fromHalfFloat(image.data[i * 4 + 2])
  228. const a = DataUtils.fromHalfFloat(image.data[i * 4 + 3])
  229. light.color.setRGB(Math.min(1, r * a), Math.min(1, g * a), Math.min(1, b * a))
  230. light.intensity = Math.min(a * Math.max(r, g, b), maxIntensityClamp)
  231. },
  232. }
  233. }
  234. init().finally(_testFinish)