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.

DepthBufferPlugin.ts 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import {
  2. BasicDepthPacking,
  3. BufferGeometry,
  4. Camera,
  5. Color,
  6. DepthPackingStrategies,
  7. DoubleSide,
  8. FrontSide,
  9. MeshDepthMaterial,
  10. MeshDepthMaterialParameters,
  11. NoBlending,
  12. Object3D,
  13. Scene,
  14. Texture,
  15. TextureDataType,
  16. UnsignedByteType,
  17. WebGLRenderer,
  18. WebGLRenderTarget,
  19. } from 'three'
  20. import {GBufferRenderPass} from '../../postprocessing'
  21. import {ThreeViewer} from '../../viewer'
  22. import {MaterialExtension} from '../../materials'
  23. import {PipelinePassPlugin} from '../base/PipelinePassPlugin'
  24. import {uiDropdown, uiFolderContainer, uiImage} from 'uiconfig.js'
  25. import {shaderReplaceString} from '../../utils'
  26. import {onChange} from 'ts-browser-helpers'
  27. import DepthBufferUnpack from './shaders/DepthBufferPlugin.unpack.glsl'
  28. import {threeConstMappings} from '../../three'
  29. import {IMaterial, PhysicalMaterial} from '../../core'
  30. export type DepthBufferPluginEventTypes = ''
  31. // type DepthBufferPluginTarget = WebGLMultipleRenderTargets | WebGLRenderTarget
  32. export type DepthBufferPluginTarget = WebGLRenderTarget
  33. export type DepthBufferPluginPass = GBufferRenderPass<'depth', DepthBufferPluginTarget>
  34. /**
  35. * Depth Buffer Plugin
  36. *
  37. * Adds a pre-render pass to render the depth buffer to a render target that can be used as gbuffer or for postprocessing.
  38. * @category Plugins
  39. */
  40. @uiFolderContainer('Depth Buffer Plugin')
  41. export class DepthBufferPlugin
  42. extends PipelinePassPlugin<DepthBufferPluginPass, 'depth', DepthBufferPluginEventTypes> {
  43. readonly passId = 'depth'
  44. public static readonly PluginType = 'DepthBufferPlugin'
  45. target?: DepthBufferPluginTarget
  46. @uiImage('Depth Buffer' /* {readOnly: true}*/) texture?: Texture
  47. // @uiConfig() // not supported in this material yet
  48. readonly material: MeshDepthMaterial = new MeshDepthMaterialOverride({
  49. depthPacking: BasicDepthPacking,
  50. blending: NoBlending,
  51. transparent: true,
  52. })
  53. @onChange(DepthBufferPlugin.prototype._depthPackingChanged)
  54. @uiDropdown('Depth Packing', threeConstMappings.DepthPackingStrategies.uiConfig) depthPacking: DepthPackingStrategies
  55. // @onChange2(DepthBufferPlugin.prototype._createTarget)
  56. // @uiDropdown('Buffer Type', threeConstMappings.TextureDataType.uiConfig)
  57. readonly bufferType: TextureDataType // cannot be changed after creation (for now)
  58. // @uiToggle()
  59. // @onChange2(DepthBufferPlugin.prototype._createTarget)
  60. readonly isPrimaryGBuffer: boolean // cannot be changed after creation (for now)
  61. protected _depthPackingChanged() {
  62. this.material.depthPacking = this.depthPacking
  63. this.material.needsUpdate = true
  64. if (this.unpackExtension && this.unpackExtension.extraDefines) {
  65. this.unpackExtension.extraDefines.DEPTH_PACKING = this.depthPacking
  66. this.unpackExtension.setDirty?.()
  67. }
  68. this.setDirty()
  69. }
  70. unpackExtension: MaterialExtension = {
  71. shaderExtender: (shader)=>{
  72. shader.fragmentShader = shaderReplaceString(shader.fragmentShader,
  73. '#include <packing>',
  74. '\n' + DepthBufferUnpack + '\n', {append: true})
  75. },
  76. extraUniforms: {
  77. tDepthBuffer: ()=>({value: this.target?.texture}),
  78. },
  79. extraDefines: {
  80. ['DEPTH_PACKING']: BasicDepthPacking,
  81. ['HAS_DEPTH_BUFFER']: ()=>this.target?.texture ? 1 : undefined,
  82. ['HAS_GBUFFER']: ()=>this.isPrimaryGBuffer && this.target?.texture ? 1 : undefined,
  83. },
  84. priority: 100,
  85. isCompatible: () => true,
  86. }
  87. private _isPrimaryGBufferSet = false
  88. protected _createTarget(recreate = true) {
  89. if (!this._viewer) return
  90. if (recreate) this._disposeTarget()
  91. if (!this.target)
  92. this.target = this._viewer.renderManager.createTarget<DepthBufferPluginTarget>(
  93. {
  94. depthBuffer: true,
  95. samples: this._viewer.renderManager.composerTarget.samples || 0,
  96. type: this.bufferType,
  97. // magFilter: NearestFilter,
  98. // minFilter: NearestFilter,
  99. // generateMipmaps: false,
  100. // encoding: LinearEncoding,
  101. })
  102. this.texture = this.target.texture
  103. this.texture.name = 'depthBuffer'
  104. if (this._pass) this._pass.target = this.target
  105. if (this.isPrimaryGBuffer) {
  106. this._viewer.renderManager.gbufferTarget = this.target
  107. this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension])
  108. this._isPrimaryGBufferSet = true
  109. }
  110. }
  111. protected _disposeTarget() {
  112. if (!this._viewer) return
  113. if (this.target) {
  114. this._viewer.renderManager.disposeTarget(this.target)
  115. this.target = undefined
  116. }
  117. this.texture = undefined
  118. if (this._isPrimaryGBufferSet) { // using a separate flag as when isPrimaryGBuffer is changed, we cannot check it.
  119. this._viewer.renderManager.gbufferTarget = undefined
  120. // this._viewer.renderManager.screenPass.material.unregisterMaterialExtensions([this.unpackExtension]) // todo
  121. this._isPrimaryGBufferSet = false
  122. }
  123. }
  124. protected _createPass() {
  125. this._createTarget(true)
  126. if (!this.target) throw new Error('DepthBufferPlugin: target not created')
  127. this.material.userData.isGBufferMaterial = true
  128. const pass = new GBufferRenderPass('depth', this.target, this.material, new Color(0, 0, 0), 1)
  129. const preprocessMaterial = pass.preprocessMaterial
  130. pass.preprocessMaterial = (m) => preprocessMaterial(m, m.userData.renderToDepth)
  131. pass.before = ['render']
  132. pass.after = []
  133. pass.required = ['render']
  134. return pass
  135. }
  136. constructor(
  137. bufferType: TextureDataType = UnsignedByteType,
  138. isPrimaryGBuffer = false,
  139. enabled = true,
  140. depthPacking: DepthPackingStrategies = BasicDepthPacking,
  141. ) {
  142. super()
  143. this.enabled = enabled
  144. this.depthPacking = depthPacking
  145. this.bufferType = bufferType
  146. this.isPrimaryGBuffer = isPrimaryGBuffer
  147. }
  148. onRemove(viewer: ThreeViewer): void {
  149. this._disposeTarget()
  150. return super.onRemove(viewer)
  151. }
  152. }
  153. class MeshDepthMaterialOverride extends MeshDepthMaterial {
  154. constructor(parameters: MeshDepthMaterialParameters) {
  155. super(parameters)
  156. this.reset()
  157. }
  158. onBeforeRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  159. super.onBeforeRender(renderer, scene, camera, geometry, object)
  160. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  161. if (Array.isArray(material)) { // todo: add support for multi materials.
  162. material = material[0]
  163. }
  164. if (!material) return
  165. if (material.map !== undefined) this.map = material.map // in case there is alpha in the map.
  166. if (material.side !== undefined) this.side = material.side ?? FrontSide
  167. if (material.alphaMap !== undefined) this.alphaMap = material.alphaMap
  168. if (material.alphaTest !== undefined) this.alphaTest = material.alphaTest < 1e-4 ? 1e-4 : material.alphaTest
  169. if (material.displacementMap !== undefined) this.displacementMap = material.displacementMap
  170. if (material.displacementScale !== undefined) this.displacementScale = material.displacementScale
  171. if (material.displacementBias !== undefined) this.displacementBias = material.displacementBias
  172. if (material.wireframe !== undefined) this.wireframe = material.wireframe
  173. if (material.wireframeLinewidth !== undefined) this.wireframeLinewidth = material.wireframeLinewidth
  174. this.needsUpdate = true
  175. }
  176. onAfterRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  177. super.onAfterRender(renderer, scene, camera, geometry, object)
  178. this.reset()
  179. }
  180. reset() {
  181. this.map = null
  182. this.side = DoubleSide
  183. this.alphaMap = null
  184. this.alphaTest = 0.001
  185. this.displacementMap = null
  186. this.displacementScale = 1
  187. this.displacementBias = 0
  188. this.wireframe = false
  189. this.wireframeLinewidth = 1
  190. }
  191. }