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.

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