renderTargetTexture.ts 37 KB

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