prePassRenderer.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import { MultiRenderTarget } from "../Materials/Textures/multiRenderTarget";
  2. import { Scene } from "../scene";
  3. import { Engine } from "../Engines/engine";
  4. import { Constants } from "../Engines/constants";
  5. import { ImageProcessingPostProcess } from "../PostProcesses/imageProcessingPostProcess";
  6. import { PostProcess } from "../PostProcesses/postProcess";
  7. import { Effect } from "../Materials/effect";
  8. import { _DevTools } from '../Misc/devTools';
  9. import { Color4 } from "../Maths/math.color";
  10. import { PrePassEffectConfiguration } from "./prePassEffectConfiguration";
  11. import { Nullable } from "../types";
  12. import { AbstractMesh } from '../Meshes/abstractMesh';
  13. import { Material } from '../Materials/material';
  14. import { SubMesh } from '../Meshes/subMesh';
  15. import { GeometryBufferRenderer } from '../Rendering/geometryBufferRenderer';
  16. /**
  17. * Renders a pre pass of the scene
  18. * This means every mesh in the scene will be rendered to a render target texture
  19. * And then this texture will be composited to the rendering canvas with post processes
  20. * It is necessary for effects like subsurface scattering or deferred shading
  21. */
  22. export class PrePassRenderer {
  23. /** @hidden */
  24. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  25. throw _DevTools.WarnImport("PrePassRendererSceneComponent");
  26. }
  27. private _textureFormats = [
  28. {
  29. type: Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE,
  30. format: Constants.TEXTURETYPE_HALF_FLOAT,
  31. },
  32. {
  33. type: Constants.PREPASS_POSITION_TEXTURE_TYPE,
  34. format: Constants.TEXTURETYPE_HALF_FLOAT,
  35. },
  36. {
  37. type: Constants.PREPASS_VELOCITY_TEXTURE_TYPE,
  38. format: Constants.TEXTURETYPE_HALF_FLOAT,
  39. },
  40. {
  41. type: Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE,
  42. format: Constants.TEXTURETYPE_UNSIGNED_INT,
  43. },
  44. {
  45. type: Constants.PREPASS_COLOR_TEXTURE_TYPE,
  46. format: Constants.TEXTURETYPE_HALF_FLOAT,
  47. },
  48. {
  49. type: Constants.PREPASS_DEPTHNORMAL_TEXTURE_TYPE,
  50. format: Constants.TEXTURETYPE_HALF_FLOAT,
  51. },
  52. {
  53. type: Constants.PREPASS_ALBEDO_TEXTURE_TYPE,
  54. format: Constants.TEXTURETYPE_UNSIGNED_INT,
  55. },
  56. ];
  57. /**
  58. * To save performance, we can excluded skinned meshes from the prepass
  59. */
  60. public excludedSkinnedMesh: AbstractMesh[] = [];
  61. /**
  62. * Force material to be excluded from the prepass
  63. * Can be useful when `useGeometryBufferFallback` is set to `true`
  64. * and you don't want a material to show in the effect.
  65. */
  66. public excludedMaterials: Material[] = [];
  67. private _textureIndices: number[] = [];
  68. private _scene: Scene;
  69. private _engine: Engine;
  70. private _isDirty: boolean = false;
  71. /**
  72. * Number of textures in the multi render target texture where the scene is directly rendered
  73. */
  74. public mrtCount: number = 0;
  75. /**
  76. * The render target where the scene is directly rendered
  77. */
  78. public prePassRT: MultiRenderTarget;
  79. private _multiRenderAttachments: number[];
  80. private _defaultAttachments: number[];
  81. private _clearAttachments: number[];
  82. private _postProcesses: PostProcess[] = [];
  83. private readonly _clearColor = new Color4(0, 0, 0, 0);
  84. /**
  85. * Image processing post process for composition
  86. */
  87. public imageProcessingPostProcess: ImageProcessingPostProcess;
  88. /**
  89. * Configuration for prepass effects
  90. */
  91. private _effectConfigurations: PrePassEffectConfiguration[] = [];
  92. private _mrtFormats: number[] = [];
  93. private _mrtLayout: number[];
  94. private _enabled: boolean = false;
  95. /**
  96. * Indicates if the prepass is enabled
  97. */
  98. public get enabled() {
  99. return this._enabled;
  100. }
  101. /**
  102. * How many samples are used for MSAA of the scene render target
  103. */
  104. public get samples() {
  105. return this.prePassRT.samples;
  106. }
  107. public set samples(n: number) {
  108. if (!this.imageProcessingPostProcess) {
  109. this._createCompositionEffect();
  110. }
  111. this.prePassRT.samples = n;
  112. }
  113. private _geometryBuffer: Nullable<GeometryBufferRenderer>;
  114. private _useGeometryBufferFallback = true;
  115. /**
  116. * Uses the geometry buffer renderer as a fallback for non prepass capable effects
  117. */
  118. public get useGeometryBufferFallback() : boolean {
  119. return this._useGeometryBufferFallback;
  120. }
  121. public set useGeometryBufferFallback(value: boolean) {
  122. this._useGeometryBufferFallback = value;
  123. if (value) {
  124. this._geometryBuffer = this._scene.enableGeometryBufferRenderer();
  125. if (!this._geometryBuffer) {
  126. // Not supported
  127. this._useGeometryBufferFallback = false;
  128. return;
  129. }
  130. this._geometryBuffer.renderList = [];
  131. this._geometryBuffer._linkPrePassRenderer(this);
  132. this._updateGeometryBufferLayout();
  133. } else {
  134. if (this._geometryBuffer) {
  135. this._geometryBuffer._unlinkPrePassRenderer();
  136. }
  137. this._geometryBuffer = null;
  138. this._scene.disableGeometryBufferRenderer();
  139. }
  140. }
  141. /**
  142. * Instanciates a prepass renderer
  143. * @param scene The scene
  144. */
  145. constructor(scene: Scene) {
  146. this._scene = scene;
  147. this._engine = scene.getEngine();
  148. PrePassRenderer._SceneComponentInitialization(this._scene);
  149. this._resetLayout();
  150. }
  151. private _initializeAttachments() {
  152. const multiRenderLayout = [];
  153. const clearLayout = [false];
  154. const defaultLayout = [true];
  155. for (let i = 0; i < this.mrtCount; i++) {
  156. multiRenderLayout.push(true);
  157. if (i > 0) {
  158. clearLayout.push(true);
  159. defaultLayout.push(false);
  160. }
  161. }
  162. this._multiRenderAttachments = this._engine.buildTextureLayout(multiRenderLayout);
  163. this._clearAttachments = this._engine.buildTextureLayout(clearLayout);
  164. this._defaultAttachments = this._engine.buildTextureLayout(defaultLayout);
  165. }
  166. private _createCompositionEffect() {
  167. this.prePassRT = new MultiRenderTarget("sceneprePassRT", { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, this.mrtCount, this._scene,
  168. { generateMipMaps: false, generateDepthTexture: true, defaultType: Constants.TEXTURETYPE_UNSIGNED_INT, types: this._mrtFormats });
  169. this.prePassRT.samples = 1;
  170. this._initializeAttachments();
  171. if (this._useGeometryBufferFallback && !this._geometryBuffer) {
  172. // Initializes the link with geometry buffer
  173. this.useGeometryBufferFallback = true;
  174. }
  175. this.imageProcessingPostProcess = new ImageProcessingPostProcess("sceneCompositionPass", 1, null, undefined, this._engine);
  176. this.imageProcessingPostProcess.autoClear = false;
  177. }
  178. /**
  179. * Indicates if rendering a prepass is supported
  180. */
  181. public get isSupported() {
  182. return this._engine.webGLVersion > 1 || this._scene.getEngine().getCaps().drawBuffersExtension;
  183. }
  184. /**
  185. * Sets the proper output textures to draw in the engine.
  186. * @param effect The effect that is drawn. It can be or not be compatible with drawing to several output textures.
  187. * @param subMesh Submesh on which the effect is applied
  188. */
  189. public bindAttachmentsForEffect(effect: Effect, subMesh: SubMesh) {
  190. if (this.enabled) {
  191. if (effect._multiTarget) {
  192. this._engine.bindAttachments(this._multiRenderAttachments);
  193. } else {
  194. this._engine.bindAttachments(this._defaultAttachments);
  195. if (this._geometryBuffer) {
  196. const material = subMesh.getMaterial();
  197. if (material && this.excludedMaterials.indexOf(material) === -1) {
  198. this._geometryBuffer.renderList!.push(subMesh.getRenderingMesh());
  199. }
  200. }
  201. }
  202. }
  203. }
  204. /**
  205. * @hidden
  206. */
  207. public _beforeCameraDraw() {
  208. if (this._isDirty) {
  209. this._update();
  210. }
  211. if (this._geometryBuffer) {
  212. this._geometryBuffer.renderList!.length = 0;
  213. }
  214. this._bindFrameBuffer();
  215. }
  216. /**
  217. * @hidden
  218. */
  219. public _afterCameraDraw() {
  220. if (this._enabled) {
  221. const firstCameraPP = this._scene.activeCamera && this._scene.activeCamera._getFirstPostProcess();
  222. if (firstCameraPP) {
  223. this._scene.postProcessManager._prepareFrame();
  224. }
  225. this._scene.postProcessManager.directRender(this._postProcesses, firstCameraPP ? firstCameraPP.inputTexture : null);
  226. }
  227. }
  228. private _checkRTSize() {
  229. var requiredWidth = this._engine.getRenderWidth(true);
  230. var requiredHeight = this._engine.getRenderHeight(true);
  231. var width = this.prePassRT.getRenderWidth();
  232. var height = this.prePassRT.getRenderHeight();
  233. if (width !== requiredWidth || height !== requiredHeight) {
  234. this.prePassRT.resize({ width: requiredWidth, height: requiredHeight });
  235. this._updateGeometryBufferLayout();
  236. this._bindPostProcessChain();
  237. }
  238. }
  239. private _bindFrameBuffer() {
  240. if (this._enabled) {
  241. this._checkRTSize();
  242. var internalTexture = this.prePassRT.getInternalTexture();
  243. if (internalTexture) {
  244. this._engine.bindFramebuffer(internalTexture);
  245. }
  246. }
  247. }
  248. /**
  249. * Clears the scene render target (in the sense of settings pixels to the scene clear color value)
  250. */
  251. public clear() {
  252. if (this._enabled) {
  253. this._bindFrameBuffer();
  254. // Regular clear color with the scene clear color of the 1st attachment
  255. this._engine.clear(this._scene.clearColor,
  256. this._scene.autoClear || this._scene.forceWireframe || this._scene.forcePointsCloud,
  257. this._scene.autoClearDepthAndStencil,
  258. this._scene.autoClearDepthAndStencil);
  259. // Clearing other attachment with 0 on all other attachments
  260. this._engine.bindAttachments(this._clearAttachments);
  261. this._engine.clear(this._clearColor, true, false, false);
  262. this._engine.bindAttachments(this._defaultAttachments);
  263. }
  264. }
  265. private _setState(enabled: boolean) {
  266. this._enabled = enabled;
  267. this._scene.prePass = enabled;
  268. if (this.imageProcessingPostProcess) {
  269. this.imageProcessingPostProcess.imageProcessingConfiguration.applyByPostProcess = enabled;
  270. }
  271. }
  272. private _updateGeometryBufferLayout() {
  273. if (this._geometryBuffer) {
  274. this._geometryBuffer._resetLayout();
  275. const texturesActivated = [];
  276. for (let i = 0; i < this._mrtLayout.length; i++) {
  277. texturesActivated.push(false);
  278. }
  279. this._geometryBuffer._linkInternalTexture(this.prePassRT.getInternalTexture()!);
  280. const matches = [
  281. {
  282. prePassConstant: Constants.PREPASS_DEPTHNORMAL_TEXTURE_TYPE,
  283. geometryBufferConstant: GeometryBufferRenderer.DEPTHNORMAL_TEXTURE_TYPE,
  284. },
  285. {
  286. prePassConstant: Constants.PREPASS_POSITION_TEXTURE_TYPE,
  287. geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE,
  288. },
  289. {
  290. prePassConstant: Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE,
  291. geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE,
  292. },
  293. {
  294. prePassConstant: Constants.PREPASS_VELOCITY_TEXTURE_TYPE,
  295. geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE,
  296. }
  297. ];
  298. // replace textures in the geometryBuffer RT
  299. for (let i = 0; i < matches.length; i++) {
  300. const index = this._mrtLayout.indexOf(matches[i].prePassConstant);
  301. if (index !== -1) {
  302. this._geometryBuffer._forceTextureType(matches[i].geometryBufferConstant, index);
  303. texturesActivated[index] = true;
  304. }
  305. }
  306. this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(texturesActivated));
  307. }
  308. }
  309. /**
  310. * Adds an effect configuration to the prepass.
  311. * If an effect has already been added, it won't add it twice and will return the configuration
  312. * already present.
  313. * @param cfg the effect configuration
  314. * @return the effect configuration now used by the prepass
  315. */
  316. public addEffectConfiguration(cfg: PrePassEffectConfiguration) : PrePassEffectConfiguration {
  317. // Do not add twice
  318. for (let i = 0; i < this._effectConfigurations.length; i++) {
  319. if (this._effectConfigurations[i].name === cfg.name) {
  320. return this._effectConfigurations[i];
  321. }
  322. }
  323. this._effectConfigurations.push(cfg);
  324. return cfg;
  325. }
  326. /**
  327. * Returns the index of a texture in the multi render target texture array.
  328. * @param type Texture type
  329. * @return The index
  330. */
  331. public getIndex(type: number) : number {
  332. return this._textureIndices[type];
  333. }
  334. private _enable() {
  335. const previousMrtCount = this.mrtCount;
  336. for (let i = 0; i < this._effectConfigurations.length; i++) {
  337. if (this._effectConfigurations[i].enabled) {
  338. this._enableTextures(this._effectConfigurations[i].texturesRequired);
  339. }
  340. }
  341. if (this.prePassRT && this.mrtCount !== previousMrtCount) {
  342. this.prePassRT.updateCount(this.mrtCount, { types: this._mrtFormats });
  343. }
  344. this._updateGeometryBufferLayout();
  345. this._resetPostProcessChain();
  346. for (let i = 0; i < this._effectConfigurations.length; i++) {
  347. if (this._effectConfigurations[i].enabled) {
  348. if (!this._effectConfigurations[i].postProcess && this._effectConfigurations[i].createPostProcess) {
  349. this._effectConfigurations[i].createPostProcess!();
  350. }
  351. if (this._effectConfigurations[i].postProcess) {
  352. this._postProcesses.push(this._effectConfigurations[i].postProcess!);
  353. }
  354. }
  355. }
  356. this._initializeAttachments();
  357. if (!this.imageProcessingPostProcess) {
  358. this._createCompositionEffect();
  359. }
  360. this._postProcesses.push(this.imageProcessingPostProcess);
  361. this._bindPostProcessChain();
  362. this._setState(true);
  363. }
  364. private _disable() {
  365. this._setState(false);
  366. this._resetLayout();
  367. for (let i = 0; i < this._effectConfigurations.length; i++) {
  368. this._effectConfigurations[i].enabled = false;
  369. }
  370. }
  371. private _resetLayout() {
  372. for (let i = 0 ; i < this._textureFormats.length; i++) {
  373. this._textureIndices[this._textureFormats[i].type] = -1;
  374. }
  375. this._textureIndices[Constants.PREPASS_COLOR_TEXTURE_TYPE] = 0;
  376. this._mrtLayout = [Constants.PREPASS_COLOR_TEXTURE_TYPE];
  377. this._mrtFormats = [Constants.TEXTURETYPE_HALF_FLOAT];
  378. this.mrtCount = 1;
  379. }
  380. private _resetPostProcessChain() {
  381. this._postProcesses = [];
  382. if (this.imageProcessingPostProcess) {
  383. this.imageProcessingPostProcess.restoreDefaultInputTexture();
  384. }
  385. for (let i = 0; i < this._effectConfigurations.length; i++) {
  386. if (this._effectConfigurations[i].postProcess) {
  387. this._effectConfigurations[i].postProcess!.restoreDefaultInputTexture();
  388. }
  389. }
  390. }
  391. private _bindPostProcessChain() {
  392. this._postProcesses[0].inputTexture = this.prePassRT.getInternalTexture()!;
  393. }
  394. /**
  395. * Marks the prepass renderer as dirty, triggering a check if the prepass is necessary for the next rendering.
  396. */
  397. public markAsDirty() {
  398. this._isDirty = true;
  399. }
  400. /**
  401. * Enables a texture on the MultiRenderTarget for prepass
  402. */
  403. private _enableTextures(types: number[]) {
  404. for (let i = 0; i < types.length; i++) {
  405. let type = types[i];
  406. if (this._textureIndices[type] === -1) {
  407. this._textureIndices[type] = this._mrtLayout.length;
  408. this._mrtLayout.push(type);
  409. this._mrtFormats.push(this._textureFormats[type].format);
  410. this.mrtCount++;
  411. }
  412. }
  413. }
  414. private _update() {
  415. this._disable();
  416. let enablePrePass = false;
  417. for (let i = 0; i < this._scene.materials.length; i++) {
  418. if (this._scene.materials[i].setPrePassRenderer(this)) {
  419. enablePrePass = true;
  420. }
  421. }
  422. const camera = this._scene.activeCamera;
  423. if (!camera) {
  424. return;
  425. }
  426. const postProcesses = (<Nullable<PostProcess[]>>camera._postProcesses.filter((pp) => { return pp != null; }));
  427. if (postProcesses) {
  428. for (let i = 0; i < postProcesses.length; i++) {
  429. if (postProcesses[i].setPrePassRenderer(this)) {
  430. enablePrePass = true;
  431. }
  432. }
  433. }
  434. this._markAllMaterialsAsPrePassDirty();
  435. this._isDirty = false;
  436. if (enablePrePass) {
  437. this._enable();
  438. }
  439. if (!this.enabled) {
  440. // Prepass disabled, we render only on 1 color attachment
  441. this._engine.restoreDefaultFramebuffer();
  442. this._engine.restoreSingleAttachment();
  443. }
  444. }
  445. private _markAllMaterialsAsPrePassDirty() {
  446. const materials = this._scene.materials;
  447. for (let i = 0; i < materials.length; i++) {
  448. materials[i].markAsDirty(Material.PrePassDirtyFlag);
  449. }
  450. }
  451. /**
  452. * Disposes the prepass renderer.
  453. */
  454. public dispose() {
  455. for (let i = 0; i < this._effectConfigurations.length; i++) {
  456. if (this._effectConfigurations[i].dispose) {
  457. this._effectConfigurations[i].dispose!();
  458. }
  459. }
  460. this.imageProcessingPostProcess.dispose();
  461. this.prePassRT.dispose();
  462. }
  463. }