highlightLayer.ts 32 KB

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