babylon.highlightlayer.ts 36 KB

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