highlightLayer.ts 30 KB

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