babylon.renderTargetTexture.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. module BABYLON {
  2. export class RenderTargetTexture extends Texture {
  3. public static _REFRESHRATE_RENDER_ONCE: number = 0;
  4. public static _REFRESHRATE_RENDER_ONEVERYFRAME: number = 1;
  5. public static _REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number = 2;
  6. public static get REFRESHRATE_RENDER_ONCE(): number {
  7. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  8. }
  9. public static get REFRESHRATE_RENDER_ONEVERYFRAME(): number {
  10. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  11. }
  12. public static get REFRESHRATE_RENDER_ONEVERYTWOFRAMES(): number {
  13. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  14. }
  15. /**
  16. * Use this predicate to dynamically define the list of mesh you want to render.
  17. * If set, the renderList property will be overwritten.
  18. */
  19. public renderListPredicate: (AbstractMesh: AbstractMesh) => boolean;
  20. private _renderList: Nullable<Array<AbstractMesh>>;
  21. /**
  22. * Use this list to define the list of mesh you want to render.
  23. */
  24. public get renderList(): Nullable<Array<AbstractMesh>> {
  25. return this._renderList;
  26. }
  27. public set renderList(value: Nullable<Array<AbstractMesh>>) {
  28. this._renderList = value;
  29. if (this._renderList) {
  30. this._hookArray(this._renderList);
  31. }
  32. }
  33. private _hookArray(array: AbstractMesh[]): void {
  34. var oldPush = array.push;
  35. array.push = (...items: AbstractMesh[]) => {
  36. var result = oldPush.apply(array, items);
  37. this.getScene()!.meshes.forEach(mesh => {
  38. mesh._markSubMeshesAsLightDirty();
  39. })
  40. return result;
  41. }
  42. var oldSplice = array.splice;
  43. array.splice = (index: number, deleteCount?: number) => {
  44. var deleted = oldSplice.apply(array, [index, deleteCount]);
  45. this.getScene()!.meshes.forEach(mesh => {
  46. mesh._markSubMeshesAsLightDirty();
  47. })
  48. return deleted;
  49. }
  50. }
  51. public renderParticles = true;
  52. public renderSprites = false;
  53. public coordinatesMode = Texture.PROJECTION_MODE;
  54. public activeCamera: Nullable<Camera>;
  55. public customRenderFunction: (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>, beforeTransparents?: () => void) => void;
  56. public useCameraPostProcesses: boolean;
  57. public ignoreCameraViewport: boolean = false;
  58. private _postProcessManager: Nullable<PostProcessManager>;
  59. private _postProcesses: PostProcess[];
  60. private _resizeObserver: Nullable<Observer<Engine>>;
  61. // Events
  62. /**
  63. * An event triggered when the texture is unbind.
  64. */
  65. public onBeforeBindObservable = new Observable<RenderTargetTexture>();
  66. /**
  67. * An event triggered when the texture is unbind.
  68. */
  69. public onAfterUnbindObservable = new Observable<RenderTargetTexture>();
  70. private _onAfterUnbindObserver: Nullable<Observer<RenderTargetTexture>>;
  71. public set onAfterUnbind(callback: () => void) {
  72. if (this._onAfterUnbindObserver) {
  73. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  74. }
  75. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  76. }
  77. /**
  78. * An event triggered before rendering the texture
  79. */
  80. public onBeforeRenderObservable = new Observable<number>();
  81. private _onBeforeRenderObserver: Nullable<Observer<number>>;
  82. public set onBeforeRender(callback: (faceIndex: number) => void) {
  83. if (this._onBeforeRenderObserver) {
  84. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  85. }
  86. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87. }
  88. /**
  89. * An event triggered after rendering the texture
  90. */
  91. public onAfterRenderObservable = new Observable<number>();
  92. private _onAfterRenderObserver: Nullable<Observer<number>>;
  93. public set onAfterRender(callback: (faceIndex: number) => void) {
  94. if (this._onAfterRenderObserver) {
  95. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96. }
  97. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98. }
  99. /**
  100. * An event triggered after the texture clear
  101. */
  102. public onClearObservable = new Observable<Engine>();
  103. private _onClearObserver: Nullable<Observer<Engine>>;
  104. public set onClear(callback: (Engine: Engine) => void) {
  105. if (this._onClearObserver) {
  106. this.onClearObservable.remove(this._onClearObserver);
  107. }
  108. this._onClearObserver = this.onClearObservable.add(callback);
  109. }
  110. public clearColor: Color4;
  111. protected _size: number | { width: number, height: number };
  112. protected _initialSizeParameter: number | { width: number, height: number } | { ratio: number }
  113. protected _sizeRatio: Nullable<number>;
  114. /** @hidden */
  115. public _generateMipMaps: boolean;
  116. protected _renderingManager: RenderingManager;
  117. /** @hidden */
  118. public _waitingRenderList: string[];
  119. protected _doNotChangeAspectRatio: boolean;
  120. protected _currentRefreshId = -1;
  121. protected _refreshRate = 1;
  122. protected _textureMatrix: Matrix;
  123. protected _samples = 1;
  124. protected _renderTargetOptions: RenderTargetCreationOptions;
  125. public get renderTargetOptions(): RenderTargetCreationOptions {
  126. return this._renderTargetOptions;
  127. }
  128. protected _engine: Engine;
  129. protected _onRatioRescale(): void {
  130. if (this._sizeRatio) {
  131. this.resize(this._initialSizeParameter);
  132. }
  133. }
  134. /**
  135. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  136. * It must define where the camera used to render the texture is set
  137. */
  138. public boundingBoxPosition = Vector3.Zero();
  139. private _boundingBoxSize: Vector3;
  140. /**
  141. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  142. * When defined, the cubemap will switch to local mode
  143. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  144. * @example https://www.babylonjs-playground.com/#RNASML
  145. */
  146. public set boundingBoxSize(value: Vector3) {
  147. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  148. return;
  149. }
  150. this._boundingBoxSize = value;
  151. let scene = this.getScene();
  152. if (scene) {
  153. scene.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  154. }
  155. }
  156. public get boundingBoxSize(): Vector3 {
  157. return this._boundingBoxSize;
  158. }
  159. /**
  160. * In case the RTT has been created with a depth texture, get the associated
  161. * depth texture.
  162. * Otherwise, return null.
  163. */
  164. public depthStencilTexture: Nullable<InternalTexture>;
  165. /**
  166. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  167. * or used a shadow, depth texture...
  168. * @param name The friendly name of the texture
  169. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  170. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  171. * @param generateMipMaps True if mip maps need to be generated after render.
  172. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  173. * @param type The type of the buffer in the RTT (int, half float, float...)
  174. * @param isCube True if a cube texture needs to be created
  175. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  176. * @param generateDepthBuffer True to generate a depth buffer
  177. * @param generateStencilBuffer True to generate a stencil buffer
  178. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  179. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  180. */
  181. constructor(name: string, size: number | { width: number, height: number } | { ratio: number }, scene: Nullable<Scene>, generateMipMaps?: boolean, doNotChangeAspectRatio: boolean = true, type: number = Engine.TEXTURETYPE_UNSIGNED_INT, public isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = Engine.TEXTUREFORMAT_RGBA) {
  182. super(null, scene, !generateMipMaps);
  183. scene = this.getScene();
  184. if (!scene) {
  185. return;
  186. }
  187. this.renderList = new Array<AbstractMesh>();
  188. this._engine = scene.getEngine();
  189. this.name = name;
  190. this.isRenderTarget = true;
  191. this._initialSizeParameter = size;
  192. this._processSizeParameter(size);
  193. this._resizeObserver = this.getScene()!.getEngine().onResizeObservable.add(() => {
  194. });
  195. this._generateMipMaps = generateMipMaps ? true : false;
  196. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  197. // Rendering groups
  198. this._renderingManager = new RenderingManager(scene);
  199. this._renderingManager._useSceneAutoClearSetup = true;
  200. if (isMulti) {
  201. return;
  202. }
  203. this._renderTargetOptions = {
  204. generateMipMaps: generateMipMaps,
  205. type: type,
  206. format: format,
  207. samplingMode: samplingMode,
  208. generateDepthBuffer: generateDepthBuffer,
  209. generateStencilBuffer: generateStencilBuffer
  210. };
  211. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  212. this.wrapU = Texture.CLAMP_ADDRESSMODE;
  213. this.wrapV = Texture.CLAMP_ADDRESSMODE;
  214. }
  215. if (isCube) {
  216. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  217. this.coordinatesMode = Texture.INVCUBIC_MODE;
  218. this._textureMatrix = Matrix.Identity();
  219. } else {
  220. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  221. }
  222. }
  223. /**
  224. * Creates a depth stencil texture.
  225. * This is only available in WebGL 2 or with the depth texture extension available.
  226. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  227. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  228. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  229. */
  230. public createDepthStencilTexture(comparisonFunction: number = 0, bilinearFiltering: boolean = true, generateStencil: boolean = false): void {
  231. if (!this.getScene()) {
  232. return;
  233. }
  234. var engine = this.getScene()!.getEngine();
  235. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  236. bilinearFiltering,
  237. comparisonFunction,
  238. generateStencil,
  239. isCube: this.isCube
  240. });
  241. engine.setFrameBufferDepthStencilTexture(this);
  242. }
  243. private _processSizeParameter(size: number | { width: number, height: number } | { ratio: number }): void {
  244. if ((<{ ratio: number }>size).ratio) {
  245. this._sizeRatio = (<{ ratio: number }>size).ratio;
  246. this._size = {
  247. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  248. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  249. }
  250. } else {
  251. this._size = <number | { width: number, height: number }>size;
  252. }
  253. }
  254. public get samples(): number {
  255. return this._samples;
  256. }
  257. public set samples(value: number) {
  258. if (this._samples === value) {
  259. return;
  260. }
  261. let scene = this.getScene();
  262. if (!scene) {
  263. return;
  264. }
  265. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  266. }
  267. public resetRefreshCounter(): void {
  268. this._currentRefreshId = -1;
  269. }
  270. public get refreshRate(): number {
  271. return this._refreshRate;
  272. }
  273. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  274. public set refreshRate(value: number) {
  275. this._refreshRate = value;
  276. this.resetRefreshCounter();
  277. }
  278. public addPostProcess(postProcess: PostProcess): void {
  279. if (!this._postProcessManager) {
  280. let scene = this.getScene();
  281. if (!scene) {
  282. return;
  283. }
  284. this._postProcessManager = new PostProcessManager(scene);
  285. this._postProcesses = new Array<PostProcess>();
  286. }
  287. this._postProcesses.push(postProcess);
  288. this._postProcesses[0].autoClear = false;
  289. }
  290. public clearPostProcesses(dispose?: boolean): void {
  291. if (!this._postProcesses) {
  292. return;
  293. }
  294. if (dispose) {
  295. for (var postProcess of this._postProcesses) {
  296. postProcess.dispose();
  297. }
  298. }
  299. this._postProcesses = [];
  300. }
  301. public removePostProcess(postProcess: PostProcess): void {
  302. if (!this._postProcesses) {
  303. return;
  304. }
  305. var index = this._postProcesses.indexOf(postProcess);
  306. if (index === -1) {
  307. return;
  308. }
  309. this._postProcesses.splice(index, 1);
  310. if (this._postProcesses.length > 0) {
  311. this._postProcesses[0].autoClear = false;
  312. }
  313. }
  314. /** @hidden */
  315. public _shouldRender(): boolean {
  316. if (this._currentRefreshId === -1) { // At least render once
  317. this._currentRefreshId = 1;
  318. return true;
  319. }
  320. if (this.refreshRate === this._currentRefreshId) {
  321. this._currentRefreshId = 1;
  322. return true;
  323. }
  324. this._currentRefreshId++;
  325. return false;
  326. }
  327. public getRenderSize(): number {
  328. if ((<{ width: number, height: number }>this._size).width) {
  329. return (<{ width: number, height: number }>this._size).width;
  330. }
  331. return <number>this._size;
  332. }
  333. public getRenderWidth(): number {
  334. if ((<{ width: number, height: number }>this._size).width) {
  335. return (<{ width: number, height: number }>this._size).width;
  336. }
  337. return <number>this._size;
  338. }
  339. public getRenderHeight(): number {
  340. if ((<{ width: number, height: number }>this._size).width) {
  341. return (<{ width: number, height: number }>this._size).height;
  342. }
  343. return <number>this._size;
  344. }
  345. public get canRescale(): boolean {
  346. return true;
  347. }
  348. public scale(ratio: number): void {
  349. var newSize = this.getRenderSize() * ratio;
  350. this.resize(newSize);
  351. }
  352. public getReflectionTextureMatrix(): Matrix {
  353. if (this.isCube) {
  354. return this._textureMatrix;
  355. }
  356. return super.getReflectionTextureMatrix();
  357. }
  358. public resize(size: number | { width: number, height: number } | { ratio: number }) {
  359. this.releaseInternalTexture();
  360. let scene = this.getScene();
  361. if (!scene) {
  362. return;
  363. }
  364. this._processSizeParameter(size);
  365. if (this.isCube) {
  366. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  367. } else {
  368. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  369. }
  370. }
  371. public render(useCameraPostProcess: boolean = false, dumpForDebug: boolean = false) {
  372. var scene = this.getScene();
  373. if (!scene) {
  374. return;
  375. }
  376. var engine = scene.getEngine();
  377. if (this.useCameraPostProcesses !== undefined) {
  378. useCameraPostProcess = this.useCameraPostProcesses;
  379. }
  380. if (this._waitingRenderList) {
  381. this.renderList = [];
  382. for (var index = 0; index < this._waitingRenderList.length; index++) {
  383. var id = this._waitingRenderList[index];
  384. let mesh = scene.getMeshByID(id);
  385. if (mesh) {
  386. this.renderList.push(mesh);
  387. }
  388. }
  389. delete this._waitingRenderList;
  390. }
  391. // Is predicate defined?
  392. if (this.renderListPredicate) {
  393. if (this.renderList) {
  394. this.renderList.splice(0); // Clear previous renderList
  395. } else {
  396. this.renderList = [];
  397. }
  398. var scene = this.getScene();
  399. if (!scene) {
  400. return;
  401. }
  402. var sceneMeshes = scene.meshes;
  403. for (var index = 0; index < sceneMeshes.length; index++) {
  404. var mesh = sceneMeshes[index];
  405. if (this.renderListPredicate(mesh)) {
  406. this.renderList.push(mesh);
  407. }
  408. }
  409. }
  410. this.onBeforeBindObservable.notifyObservers(this);
  411. // Set custom projection.
  412. // Needs to be before binding to prevent changing the aspect ratio.
  413. let camera: Nullable<Camera>;
  414. if (this.activeCamera) {
  415. camera = this.activeCamera;
  416. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  417. if (this.activeCamera !== scene.activeCamera) {
  418. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  419. }
  420. }
  421. else {
  422. camera = scene.activeCamera;
  423. if (camera) {
  424. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  425. }
  426. }
  427. // Prepare renderingManager
  428. this._renderingManager.reset();
  429. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  430. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  431. var sceneRenderId = scene.getRenderId();
  432. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  433. var mesh = currentRenderList[meshIndex];
  434. if (mesh) {
  435. if (!mesh.isReady(this.refreshRate === 0)) {
  436. this.resetRefreshCounter();
  437. continue;
  438. }
  439. mesh._preActivateForIntermediateRendering(sceneRenderId);
  440. let isMasked;
  441. if (!this.renderList && camera) {
  442. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  443. } else {
  444. isMasked = false;
  445. }
  446. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  447. mesh._activate(sceneRenderId);
  448. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  449. var subMesh = mesh.subMeshes[subIndex];
  450. scene._activeIndices.addCount(subMesh.indexCount, false);
  451. this._renderingManager.dispatch(subMesh, mesh);
  452. }
  453. }
  454. }
  455. }
  456. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  457. var particleSystem = scene.particleSystems[particleIndex];
  458. let emitter: any = particleSystem.emitter;
  459. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  460. continue;
  461. }
  462. if (currentRenderList.indexOf(emitter) >= 0) {
  463. this._renderingManager.dispatchParticles(particleSystem);
  464. }
  465. }
  466. if (this.isCube) {
  467. for (var face = 0; face < 6; face++) {
  468. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  469. scene.incrementRenderId();
  470. scene.resetCachedMaterial();
  471. }
  472. } else {
  473. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  474. }
  475. this.onAfterUnbindObservable.notifyObservers(this);
  476. if (scene.activeCamera) {
  477. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  478. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  479. }
  480. engine.setViewport(scene.activeCamera.viewport);
  481. }
  482. scene.resetCachedMaterial();
  483. }
  484. private _bestReflectionRenderTargetDimension(renderDimension: number, scale: number): number {
  485. let minimum = 128;
  486. let x = renderDimension * scale;
  487. let curved = Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  488. // Ensure we don't exceed the render dimension (while staying POT)
  489. return Math.min(Tools.FloorPOT(renderDimension), curved);
  490. }
  491. protected unbindFrameBuffer(engine: Engine, faceIndex: number): void {
  492. if (!this._texture) {
  493. return;
  494. }
  495. engine.unBindFramebuffer(this._texture, this.isCube, () => {
  496. this.onAfterRenderObservable.notifyObservers(faceIndex);
  497. });
  498. }
  499. private renderToTarget(faceIndex: number, currentRenderList: AbstractMesh[], currentRenderListLength: number, useCameraPostProcess: boolean, dumpForDebug: boolean): void {
  500. var scene = this.getScene();
  501. if (!scene) {
  502. return;
  503. }
  504. var engine = scene.getEngine();
  505. if (!this._texture) {
  506. return;
  507. }
  508. // Bind
  509. if (this._postProcessManager) {
  510. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  511. }
  512. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  513. if (this._texture) {
  514. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  515. }
  516. }
  517. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  518. // Clear
  519. if (this.onClearObservable.hasObservers()) {
  520. this.onClearObservable.notifyObservers(engine);
  521. } else {
  522. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  523. }
  524. if (!this._doNotChangeAspectRatio) {
  525. scene.updateTransformMatrix(true);
  526. }
  527. // Render
  528. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  529. if (this._postProcessManager) {
  530. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  531. }
  532. else if (useCameraPostProcess) {
  533. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  534. }
  535. if (!this._doNotChangeAspectRatio) {
  536. scene.updateTransformMatrix(true);
  537. }
  538. // Dump ?
  539. if (dumpForDebug) {
  540. Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  541. }
  542. // Unbind
  543. if (!this.isCube || faceIndex === 5) {
  544. if (this.isCube) {
  545. if (faceIndex === 5) {
  546. engine.generateMipMapsForCubemap(this._texture);
  547. }
  548. }
  549. this.unbindFrameBuffer(engine, faceIndex);
  550. } else {
  551. this.onAfterRenderObservable.notifyObservers(faceIndex);
  552. }
  553. }
  554. /**
  555. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  556. * This allowed control for front to back rendering or reversly depending of the special needs.
  557. *
  558. * @param renderingGroupId The rendering group id corresponding to its index
  559. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  560. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  561. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  562. */
  563. public setRenderingOrder(renderingGroupId: number,
  564. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  565. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  566. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  567. this._renderingManager.setRenderingOrder(renderingGroupId,
  568. opaqueSortCompareFn,
  569. alphaTestSortCompareFn,
  570. transparentSortCompareFn);
  571. }
  572. /**
  573. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  574. *
  575. * @param renderingGroupId The rendering group id corresponding to its index
  576. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  577. */
  578. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean): void {
  579. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  580. this._renderingManager._useSceneAutoClearSetup = false;
  581. }
  582. public clone(): RenderTargetTexture {
  583. var textureSize = this.getSize();
  584. var newTexture = new RenderTargetTexture(
  585. this.name,
  586. textureSize,
  587. this.getScene(),
  588. this._renderTargetOptions.generateMipMaps,
  589. this._doNotChangeAspectRatio,
  590. this._renderTargetOptions.type,
  591. this.isCube,
  592. this._renderTargetOptions.samplingMode,
  593. this._renderTargetOptions.generateDepthBuffer,
  594. this._renderTargetOptions.generateStencilBuffer
  595. );
  596. // Base texture
  597. newTexture.hasAlpha = this.hasAlpha;
  598. newTexture.level = this.level;
  599. // RenderTarget Texture
  600. newTexture.coordinatesMode = this.coordinatesMode;
  601. if (this.renderList) {
  602. newTexture.renderList = this.renderList.slice(0);
  603. }
  604. return newTexture;
  605. }
  606. public serialize(): any {
  607. if (!this.name) {
  608. return null;
  609. }
  610. var serializationObject = super.serialize();
  611. serializationObject.renderTargetSize = this.getRenderSize();
  612. serializationObject.renderList = [];
  613. if (this.renderList) {
  614. for (var index = 0; index < this.renderList.length; index++) {
  615. serializationObject.renderList.push(this.renderList[index].id);
  616. }
  617. }
  618. return serializationObject;
  619. }
  620. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  621. public disposeFramebufferObjects(): void {
  622. let objBuffer = this.getInternalTexture();
  623. let scene = this.getScene();
  624. if (objBuffer && scene) {
  625. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  626. }
  627. }
  628. public dispose(): void {
  629. if (this._postProcessManager) {
  630. this._postProcessManager.dispose();
  631. this._postProcessManager = null;
  632. }
  633. this.clearPostProcesses(true);
  634. if (this._resizeObserver) {
  635. this.getScene()!.getEngine().onResizeObservable.remove(this._resizeObserver);
  636. this._resizeObserver = null;
  637. }
  638. this.renderList = null;
  639. // Remove from custom render targets
  640. var scene = this.getScene();
  641. if (!scene) {
  642. return;
  643. }
  644. var index = scene.customRenderTargets.indexOf(this);
  645. if (index >= 0) {
  646. scene.customRenderTargets.splice(index, 1);
  647. }
  648. for (var camera of scene.cameras) {
  649. index = camera.customRenderTargets.indexOf(this);
  650. if (index >= 0) {
  651. camera.customRenderTargets.splice(index, 1);
  652. }
  653. }
  654. super.dispose();
  655. }
  656. /** @hidden */
  657. public _rebuild(): void {
  658. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  659. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  660. }
  661. if (this._postProcessManager) {
  662. this._postProcessManager._rebuild();
  663. }
  664. }
  665. /**
  666. * Clear the info related to rendering groups preventing retention point in material dispose.
  667. */
  668. public freeRenderingGroups(): void {
  669. if (this._renderingManager) {
  670. this._renderingManager.freeRenderingGroups();
  671. }
  672. }
  673. }
  674. }