babylon.highlightLayer.ts 31 KB

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