threepipe
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

GBufferPlugin.ts 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. // LINEAR_DEPTH: 1, // to tell that the depth is linear. todo; see SSAOPlugin. also add support in DepthBufferPlugin?
  126. },
  127. priority: 100,
  128. isCompatible: () => true,
  129. }
  130. private _isPrimaryGBufferSet = false
  131. protected _createTargetAndMaterial(recreateTarget = true) {
  132. if (!this._viewer) return
  133. if (recreateTarget) this._disposeTarget()
  134. const useMultiple = this._viewer?.renderManager.isWebGL2 && this.renderFlagsBuffer
  135. if (!this.target) {
  136. this.target = this._viewer.renderManager.createTarget<GBufferPluginTarget>(
  137. {
  138. depthBuffer: true,
  139. samples: this._viewer.renderManager.zPrepass && this.isPrimaryGBuffer ? // requirement for zPrepass
  140. this._viewer.renderManager.composerTarget.samples || 0 : 0,
  141. type: this.bufferType,
  142. textureCount: useMultiple ? 2 : 1,
  143. depthTexture: this.renderDepthTexture,
  144. depthTextureType: this.depthTextureType,
  145. // magFilter: NearestFilter,
  146. // minFilter: NearestFilter,
  147. // generateMipmaps: false,
  148. // encoding: LinearEncoding,
  149. wrapS: ClampToEdgeWrapping,
  150. wrapT: ClampToEdgeWrapping,
  151. })
  152. if (Array.isArray(this.target.texture)) {
  153. this.target.texture[0].name = 'gbufferDepthNormal'
  154. this.target.texture[1].name = 'gbufferFlags'
  155. this.textures = this.target.texture
  156. } else {
  157. this.target.texture.name = 'gbufferDepthNormal'
  158. this.textures.push(this.target.texture)
  159. }
  160. }
  161. if (!this.material) {
  162. this.material = new GBufferMaterial(useMultiple, {
  163. blending: NoBlending,
  164. transparent: true,
  165. })
  166. }
  167. if (this._pass) this._pass.target = this.target
  168. if (this.isPrimaryGBuffer) {
  169. this._viewer.renderManager.gbufferTarget = this.target
  170. this._viewer.renderManager.gbufferUnpackExtension = this.unpackExtension
  171. this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension])
  172. this._isPrimaryGBufferSet = true
  173. }
  174. }
  175. protected _disposeTarget() {
  176. if (!this._viewer) return
  177. if (this.target) {
  178. this._viewer.renderManager.disposeTarget(this.target)
  179. this.target = undefined
  180. }
  181. this.textures = []
  182. if (this._isPrimaryGBufferSet) { // using a separate flag as when isPrimaryGBuffer is changed, we cannot check it.
  183. this._viewer.renderManager.gbufferTarget = undefined
  184. this._viewer.renderManager.gbufferUnpackExtension = undefined
  185. // this._viewer.renderManager.screenPass.material.unregisterMaterialExtensions([this.unpackExtension]) // todo
  186. this._isPrimaryGBufferSet = false
  187. }
  188. }
  189. protected _createPass() {
  190. this._createTargetAndMaterial(true)
  191. if (!this.target) throw new Error('GBufferPlugin: target not created')
  192. if (!this.material) throw new Error('GBufferPlugin: material not created')
  193. this.material.userData.isGBufferMaterial = true
  194. const pass = new GBufferRenderPass(this.passId, this.target, this.material, new Color(1, 1, 1), 1)
  195. const preprocessMaterial = pass.preprocessMaterial
  196. pass.preprocessMaterial = (m) => preprocessMaterial(m, m.userData.renderToDepth) // if renderToDepth is undefined then renderToGbuffer is taken internally
  197. pass.before = ['render']
  198. pass.after = []
  199. pass.required = ['render']
  200. return pass
  201. }
  202. protected _beforeRender(scene: IScene, camera: ICamera, renderManager: IRenderManager): boolean {
  203. if (!super._beforeRender(scene, camera, renderManager) || !this.material) return false
  204. camera.updateShaderProperties(this.material)
  205. return true
  206. }
  207. constructor(
  208. bufferType: TextureDataType = UnsignedByteType,
  209. isPrimaryGBuffer = true,
  210. enabled = true,
  211. public renderFlagsBuffer: boolean = true,
  212. public renderDepthTexture: boolean = false,
  213. public depthTextureType: typeof UnsignedShortType | typeof UnsignedIntType | typeof FloatType /* | typeof UnsignedInt248Type*/ = UnsignedIntType,
  214. // packing: DepthPackingStrategies = BasicDepthPacking,
  215. ) {
  216. super()
  217. this.enabled = enabled
  218. this.bufferType = bufferType
  219. this.isPrimaryGBuffer = isPrimaryGBuffer
  220. // this.depthPacking = depthPacking
  221. }
  222. registerGBufferUpdater(key: string, updater: GBufferUpdater['updateGBufferFlags']): void {
  223. if (this.material) this.material.flagUpdaters.set(key, updater)
  224. }
  225. unregisterGBufferUpdater(key: string): void {
  226. if (this.material) this.material.flagUpdaters.delete(key)
  227. }
  228. onRemove(viewer: ThreeViewer): void {
  229. this._disposeTarget()
  230. this.material?.dispose()
  231. this.material = undefined
  232. return super.onRemove(viewer)
  233. }
  234. /**
  235. * @deprecated use {@link normalDepthTexture} instead
  236. */
  237. getDepthNormal() {
  238. return this.textures.length > 0 ? this.textures[0] : undefined
  239. }
  240. /**
  241. * @deprecated use {@link flagsTexture} instead
  242. */
  243. getFlagsTexture() {
  244. return this.textures.length > 1 ? this.textures[1] : undefined
  245. }
  246. /**
  247. * @deprecated use {@link target} instead
  248. */
  249. getTarget() {
  250. return this.target
  251. }
  252. /**
  253. * @deprecated use {@link unpackExtension} instead
  254. */
  255. getUnpackSnippet(): string {
  256. return GBufferUnpack
  257. }
  258. /**
  259. * @deprecated use {@link unpackExtension} instead, it adds the same uniforms and defines
  260. * @param material
  261. */
  262. updateShaderProperties(material: {defines: Record<string, string | number | undefined>; uniforms: {[p: string]: IUniform}, needsUpdate?: boolean}): this {
  263. if (material.uniforms.tNormalDepth) material.uniforms.tNormalDepth.value = this.normalDepthTexture ?? undefined
  264. else this._viewer?.console.warn('BaseRenderer: no uniform: tNormalDepth')
  265. if (material.uniforms.tGBufferFlags) {
  266. material.uniforms.tGBufferFlags.value = this.flagsTexture ?? undefined
  267. const t = material.uniforms.tGBufferFlags.value ? 1 : 0
  268. if (t !== material.defines.GBUFFER_HAS_FLAGS) {
  269. material.defines.GBUFFER_HAS_FLAGS = t
  270. material.needsUpdate = true
  271. }
  272. }
  273. return this
  274. }
  275. }
  276. /**
  277. * Renders DepthNormal to a texture and flags to another
  278. */
  279. export class GBufferMaterial extends ShaderMaterial2 {
  280. constructor(multipleRT = true, parameters?: ShaderMaterialParameters & IMaterialParameters) {
  281. super({
  282. vertexShader: GBufferMatVert,
  283. fragmentShader: GBufferMatFrag,
  284. uniforms: UniformsUtils.merge([
  285. UniformsLib.common,
  286. UniformsLib.bumpmap,
  287. UniformsLib.normalmap,
  288. UniformsLib.displacementmap,
  289. {
  290. cameraNearFar: {value: new Vector2(0.1, 1000)}, // this has to be set from outside
  291. flags: {value: new Vector4(255, 255, 255, 255)},
  292. },
  293. ]),
  294. defines: {
  295. // eslint-disable-next-line @typescript-eslint/naming-convention
  296. IS_GLSL3: multipleRT ? '1' : '0',
  297. },
  298. glslVersion: multipleRT ? GLSL3 : GLSL1,
  299. ...parameters,
  300. })
  301. this.reset()
  302. }
  303. flagUpdaters: Map<string, GBufferUpdater['updateGBufferFlags']> = new Map()
  304. normalMapType: NormalMapTypes = TangentSpaceNormalMap
  305. flatShading = false
  306. onBeforeRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  307. super.onBeforeRender(renderer, scene, camera, geometry, object)
  308. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  309. if (Array.isArray(material)) { // todo: add support for multi materials.
  310. material = material[0]
  311. }
  312. if (!material) return
  313. const setMap = (key: keyof IMaterial)=>{
  314. const map = material[key]
  315. if (!map) return
  316. this.uniforms[key].value = map
  317. if (!this.uniforms[key + 'Transform']) console.error('GBufferMaterial: ' + key + 'Transform is not defined in uniform')
  318. else renderer.materials.refreshTransformUniform(map, this.uniforms[key + 'Transform'])
  319. }
  320. setMap('map')
  321. if (material.side !== undefined) this.side = material.side ?? DoubleSide
  322. setMap('alphaMap')
  323. if (material.alphaTest !== undefined) this.alphaTest = material.alphaTest < 1e-4 ? 1e-4 : material.alphaTest
  324. setMap('bumpMap')
  325. if (material.bumpScale !== undefined) this.uniforms.bumpScale.value = material.bumpScale
  326. setMap('normalMap')
  327. if (material.normalScale !== undefined) this.uniforms.normalScale.value.copy(material.normalScale)
  328. if (material.normalMapType !== undefined) this.normalMapType = material.normalMapType
  329. if (material.flatShading !== undefined) this.flatShading = material.flatShading
  330. setMap('displacementMap')
  331. if (material.displacementScale !== undefined) this.uniforms.displacementScale.value = material.displacementScale
  332. if (material.displacementBias !== undefined) this.uniforms.displacementBias.value = material.displacementBias
  333. if (material.wireframe !== undefined) this.wireframe = material.wireframe
  334. if (material.wireframeLinewidth !== undefined) this.wireframeLinewidth = material.wireframeLinewidth
  335. /*
  336. GBuffer Flags has the following data
  337. 1st Rendertarget has Depth and Normal buffers
  338. 2nd Render Target::
  339. x : Empty
  340. y : first 3 bits lut index, second 5 bits bevel radius
  341. z : material id (userData.gBufferData?.materialId, userData.matId)
  342. w : this field is for setting bits - lutEnable-0, tonemap-1, bloom-2
  343. */
  344. this.uniforms.flags.value.set(255, 255, 255, 255)
  345. const materialId = material.userData.gBufferData?.materialId ?? material.userData.matId // matId for backward compatibility
  346. this.uniforms.flags.value.z = materialId || 0
  347. this.flagUpdaters.forEach((updater)=> updater(this.uniforms.flags.value, {material, renderer, scene, camera, geometry, object}))
  348. this.uniforms.flags.value.x /= 255
  349. this.uniforms.flags.value.y /= 255
  350. this.uniforms.flags.value.z /= 255
  351. this.uniforms.flags.value.w /= 255
  352. this.uniformsNeedUpdate = true
  353. updateMaterialDefines({
  354. // ['USE_ALPHAMAP']: this.uniforms.alphaMap.value ? 1 : undefined,
  355. ['ALPHAMAP_UV']: this.uniforms.alphaMap.value ? 'uv' : undefined, // todo use getChannel, see WebGLPrograms.js
  356. ['USE_DISPLACEMENTMAP']: this.uniforms.displacementMap.value ? 1 : undefined,
  357. ['DISPLACEMENTMAP_UV']: this.uniforms.displacementMap.value ? 'uv' : undefined, // todo use getChannel, see WebGLPrograms.js
  358. ['ALPHA_I_RGBA_PACKING']: material.userData.ALPHA_I_RGBA_PACKING ? 1 : undefined,
  359. ['FORCED_LINEAR_DEPTH']: material.userData.forcedLinearDepth ?? undefined, // todo add to DepthBufferPlugin as well.
  360. }, material)
  361. // todo: do the same in DepthBufferPlugin and NormalBufferPlugin
  362. // what about the material extension settings in the userData of the source materials?
  363. if (material.materialExtensions?.length) {
  364. this.registerMaterialExtensions(material.materialExtensions)
  365. }
  366. // this.transparent = true
  367. this.needsUpdate = true
  368. }
  369. onAfterRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  370. super.onAfterRender(renderer, scene, camera, geometry, object)
  371. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  372. if (Array.isArray(material)) { // todo: add support for multi materials.
  373. material = material[0]
  374. }
  375. if (!material) return
  376. if (material.materialExtensions?.length) {
  377. this.unregisterMaterialExtensions(material.materialExtensions)
  378. }
  379. this.reset()
  380. }
  381. reset() {
  382. this.uniforms.map.value = null
  383. this.side = DoubleSide
  384. this.uniforms.alphaMap.value = null
  385. this.alphaTest = 0.001
  386. this.uniforms.bumpMap.value = null
  387. this.uniforms.bumpScale.value = 1
  388. this.uniforms.normalMap.value = null
  389. this.uniforms.normalScale.value.set(1, 1)
  390. this.normalMapType = TangentSpaceNormalMap
  391. this.flatShading = false
  392. this.uniforms.displacementMap.value = null
  393. this.uniforms.displacementScale.value = 1
  394. this.uniforms.displacementBias.value = 0
  395. this.uniforms.flags.value.set(255, 255, 255, 255)
  396. this.wireframe = false
  397. this.wireframeLinewidth = 1
  398. }
  399. }
  400. /**
  401. * @deprecated use GBufferMaterial instead
  402. */
  403. export class DepthNormalMaterial extends GBufferMaterial {
  404. constructor(multipleRT: boolean, parameters?: ShaderMaterialParameters & IMaterialParameters) {
  405. super(multipleRT, parameters)
  406. console.warn('DepthNormalMaterial is deprecated, use GBufferMaterial instead')
  407. }
  408. }