babylon.highlightlayer.ts 39 KB

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