layer.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import { Observer, Observable } from "../Misc/observable";
  2. import { Nullable } from "../types";
  3. import { Scene } from "../scene";
  4. import { Vector2 } from "../Maths/math.vector";
  5. import { Color4 } from '../Maths/math.color';
  6. import { EngineStore } from "../Engines/engineStore";
  7. import { VertexBuffer } from "../Meshes/buffer";
  8. import { Effect } from "../Materials/effect";
  9. import { Material } from "../Materials/material";
  10. import { Texture } from "../Materials/Textures/texture";
  11. import { SceneComponentConstants } from "../sceneComponent";
  12. import { LayerSceneComponent } from "./layerSceneComponent";
  13. import { Constants } from "../Engines/constants";
  14. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  15. import "../Shaders/layer.fragment";
  16. import "../Shaders/layer.vertex";
  17. import { DataBuffer } from '../Meshes/dataBuffer';
  18. /**
  19. * This represents a full screen 2d layer.
  20. * This can be useful to display a picture in the background of your scene for instance.
  21. * @see https://www.babylonjs-playground.com/#08A2BS#1
  22. */
  23. export class Layer {
  24. /**
  25. * Define the texture the layer should display.
  26. */
  27. public texture: Nullable<Texture>;
  28. /**
  29. * Is the layer in background or foreground.
  30. */
  31. public isBackground: boolean;
  32. /**
  33. * Define the color of the layer (instead of texture).
  34. */
  35. public color: Color4;
  36. /**
  37. * Define the scale of the layer in order to zoom in out of the texture.
  38. */
  39. public scale = new Vector2(1, 1);
  40. /**
  41. * Define an offset for the layer in order to shift the texture.
  42. */
  43. public offset = new Vector2(0, 0);
  44. /**
  45. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  46. */
  47. public alphaBlendingMode = Constants.ALPHA_COMBINE;
  48. /**
  49. * Define if the layer should alpha test or alpha blend with the rest of the scene.
  50. * Alpha test will not mix with the background color in case of transparency.
  51. * It will either use the texture color or the background depending on the alpha value of the current pixel.
  52. */
  53. public alphaTest: boolean;
  54. /**
  55. * Define a mask to restrict the layer to only some of the scene cameras.
  56. */
  57. public layerMask: number = 0x0FFFFFFF;
  58. /**
  59. * Define the list of render target the layer is visible into.
  60. */
  61. public renderTargetTextures: RenderTargetTexture[] = [];
  62. /**
  63. * Define if the layer is only used in renderTarget or if it also
  64. * renders in the main frame buffer of the canvas.
  65. */
  66. public renderOnlyInRenderTargetTextures = false;
  67. private _scene: Scene;
  68. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  69. private _indexBuffer: Nullable<DataBuffer>;
  70. private _effect: Effect;
  71. private _previousDefines: string;
  72. /**
  73. * An event triggered when the layer is disposed.
  74. */
  75. public onDisposeObservable = new Observable<Layer>();
  76. private _onDisposeObserver: Nullable<Observer<Layer>>;
  77. /**
  78. * Back compatibility with callback before the onDisposeObservable existed.
  79. * The set callback will be triggered when the layer has been disposed.
  80. */
  81. public set onDispose(callback: () => void) {
  82. if (this._onDisposeObserver) {
  83. this.onDisposeObservable.remove(this._onDisposeObserver);
  84. }
  85. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86. }
  87. /**
  88. * An event triggered before rendering the scene
  89. */
  90. public onBeforeRenderObservable = new Observable<Layer>();
  91. private _onBeforeRenderObserver: Nullable<Observer<Layer>>;
  92. /**
  93. * Back compatibility with callback before the onBeforeRenderObservable existed.
  94. * The set callback will be triggered just before rendering the layer.
  95. */
  96. public set onBeforeRender(callback: () => void) {
  97. if (this._onBeforeRenderObserver) {
  98. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99. }
  100. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  101. }
  102. /**
  103. * An event triggered after rendering the scene
  104. */
  105. public onAfterRenderObservable = new Observable<Layer>();
  106. private _onAfterRenderObserver: Nullable<Observer<Layer>>;
  107. /**
  108. * Back compatibility with callback before the onAfterRenderObservable existed.
  109. * The set callback will be triggered just after rendering the layer.
  110. */
  111. public set onAfterRender(callback: () => void) {
  112. if (this._onAfterRenderObserver) {
  113. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114. }
  115. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  116. }
  117. /**
  118. * Instantiates a new layer.
  119. * This represents a full screen 2d layer.
  120. * This can be useful to display a picture in the background of your scene for instance.
  121. * @see https://www.babylonjs-playground.com/#08A2BS#1
  122. * @param name Define the name of the layer in the scene
  123. * @param imgUrl Define the url of the texture to display in the layer
  124. * @param scene Define the scene the layer belongs to
  125. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  126. * @param color Defines a color for the layer
  127. */
  128. constructor(
  129. /**
  130. * Define the name of the layer.
  131. */
  132. public name: string,
  133. imgUrl: Nullable<string>,
  134. scene: Nullable<Scene>,
  135. isBackground?: boolean, color?: Color4) {
  136. this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null;
  137. this.isBackground = isBackground === undefined ? true : isBackground;
  138. this.color = color === undefined ? new Color4(1, 1, 1, 1) : color;
  139. this._scene = <Scene>(scene || EngineStore.LastCreatedScene);
  140. let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER) as LayerSceneComponent;
  141. if (!layerComponent) {
  142. layerComponent = new LayerSceneComponent(this._scene);
  143. this._scene._addComponent(layerComponent);
  144. }
  145. this._scene.layers.push(this);
  146. var engine = this._scene.getEngine();
  147. // VBO
  148. var vertices = [];
  149. vertices.push(1, 1);
  150. vertices.push(-1, 1);
  151. vertices.push(-1, -1);
  152. vertices.push(1, -1);
  153. var vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  154. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  155. this._createIndexBuffer();
  156. }
  157. private _createIndexBuffer(): void {
  158. var engine = this._scene.getEngine();
  159. // Indices
  160. var indices = [];
  161. indices.push(0);
  162. indices.push(1);
  163. indices.push(2);
  164. indices.push(0);
  165. indices.push(2);
  166. indices.push(3);
  167. this._indexBuffer = engine.createIndexBuffer(indices);
  168. }
  169. /** @hidden */
  170. public _rebuild(): void {
  171. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  172. if (vb) {
  173. vb._rebuild();
  174. }
  175. this._createIndexBuffer();
  176. }
  177. /**
  178. * Renders the layer in the scene.
  179. */
  180. public render(): void {
  181. var engine = this._scene.getEngine();
  182. var defines = "";
  183. if (this.alphaTest) {
  184. defines = "#define ALPHATEST";
  185. }
  186. if (this.texture && !this.texture.gammaSpace) {
  187. defines += "\r\n#define LINEAR";
  188. }
  189. if (this._previousDefines !== defines) {
  190. this._previousDefines = defines;
  191. this._effect = engine.createEffect("layer",
  192. [VertexBuffer.PositionKind],
  193. ["textureMatrix", "color", "scale", "offset"],
  194. ["textureSampler"], defines);
  195. }
  196. var currentEffect = this._effect;
  197. // Check
  198. if (!currentEffect || !currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  199. return;
  200. }
  201. var engine = this._scene.getEngine();
  202. this.onBeforeRenderObservable.notifyObservers(this);
  203. // Render
  204. engine.enableEffect(currentEffect);
  205. engine.setState(false);
  206. // Texture
  207. currentEffect.setTexture("textureSampler", this.texture);
  208. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  209. // Color
  210. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  211. // Scale / offset
  212. currentEffect.setVector2("offset", this.offset);
  213. currentEffect.setVector2("scale", this.scale);
  214. // VBOs
  215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  216. // Draw order
  217. if (!this.alphaTest) {
  218. engine.setAlphaMode(this.alphaBlendingMode);
  219. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  220. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  221. }
  222. else {
  223. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  224. }
  225. this.onAfterRenderObservable.notifyObservers(this);
  226. }
  227. /**
  228. * Disposes and releases the associated ressources.
  229. */
  230. public dispose(): void {
  231. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  232. if (vertexBuffer) {
  233. vertexBuffer.dispose();
  234. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  235. }
  236. if (this._indexBuffer) {
  237. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  238. this._indexBuffer = null;
  239. }
  240. if (this.texture) {
  241. this.texture.dispose();
  242. this.texture = null;
  243. }
  244. // Clean RTT list
  245. this.renderTargetTextures = [];
  246. // Remove from scene
  247. var index = this._scene.layers.indexOf(this);
  248. this._scene.layers.splice(index, 1);
  249. // Callback
  250. this.onDisposeObservable.notifyObservers(this);
  251. this.onDisposeObservable.clear();
  252. this.onAfterRenderObservable.clear();
  253. this.onBeforeRenderObservable.clear();
  254. }
  255. }