highlightLayer.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. import { serialize, SerializationHelper } from "../Misc/decorators";
  2. import { Observer, Observable } from "../Misc/observable";
  3. import { Tools } from "../Misc/tools";
  4. import { Nullable } from "../types";
  5. import { Camera } from "../Cameras/camera";
  6. import { Scene } from "../scene";
  7. import { Vector2, Color3, Color4 } from "../Maths/math";
  8. import { Engine } from "../Engines/engine";
  9. import { VertexBuffer } from "../Meshes/buffer";
  10. import { SubMesh } from "../Meshes/subMesh";
  11. import { AbstractMesh } from "../Meshes/abstractMesh";
  12. import { Mesh } from "../Meshes/mesh";
  13. import { Effect } from "../Materials/effect";
  14. import { Material } from "../Materials/material";
  15. import { Texture } from "../Materials/Textures/texture";
  16. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  17. import { PostProcess, PostProcessOptions } from "../PostProcesses/postProcess";
  18. import { PassPostProcess } from "../PostProcesses/passPostProcess";
  19. import { BlurPostProcess } from "../PostProcesses/blurPostProcess";
  20. import { _TimeToken } from "../Instrumentation/timeToken";
  21. import { _DepthCullingState, _StencilState, _AlphaState } from "../States/index";
  22. import { EffectLayer } from "./effectLayer";
  23. import { AbstractScene } from "../abstractScene";
  24. import { Constants } from "../Engines/constants";
  25. import { Logger } from "../Misc/logger";
  26. import { _TypeStore } from '../Misc/typeStore';
  27. import "../Shaders/glowMapMerge.fragment";
  28. import "../Shaders/glowMapMerge.vertex";
  29. import "../Shaders/glowBlurPostProcess.fragment";
  30. declare module "../abstractScene" {
  31. export interface AbstractScene {
  32. /**
  33. * Return a the first highlight layer of the scene with a given name.
  34. * @param name The name of the highlight layer to look for.
  35. * @return The highlight layer if found otherwise null.
  36. */
  37. getHighlightLayerByName(name: string): Nullable<HighlightLayer>;
  38. }
  39. }
  40. AbstractScene.prototype.getHighlightLayerByName = function(name: string): Nullable<HighlightLayer> {
  41. for (var index = 0; index < this.effectLayers.length; index++) {
  42. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  43. return (<any>this.effectLayers[index]) as HighlightLayer;
  44. }
  45. }
  46. return null;
  47. };
  48. /**
  49. * Special Glow Blur post process only blurring the alpha channel
  50. * It enforces keeping the most luminous color in the color channel.
  51. */
  52. class GlowBlurPostProcess extends PostProcess {
  53. constructor(name: string, public direction: Vector2, public kernel: number, options: number | PostProcessOptions, camera: Nullable<Camera>, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
  54. super(name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  55. this.onApplyObservable.add((effect: Effect) => {
  56. effect.setFloat2("screenSize", this.width, this.height);
  57. effect.setVector2("direction", this.direction);
  58. effect.setFloat("blurWidth", this.kernel);
  59. });
  60. }
  61. }
  62. /**
  63. * Highlight layer options. This helps customizing the behaviour
  64. * of the highlight layer.
  65. */
  66. export interface IHighlightLayerOptions {
  67. /**
  68. * Multiplication factor apply to the canvas size to compute the render target size
  69. * used to generated the glowing objects (the smaller the faster).
  70. */
  71. mainTextureRatio: number;
  72. /**
  73. * Enforces a fixed size texture to ensure resize independant blur.
  74. */
  75. mainTextureFixedSize?: number;
  76. /**
  77. * Multiplication factor apply to the main texture size in the first step of the blur to reduce the size
  78. * of the picture to blur (the smaller the faster).
  79. */
  80. blurTextureSizeRatio: number;
  81. /**
  82. * How big in texel of the blur texture is the vertical blur.
  83. */
  84. blurVerticalSize: number;
  85. /**
  86. * How big in texel of the blur texture is the horizontal blur.
  87. */
  88. blurHorizontalSize: number;
  89. /**
  90. * Alpha blending mode used to apply the blur. Default is combine.
  91. */
  92. alphaBlendingMode: number;
  93. /**
  94. * The camera attached to the layer.
  95. */
  96. camera: Nullable<Camera>;
  97. /**
  98. * Should we display highlight as a solid stroke?
  99. */
  100. isStroke?: boolean;
  101. /**
  102. * The rendering group to draw the layer in.
  103. */
  104. renderingGroupId: number;
  105. }
  106. /**
  107. * Storage interface grouping all the information required for glowing a mesh.
  108. */
  109. interface IHighlightLayerMesh {
  110. /**
  111. * The glowy mesh
  112. */
  113. mesh: Mesh;
  114. /**
  115. * The color of the glow
  116. */
  117. color: Color3;
  118. /**
  119. * The mesh render callback use to insert stencil information
  120. */
  121. observerHighlight: Nullable<Observer<Mesh>>;
  122. /**
  123. * The mesh render callback use to come to the default behavior
  124. */
  125. observerDefault: Nullable<Observer<Mesh>>;
  126. /**
  127. * If it exists, the emissive color of the material will be used to generate the glow.
  128. * Else it falls back to the current color.
  129. */
  130. glowEmissiveOnly: boolean;
  131. }
  132. /**
  133. * Storage interface grouping all the information required for an excluded mesh.
  134. */
  135. interface IHighlightLayerExcludedMesh {
  136. /**
  137. * The glowy mesh
  138. */
  139. mesh: Mesh;
  140. /**
  141. * The mesh render callback use to prevent stencil use
  142. */
  143. beforeBind: Nullable<Observer<Mesh>>;
  144. /**
  145. * The mesh render callback use to restore previous stencil use
  146. */
  147. afterRender: Nullable<Observer<Mesh>>;
  148. }
  149. /**
  150. * The highlight layer Helps adding a glow effect around a mesh.
  151. *
  152. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  153. * glowy meshes to your scene.
  154. *
  155. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  156. */
  157. export class HighlightLayer extends EffectLayer {
  158. /**
  159. * Effect Name of the highlight layer.
  160. */
  161. public static readonly EffectName = "HighlightLayer";
  162. /**
  163. * The neutral color used during the preparation of the glow effect.
  164. * This is black by default as the blend operation is a blend operation.
  165. */
  166. public static NeutralColor: Color4 = new Color4(0, 0, 0, 0);
  167. /**
  168. * Stencil value used for glowing meshes.
  169. */
  170. public static GlowingMeshStencilReference = 0x02;
  171. /**
  172. * Stencil value used for the other meshes in the scene.
  173. */
  174. public static NormalMeshStencilReference = 0x01;
  175. /**
  176. * Specifies whether or not the inner glow is ACTIVE in the layer.
  177. */
  178. @serialize()
  179. public innerGlow: boolean = true;
  180. /**
  181. * Specifies whether or not the outer glow is ACTIVE in the layer.
  182. */
  183. @serialize()
  184. public outerGlow: boolean = true;
  185. /**
  186. * Specifies the horizontal size of the blur.
  187. */
  188. public set blurHorizontalSize(value: number) {
  189. this._horizontalBlurPostprocess.kernel = value;
  190. }
  191. /**
  192. * Specifies the vertical size of the blur.
  193. */
  194. public set blurVerticalSize(value: number) {
  195. this._verticalBlurPostprocess.kernel = value;
  196. }
  197. /**
  198. * Gets the horizontal size of the blur.
  199. */
  200. @serialize()
  201. public get blurHorizontalSize(): number {
  202. return this._horizontalBlurPostprocess.kernel;
  203. }
  204. /**
  205. * Gets the vertical size of the blur.
  206. */
  207. @serialize()
  208. public get blurVerticalSize(): number {
  209. return this._verticalBlurPostprocess.kernel;
  210. }
  211. /**
  212. * An event triggered when the highlight layer is being blurred.
  213. */
  214. public onBeforeBlurObservable = new Observable<HighlightLayer>();
  215. /**
  216. * An event triggered when the highlight layer has been blurred.
  217. */
  218. public onAfterBlurObservable = new Observable<HighlightLayer>();
  219. private _instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  220. @serialize("options")
  221. private _options: IHighlightLayerOptions;
  222. private _downSamplePostprocess: PassPostProcess;
  223. private _horizontalBlurPostprocess: GlowBlurPostProcess;
  224. private _verticalBlurPostprocess: GlowBlurPostProcess;
  225. private _blurTexture: RenderTargetTexture;
  226. private _meshes: Nullable<{ [id: string]: Nullable<IHighlightLayerMesh> }> = {};
  227. private _excludedMeshes: Nullable<{ [id: string]: Nullable<IHighlightLayerExcludedMesh> }> = {};
  228. /**
  229. * Instantiates a new highlight Layer and references it to the scene..
  230. * @param name The name of the layer
  231. * @param scene The scene to use the layer in
  232. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  233. */
  234. constructor(public name: string, scene: Scene, options?: Partial<IHighlightLayerOptions>) {
  235. super(name, scene);
  236. this.neutralColor = HighlightLayer.NeutralColor;
  237. // Warn on stencil
  238. if (!this._engine.isStencilEnable) {
  239. Logger.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }");
  240. }
  241. // Adapt options
  242. this._options = {
  243. mainTextureRatio: 0.5,
  244. blurTextureSizeRatio: 0.5,
  245. blurHorizontalSize: 1.0,
  246. blurVerticalSize: 1.0,
  247. alphaBlendingMode: Constants.ALPHA_COMBINE,
  248. camera: null,
  249. renderingGroupId: -1,
  250. ...options,
  251. };
  252. // Initialize the layer
  253. this._init({
  254. alphaBlendingMode: this._options.alphaBlendingMode,
  255. camera: this._options.camera,
  256. mainTextureFixedSize: this._options.mainTextureFixedSize,
  257. mainTextureRatio: this._options.mainTextureRatio,
  258. renderingGroupId: this._options.renderingGroupId
  259. });
  260. // Do not render as long as no meshes have been added
  261. this._shouldRender = false;
  262. }
  263. /**
  264. * Get the effect name of the layer.
  265. * @return The effect name
  266. */
  267. public getEffectName(): string {
  268. return HighlightLayer.EffectName;
  269. }
  270. /**
  271. * Create the merge effect. This is the shader use to blit the information back
  272. * to the main canvas at the end of the scene rendering.
  273. */
  274. protected _createMergeEffect(): Effect {
  275. // Effect
  276. return this._engine.createEffect("glowMapMerge",
  277. [VertexBuffer.PositionKind],
  278. ["offset"],
  279. ["textureSampler"],
  280. this._options.isStroke ? "#define STROKE \n" : undefined);
  281. }
  282. /**
  283. * Creates the render target textures and post processes used in the highlight layer.
  284. */
  285. protected _createTextureAndPostProcesses(): void {
  286. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  287. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  288. blurTextureWidth = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  289. blurTextureHeight = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  290. var textureType = 0;
  291. if (this._engine.getCaps().textureHalfFloatRender) {
  292. textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  293. }
  294. else {
  295. textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  296. }
  297. this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",
  298. {
  299. width: blurTextureWidth,
  300. height: blurTextureHeight
  301. },
  302. this._scene,
  303. false,
  304. true,
  305. textureType);
  306. this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  307. this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  308. this._blurTexture.anisotropicFilteringLevel = 16;
  309. this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  310. this._blurTexture.renderParticles = false;
  311. this._blurTexture.ignoreCameraViewport = true;
  312. this._textures = [this._blurTexture];
  313. if (this._options.alphaBlendingMode === Constants.ALPHA_COMBINE) {
  314. this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio,
  315. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  316. this._downSamplePostprocess.onApplyObservable.add((effect) => {
  317. effect.setTexture("textureSampler", this._mainTexture);
  318. });
  319. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  320. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  321. this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {
  322. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  323. });
  324. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  325. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  326. this._verticalBlurPostprocess.onApplyObservable.add((effect) => {
  327. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  328. });
  329. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  330. }
  331. else {
  332. this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  333. width: blurTextureWidth,
  334. height: blurTextureHeight
  335. },
  336. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  337. this._horizontalBlurPostprocess.width = blurTextureWidth;
  338. this._horizontalBlurPostprocess.height = blurTextureHeight;
  339. this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {
  340. effect.setTexture("textureSampler", this._mainTexture);
  341. });
  342. this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  343. width: blurTextureWidth,
  344. height: blurTextureHeight
  345. },
  346. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  347. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  348. }
  349. this._mainTexture.onAfterUnbindObservable.add(() => {
  350. this.onBeforeBlurObservable.notifyObservers(this);
  351. let internalTexture = this._blurTexture.getInternalTexture();
  352. if (internalTexture) {
  353. this._scene.postProcessManager.directRender(
  354. this._postProcesses,
  355. internalTexture,
  356. true);
  357. }
  358. this.onAfterBlurObservable.notifyObservers(this);
  359. });
  360. // Prevent autoClear.
  361. this._postProcesses.map((pp) => { pp.autoClear = false; });
  362. }
  363. /**
  364. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  365. */
  366. public needStencil(): boolean {
  367. return true;
  368. }
  369. /**
  370. * Checks for the readiness of the element composing the layer.
  371. * @param subMesh the mesh to check for
  372. * @param useInstances specify wether or not to use instances to render the mesh
  373. * @param emissiveTexture the associated emissive texture used to generate the glow
  374. * @return true if ready otherwise, false
  375. */
  376. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  377. let material = subMesh.getMaterial();
  378. let mesh = subMesh.getRenderingMesh();
  379. if (!material || !mesh || !this._meshes) {
  380. return false;
  381. }
  382. let emissiveTexture: Nullable<Texture> = null;
  383. let highlightLayerMesh = this._meshes[mesh.uniqueId];
  384. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  385. emissiveTexture = (<any>material).emissiveTexture;
  386. }
  387. return super._isReady(subMesh, useInstances, emissiveTexture);
  388. }
  389. /**
  390. * Implementation specific of rendering the generating effect on the main canvas.
  391. * @param effect The effect used to render through
  392. */
  393. protected _internalRender(effect: Effect): void {
  394. // Texture
  395. effect.setTexture("textureSampler", this._blurTexture);
  396. // Cache
  397. var engine = this._engine;
  398. engine.cacheStencilState();
  399. // Stencil operations
  400. engine.setStencilOperationPass(Constants.REPLACE);
  401. engine.setStencilOperationFail(Constants.KEEP);
  402. engine.setStencilOperationDepthFail(Constants.KEEP);
  403. // Draw order
  404. engine.setStencilMask(0x00);
  405. engine.setStencilBuffer(true);
  406. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  407. // 2 passes inner outer
  408. if (this.outerGlow) {
  409. effect.setFloat("offset", 0);
  410. engine.setStencilFunction(Constants.NOTEQUAL);
  411. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  412. }
  413. if (this.innerGlow) {
  414. effect.setFloat("offset", 1);
  415. engine.setStencilFunction(Constants.EQUAL);
  416. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  417. }
  418. // Restore Cache
  419. engine.restoreStencilState();
  420. }
  421. /**
  422. * Returns true if the layer contains information to display, otherwise false.
  423. */
  424. public shouldRender(): boolean {
  425. if (super.shouldRender()) {
  426. return this._meshes ? true : false;
  427. }
  428. return false;
  429. }
  430. /**
  431. * Returns true if the mesh should render, otherwise false.
  432. * @param mesh The mesh to render
  433. * @returns true if it should render otherwise false
  434. */
  435. protected _shouldRenderMesh(mesh: Mesh): boolean {
  436. // Excluded Mesh
  437. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  438. return false;
  439. }
  440. if (!super.hasMesh(mesh)) {
  441. return false;
  442. }
  443. return true;
  444. }
  445. /**
  446. * Sets the required values for both the emissive texture and and the main color.
  447. */
  448. protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void {
  449. var highlightLayerMesh = this._meshes![mesh.uniqueId];
  450. if (highlightLayerMesh) {
  451. this._emissiveTextureAndColor.color.set(
  452. highlightLayerMesh.color.r,
  453. highlightLayerMesh.color.g,
  454. highlightLayerMesh.color.b,
  455. 1.0);
  456. }
  457. else {
  458. this._emissiveTextureAndColor.color.set(
  459. this.neutralColor.r,
  460. this.neutralColor.g,
  461. this.neutralColor.b,
  462. this.neutralColor.a);
  463. }
  464. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  465. this._emissiveTextureAndColor.texture = (<any>material).emissiveTexture;
  466. this._emissiveTextureAndColor.color.set(
  467. 1.0,
  468. 1.0,
  469. 1.0,
  470. 1.0);
  471. }
  472. else {
  473. this._emissiveTextureAndColor.texture = null;
  474. }
  475. }
  476. /**
  477. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  478. * @param mesh The mesh to exclude from the highlight layer
  479. */
  480. public addExcludedMesh(mesh: Mesh) {
  481. if (!this._excludedMeshes) {
  482. return;
  483. }
  484. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  485. if (!meshExcluded) {
  486. this._excludedMeshes[mesh.uniqueId] = {
  487. mesh: mesh,
  488. beforeBind: mesh.onBeforeBindObservable.add((mesh: Mesh) => {
  489. mesh.getEngine().setStencilBuffer(false);
  490. }),
  491. afterRender: mesh.onAfterRenderObservable.add((mesh: Mesh) => {
  492. mesh.getEngine().setStencilBuffer(true);
  493. }),
  494. };
  495. }
  496. }
  497. /**
  498. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  499. * @param mesh The mesh to highlight
  500. */
  501. public removeExcludedMesh(mesh: Mesh) {
  502. if (!this._excludedMeshes) {
  503. return;
  504. }
  505. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  506. if (meshExcluded) {
  507. if (meshExcluded.beforeBind) {
  508. mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind);
  509. }
  510. if (meshExcluded.afterRender) {
  511. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  512. }
  513. }
  514. this._excludedMeshes[mesh.uniqueId] = null;
  515. }
  516. /**
  517. * Determine if a given mesh will be highlighted by the current HighlightLayer
  518. * @param mesh mesh to test
  519. * @returns true if the mesh will be highlighted by the current HighlightLayer
  520. */
  521. public hasMesh(mesh: AbstractMesh): boolean {
  522. if (!this._meshes) {
  523. return false;
  524. }
  525. if (!super.hasMesh(mesh)) {
  526. return false;
  527. }
  528. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  529. }
  530. /**
  531. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  532. * @param mesh The mesh to highlight
  533. * @param color The color of the highlight
  534. * @param glowEmissiveOnly Extract the glow from the emissive texture
  535. */
  536. public addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly = false) {
  537. if (!this._meshes) {
  538. return;
  539. }
  540. var meshHighlight = this._meshes[mesh.uniqueId];
  541. if (meshHighlight) {
  542. meshHighlight.color = color;
  543. }
  544. else {
  545. this._meshes[mesh.uniqueId] = {
  546. mesh: mesh,
  547. color: color,
  548. // Lambda required for capture due to Observable this context
  549. observerHighlight: mesh.onBeforeBindObservable.add((mesh: Mesh) => {
  550. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  551. this._defaultStencilReference(mesh);
  552. }
  553. else {
  554. mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  555. }
  556. }),
  557. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  558. glowEmissiveOnly: glowEmissiveOnly
  559. };
  560. mesh.onDisposeObservable.add(() => {
  561. this._disposeMesh(mesh);
  562. });
  563. }
  564. this._shouldRender = true;
  565. }
  566. /**
  567. * Remove a mesh from the highlight layer in order to make it stop glowing.
  568. * @param mesh The mesh to highlight
  569. */
  570. public removeMesh(mesh: Mesh) {
  571. if (!this._meshes) {
  572. return;
  573. }
  574. var meshHighlight = this._meshes[mesh.uniqueId];
  575. if (meshHighlight) {
  576. if (meshHighlight.observerHighlight) {
  577. mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
  578. }
  579. if (meshHighlight.observerDefault) {
  580. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  581. }
  582. delete this._meshes[mesh.uniqueId];
  583. }
  584. this._shouldRender = false;
  585. for (var meshHighlightToCheck in this._meshes) {
  586. if (this._meshes[meshHighlightToCheck]) {
  587. this._shouldRender = true;
  588. break;
  589. }
  590. }
  591. }
  592. /**
  593. * Force the stencil to the normal expected value for none glowing parts
  594. */
  595. private _defaultStencilReference(mesh: Mesh) {
  596. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  597. }
  598. /**
  599. * Free any resources and references associated to a mesh.
  600. * Internal use
  601. * @param mesh The mesh to free.
  602. * @hidden
  603. */
  604. public _disposeMesh(mesh: Mesh): void {
  605. this.removeMesh(mesh);
  606. this.removeExcludedMesh(mesh);
  607. }
  608. /**
  609. * Dispose the highlight layer and free resources.
  610. */
  611. public dispose(): void {
  612. if (this._meshes) {
  613. // Clean mesh references
  614. for (let id in this._meshes) {
  615. let meshHighlight = this._meshes[id];
  616. if (meshHighlight && meshHighlight.mesh) {
  617. if (meshHighlight.observerHighlight) {
  618. meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
  619. }
  620. if (meshHighlight.observerDefault) {
  621. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  622. }
  623. }
  624. }
  625. this._meshes = null;
  626. }
  627. if (this._excludedMeshes) {
  628. for (let id in this._excludedMeshes) {
  629. let meshHighlight = this._excludedMeshes[id];
  630. if (meshHighlight) {
  631. if (meshHighlight.beforeBind) {
  632. meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind);
  633. }
  634. if (meshHighlight.afterRender) {
  635. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  636. }
  637. }
  638. }
  639. this._excludedMeshes = null;
  640. }
  641. super.dispose();
  642. }
  643. /**
  644. * Gets the class name of the effect layer
  645. * @returns the string with the class name of the effect layer
  646. */
  647. public getClassName(): string {
  648. return "HighlightLayer";
  649. }
  650. /**
  651. * Serializes this Highlight layer
  652. * @returns a serialized Highlight layer object
  653. */
  654. public serialize(): any {
  655. var serializationObject = SerializationHelper.Serialize(this);
  656. serializationObject.customType = "BABYLON.HighlightLayer";
  657. // Highlighted meshes
  658. serializationObject.meshes = [];
  659. if (this._meshes) {
  660. for (var m in this._meshes) {
  661. var mesh = this._meshes[m];
  662. if (mesh) {
  663. serializationObject.meshes.push({
  664. glowEmissiveOnly: mesh.glowEmissiveOnly,
  665. color: mesh.color.asArray(),
  666. meshId: mesh.mesh.id
  667. });
  668. }
  669. }
  670. }
  671. // Excluded meshes
  672. serializationObject.excludedMeshes = [];
  673. if (this._excludedMeshes) {
  674. for (var e in this._excludedMeshes) {
  675. var excludedMesh = this._excludedMeshes[e];
  676. if (excludedMesh) {
  677. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  678. }
  679. }
  680. }
  681. return serializationObject;
  682. }
  683. /**
  684. * Creates a Highlight layer from parsed Highlight layer data
  685. * @param parsedHightlightLayer defines the Highlight layer data
  686. * @param scene defines the current scene
  687. * @param rootUrl defines the root URL containing the Highlight layer information
  688. * @returns a parsed Highlight layer
  689. */
  690. public static Parse(parsedHightlightLayer: any, scene: Scene, rootUrl: string): HighlightLayer {
  691. var hl = SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl);
  692. var index;
  693. // Excluded meshes
  694. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  695. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  696. if (mesh) {
  697. hl.addExcludedMesh(<Mesh>mesh);
  698. }
  699. }
  700. // Included meshes
  701. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  702. var highlightedMesh = parsedHightlightLayer.meshes[index];
  703. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  704. if (mesh) {
  705. hl.addMesh(<Mesh>mesh, Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  706. }
  707. }
  708. return hl;
  709. }
  710. }
  711. _TypeStore.RegisteredTypes["BABYLON.HighlightLayer"] = HighlightLayer;