babylon.highlightlayer.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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: Nullable<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: Nullable<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: Nullable<Observer<Mesh>>;
  70. /**
  71. * The mesh render callback use to come to the default behavior
  72. */
  73. observerDefault: Nullable<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: Nullable<Observer<Mesh>>;
  92. /**
  93. * The mesh render callback use to restore previous stencil use
  94. */
  95. afterRender: Nullable<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]: Nullable<VertexBuffer> } = {};
  123. private _indexBuffer: Nullable<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: Nullable<{ [id: string]: Nullable<IHighlightLayerMesh> }> = {};
  134. private _maxSize: number = 0;
  135. private _shouldRender = false;
  136. private _instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  137. private _excludedMeshes: Nullable<{ [id: string]: Nullable<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(): Nullable<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. camera: null
  239. };
  240. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  241. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  242. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  243. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  244. this._options.alphaBlendingMode = this._options.alphaBlendingMode || Engine.ALPHA_COMBINE;
  245. // VBO
  246. var vertices = [];
  247. vertices.push(1, 1);
  248. vertices.push(-1, 1);
  249. vertices.push(-1, -1);
  250. vertices.push(1, -1);
  251. var vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  252. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  253. this._createIndexBuffer();
  254. // Effect
  255. this._glowMapMergeEffect = engine.createEffect("glowMapMerge",
  256. [VertexBuffer.PositionKind],
  257. ["offset"],
  258. ["textureSampler"], "");
  259. // Render target
  260. this.setMainTextureSize();
  261. // Create Textures and post processes
  262. this.createTextureAndPostProcesses();
  263. }
  264. private _createIndexBuffer(): void {
  265. var engine = this._scene.getEngine();
  266. // Indices
  267. var indices = [];
  268. indices.push(0);
  269. indices.push(1);
  270. indices.push(2);
  271. indices.push(0);
  272. indices.push(2);
  273. indices.push(3);
  274. this._indexBuffer = engine.createIndexBuffer(indices);
  275. }
  276. public _rebuild(): void {
  277. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  278. if (vb) {
  279. vb._rebuild();
  280. }
  281. this._createIndexBuffer();
  282. }
  283. /**
  284. * Creates the render target textures and post processes used in the highlight layer.
  285. */
  286. private createTextureAndPostProcesses(): void {
  287. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  288. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  289. blurTextureWidth = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  290. blurTextureHeight = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  291. this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
  292. {
  293. width: this._mainTextureDesiredSize.width,
  294. height: this._mainTextureDesiredSize.height
  295. },
  296. this._scene,
  297. false,
  298. true,
  299. Engine.TEXTURETYPE_UNSIGNED_INT);
  300. this._mainTexture.activeCamera = this._options.camera;
  301. this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  302. this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  303. this._mainTexture.anisotropicFilteringLevel = 1;
  304. this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  305. this._mainTexture.renderParticles = false;
  306. this._mainTexture.renderList = null;
  307. this._mainTexture.ignoreCameraViewport = true;
  308. this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",
  309. {
  310. width: blurTextureWidth,
  311. height: blurTextureHeight
  312. },
  313. this._scene,
  314. false,
  315. true,
  316. Engine.TEXTURETYPE_UNSIGNED_INT);
  317. this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  318. this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  319. this._blurTexture.anisotropicFilteringLevel = 16;
  320. this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  321. this._blurTexture.renderParticles = false;
  322. this._blurTexture.ignoreCameraViewport = true;
  323. this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio,
  324. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  325. this._downSamplePostprocess.onApplyObservable.add(effect => {
  326. effect.setTexture("textureSampler", this._mainTexture);
  327. });
  328. if (this._options.alphaBlendingMode === Engine.ALPHA_COMBINE) {
  329. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  330. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  331. this._horizontalBlurPostprocess.onApplyObservable.add(effect => {
  332. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  333. });
  334. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  335. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  336. this._verticalBlurPostprocess.onApplyObservable.add(effect => {
  337. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  338. });
  339. }
  340. else {
  341. this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  342. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  343. this._horizontalBlurPostprocess.onApplyObservable.add(effect => {
  344. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  345. });
  346. this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  347. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  348. this._verticalBlurPostprocess.onApplyObservable.add(effect => {
  349. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  350. });
  351. }
  352. this._mainTexture.onAfterUnbindObservable.add(() => {
  353. this.onBeforeBlurObservable.notifyObservers(this);
  354. let internalTexture = this._blurTexture.getInternalTexture();
  355. if (internalTexture) {
  356. this._scene.postProcessManager.directRender(
  357. [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess],
  358. internalTexture, true);
  359. }
  360. this.onAfterBlurObservable.notifyObservers(this);
  361. });
  362. // Custom render function
  363. var renderSubMesh = (subMesh: SubMesh): void => {
  364. if (!this._meshes) {
  365. return;
  366. }
  367. var material = subMesh.getMaterial();
  368. var mesh = subMesh.getRenderingMesh();
  369. var scene = this._scene;
  370. var engine = scene.getEngine();
  371. if (!material) {
  372. return;
  373. }
  374. // Culling
  375. engine.setState(material.backFaceCulling);
  376. // Managing instances
  377. var batch = mesh._getInstancesRenderList(subMesh._id);
  378. if (batch.mustReturn) {
  379. return;
  380. }
  381. // Excluded Mesh
  382. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  383. return;
  384. };
  385. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  386. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  387. var emissiveTexture: Nullable<Texture> = null;
  388. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  389. emissiveTexture = (<any>material).emissiveTexture;
  390. }
  391. if (this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  392. engine.enableEffect(this._glowMapGenerationEffect);
  393. mesh._bind(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode);
  394. this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  395. if (highlightLayerMesh) {
  396. this._glowMapGenerationEffect.setFloat4("color",
  397. highlightLayerMesh.color.r,
  398. highlightLayerMesh.color.g,
  399. highlightLayerMesh.color.b,
  400. 1.0);
  401. }
  402. else {
  403. this._glowMapGenerationEffect.setFloat4("color",
  404. HighlightLayer.neutralColor.r,
  405. HighlightLayer.neutralColor.g,
  406. HighlightLayer.neutralColor.b,
  407. HighlightLayer.neutralColor.a);
  408. }
  409. // Alpha test
  410. if (material && material.needAlphaTesting()) {
  411. var alphaTexture = material.getAlphaTestTexture();
  412. if (alphaTexture) {
  413. this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  414. let textureMatrix = alphaTexture.getTextureMatrix();
  415. if (textureMatrix) {
  416. this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  417. }
  418. }
  419. }
  420. // Glow emissive only
  421. if (emissiveTexture) {
  422. this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  423. this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  424. }
  425. // Bones
  426. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  427. this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  428. }
  429. // Draw
  430. mesh._processRendering(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  431. (isInstance, world) => this._glowMapGenerationEffect.setMatrix("world", world));
  432. } else {
  433. // Need to reset refresh rate of the shadowMap
  434. this._mainTexture.resetRefreshCounter();
  435. }
  436. };
  437. this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  438. this.onBeforeRenderMainTextureObservable.notifyObservers(this);
  439. var index: number;
  440. let engine = this._scene.getEngine();
  441. if (depthOnlySubMeshes.length) {
  442. engine.setColorWrite(false);
  443. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  444. renderSubMesh(depthOnlySubMeshes.data[index]);
  445. }
  446. engine.setColorWrite(true);
  447. }
  448. for (index = 0; index < opaqueSubMeshes.length; index++) {
  449. renderSubMesh(opaqueSubMeshes.data[index]);
  450. }
  451. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  452. renderSubMesh(alphaTestSubMeshes.data[index]);
  453. }
  454. for (index = 0; index < transparentSubMeshes.length; index++) {
  455. renderSubMesh(transparentSubMeshes.data[index]);
  456. }
  457. };
  458. this._mainTexture.onClearObservable.add((engine: Engine) => {
  459. engine.clear(HighlightLayer.neutralColor, true, true, true);
  460. });
  461. }
  462. /**
  463. * Checks for the readiness of the element composing the layer.
  464. * @param subMesh the mesh to check for
  465. * @param useInstances specify wether or not to use instances to render the mesh
  466. * @param emissiveTexture the associated emissive texture used to generate the glow
  467. * @return true if ready otherwise, false
  468. */
  469. private isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable<Texture>): boolean {
  470. let material = subMesh.getMaterial();
  471. if (!material) {
  472. return false;
  473. }
  474. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  475. return false;
  476. }
  477. var defines = [];
  478. var attribs = [VertexBuffer.PositionKind];
  479. var mesh = subMesh.getMesh();
  480. var uv1 = false;
  481. var uv2 = false;
  482. // Alpha test
  483. if (material && material.needAlphaTesting()) {
  484. var alphaTexture = material.getAlphaTestTexture();
  485. if (alphaTexture) {
  486. defines.push("#define ALPHATEST");
  487. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  488. alphaTexture.coordinatesIndex === 1) {
  489. defines.push("#define DIFFUSEUV2");
  490. uv2 = true;
  491. }
  492. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  493. defines.push("#define DIFFUSEUV1");
  494. uv1 = true;
  495. }
  496. }
  497. }
  498. // Emissive
  499. if (emissiveTexture) {
  500. defines.push("#define EMISSIVE");
  501. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  502. emissiveTexture.coordinatesIndex === 1) {
  503. defines.push("#define EMISSIVEUV2");
  504. uv2 = true;
  505. }
  506. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  507. defines.push("#define EMISSIVEUV1");
  508. uv1 = true;
  509. }
  510. }
  511. if (uv1) {
  512. attribs.push(VertexBuffer.UVKind);
  513. defines.push("#define UV1");
  514. }
  515. if (uv2) {
  516. attribs.push(VertexBuffer.UV2Kind);
  517. defines.push("#define UV2");
  518. }
  519. // Bones
  520. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  521. attribs.push(VertexBuffer.MatricesIndicesKind);
  522. attribs.push(VertexBuffer.MatricesWeightsKind);
  523. if (mesh.numBoneInfluencers > 4) {
  524. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  525. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  526. }
  527. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  528. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  529. } else {
  530. defines.push("#define NUM_BONE_INFLUENCERS 0");
  531. }
  532. // Instances
  533. if (useInstances) {
  534. defines.push("#define INSTANCES");
  535. attribs.push("world0");
  536. attribs.push("world1");
  537. attribs.push("world2");
  538. attribs.push("world3");
  539. }
  540. // Get correct effect
  541. var join = defines.join("\n");
  542. if (this._cachedDefines !== join) {
  543. this._cachedDefines = join;
  544. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  545. attribs,
  546. ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"],
  547. ["diffuseSampler", "emissiveSampler"], join);
  548. }
  549. return this._glowMapGenerationEffect.isReady();
  550. }
  551. /**
  552. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  553. */
  554. public render(): void {
  555. var currentEffect = this._glowMapMergeEffect;
  556. // Check
  557. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  558. return;
  559. var engine = this._scene.getEngine();
  560. this.onBeforeComposeObservable.notifyObservers(this);
  561. // Render
  562. engine.enableEffect(currentEffect);
  563. engine.setState(false);
  564. // Cache
  565. var previousStencilBuffer = engine.getStencilBuffer();
  566. var previousStencilFunction = engine.getStencilFunction();
  567. var previousStencilMask = engine.getStencilMask();
  568. var previousStencilOperationPass = engine.getStencilOperationPass();
  569. var previousStencilOperationFail = engine.getStencilOperationFail();
  570. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  571. var previousAlphaMode = engine.getAlphaMode();
  572. // Texture
  573. currentEffect.setTexture("textureSampler", this._blurTexture);
  574. // VBOs
  575. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  576. // Stencil operations
  577. engine.setStencilOperationPass(Engine.REPLACE);
  578. engine.setStencilOperationFail(Engine.KEEP);
  579. engine.setStencilOperationDepthFail(Engine.KEEP);
  580. // Draw order
  581. engine.setAlphaMode(this._options.alphaBlendingMode);
  582. engine.setStencilMask(0x00);
  583. engine.setStencilBuffer(true);
  584. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  585. if (this.outerGlow) {
  586. currentEffect.setFloat("offset", 0);
  587. engine.setStencilFunction(Engine.NOTEQUAL);
  588. engine.draw(true, 0, 6);
  589. }
  590. if (this.innerGlow) {
  591. currentEffect.setFloat("offset", 1);
  592. engine.setStencilFunction(Engine.EQUAL);
  593. engine.draw(true, 0, 6);
  594. }
  595. // Restore Cache
  596. engine.setStencilFunction(previousStencilFunction);
  597. engine.setStencilMask(previousStencilMask);
  598. engine.setAlphaMode(previousAlphaMode);
  599. engine.setStencilBuffer(previousStencilBuffer);
  600. engine.setStencilOperationPass(previousStencilOperationPass);
  601. engine.setStencilOperationFail(previousStencilOperationFail);
  602. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  603. (<any>engine)._stencilState.reset();
  604. this.onAfterComposeObservable.notifyObservers(this);
  605. // Handle size changes.
  606. var size = this._mainTexture.getSize();
  607. this.setMainTextureSize();
  608. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  609. // Recreate RTT and post processes on size change.
  610. this.onSizeChangedObservable.notifyObservers(this);
  611. this.disposeTextureAndPostProcesses();
  612. this.createTextureAndPostProcesses();
  613. }
  614. }
  615. /**
  616. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  617. * @param mesh The mesh to exclude from the highlight layer
  618. */
  619. public addExcludedMesh(mesh: Mesh) {
  620. if (!this._excludedMeshes) {
  621. return;
  622. }
  623. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  624. if (!meshExcluded) {
  625. this._excludedMeshes[mesh.uniqueId] = {
  626. mesh: mesh,
  627. beforeRender: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  628. mesh.getEngine().setStencilBuffer(false);
  629. }),
  630. afterRender: mesh.onAfterRenderObservable.add((mesh: Mesh) => {
  631. mesh.getEngine().setStencilBuffer(true);
  632. }),
  633. }
  634. }
  635. }
  636. /**
  637. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  638. * @param mesh The mesh to highlight
  639. */
  640. public removeExcludedMesh(mesh: Mesh) {
  641. if (!this._excludedMeshes) {
  642. return;
  643. }
  644. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  645. if (meshExcluded) {
  646. if (meshExcluded.beforeRender) {
  647. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  648. }
  649. if (meshExcluded.afterRender) {
  650. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  651. }
  652. }
  653. this._excludedMeshes[mesh.uniqueId] = null;
  654. }
  655. /**
  656. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  657. * @param mesh The mesh to highlight
  658. * @param color The color of the highlight
  659. * @param glowEmissiveOnly Extract the glow from the emissive texture
  660. */
  661. public addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly = false) {
  662. if (!this._meshes) {
  663. return;
  664. }
  665. var meshHighlight = this._meshes[mesh.uniqueId];
  666. if (meshHighlight) {
  667. meshHighlight.color = color;
  668. }
  669. else {
  670. this._meshes[mesh.uniqueId] = {
  671. mesh: mesh,
  672. color: color,
  673. // Lambda required for capture due to Observable this context
  674. observerHighlight: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  675. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  676. this.defaultStencilReference(mesh);
  677. }
  678. else {
  679. mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  680. }
  681. }),
  682. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  683. glowEmissiveOnly: glowEmissiveOnly
  684. };
  685. }
  686. this._shouldRender = true;
  687. }
  688. /**
  689. * Remove a mesh from the highlight layer in order to make it stop glowing.
  690. * @param mesh The mesh to highlight
  691. */
  692. public removeMesh(mesh: Mesh) {
  693. if (!this._meshes) {
  694. return;
  695. }
  696. var meshHighlight = this._meshes[mesh.uniqueId];
  697. if (meshHighlight) {
  698. if (meshHighlight.observerHighlight) {
  699. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  700. }
  701. if (meshHighlight.observerDefault) {
  702. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  703. }
  704. }
  705. this._meshes[mesh.uniqueId] = null;
  706. this._shouldRender = false;
  707. for (var meshHighlightToCheck in this._meshes) {
  708. if (meshHighlightToCheck) {
  709. this._shouldRender = true;
  710. break;
  711. }
  712. }
  713. }
  714. /**
  715. * Returns true if the layer contains information to display, otherwise false.
  716. */
  717. public shouldRender(): boolean {
  718. return this.isEnabled && this._shouldRender;
  719. }
  720. /**
  721. * Sets the main texture desired size which is the closest power of two
  722. * of the engine canvas size.
  723. */
  724. private setMainTextureSize(): void {
  725. if (this._options.mainTextureFixedSize) {
  726. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  727. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  728. }
  729. else {
  730. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  731. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  732. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  733. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  734. }
  735. }
  736. /**
  737. * Force the stencil to the normal expected value for none glowing parts
  738. */
  739. private defaultStencilReference(mesh: Mesh) {
  740. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  741. }
  742. /**
  743. * Dispose only the render target textures and post process.
  744. */
  745. private disposeTextureAndPostProcesses(): void {
  746. this._blurTexture.dispose();
  747. this._mainTexture.dispose();
  748. this._downSamplePostprocess.dispose();
  749. this._horizontalBlurPostprocess.dispose();
  750. this._verticalBlurPostprocess.dispose();
  751. }
  752. /**
  753. * Dispose the highlight layer and free resources.
  754. */
  755. public dispose(): void {
  756. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  757. if (vertexBuffer) {
  758. vertexBuffer.dispose();
  759. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  760. }
  761. if (this._indexBuffer) {
  762. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  763. this._indexBuffer = null;
  764. }
  765. // Clean textures and post processes
  766. this.disposeTextureAndPostProcesses();
  767. if (this._meshes) {
  768. // Clean mesh references
  769. for (let id in this._meshes) {
  770. let meshHighlight = this._meshes[id];
  771. if (meshHighlight && meshHighlight.mesh) {
  772. if (meshHighlight.observerHighlight) {
  773. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  774. }
  775. if (meshHighlight.observerDefault) {
  776. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  777. }
  778. }
  779. }
  780. this._meshes = null;
  781. }
  782. if (this._excludedMeshes) {
  783. for (let id in this._excludedMeshes) {
  784. let meshHighlight = this._excludedMeshes[id];
  785. if (meshHighlight) {
  786. if (meshHighlight.beforeRender) {
  787. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  788. }
  789. if (meshHighlight.afterRender) {
  790. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  791. }
  792. }
  793. }
  794. this._excludedMeshes = null;
  795. }
  796. // Remove from scene
  797. var index = this._scene.highlightLayers.indexOf(this, 0);
  798. if (index > -1) {
  799. this._scene.highlightLayers.splice(index, 1);
  800. }
  801. // Callback
  802. this.onDisposeObservable.notifyObservers(this);
  803. this.onDisposeObservable.clear();
  804. this.onBeforeRenderMainTextureObservable.clear();
  805. this.onBeforeBlurObservable.clear();
  806. this.onBeforeComposeObservable.clear();
  807. this.onAfterComposeObservable.clear();
  808. this.onSizeChangedObservable.clear();
  809. }
  810. }
  811. }