renderTargetTexture.ts 41 KB

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