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.

GBufferPlugin.ts 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import {
  2. BufferGeometry,
  3. Camera,
  4. ClampToEdgeWrapping,
  5. Color,
  6. DepthTexture,
  7. DoubleSide,
  8. FloatType,
  9. GLSL1,
  10. GLSL3,
  11. IUniform,
  12. NoBlending,
  13. NormalMapTypes,
  14. Object3D,
  15. Scene,
  16. ShaderMaterialParameters,
  17. TangentSpaceNormalMap,
  18. Texture,
  19. TextureDataType,
  20. UniformsLib,
  21. UniformsUtils,
  22. UnsignedByteType,
  23. UnsignedIntType,
  24. UnsignedShortType,
  25. Vector2,
  26. Vector4,
  27. WebGLMultipleRenderTargets,
  28. WebGLRenderer,
  29. WebGLRenderTarget,
  30. } from 'three'
  31. import {GBufferRenderPass} from '../../postprocessing'
  32. import {ThreeViewer} from '../../viewer'
  33. import {MaterialExtension, updateMaterialDefines} from '../../materials'
  34. import {PipelinePassPlugin} from '../base/PipelinePassPlugin'
  35. import {uiFolderContainer, uiImage} from 'uiconfig.js'
  36. import {shaderReplaceString} from '../../utils'
  37. import GBufferUnpack from './shaders/GBufferPlugin.unpack.glsl'
  38. import GBufferMatVert from './shaders/GBufferPlugin.mat.vert.glsl'
  39. import GBufferMatFrag from './shaders/GBufferPlugin.mat.frag.glsl'
  40. import {
  41. ICamera,
  42. IMaterial,
  43. IMaterialParameters,
  44. IRenderManager,
  45. IScene,
  46. ITexture,
  47. PhysicalMaterial,
  48. ShaderMaterial2,
  49. } from '../../core'
  50. export type GBufferPluginEventTypes = ''
  51. type GBufferPluginTarget = WebGLMultipleRenderTargets | WebGLRenderTarget
  52. // export type GBufferPluginTarget = WebGLRenderTarget
  53. export type GBufferPluginPass = GBufferRenderPass<'gbuffer', GBufferPluginTarget>
  54. export interface GBufferUpdaterContext {
  55. material: IMaterial, renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D
  56. }
  57. export interface GBufferUpdater {
  58. updateGBufferFlags: (data: Vector4, context: GBufferUpdaterContext) => void
  59. }
  60. /**
  61. * G-Buffer Plugin
  62. *
  63. * Adds a pre-render pass to render the g-buffer(depth+normal+flags) to render target(s) that can be used as gbuffer and for postprocessing.
  64. * @category Plugins
  65. */
  66. @uiFolderContainer('G-Buffer Plugin')
  67. export class GBufferPlugin
  68. extends PipelinePassPlugin<GBufferPluginPass, 'gbuffer', GBufferPluginEventTypes> {
  69. readonly passId = 'gbuffer'
  70. public static readonly PluginType = 'GBuffer'
  71. target?: GBufferPluginTarget
  72. // @uiConfig(/* {readOnly: true}*/) // todo: fix bug in uiconfig or tpImageGenerator because of which 0 index is not showing in the UI, when we uncomment this
  73. textures: Texture[] = []
  74. @uiImage(/* {readOnly: true}*/)
  75. get normalDepthTexture(): ITexture|undefined {
  76. return this.textures[0]
  77. }
  78. @uiImage(/* {readOnly: true}*/)
  79. get flagsTexture(): ITexture|undefined {
  80. return this.textures[1]
  81. }
  82. @uiImage(/* {readOnly: true}*/)
  83. get depthTexture(): (ITexture&DepthTexture)|undefined {
  84. return this.target?.depthTexture
  85. }
  86. // @uiConfig() // not supported in this material yet
  87. material?: GBufferMaterial
  88. // @onChange(GBufferPlugin.prototype._depthPackingChanged)
  89. // @uiDropdown('Depth Packing', threeConstMappings.DepthPackingStrategies.uiConfig) packing: DepthPackingStrategies
  90. // @onChange2(GBufferPlugin.prototype._createTargetAndMaterial)
  91. // @uiDropdown('Buffer Type', threeConstMappings.TextureDataType.uiConfig)
  92. readonly bufferType: TextureDataType // cannot be changed after creation (for now)
  93. // @uiToggle()
  94. // @onChange2(GBufferPlugin.prototype._createTargetAndMaterial)
  95. readonly isPrimaryGBuffer: boolean // cannot be changed after creation (for now)
  96. // protected _depthPackingChanged() {
  97. // this.material.depthPacking = this.depthPacking
  98. // this.material.needsUpdate = true
  99. // if (this.unpackExtension && this.unpackExtension.extraDefines) {
  100. // this.unpackExtension.extraDefines.DEPTH_PACKING = this.depthPacking
  101. // this.unpackExtension.setDirty?.()
  102. // }
  103. // this.setDirty()
  104. // }
  105. unpackExtension: MaterialExtension = {
  106. shaderExtender: (shader)=>{
  107. const includes = ['gbuffer_unpack', 'packing'] as const
  108. const include = includes.find(i=>shader.fragmentShader.includes(`#include <${i}>`))
  109. shader.fragmentShader = shaderReplaceString(shader.fragmentShader,
  110. `#include <${include}>`,
  111. '\n' + GBufferUnpack + '\n', {append: include === 'packing'})
  112. },
  113. extraUniforms: {
  114. tNormalDepth: ()=>({value: this.normalDepthTexture}),
  115. tGBufferFlags: ()=>({value: this.flagsTexture}),
  116. tGBufferDepthTexture: ()=>({value: this.depthTexture}),
  117. },
  118. extraDefines: {
  119. // ['GBUFFER_PACKING']: BasicDepthPacking,
  120. ['HAS_NORMAL_DEPTH_BUFFER']: ()=>this.normalDepthTexture ? 1 : undefined,
  121. ['GBUFFER_HAS_DEPTH_TEXTURE']: ()=>this.depthTexture ? 1 : undefined,
  122. ['GBUFFER_HAS_FLAGS']: ()=>this.flagsTexture ? 1 : undefined,
  123. // ['HAS_FLAGS_BUFFER']: ()=>this.flagsTexture ? 1 : undefined,
  124. ['HAS_GBUFFER']: ()=>this.isPrimaryGBuffer && this.normalDepthTexture ? 1 : undefined,
  125. },
  126. priority: 100,
  127. isCompatible: () => true,
  128. }
  129. private _isPrimaryGBufferSet = false
  130. protected _createTargetAndMaterial(recreateTarget = true) {
  131. if (!this._viewer) return
  132. if (recreateTarget) this._disposeTarget()
  133. const useMultiple = this._viewer?.renderManager.isWebGL2 && this.renderFlagsBuffer
  134. if (!this.target) {
  135. this.target = this._viewer.renderManager.createTarget<GBufferPluginTarget>(
  136. {
  137. depthBuffer: true,
  138. samples: this._viewer.renderManager.zPrepass && this.isPrimaryGBuffer ? // requirement for zPrepass
  139. this._viewer.renderManager.composerTarget.samples || 0 : 0,
  140. type: this.bufferType,
  141. textureCount: useMultiple ? 2 : 1,
  142. depthTexture: this.renderDepthTexture,
  143. depthTextureType: this.depthTextureType,
  144. // magFilter: NearestFilter,
  145. // minFilter: NearestFilter,
  146. // generateMipmaps: false,
  147. // encoding: LinearEncoding,
  148. wrapS: ClampToEdgeWrapping,
  149. wrapT: ClampToEdgeWrapping,
  150. })
  151. if (Array.isArray(this.target.texture)) {
  152. this.target.texture[0].name = 'gbufferDepthNormal'
  153. this.target.texture[1].name = 'gbufferFlags'
  154. this.textures = this.target.texture
  155. } else {
  156. this.target.texture.name = 'gbufferDepthNormal'
  157. this.textures.push(this.target.texture)
  158. }
  159. }
  160. if (!this.material) {
  161. this.material = new GBufferMaterial(useMultiple, {
  162. blending: NoBlending,
  163. transparent: true,
  164. })
  165. }
  166. if (this._pass) this._pass.target = this.target
  167. if (this.isPrimaryGBuffer) {
  168. this._viewer.renderManager.gbufferTarget = this.target
  169. this._viewer.renderManager.gbufferUnpackExtension = this.unpackExtension
  170. this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension])
  171. this._isPrimaryGBufferSet = true
  172. }
  173. }
  174. protected _disposeTarget() {
  175. if (!this._viewer) return
  176. if (this.target) {
  177. this._viewer.renderManager.disposeTarget(this.target)
  178. this.target = undefined
  179. }
  180. this.textures = []
  181. if (this._isPrimaryGBufferSet) { // using a separate flag as when isPrimaryGBuffer is changed, we cannot check it.
  182. this._viewer.renderManager.gbufferTarget = undefined
  183. this._viewer.renderManager.gbufferUnpackExtension = undefined
  184. // this._viewer.renderManager.screenPass.material.unregisterMaterialExtensions([this.unpackExtension]) // todo
  185. this._isPrimaryGBufferSet = false
  186. }
  187. }
  188. protected _createPass() {
  189. this._createTargetAndMaterial(true)
  190. if (!this.target) throw new Error('GBufferPlugin: target not created')
  191. if (!this.material) throw new Error('GBufferPlugin: material not created')
  192. this.material.userData.isGBufferMaterial = true
  193. const pass = new GBufferRenderPass(this.passId, this.target, this.material, new Color(1, 1, 1), 1)
  194. const preprocessMaterial = pass.preprocessMaterial
  195. pass.preprocessMaterial = (m) => preprocessMaterial(m, m.userData.renderToDepth) // if renderToDepth is undefined then renderToGbuffer is taken internally
  196. pass.before = ['render']
  197. pass.after = []
  198. pass.required = ['render']
  199. return pass
  200. }
  201. protected _beforeRender(scene: IScene, camera: ICamera, renderManager: IRenderManager): boolean {
  202. if (!super._beforeRender(scene, camera, renderManager) || !this.material) return false
  203. camera.updateShaderProperties(this.material)
  204. return true
  205. }
  206. constructor(
  207. bufferType: TextureDataType = UnsignedByteType,
  208. isPrimaryGBuffer = true,
  209. enabled = true,
  210. public renderFlagsBuffer: boolean = true,
  211. public renderDepthTexture: boolean = false,
  212. public depthTextureType: typeof UnsignedShortType | typeof UnsignedIntType | typeof FloatType /* | typeof UnsignedInt248Type*/ = UnsignedIntType,
  213. // packing: DepthPackingStrategies = BasicDepthPacking,
  214. ) {
  215. super()
  216. this.enabled = enabled
  217. this.bufferType = bufferType
  218. this.isPrimaryGBuffer = isPrimaryGBuffer
  219. // this.depthPacking = depthPacking
  220. }
  221. registerGBufferUpdater(key: string, updater: GBufferUpdater['updateGBufferFlags']): void {
  222. if (this.material) this.material.flagUpdaters.set(key, updater)
  223. }
  224. unregisterGBufferUpdater(key: string): void {
  225. if (this.material) this.material.flagUpdaters.delete(key)
  226. }
  227. onRemove(viewer: ThreeViewer): void {
  228. this._disposeTarget()
  229. this.material?.dispose()
  230. this.material = undefined
  231. return super.onRemove(viewer)
  232. }
  233. /**
  234. * @deprecated use {@link normalDepthTexture} instead
  235. */
  236. getDepthNormal() {
  237. return this.textures.length > 0 ? this.textures[0] : undefined
  238. }
  239. /**
  240. * @deprecated use {@link flagsTexture} instead
  241. */
  242. getFlagsTexture() {
  243. return this.textures.length > 1 ? this.textures[1] : undefined
  244. }
  245. /**
  246. * @deprecated use {@link target} instead
  247. */
  248. getTarget() {
  249. return this.target
  250. }
  251. /**
  252. * @deprecated use {@link unpackExtension} instead
  253. */
  254. getUnpackSnippet(): string {
  255. return GBufferUnpack
  256. }
  257. /**
  258. * @deprecated use {@link unpackExtension} instead, it adds the same uniforms and defines
  259. * @param material
  260. */
  261. updateShaderProperties(material: {defines: Record<string, string | number | undefined>; uniforms: {[p: string]: IUniform}, needsUpdate?: boolean}): this {
  262. if (material.uniforms.tNormalDepth) material.uniforms.tNormalDepth.value = this.normalDepthTexture ?? undefined
  263. else this._viewer?.console.warn('BaseRenderer: no uniform: tNormalDepth')
  264. if (material.uniforms.tGBufferFlags) {
  265. material.uniforms.tGBufferFlags.value = this.flagsTexture ?? undefined
  266. const t = material.uniforms.tGBufferFlags.value ? 1 : 0
  267. if (t !== material.defines.GBUFFER_HAS_FLAGS) {
  268. material.defines.GBUFFER_HAS_FLAGS = t
  269. material.needsUpdate = true
  270. }
  271. }
  272. return this
  273. }
  274. }
  275. /**
  276. * Renders DepthNormal to a texture and flags to another
  277. */
  278. export class GBufferMaterial extends ShaderMaterial2 {
  279. constructor(multipleRT = true, parameters?: ShaderMaterialParameters & IMaterialParameters) {
  280. super({
  281. vertexShader: GBufferMatVert,
  282. fragmentShader: GBufferMatFrag,
  283. uniforms: UniformsUtils.merge([
  284. UniformsLib.common,
  285. UniformsLib.bumpmap,
  286. UniformsLib.normalmap,
  287. UniformsLib.displacementmap,
  288. {
  289. cameraNearFar: {value: new Vector2(0.1, 1000)}, // this has to be set from outside
  290. flags: {value: new Vector4(255, 255, 255, 255)},
  291. },
  292. ]),
  293. defines: {
  294. // eslint-disable-next-line @typescript-eslint/naming-convention
  295. IS_GLSL3: multipleRT ? '1' : '0',
  296. },
  297. glslVersion: multipleRT ? GLSL3 : GLSL1,
  298. ...parameters,
  299. })
  300. this.reset()
  301. }
  302. flagUpdaters: Map<string, GBufferUpdater['updateGBufferFlags']> = new Map()
  303. normalMapType: NormalMapTypes = TangentSpaceNormalMap
  304. flatShading = false
  305. onBeforeRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  306. super.onBeforeRender(renderer, scene, camera, geometry, object)
  307. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  308. if (Array.isArray(material)) { // todo: add support for multi materials.
  309. material = material[0]
  310. }
  311. if (!material) return
  312. const setMap = (key: keyof IMaterial)=>{
  313. const map = material[key]
  314. if (!map) return
  315. this.uniforms[key].value = map
  316. if (!this.uniforms[key + 'Transform']) console.error('GBufferMaterial: ' + key + 'Transform is not defined in uniform')
  317. else renderer.materials.refreshTransformUniform(map, this.uniforms[key + 'Transform'])
  318. }
  319. setMap('map')
  320. if (material.side !== undefined) this.side = material.side ?? DoubleSide
  321. setMap('alphaMap')
  322. if (material.alphaTest !== undefined) this.alphaTest = material.alphaTest < 1e-4 ? 1e-4 : material.alphaTest
  323. setMap('bumpMap')
  324. if (material.bumpScale !== undefined) this.uniforms.bumpScale.value = material.bumpScale
  325. setMap('normalMap')
  326. if (material.normalScale !== undefined) this.uniforms.normalScale.value.copy(material.normalScale)
  327. if (material.normalMapType !== undefined) this.normalMapType = material.normalMapType
  328. if (material.flatShading !== undefined) this.flatShading = material.flatShading
  329. setMap('displacementMap')
  330. if (material.displacementScale !== undefined) this.uniforms.displacementScale.value = material.displacementScale
  331. if (material.displacementBias !== undefined) this.uniforms.displacementBias.value = material.displacementBias
  332. if (material.wireframe !== undefined) this.wireframe = material.wireframe
  333. if (material.wireframeLinewidth !== undefined) this.wireframeLinewidth = material.wireframeLinewidth
  334. /*
  335. GBuffer Flags has the following data
  336. 1st Rendertarget has Depth and Normal buffers
  337. 2nd Render Target::
  338. x : Empty
  339. y : first 3 bits lut index, second 5 bits bevel radius
  340. z : material id (userData.gBufferData?.materialId, userData.matId)
  341. w : this field is for setting bits - lutEnable-0, tonemap-1, bloom-2
  342. */
  343. this.uniforms.flags.value.set(255, 255, 255, 255)
  344. const materialId = material.userData.gBufferData?.materialId ?? material.userData.matId // matId for backward compatibility
  345. this.uniforms.flags.value.z = materialId || 0
  346. this.flagUpdaters.forEach((updater)=> updater(this.uniforms.flags.value, {material, renderer, scene, camera, geometry, object}))
  347. this.uniforms.flags.value.x /= 255
  348. this.uniforms.flags.value.y /= 255
  349. this.uniforms.flags.value.z /= 255
  350. this.uniforms.flags.value.w /= 255
  351. this.uniformsNeedUpdate = true
  352. updateMaterialDefines({
  353. // ['USE_ALPHAMAP']: this.uniforms.alphaMap.value ? 1 : undefined,
  354. ['ALPHAMAP_UV']: this.uniforms.alphaMap.value ? 'uv' : undefined, // todo use getChannel, see WebGLPrograms.js
  355. ['USE_DISPLACEMENTMAP']: this.uniforms.displacementMap.value ? 1 : undefined,
  356. ['DISPLACEMENTMAP_UV']: this.uniforms.displacementMap.value ? 'uv' : undefined, // todo use getChannel, see WebGLPrograms.js
  357. ['ALPHA_I_RGBA_PACKING']: material.userData.ALPHA_I_RGBA_PACKING ? 1 : undefined,
  358. ['FORCED_LINEAR_DEPTH']: material.userData.forcedLinearDepth ?? undefined,
  359. }, material)
  360. // todo: do the same in DepthBufferPlugin and NormalBufferPlugin
  361. // what about the material extension settings in the userData of the source materials?
  362. if (material.materialExtensions?.length) {
  363. this.registerMaterialExtensions(material.materialExtensions)
  364. }
  365. // this.transparent = true
  366. this.needsUpdate = true
  367. }
  368. onAfterRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  369. super.onAfterRender(renderer, scene, camera, geometry, object)
  370. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  371. if (Array.isArray(material)) { // todo: add support for multi materials.
  372. material = material[0]
  373. }
  374. if (!material) return
  375. if (material.materialExtensions?.length) {
  376. this.unregisterMaterialExtensions(material.materialExtensions)
  377. }
  378. this.reset()
  379. }
  380. reset() {
  381. this.uniforms.map.value = null
  382. this.side = DoubleSide
  383. this.uniforms.alphaMap.value = null
  384. this.alphaTest = 0.001
  385. this.uniforms.bumpMap.value = null
  386. this.uniforms.bumpScale.value = 1
  387. this.uniforms.normalMap.value = null
  388. this.uniforms.normalScale.value.set(1, 1)
  389. this.normalMapType = TangentSpaceNormalMap
  390. this.flatShading = false
  391. this.uniforms.displacementMap.value = null
  392. this.uniforms.displacementScale.value = 1
  393. this.uniforms.displacementBias.value = 0
  394. this.uniforms.flags.value.set(255, 255, 255, 255)
  395. this.wireframe = false
  396. this.wireframeLinewidth = 1
  397. }
  398. }
  399. /**
  400. * @deprecated use GBufferMaterial instead
  401. */
  402. export class DepthNormalMaterial extends GBufferMaterial {
  403. constructor(multipleRT: boolean, parameters?: ShaderMaterialParameters & IMaterialParameters) {
  404. super(multipleRT, parameters)
  405. console.warn('DepthNormalMaterial is deprecated, use GBufferMaterial instead')
  406. }
  407. }