babylon.highlightlayer.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. module BABYLON {
  2. /**
  3. * Special Glow Blur post process only blurring the alpha channel
  4. * It enforces keeping the most luminous color in the color channel.
  5. */
  6. class GlowBlurPostProcess extends PostProcess {
  7. constructor(name: string, public direction: Vector2, public blurWidth: number, options: number | PostProcessOptions, camera: Camera, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
  8. super(name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  9. this.onApplyObservable.add((effect: Effect) => {
  10. effect.setFloat2("screenSize", this.width, this.height);
  11. effect.setVector2("direction", this.direction);
  12. effect.setFloat("blurWidth", this.blurWidth);
  13. });
  14. }
  15. }
  16. /**
  17. * Highlight layer options. This helps customizing the behaviour
  18. * of the highlight layer.
  19. */
  20. export interface IHighlightLayerOptions {
  21. /**
  22. * Multiplication factor apply to the canvas size to compute the render target size
  23. * used to generated the glowing objects (the smaller the faster).
  24. */
  25. mainTextureRatio?: number;
  26. /**
  27. * Multiplication factor apply to the main texture size in the first step of the blur to reduce the size
  28. * of the picture to blur (the smaller the faster).
  29. */
  30. blurTextureSizeRatio?: number;
  31. /**
  32. * How big in texel of the blur texture is the vertical blur.
  33. */
  34. blurVerticalSize?: number;
  35. /**
  36. * How big in texel of the blur texture is the horizontal blur.
  37. */
  38. blurHorizontalSize?: number;
  39. /**
  40. * Alpha blending mode used to apply the blur. Default is combine.
  41. */
  42. alphaBlendingMode?: number
  43. /**
  44. * The camera attached to the layer.
  45. */
  46. camera?: Camera;
  47. }
  48. /**
  49. * Storage interface grouping all the information required for glowing a mesh.
  50. */
  51. interface IHighlightLayerMesh {
  52. /**
  53. * The glowy mesh
  54. */
  55. mesh: Mesh;
  56. /**
  57. * The color of the glow
  58. */
  59. color: Color3;
  60. /**
  61. * The mesh render callback use to insert stencil information
  62. */
  63. observerHighlight: Observer<Mesh>;
  64. /**
  65. * The mesh render callback use to come to the default behavior
  66. */
  67. observerDefault: Observer<Mesh>;
  68. /**
  69. * If it exists, the emissive color of the material will be used to generate the glow.
  70. * Else it falls back to the current color.
  71. */
  72. glowEmissiveOnly: boolean;
  73. }
  74. /**
  75. * Storage interface grouping all the information required for an excluded mesh.
  76. */
  77. interface IHighlightLayerExcludedMesh {
  78. /**
  79. * The glowy mesh
  80. */
  81. mesh: Mesh;
  82. /**
  83. * The mesh render callback use to prevent stencil use
  84. */
  85. beforeRender: Observer<Mesh>;
  86. /**
  87. * The mesh render callback use to restore previous stencil use
  88. */
  89. afterRender: Observer<Mesh>;
  90. }
  91. /**
  92. * The highlight layer Helps adding a glow effect around a mesh.
  93. *
  94. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95. * glowy meshes to your scene.
  96. *
  97. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  98. */
  99. export class HighlightLayer {
  100. /**
  101. * The neutral color used during the preparation of the glow effect.
  102. * This is black by default as the blend operation is a blend operation.
  103. */
  104. public static neutralColor: Color4 = new Color4(0, 0, 0, 0);
  105. /**
  106. * Stencil value used for glowing meshes.
  107. */
  108. public static glowingMeshStencilReference = 0x02;
  109. /**
  110. * Stencil value used for the other meshes in the scene.
  111. */
  112. public static normalMeshStencilReference = 0x01;
  113. private _scene: Scene;
  114. private _engine: Engine;
  115. private _options: IHighlightLayerOptions;
  116. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  117. private _indexBuffer: WebGLBuffer;
  118. private _downSamplePostprocess: PassPostProcess;
  119. private _horizontalBlurPostprocess: GlowBlurPostProcess;
  120. private _verticalBlurPostprocess: GlowBlurPostProcess;
  121. private _cachedDefines: string;
  122. private _glowMapGenerationEffect: Effect;
  123. private _glowMapMergeEffect: Effect;
  124. private _blurTexture: RenderTargetTexture;
  125. private _mainTexture: RenderTargetTexture;
  126. private _mainTextureDesiredSize: ISize = { width: 0, height: 0 };
  127. private _meshes: { [id: string]: IHighlightLayerMesh } = {};
  128. private _maxSize: number = 0;
  129. private _shouldRender = false;
  130. private _instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  131. private _excludedMeshes: { [id: string]: IHighlightLayerExcludedMesh } = {};
  132. /**
  133. * Specifies whether or not the inner glow is ACTIVE in the layer.
  134. */
  135. public innerGlow: boolean = true;
  136. /**
  137. * Specifies whether or not the outer glow is ACTIVE in the layer.
  138. */
  139. public outerGlow: boolean = true;
  140. /**
  141. * Specifies the horizontal size of the blur.
  142. */
  143. public set blurHorizontalSize(value: number) {
  144. this._horizontalBlurPostprocess.blurWidth = value;
  145. }
  146. /**
  147. * Specifies the vertical size of the blur.
  148. */
  149. public set blurVerticalSize(value: number) {
  150. this._verticalBlurPostprocess.blurWidth = value;
  151. }
  152. /**
  153. * Gets the horizontal size of the blur.
  154. */
  155. public get blurHorizontalSize(): number {
  156. return this._horizontalBlurPostprocess.blurWidth
  157. }
  158. /**
  159. * Gets the vertical size of the blur.
  160. */
  161. public get blurVerticalSize(): number {
  162. return this._verticalBlurPostprocess.blurWidth;
  163. }
  164. /**
  165. * Gets the camera attached to the layer.
  166. */
  167. public get camera(): Camera {
  168. return this._options.camera;
  169. }
  170. /**
  171. * An event triggered when the highlight layer has been disposed.
  172. * @type {BABYLON.Observable}
  173. */
  174. public onDisposeObservable = new Observable<HighlightLayer>();
  175. /**
  176. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  177. * @type {BABYLON.Observable}
  178. */
  179. public onBeforeRenderMainTextureObservable = new Observable<HighlightLayer>();
  180. /**
  181. * An event triggered when the highlight layer is being blurred.
  182. * @type {BABYLON.Observable}
  183. */
  184. public onBeforeBlurObservable = new Observable<HighlightLayer>();
  185. /**
  186. * An event triggered when the highlight layer has been blurred.
  187. * @type {BABYLON.Observable}
  188. */
  189. public onAfterBlurObservable = new Observable<HighlightLayer>();
  190. /**
  191. * An event triggered when the glowing blurred texture is being merged in the scene.
  192. * @type {BABYLON.Observable}
  193. */
  194. public onBeforeComposeObservable = new Observable<HighlightLayer>();
  195. /**
  196. * An event triggered when the glowing blurred texture has been merged in the scene.
  197. * @type {BABYLON.Observable}
  198. */
  199. public onAfterComposeObservable = new Observable<HighlightLayer>();
  200. /**
  201. * An event triggered when the highlight layer changes its size.
  202. * @type {BABYLON.Observable}
  203. */
  204. public onSizeChangedObservable = new Observable<HighlightLayer>();
  205. /**
  206. * Instantiates a new highlight Layer and references it to the scene..
  207. * @param name The name of the layer
  208. * @param scene The scene to use the layer in
  209. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  210. */
  211. constructor(name: string, scene: Scene, options?: IHighlightLayerOptions) {
  212. this._scene = scene;
  213. var engine = scene.getEngine();
  214. this._engine = engine;
  215. this._maxSize = this._engine.getCaps().maxTextureSize;
  216. this._scene.highlightLayers.push(this);
  217. // Warn on stencil.
  218. if (!this._engine.isStencilEnable) {
  219. Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  220. }
  221. // Adapt options
  222. this._options = options || {
  223. mainTextureRatio: 0.25,
  224. blurTextureSizeRatio: 0.5,
  225. blurHorizontalSize: 1,
  226. blurVerticalSize: 1,
  227. alphaBlendingMode: Engine.ALPHA_COMBINE
  228. };
  229. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  230. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  231. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  232. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  233. this._options.alphaBlendingMode = this._options.alphaBlendingMode || Engine.ALPHA_COMBINE;
  234. // VBO
  235. var vertices = [];
  236. vertices.push(1, 1);
  237. vertices.push(-1, 1);
  238. vertices.push(-1, -1);
  239. vertices.push(1, -1);
  240. var vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  241. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  242. // Indices
  243. var indices = [];
  244. indices.push(0);
  245. indices.push(1);
  246. indices.push(2);
  247. indices.push(0);
  248. indices.push(2);
  249. indices.push(3);
  250. this._indexBuffer = engine.createIndexBuffer(indices);
  251. // Effect
  252. this._glowMapMergeEffect = engine.createEffect("glowMapMerge",
  253. [VertexBuffer.PositionKind],
  254. ["offset"],
  255. ["textureSampler"], "");
  256. // Render target
  257. this.setMainTextureSize();
  258. // Create Textures and post processes
  259. this.createTextureAndPostProcesses();
  260. }
  261. /**
  262. * Creates the render target textures and post processes used in the highlight layer.
  263. */
  264. private createTextureAndPostProcesses(): void {
  265. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  266. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  267. blurTextureWidth = Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  268. blurTextureHeight = Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  269. this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
  270. {
  271. width: this._mainTextureDesiredSize.width,
  272. height: this._mainTextureDesiredSize.height
  273. },
  274. this._scene,
  275. false,
  276. true,
  277. Engine.TEXTURETYPE_UNSIGNED_INT);
  278. this._mainTexture.activeCamera = this._options.camera;
  279. this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  280. this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  281. this._mainTexture.anisotropicFilteringLevel = 1;
  282. this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  283. this._mainTexture.renderParticles = false;
  284. this._mainTexture.renderList = null;
  285. this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",
  286. {
  287. width: blurTextureWidth,
  288. height: blurTextureHeight
  289. },
  290. this._scene,
  291. false,
  292. true,
  293. Engine.TEXTURETYPE_UNSIGNED_INT);
  294. this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  295. this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  296. this._blurTexture.anisotropicFilteringLevel = 16;
  297. this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  298. this._blurTexture.renderParticles = false;
  299. this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio,
  300. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  301. this._downSamplePostprocess.onApplyObservable.add(effect => {
  302. effect.setTexture("textureSampler", this._mainTexture);
  303. });
  304. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  305. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  306. this._horizontalBlurPostprocess.onApplyObservable.add(effect => {
  307. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  308. });
  309. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  310. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  311. this._verticalBlurPostprocess.onApplyObservable.add(effect => {
  312. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  313. });
  314. this._mainTexture.onAfterUnbindObservable.add(() => {
  315. this.onBeforeBlurObservable.notifyObservers(this);
  316. this._scene.postProcessManager.directRender(
  317. [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess],
  318. this._blurTexture.getInternalTexture());
  319. this.onAfterBlurObservable.notifyObservers(this);
  320. });
  321. // Custom render function
  322. var renderSubMesh = (subMesh: SubMesh): void => {
  323. var mesh = subMesh.getRenderingMesh();
  324. var scene = this._scene;
  325. var engine = scene.getEngine();
  326. // Culling
  327. engine.setState(subMesh.getMaterial().backFaceCulling);
  328. // Managing instances
  329. var batch = mesh._getInstancesRenderList(subMesh._id);
  330. if (batch.mustReturn) {
  331. return;
  332. }
  333. // Excluded Mesh
  334. if (this._excludedMeshes[mesh.id]) {
  335. return;
  336. };
  337. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  338. var highlightLayerMesh = this._meshes[mesh.id];
  339. var material = subMesh.getMaterial();
  340. var emissiveTexture: Texture = null;
  341. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  342. emissiveTexture = (<any>material).emissiveTexture;
  343. }
  344. if (this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  345. engine.enableEffect(this._glowMapGenerationEffect);
  346. mesh._bind(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode);
  347. this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  348. if (highlightLayerMesh) {
  349. this._glowMapGenerationEffect.setFloat4("color",
  350. highlightLayerMesh.color.r,
  351. highlightLayerMesh.color.g,
  352. highlightLayerMesh.color.b,
  353. 1.0);
  354. }
  355. else {
  356. this._glowMapGenerationEffect.setFloat4("color",
  357. HighlightLayer.neutralColor.r,
  358. HighlightLayer.neutralColor.g,
  359. HighlightLayer.neutralColor.b,
  360. HighlightLayer.neutralColor.a);
  361. }
  362. // Alpha test
  363. if (material && material.needAlphaTesting()) {
  364. var alphaTexture = material.getAlphaTestTexture();
  365. this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  366. this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  367. }
  368. // Glow emissive only
  369. if (emissiveTexture) {
  370. this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  371. this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  372. }
  373. // Bones
  374. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  375. this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  376. }
  377. // Draw
  378. mesh._processRendering(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  379. (isInstance, world) => this._glowMapGenerationEffect.setMatrix("world", world));
  380. } else {
  381. // Need to reset refresh rate of the shadowMap
  382. this._mainTexture.resetRefreshCounter();
  383. }
  384. };
  385. this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  386. this.onBeforeRenderMainTextureObservable.notifyObservers(this);
  387. var index: number;
  388. for (index = 0; index < opaqueSubMeshes.length; index++) {
  389. renderSubMesh(opaqueSubMeshes.data[index]);
  390. }
  391. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  392. renderSubMesh(alphaTestSubMeshes.data[index]);
  393. }
  394. for (index = 0; index < transparentSubMeshes.length; index++) {
  395. renderSubMesh(transparentSubMeshes.data[index]);
  396. }
  397. };
  398. this._mainTexture.onClearObservable.add((engine: Engine) => {
  399. engine.clear(HighlightLayer.neutralColor, true, true, true);
  400. });
  401. }
  402. /**
  403. * Checks for the readiness of the element composing the layer.
  404. * @param subMesh the mesh to check for
  405. * @param useInstances specify wether or not to use instances to render the mesh
  406. * @param emissiveTexture the associated emissive texture used to generate the glow
  407. * @return true if ready otherwise, false
  408. */
  409. private isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Texture): boolean {
  410. if (!subMesh.getMaterial().isReady()) {
  411. return false;
  412. }
  413. var defines = [];
  414. var attribs = [VertexBuffer.PositionKind];
  415. var mesh = subMesh.getMesh();
  416. var material = subMesh.getMaterial();
  417. var uv1 = false;
  418. var uv2 = false;
  419. // Alpha test
  420. if (material && material.needAlphaTesting()) {
  421. var alphaTexture = material.getAlphaTestTexture();
  422. if (alphaTexture) {
  423. defines.push("#define ALPHATEST");
  424. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  425. alphaTexture.coordinatesIndex === 1) {
  426. defines.push("#define DIFFUSEUV2");
  427. uv2 = true;
  428. }
  429. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  430. defines.push("#define DIFFUSEUV1");
  431. uv1 = true;
  432. }
  433. }
  434. }
  435. // Emissive
  436. if (emissiveTexture) {
  437. defines.push("#define EMISSIVE");
  438. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  439. emissiveTexture.coordinatesIndex === 1) {
  440. defines.push("#define EMISSIVEUV2");
  441. uv2 = true;
  442. }
  443. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  444. defines.push("#define EMISSIVEUV1");
  445. uv1 = true;
  446. }
  447. }
  448. if (uv1) {
  449. attribs.push(VertexBuffer.UVKind);
  450. defines.push("#define UV1");
  451. }
  452. if (uv2) {
  453. attribs.push(VertexBuffer.UV2Kind);
  454. defines.push("#define UV2");
  455. }
  456. // Bones
  457. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  458. attribs.push(VertexBuffer.MatricesIndicesKind);
  459. attribs.push(VertexBuffer.MatricesWeightsKind);
  460. if (mesh.numBoneInfluencers > 4) {
  461. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  462. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  463. }
  464. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  465. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  466. } else {
  467. defines.push("#define NUM_BONE_INFLUENCERS 0");
  468. }
  469. // Instances
  470. if (useInstances) {
  471. defines.push("#define INSTANCES");
  472. attribs.push("world0");
  473. attribs.push("world1");
  474. attribs.push("world2");
  475. attribs.push("world3");
  476. }
  477. // Get correct effect
  478. var join = defines.join("\n");
  479. if (this._cachedDefines !== join) {
  480. this._cachedDefines = join;
  481. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  482. attribs,
  483. ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"],
  484. ["diffuseSampler", "emissiveSampler"], join);
  485. }
  486. return this._glowMapGenerationEffect.isReady();
  487. }
  488. /**
  489. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  490. */
  491. public render(): void {
  492. var currentEffect = this._glowMapMergeEffect;
  493. // Check
  494. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  495. return;
  496. var engine = this._scene.getEngine();
  497. this.onBeforeComposeObservable.notifyObservers(this);
  498. // Render
  499. engine.enableEffect(currentEffect);
  500. engine.setState(false);
  501. // Cache
  502. var previousStencilBuffer = engine.getStencilBuffer();
  503. var previousStencilFunction = engine.getStencilFunction();
  504. var previousStencilMask = engine.getStencilMask();
  505. var previousAlphaMode = engine.getAlphaMode();
  506. // Texture
  507. currentEffect.setTexture("textureSampler", this._blurTexture);
  508. // VBOs
  509. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  510. // Draw order
  511. engine.setAlphaMode(this._options.alphaBlendingMode);
  512. engine.setStencilMask(0x00);
  513. engine.setStencilBuffer(true);
  514. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  515. if (this.outerGlow) {
  516. currentEffect.setFloat("offset", 0);
  517. engine.setStencilFunction(Engine.NOTEQUAL);
  518. engine.draw(true, 0, 6);
  519. }
  520. if (this.innerGlow) {
  521. currentEffect.setFloat("offset", 1);
  522. engine.setStencilFunction(Engine.EQUAL);
  523. engine.draw(true, 0, 6);
  524. }
  525. // Restore Cache
  526. engine.setStencilFunction(previousStencilFunction);
  527. engine.setStencilMask(previousStencilMask);
  528. engine.setAlphaMode(previousAlphaMode);
  529. engine.setStencilBuffer(previousStencilBuffer);
  530. this.onAfterComposeObservable.notifyObservers(this);
  531. // Handle size changes.
  532. var size = this._mainTexture.getSize();
  533. this.setMainTextureSize();
  534. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  535. // Recreate RTT and post processes on size change.
  536. this.onSizeChangedObservable.notifyObservers(this);
  537. this.disposeTextureAndPostProcesses();
  538. this.createTextureAndPostProcesses();
  539. }
  540. }
  541. /**
  542. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  543. * @param mesh The mesh to exclude from the highlight layer
  544. */
  545. public addExcludedMesh(mesh: Mesh) {
  546. if (mesh instanceof BABYLON.InstancedMesh) {
  547. mesh = (<BABYLON.InstancedMesh> mesh).sourceMesh;
  548. }
  549. var meshExcluded = this._excludedMeshes[mesh.id];
  550. if (!meshExcluded) {
  551. this._excludedMeshes[mesh.id] = {
  552. mesh: mesh,
  553. beforeRender: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  554. mesh.getEngine().setStencilBuffer(false);
  555. }),
  556. afterRender: mesh.onAfterRenderObservable.add((mesh: Mesh) => {
  557. mesh.getEngine().setStencilBuffer(true);
  558. }),
  559. }
  560. }
  561. }
  562. /**
  563. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  564. * @param mesh The mesh to highlight
  565. */
  566. public removeExcludedMesh(mesh: Mesh) {
  567. if (mesh instanceof BABYLON.InstancedMesh) {
  568. mesh = (<BABYLON.InstancedMesh> mesh).sourceMesh;
  569. }
  570. var meshExcluded = this._excludedMeshes[mesh.id];
  571. if (meshExcluded) {
  572. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  573. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  574. }
  575. this._excludedMeshes[mesh.id] = undefined;
  576. }
  577. /**
  578. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  579. * @param mesh The mesh to highlight
  580. * @param color The color of the highlight
  581. * @param glowEmissiveOnly Extract the glow from the emissive texture
  582. */
  583. public addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly = false) {
  584. if (mesh instanceof BABYLON.InstancedMesh) {
  585. mesh = (<BABYLON.InstancedMesh> mesh).sourceMesh;
  586. }
  587. var meshHighlight = this._meshes[mesh.id];
  588. if (meshHighlight) {
  589. meshHighlight.color = color;
  590. }
  591. else {
  592. this._meshes[mesh.id] = {
  593. mesh: mesh,
  594. color: color,
  595. // Lambda required for capture due to Observable this context
  596. observerHighlight: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  597. if (this._excludedMeshes[mesh.id]) {
  598. this.defaultStencilReference(mesh);
  599. }
  600. else {
  601. mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  602. }
  603. }),
  604. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  605. glowEmissiveOnly: glowEmissiveOnly
  606. };
  607. }
  608. this._shouldRender = true;
  609. }
  610. /**
  611. * Remove a mesh from the highlight layer in order to make it stop glowing.
  612. * @param mesh The mesh to highlight
  613. */
  614. public removeMesh(mesh: Mesh) {
  615. if (mesh instanceof BABYLON.InstancedMesh) {
  616. mesh = (<BABYLON.InstancedMesh> mesh).sourceMesh;
  617. }
  618. var meshHighlight = this._meshes[mesh.id];
  619. if (meshHighlight) {
  620. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  621. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  622. }
  623. this._meshes[mesh.id] = undefined;
  624. this._shouldRender = false;
  625. for (var meshHighlightToCheck in this._meshes) {
  626. if (meshHighlightToCheck) {
  627. this._shouldRender = true;
  628. break;
  629. }
  630. }
  631. }
  632. /**
  633. * Returns true if the layer contains information to display, otherwise false.
  634. */
  635. public shouldRender(): boolean {
  636. return this._shouldRender;
  637. }
  638. /**
  639. * Sets the main texture desired size which is the closest power of two
  640. * of the engine canvas size.
  641. */
  642. private setMainTextureSize(): void {
  643. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  644. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  645. this._mainTextureDesiredSize.width = Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  646. this._mainTextureDesiredSize.height = Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  647. }
  648. /**
  649. * Force the stencil to the normal expected value for none glowing parts
  650. */
  651. private defaultStencilReference(mesh: Mesh) {
  652. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  653. }
  654. /**
  655. * Dispose only the render target textures and post process.
  656. */
  657. private disposeTextureAndPostProcesses(): void {
  658. this._blurTexture.dispose();
  659. this._mainTexture.dispose();
  660. this._downSamplePostprocess.dispose();
  661. this._horizontalBlurPostprocess.dispose();
  662. this._verticalBlurPostprocess.dispose();
  663. }
  664. /**
  665. * Dispose the highlight layer and free resources.
  666. */
  667. public dispose(): void {
  668. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  669. if (vertexBuffer) {
  670. vertexBuffer.dispose();
  671. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  672. }
  673. if (this._indexBuffer) {
  674. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  675. this._indexBuffer = null;
  676. }
  677. // Clean textures and post processes
  678. this.disposeTextureAndPostProcesses();
  679. // Clean mesh references
  680. for (let id in this._meshes) {
  681. let meshHighlight = this._meshes[id];
  682. if (meshHighlight && meshHighlight.mesh) {
  683. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  684. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  685. }
  686. }
  687. this._meshes = null;
  688. for (let id in this._excludedMeshes) {
  689. let meshHighlight = this._excludedMeshes[id];
  690. if (meshHighlight) {
  691. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  692. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  693. }
  694. }
  695. this._excludedMeshes = null;
  696. // Remove from scene
  697. var index = this._scene.highlightLayers.indexOf(this, 0);
  698. if (index > -1) {
  699. this._scene.highlightLayers.splice(index, 1);
  700. }
  701. // Callback
  702. this.onDisposeObservable.notifyObservers(this);
  703. this.onDisposeObservable.clear();
  704. this.onBeforeRenderMainTextureObservable.clear();
  705. this.onBeforeBlurObservable.clear();
  706. this.onBeforeComposeObservable.clear();
  707. this.onAfterComposeObservable.clear();
  708. this.onSizeChangedObservable.clear();
  709. }
  710. }
  711. }