renderTargetTexture.ts 38 KB

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