renderTargetTexture.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. import { Observer, Observable } from "../../Misc/observable";
  2. import { Tools } from "../../Misc/tools";
  3. import { SmartArray } from "../../Misc/smartArray";
  4. import { Nullable } from "../../types";
  5. import { Camera } from "../../Cameras/camera";
  6. import { Scene } from "../../scene";
  7. import { Matrix, Vector3, Color4 } from "../../Maths/math";
  8. import { RenderTargetCreationOptions } from "../../Materials/Textures/renderTargetCreationOptions";
  9. import { AbstractMesh } from "../../Meshes/abstractMesh";
  10. import { SubMesh } from "../../Meshes/subMesh";
  11. import { InternalTexture } from "../../Materials/Textures/internalTexture";
  12. import { Texture } from "../../Materials/Textures/texture";
  13. import { PostProcessManager } from "../../PostProcesses/postProcessManager";
  14. import { PostProcess } from "../../PostProcesses/postProcess";
  15. import { RenderingManager } from "../../Rendering/renderingManager";
  16. import { Constants } from "../../Engines/constants";
  17. declare type Engine = import("../../Engines/engine").Engine;
  18. /**
  19. * This Helps creating a texture that will be created from a camera in your scene.
  20. * It is basically a dynamic texture that could be used to create special effects for instance.
  21. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  22. */
  23. export class RenderTargetTexture extends Texture {
  24. /**
  25. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  26. */
  27. public static readonly REFRESHRATE_RENDER_ONCE: number = 0;
  28. /**
  29. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  30. */
  31. public static readonly REFRESHRATE_RENDER_ONEVERYFRAME: number = 1;
  32. /**
  33. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  34. * the central point of your effect and can save a lot of performances.
  35. */
  36. public static readonly REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number = 2;
  37. /**
  38. * Use this predicate to dynamically define the list of mesh you want to render.
  39. * If set, the renderList property will be overwritten.
  40. */
  41. public renderListPredicate: (AbstractMesh: AbstractMesh) => boolean;
  42. private _renderList: Nullable<Array<AbstractMesh>>;
  43. /**
  44. * Use this list to define the list of mesh you want to render.
  45. */
  46. public get renderList(): Nullable<Array<AbstractMesh>> {
  47. return this._renderList;
  48. }
  49. public set renderList(value: Nullable<Array<AbstractMesh>>) {
  50. this._renderList = value;
  51. if (this._renderList) {
  52. this._hookArray(this._renderList);
  53. }
  54. }
  55. private _hookArray(array: AbstractMesh[]): void {
  56. var oldPush = array.push;
  57. array.push = (...items: AbstractMesh[]) => {
  58. let wasEmpty = array.length === 0;
  59. var result = oldPush.apply(array, items);
  60. if (wasEmpty) {
  61. this.getScene()!.meshes.forEach((mesh) => {
  62. mesh._markSubMeshesAsLightDirty();
  63. });
  64. }
  65. return result;
  66. };
  67. var oldSplice = array.splice;
  68. array.splice = (index: number, deleteCount?: number) => {
  69. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70. if (array.length === 0) {
  71. this.getScene()!.meshes.forEach((mesh) => {
  72. mesh._markSubMeshesAsLightDirty();
  73. });
  74. }
  75. return deleted;
  76. };
  77. }
  78. /**
  79. * Define if particles should be rendered in your texture.
  80. */
  81. public renderParticles = true;
  82. /**
  83. * Define if sprites should be rendered in your texture.
  84. */
  85. public renderSprites = false;
  86. /**
  87. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  88. */
  89. public coordinatesMode = Texture.PROJECTION_MODE;
  90. /**
  91. * Define the camera used to render the texture.
  92. */
  93. public activeCamera: Nullable<Camera>;
  94. /**
  95. * Override the render function of the texture with your own one.
  96. */
  97. public customRenderFunction: (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>, beforeTransparents?: () => void) => void;
  98. /**
  99. * Define if camera post processes should be use while rendering the texture.
  100. */
  101. public useCameraPostProcesses: boolean;
  102. /**
  103. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  104. */
  105. public ignoreCameraViewport: boolean = false;
  106. private _postProcessManager: Nullable<PostProcessManager>;
  107. private _postProcesses: PostProcess[];
  108. private _resizeObserver: Nullable<Observer<Engine>>;
  109. /**
  110. * An event triggered when the texture is unbind.
  111. */
  112. public onBeforeBindObservable = new Observable<RenderTargetTexture>();
  113. /**
  114. * An event triggered when the texture is unbind.
  115. */
  116. public onAfterUnbindObservable = new Observable<RenderTargetTexture>();
  117. private _onAfterUnbindObserver: Nullable<Observer<RenderTargetTexture>>;
  118. /**
  119. * Set a after unbind callback in the texture.
  120. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  121. */
  122. public set onAfterUnbind(callback: () => void) {
  123. if (this._onAfterUnbindObserver) {
  124. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  125. }
  126. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  127. }
  128. /**
  129. * An event triggered before rendering the texture
  130. */
  131. public onBeforeRenderObservable = new Observable<number>();
  132. private _onBeforeRenderObserver: Nullable<Observer<number>>;
  133. /**
  134. * Set a before render callback in the texture.
  135. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  136. */
  137. public set onBeforeRender(callback: (faceIndex: number) => void) {
  138. if (this._onBeforeRenderObserver) {
  139. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  140. }
  141. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  142. }
  143. /**
  144. * An event triggered after rendering the texture
  145. */
  146. public onAfterRenderObservable = new Observable<number>();
  147. private _onAfterRenderObserver: Nullable<Observer<number>>;
  148. /**
  149. * Set a after render callback in the texture.
  150. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  151. */
  152. public set onAfterRender(callback: (faceIndex: number) => void) {
  153. if (this._onAfterRenderObserver) {
  154. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  155. }
  156. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  157. }
  158. /**
  159. * An event triggered after the texture clear
  160. */
  161. public onClearObservable = new Observable<Engine>();
  162. private _onClearObserver: Nullable<Observer<Engine>>;
  163. /**
  164. * Set a clear callback in the texture.
  165. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  166. */
  167. public set onClear(callback: (Engine: Engine) => void) {
  168. if (this._onClearObserver) {
  169. this.onClearObservable.remove(this._onClearObserver);
  170. }
  171. this._onClearObserver = this.onClearObservable.add(callback);
  172. }
  173. /**
  174. * Define the clear color of the Render Target if it should be different from the scene.
  175. */
  176. public clearColor: Color4;
  177. protected _size: number | { width: number, height: number };
  178. protected _initialSizeParameter: number | { width: number, height: number } | { ratio: number };
  179. protected _sizeRatio: Nullable<number>;
  180. /** @hidden */
  181. public _generateMipMaps: boolean;
  182. protected _renderingManager: RenderingManager;
  183. /** @hidden */
  184. public _waitingRenderList: string[];
  185. protected _doNotChangeAspectRatio: boolean;
  186. protected _currentRefreshId = -1;
  187. protected _refreshRate = 1;
  188. protected _textureMatrix: Matrix;
  189. protected _samples = 1;
  190. protected _renderTargetOptions: RenderTargetCreationOptions;
  191. /**
  192. * Gets render target creation options that were used.
  193. */
  194. public get renderTargetOptions(): RenderTargetCreationOptions {
  195. return this._renderTargetOptions;
  196. }
  197. protected _engine: Engine;
  198. protected _onRatioRescale(): void {
  199. if (this._sizeRatio) {
  200. this.resize(this._initialSizeParameter);
  201. }
  202. }
  203. /**
  204. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  205. * It must define where the camera used to render the texture is set
  206. */
  207. public boundingBoxPosition = Vector3.Zero();
  208. private _boundingBoxSize: Vector3;
  209. /**
  210. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  211. * When defined, the cubemap will switch to local mode
  212. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  213. * @example https://www.babylonjs-playground.com/#RNASML
  214. */
  215. public set boundingBoxSize(value: Vector3) {
  216. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  217. return;
  218. }
  219. this._boundingBoxSize = value;
  220. let scene = this.getScene();
  221. if (scene) {
  222. scene.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  223. }
  224. }
  225. public get boundingBoxSize(): Vector3 {
  226. return this._boundingBoxSize;
  227. }
  228. /**
  229. * In case the RTT has been created with a depth texture, get the associated
  230. * depth texture.
  231. * Otherwise, return null.
  232. */
  233. public depthStencilTexture: Nullable<InternalTexture>;
  234. /**
  235. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  236. * or used a shadow, depth texture...
  237. * @param name The friendly name of the texture
  238. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  239. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  240. * @param generateMipMaps True if mip maps need to be generated after render.
  241. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  242. * @param type The type of the buffer in the RTT (int, half float, float...)
  243. * @param isCube True if a cube texture needs to be created
  244. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  245. * @param generateDepthBuffer True to generate a depth buffer
  246. * @param generateStencilBuffer True to generate a stencil buffer
  247. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  248. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  249. * @param delayAllocation if the texture allocation should be delayed (default: false)
  250. */
  251. constructor(name: string, size: number | { width: number, height: number } | { ratio: number }, scene: Nullable<Scene>, generateMipMaps?: boolean, doNotChangeAspectRatio: boolean = true, type: number = Constants.TEXTURETYPE_UNSIGNED_INT, public isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = Constants.TEXTUREFORMAT_RGBA, delayAllocation = false) {
  252. super(null, scene, !generateMipMaps);
  253. scene = this.getScene();
  254. if (!scene) {
  255. return;
  256. }
  257. this.renderList = new Array<AbstractMesh>();
  258. this._engine = scene.getEngine();
  259. this.name = name;
  260. this.isRenderTarget = true;
  261. this._initialSizeParameter = size;
  262. this._processSizeParameter(size);
  263. this._resizeObserver = this.getScene()!.getEngine().onResizeObservable.add(() => {
  264. });
  265. this._generateMipMaps = generateMipMaps ? true : false;
  266. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  267. // Rendering groups
  268. this._renderingManager = new RenderingManager(scene);
  269. this._renderingManager._useSceneAutoClearSetup = true;
  270. if (isMulti) {
  271. return;
  272. }
  273. this._renderTargetOptions = {
  274. generateMipMaps: generateMipMaps,
  275. type: type,
  276. format: format,
  277. samplingMode: samplingMode,
  278. generateDepthBuffer: generateDepthBuffer,
  279. generateStencilBuffer: generateStencilBuffer
  280. };
  281. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  282. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  283. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  284. }
  285. if (!delayAllocation) {
  286. if (isCube) {
  287. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  288. this.coordinatesMode = Texture.INVCUBIC_MODE;
  289. this._textureMatrix = Matrix.Identity();
  290. } else {
  291. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  292. }
  293. }
  294. }
  295. /**
  296. * Creates a depth stencil texture.
  297. * This is only available in WebGL 2 or with the depth texture extension available.
  298. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  299. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  300. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  301. */
  302. public createDepthStencilTexture(comparisonFunction: number = 0, bilinearFiltering: boolean = true, generateStencil: boolean = false): void {
  303. if (!this.getScene()) {
  304. return;
  305. }
  306. var engine = this.getScene()!.getEngine();
  307. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  308. bilinearFiltering,
  309. comparisonFunction,
  310. generateStencil,
  311. isCube: this.isCube
  312. });
  313. engine.setFrameBufferDepthStencilTexture(this);
  314. }
  315. private _processSizeParameter(size: number | { width: number, height: number } | { ratio: number }): void {
  316. if ((<{ ratio: number }>size).ratio) {
  317. this._sizeRatio = (<{ ratio: number }>size).ratio;
  318. this._size = {
  319. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  320. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  321. };
  322. } else {
  323. this._size = <number | { width: number, height: number }>size;
  324. }
  325. }
  326. /**
  327. * Define the number of samples to use in case of MSAA.
  328. * It defaults to one meaning no MSAA has been enabled.
  329. */
  330. public get samples(): number {
  331. return this._samples;
  332. }
  333. public set samples(value: number) {
  334. if (this._samples === value) {
  335. return;
  336. }
  337. let scene = this.getScene();
  338. if (!scene) {
  339. return;
  340. }
  341. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  342. }
  343. /**
  344. * Resets the refresh counter of the texture and start bak from scratch.
  345. * Could be useful to regenerate the texture if it is setup to render only once.
  346. */
  347. public resetRefreshCounter(): void {
  348. this._currentRefreshId = -1;
  349. }
  350. /**
  351. * Define the refresh rate of the texture or the rendering frequency.
  352. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  353. */
  354. public get refreshRate(): number {
  355. return this._refreshRate;
  356. }
  357. public set refreshRate(value: number) {
  358. this._refreshRate = value;
  359. this.resetRefreshCounter();
  360. }
  361. /**
  362. * Adds a post process to the render target rendering passes.
  363. * @param postProcess define the post process to add
  364. */
  365. public addPostProcess(postProcess: PostProcess): void {
  366. if (!this._postProcessManager) {
  367. let scene = this.getScene();
  368. if (!scene) {
  369. return;
  370. }
  371. this._postProcessManager = new PostProcessManager(scene);
  372. this._postProcesses = new Array<PostProcess>();
  373. }
  374. this._postProcesses.push(postProcess);
  375. this._postProcesses[0].autoClear = false;
  376. }
  377. /**
  378. * Clear all the post processes attached to the render target
  379. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  380. */
  381. public clearPostProcesses(dispose: boolean = false): void {
  382. if (!this._postProcesses) {
  383. return;
  384. }
  385. if (dispose) {
  386. for (var postProcess of this._postProcesses) {
  387. postProcess.dispose();
  388. }
  389. }
  390. this._postProcesses = [];
  391. }
  392. /**
  393. * Remove one of the post process from the list of attached post processes to the texture
  394. * @param postProcess define the post process to remove from the list
  395. */
  396. public removePostProcess(postProcess: PostProcess): void {
  397. if (!this._postProcesses) {
  398. return;
  399. }
  400. var index = this._postProcesses.indexOf(postProcess);
  401. if (index === -1) {
  402. return;
  403. }
  404. this._postProcesses.splice(index, 1);
  405. if (this._postProcesses.length > 0) {
  406. this._postProcesses[0].autoClear = false;
  407. }
  408. }
  409. /** @hidden */
  410. public _shouldRender(): boolean {
  411. if (this._currentRefreshId === -1) { // At least render once
  412. this._currentRefreshId = 1;
  413. return true;
  414. }
  415. if (this.refreshRate === this._currentRefreshId) {
  416. this._currentRefreshId = 1;
  417. return true;
  418. }
  419. this._currentRefreshId++;
  420. return false;
  421. }
  422. /**
  423. * Gets the actual render size of the texture.
  424. * @returns the width of the render size
  425. */
  426. public getRenderSize(): number {
  427. return this.getRenderWidth();
  428. }
  429. /**
  430. * Gets the actual render width of the texture.
  431. * @returns the width of the render size
  432. */
  433. public getRenderWidth(): number {
  434. if ((<{ width: number, height: number }>this._size).width) {
  435. return (<{ width: number, height: number }>this._size).width;
  436. }
  437. return <number>this._size;
  438. }
  439. /**
  440. * Gets the actual render height of the texture.
  441. * @returns the height of the render size
  442. */
  443. public getRenderHeight(): number {
  444. if ((<{ width: number, height: number }>this._size).width) {
  445. return (<{ width: number, height: number }>this._size).height;
  446. }
  447. return <number>this._size;
  448. }
  449. /**
  450. * Get if the texture can be rescaled or not.
  451. */
  452. public get canRescale(): boolean {
  453. return true;
  454. }
  455. /**
  456. * Resize the texture using a ratio.
  457. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  458. */
  459. public scale(ratio: number): void {
  460. var newSize = this.getRenderSize() * ratio;
  461. this.resize(newSize);
  462. }
  463. /**
  464. * Get the texture reflection matrix used to rotate/transform the reflection.
  465. * @returns the reflection matrix
  466. */
  467. public getReflectionTextureMatrix(): Matrix {
  468. if (this.isCube) {
  469. return this._textureMatrix;
  470. }
  471. return super.getReflectionTextureMatrix();
  472. }
  473. /**
  474. * Resize the texture to a new desired size.
  475. * Be carrefull as it will recreate all the data in the new texture.
  476. * @param size Define the new size. It can be:
  477. * - a number for squared texture,
  478. * - an object containing { width: number, height: number }
  479. * - or an object containing a ratio { ratio: number }
  480. */
  481. public resize(size: number | { width: number, height: number } | { ratio: number }): void {
  482. this.releaseInternalTexture();
  483. let scene = this.getScene();
  484. if (!scene) {
  485. return;
  486. }
  487. this._processSizeParameter(size);
  488. if (this.isCube) {
  489. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  490. } else {
  491. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  492. }
  493. }
  494. /**
  495. * Renders all the objects from the render list into the texture.
  496. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  497. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  498. */
  499. public render(useCameraPostProcess: boolean = false, dumpForDebug: boolean = false): void {
  500. var scene = this.getScene();
  501. if (!scene) {
  502. return;
  503. }
  504. var engine = scene.getEngine();
  505. if (this.useCameraPostProcesses !== undefined) {
  506. useCameraPostProcess = this.useCameraPostProcesses;
  507. }
  508. if (this._waitingRenderList) {
  509. this.renderList = [];
  510. for (var index = 0; index < this._waitingRenderList.length; index++) {
  511. var id = this._waitingRenderList[index];
  512. let mesh = scene.getMeshByID(id);
  513. if (mesh) {
  514. this.renderList.push(mesh);
  515. }
  516. }
  517. delete this._waitingRenderList;
  518. }
  519. // Is predicate defined?
  520. if (this.renderListPredicate) {
  521. if (this.renderList) {
  522. this.renderList.length = 0; // Clear previous renderList
  523. } else {
  524. this.renderList = [];
  525. }
  526. var scene = this.getScene();
  527. if (!scene) {
  528. return;
  529. }
  530. var sceneMeshes = scene.meshes;
  531. for (var index = 0; index < sceneMeshes.length; index++) {
  532. var mesh = sceneMeshes[index];
  533. if (this.renderListPredicate(mesh)) {
  534. this.renderList.push(mesh);
  535. }
  536. }
  537. }
  538. this.onBeforeBindObservable.notifyObservers(this);
  539. // Set custom projection.
  540. // Needs to be before binding to prevent changing the aspect ratio.
  541. let camera: Nullable<Camera>;
  542. if (this.activeCamera) {
  543. camera = this.activeCamera;
  544. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  545. if (this.activeCamera !== scene.activeCamera) {
  546. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  547. }
  548. }
  549. else {
  550. camera = scene.activeCamera;
  551. if (camera) {
  552. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  553. }
  554. }
  555. // Prepare renderingManager
  556. this._renderingManager.reset();
  557. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  558. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  559. var sceneRenderId = scene.getRenderId();
  560. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  561. var mesh = currentRenderList[meshIndex];
  562. if (mesh) {
  563. if (!mesh.isReady(this.refreshRate === 0)) {
  564. this.resetRefreshCounter();
  565. continue;
  566. }
  567. mesh._preActivateForIntermediateRendering(sceneRenderId);
  568. let isMasked;
  569. if (!this.renderList && camera) {
  570. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  571. } else {
  572. isMasked = false;
  573. }
  574. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  575. mesh._activate(sceneRenderId);
  576. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  577. var subMesh = mesh.subMeshes[subIndex];
  578. scene._activeIndices.addCount(subMesh.indexCount, false);
  579. this._renderingManager.dispatch(subMesh, mesh);
  580. }
  581. }
  582. }
  583. }
  584. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  585. var particleSystem = scene.particleSystems[particleIndex];
  586. let emitter: any = particleSystem.emitter;
  587. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  588. continue;
  589. }
  590. if (currentRenderList.indexOf(emitter) >= 0) {
  591. this._renderingManager.dispatchParticles(particleSystem);
  592. }
  593. }
  594. if (this.isCube) {
  595. for (var face = 0; face < 6; face++) {
  596. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  597. scene.incrementRenderId();
  598. scene.resetCachedMaterial();
  599. }
  600. } else {
  601. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  602. }
  603. this.onAfterUnbindObservable.notifyObservers(this);
  604. if (scene.activeCamera) {
  605. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  606. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  607. }
  608. engine.setViewport(scene.activeCamera.viewport);
  609. }
  610. scene.resetCachedMaterial();
  611. }
  612. private _bestReflectionRenderTargetDimension(renderDimension: number, scale: number): number {
  613. let minimum = 128;
  614. let x = renderDimension * scale;
  615. let curved = Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  616. // Ensure we don't exceed the render dimension (while staying POT)
  617. return Math.min(Tools.FloorPOT(renderDimension), curved);
  618. }
  619. /**
  620. * @hidden
  621. * @param faceIndex face index to bind to if this is a cubetexture
  622. */
  623. public _bindFrameBuffer(faceIndex: number = 0) {
  624. var scene = this.getScene();
  625. if (!scene) {
  626. return;
  627. }
  628. var engine = scene.getEngine();
  629. if (this._texture) {
  630. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  631. }
  632. }
  633. protected unbindFrameBuffer(engine: Engine, faceIndex: number): void {
  634. if (!this._texture) {
  635. return;
  636. }
  637. engine.unBindFramebuffer(this._texture, this.isCube, () => {
  638. this.onAfterRenderObservable.notifyObservers(faceIndex);
  639. });
  640. }
  641. private renderToTarget(faceIndex: number, currentRenderList: AbstractMesh[], useCameraPostProcess: boolean, dumpForDebug: boolean): void {
  642. var scene = this.getScene();
  643. if (!scene) {
  644. return;
  645. }
  646. var engine = scene.getEngine();
  647. if (!this._texture) {
  648. return;
  649. }
  650. // Bind
  651. if (this._postProcessManager) {
  652. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  653. }
  654. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  655. this._bindFrameBuffer(faceIndex);
  656. }
  657. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  658. // Clear
  659. if (this.onClearObservable.hasObservers()) {
  660. this.onClearObservable.notifyObservers(engine);
  661. } else {
  662. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  663. }
  664. if (!this._doNotChangeAspectRatio) {
  665. scene.updateTransformMatrix(true);
  666. }
  667. // Before Camera Draw
  668. for (let step of scene._beforeRenderTargetDrawStage) {
  669. step.action(this);
  670. }
  671. // Render
  672. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  673. // After Camera Draw
  674. for (let step of scene._afterRenderTargetDrawStage) {
  675. step.action(this);
  676. }
  677. if (this._postProcessManager) {
  678. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  679. }
  680. else if (useCameraPostProcess) {
  681. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  682. }
  683. if (!this._doNotChangeAspectRatio) {
  684. scene.updateTransformMatrix(true);
  685. }
  686. // Dump ?
  687. if (dumpForDebug) {
  688. Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  689. }
  690. // Unbind
  691. if (!this.isCube || faceIndex === 5) {
  692. if (this.isCube) {
  693. if (faceIndex === 5) {
  694. engine.generateMipMapsForCubemap(this._texture);
  695. }
  696. }
  697. this.unbindFrameBuffer(engine, faceIndex);
  698. } else {
  699. this.onAfterRenderObservable.notifyObservers(faceIndex);
  700. }
  701. }
  702. /**
  703. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  704. * This allowed control for front to back rendering or reversly depending of the special needs.
  705. *
  706. * @param renderingGroupId The rendering group id corresponding to its index
  707. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  708. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  709. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  710. */
  711. public setRenderingOrder(renderingGroupId: number,
  712. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  713. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  714. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  715. this._renderingManager.setRenderingOrder(renderingGroupId,
  716. opaqueSortCompareFn,
  717. alphaTestSortCompareFn,
  718. transparentSortCompareFn);
  719. }
  720. /**
  721. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  722. *
  723. * @param renderingGroupId The rendering group id corresponding to its index
  724. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  725. */
  726. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void {
  727. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  728. this._renderingManager._useSceneAutoClearSetup = false;
  729. }
  730. /**
  731. * Clones the texture.
  732. * @returns the cloned texture
  733. */
  734. public clone(): RenderTargetTexture {
  735. var textureSize = this.getSize();
  736. var newTexture = new RenderTargetTexture(
  737. this.name,
  738. textureSize,
  739. this.getScene(),
  740. this._renderTargetOptions.generateMipMaps,
  741. this._doNotChangeAspectRatio,
  742. this._renderTargetOptions.type,
  743. this.isCube,
  744. this._renderTargetOptions.samplingMode,
  745. this._renderTargetOptions.generateDepthBuffer,
  746. this._renderTargetOptions.generateStencilBuffer
  747. );
  748. // Base texture
  749. newTexture.hasAlpha = this.hasAlpha;
  750. newTexture.level = this.level;
  751. // RenderTarget Texture
  752. newTexture.coordinatesMode = this.coordinatesMode;
  753. if (this.renderList) {
  754. newTexture.renderList = this.renderList.slice(0);
  755. }
  756. return newTexture;
  757. }
  758. /**
  759. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  760. * @returns The JSON representation of the texture
  761. */
  762. public serialize(): any {
  763. if (!this.name) {
  764. return null;
  765. }
  766. var serializationObject = super.serialize();
  767. serializationObject.renderTargetSize = this.getRenderSize();
  768. serializationObject.renderList = [];
  769. if (this.renderList) {
  770. for (var index = 0; index < this.renderList.length; index++) {
  771. serializationObject.renderList.push(this.renderList[index].id);
  772. }
  773. }
  774. return serializationObject;
  775. }
  776. /**
  777. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  778. */
  779. public disposeFramebufferObjects(): void {
  780. let objBuffer = this.getInternalTexture();
  781. let scene = this.getScene();
  782. if (objBuffer && scene) {
  783. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  784. }
  785. }
  786. /**
  787. * Dispose the texture and release its associated resources.
  788. */
  789. public dispose(): void {
  790. if (this._postProcessManager) {
  791. this._postProcessManager.dispose();
  792. this._postProcessManager = null;
  793. }
  794. this.clearPostProcesses(true);
  795. if (this._resizeObserver) {
  796. this.getScene()!.getEngine().onResizeObservable.remove(this._resizeObserver);
  797. this._resizeObserver = null;
  798. }
  799. this.renderList = null;
  800. // Remove from custom render targets
  801. var scene = this.getScene();
  802. if (!scene) {
  803. return;
  804. }
  805. var index = scene.customRenderTargets.indexOf(this);
  806. if (index >= 0) {
  807. scene.customRenderTargets.splice(index, 1);
  808. }
  809. for (var camera of scene.cameras) {
  810. index = camera.customRenderTargets.indexOf(this);
  811. if (index >= 0) {
  812. camera.customRenderTargets.splice(index, 1);
  813. }
  814. }
  815. super.dispose();
  816. }
  817. /** @hidden */
  818. public _rebuild(): void {
  819. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  820. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  821. }
  822. if (this._postProcessManager) {
  823. this._postProcessManager._rebuild();
  824. }
  825. }
  826. /**
  827. * Clear the info related to rendering groups preventing retention point in material dispose.
  828. */
  829. public freeRenderingGroups(): void {
  830. if (this._renderingManager) {
  831. this._renderingManager.freeRenderingGroups();
  832. }
  833. }
  834. /**
  835. * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)
  836. * @returns the view count
  837. */
  838. public getViewCount() {
  839. return 1;
  840. }
  841. }
  842. Texture._CreateRenderTargetTexture = (name: string, renderTargetSize: number, scene: Scene, generateMipMaps: boolean) => {
  843. return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);
  844. };
  845. /**
  846. * Renders to multiple views with a single draw call
  847. * @see https://www.khronos.org/registry/webgl/extensions/WEBGL_multiview/
  848. */
  849. export class MultiviewRenderTarget extends RenderTargetTexture {
  850. /**
  851. * Creates a multiview render target
  852. * @param scene scene used with the render target
  853. * @param size the size of the render target (used for each view)
  854. */
  855. constructor(private scene: Scene, size: number | { width: number, height: number } | { ratio: number } = 512) {
  856. super("multiview rtt", size, scene, false, true, InternalTexture.DATASOURCE_UNKNOWN, false, undefined, false, false, true, undefined, true);
  857. var internalTexture = scene.getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight());
  858. internalTexture.isMultiview = true;
  859. this._texture = internalTexture;
  860. }
  861. /**
  862. * @hidden
  863. * @param faceIndex the face index, if its a cube texture
  864. */
  865. public _bindFrameBuffer(faceIndex: number = 0) {
  866. if (!this._texture) {
  867. return;
  868. }
  869. this.scene.getEngine().bindMultiviewFramebuffer(this._texture);
  870. }
  871. /**
  872. * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)
  873. * @returns the view count
  874. */
  875. public getViewCount() {
  876. return 2;
  877. }
  878. }