effectLayer.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. import { serialize, serializeAsColor4, serializeAsCameraReference } from "../Misc/decorators";
  2. import { Tools } from "../Misc/tools";
  3. import { SmartArray } from "../Misc/smartArray";
  4. import { Observable } from "../Misc/observable";
  5. import { Nullable } from "../types";
  6. import { Camera } from "../Cameras/camera";
  7. import { Scene } from "../scene";
  8. import { ISize } from "../Maths/math.size";
  9. import { Color4 } from '../Maths/math.color';
  10. import { Engine } from "../Engines/engine";
  11. import { EngineStore } from "../Engines/engineStore";
  12. import { VertexBuffer } from "../Meshes/buffer";
  13. import { SubMesh } from "../Meshes/subMesh";
  14. import { AbstractMesh } from "../Meshes/abstractMesh";
  15. import { Mesh } from "../Meshes/mesh";
  16. import { PostProcess } from "../PostProcesses/postProcess";
  17. import { BaseTexture } from "../Materials/Textures/baseTexture";
  18. import { Texture } from "../Materials/Textures/texture";
  19. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  20. import { Effect } from "../Materials/effect";
  21. import { Material } from "../Materials/material";
  22. import { MaterialHelper } from "../Materials/materialHelper";
  23. import { Constants } from "../Engines/constants";
  24. import "../Shaders/glowMapGeneration.fragment";
  25. import "../Shaders/glowMapGeneration.vertex";
  26. import { _DevTools } from '../Misc/devTools';
  27. import { DataBuffer } from '../Meshes/dataBuffer';
  28. import { EffectFallbacks } from '../Materials/effectFallbacks';
  29. /**
  30. * Effect layer options. This helps customizing the behaviour
  31. * of the effect layer.
  32. */
  33. export interface IEffectLayerOptions {
  34. /**
  35. * Multiplication factor apply to the canvas size to compute the render target size
  36. * used to generated the objects (the smaller the faster).
  37. */
  38. mainTextureRatio: number;
  39. /**
  40. * Enforces a fixed size texture to ensure effect stability across devices.
  41. */
  42. mainTextureFixedSize?: number;
  43. /**
  44. * Alpha blending mode used to apply the blur. Default depends of the implementation.
  45. */
  46. alphaBlendingMode: number;
  47. /**
  48. * The camera attached to the layer.
  49. */
  50. camera: Nullable<Camera>;
  51. /**
  52. * The rendering group to draw the layer in.
  53. */
  54. renderingGroupId: number;
  55. }
  56. /**
  57. * The effect layer Helps adding post process effect blended with the main pass.
  58. *
  59. * This can be for instance use to generate glow or higlight effects on the scene.
  60. *
  61. * The effect layer class can not be used directly and is intented to inherited from to be
  62. * customized per effects.
  63. */
  64. export abstract class EffectLayer {
  65. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  66. private _indexBuffer: Nullable<DataBuffer>;
  67. private _cachedDefines: string;
  68. private _effectLayerMapGenerationEffect: Effect;
  69. private _effectLayerOptions: IEffectLayerOptions;
  70. private _mergeEffect: Effect;
  71. protected _scene: Scene;
  72. protected _engine: Engine;
  73. protected _maxSize: number = 0;
  74. protected _mainTextureDesiredSize: ISize = { width: 0, height: 0 };
  75. protected _mainTexture: RenderTargetTexture;
  76. protected _shouldRender = true;
  77. protected _postProcesses: PostProcess[] = [];
  78. protected _textures: BaseTexture[] = [];
  79. protected _emissiveTextureAndColor: { texture: Nullable<BaseTexture>, color: Color4 } = { texture: null, color: new Color4() };
  80. /**
  81. * The name of the layer
  82. */
  83. @serialize()
  84. public name: string;
  85. /**
  86. * The clear color of the texture used to generate the glow map.
  87. */
  88. @serializeAsColor4()
  89. public neutralColor: Color4 = new Color4();
  90. /**
  91. * Specifies whether the highlight layer is enabled or not.
  92. */
  93. @serialize()
  94. public isEnabled: boolean = true;
  95. /**
  96. * Gets the camera attached to the layer.
  97. */
  98. @serializeAsCameraReference()
  99. public get camera(): Nullable<Camera> {
  100. return this._effectLayerOptions.camera;
  101. }
  102. /**
  103. * Gets the rendering group id the layer should render in.
  104. */
  105. @serialize()
  106. public get renderingGroupId(): number {
  107. return this._effectLayerOptions.renderingGroupId;
  108. }
  109. public set renderingGroupId(renderingGroupId: number) {
  110. this._effectLayerOptions.renderingGroupId = renderingGroupId;
  111. }
  112. /**
  113. * An event triggered when the effect layer has been disposed.
  114. */
  115. public onDisposeObservable = new Observable<EffectLayer>();
  116. /**
  117. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  118. */
  119. public onBeforeRenderMainTextureObservable = new Observable<EffectLayer>();
  120. /**
  121. * An event triggered when the generated texture is being merged in the scene.
  122. */
  123. public onBeforeComposeObservable = new Observable<EffectLayer>();
  124. /**
  125. * An event triggered when the mesh is rendered into the effect render target.
  126. */
  127. public onBeforeRenderMeshToEffect = new Observable<AbstractMesh>();
  128. /**
  129. * An event triggered after the mesh has been rendered into the effect render target.
  130. */
  131. public onAfterRenderMeshToEffect = new Observable<AbstractMesh>();
  132. /**
  133. * An event triggered when the generated texture has been merged in the scene.
  134. */
  135. public onAfterComposeObservable = new Observable<EffectLayer>();
  136. /**
  137. * An event triggered when the efffect layer changes its size.
  138. */
  139. public onSizeChangedObservable = new Observable<EffectLayer>();
  140. /** @hidden */
  141. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  142. throw _DevTools.WarnImport("EffectLayerSceneComponent");
  143. }
  144. /**
  145. * Instantiates a new effect Layer and references it in the scene.
  146. * @param name The name of the layer
  147. * @param scene The scene to use the layer in
  148. */
  149. constructor(
  150. /** The Friendly of the effect in the scene */
  151. name: string,
  152. scene: Scene) {
  153. this.name = name;
  154. this._scene = scene || EngineStore.LastCreatedScene;
  155. EffectLayer._SceneComponentInitialization(this._scene);
  156. this._engine = this._scene.getEngine();
  157. this._maxSize = this._engine.getCaps().maxTextureSize;
  158. this._scene.effectLayers.push(this);
  159. // Generate Buffers
  160. this._generateIndexBuffer();
  161. this._generateVertexBuffer();
  162. }
  163. /**
  164. * Get the effect name of the layer.
  165. * @return The effect name
  166. */
  167. public abstract getEffectName(): string;
  168. /**
  169. * Checks for the readiness of the element composing the layer.
  170. * @param subMesh the mesh to check for
  171. * @param useInstances specify whether or not to use instances to render the mesh
  172. * @return true if ready otherwise, false
  173. */
  174. public abstract isReady(subMesh: SubMesh, useInstances: boolean): boolean;
  175. /**
  176. * Returns whether or nood the layer needs stencil enabled during the mesh rendering.
  177. * @returns true if the effect requires stencil during the main canvas render pass.
  178. */
  179. public abstract needStencil(): boolean;
  180. /**
  181. * Create the merge effect. This is the shader use to blit the information back
  182. * to the main canvas at the end of the scene rendering.
  183. * @returns The effect containing the shader used to merge the effect on the main canvas
  184. */
  185. protected abstract _createMergeEffect(): Effect;
  186. /**
  187. * Creates the render target textures and post processes used in the effect layer.
  188. */
  189. protected abstract _createTextureAndPostProcesses(): void;
  190. /**
  191. * Implementation specific of rendering the generating effect on the main canvas.
  192. * @param effect The effect used to render through
  193. */
  194. protected abstract _internalRender(effect: Effect): void;
  195. /**
  196. * Sets the required values for both the emissive texture and and the main color.
  197. */
  198. protected abstract _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void;
  199. /**
  200. * Free any resources and references associated to a mesh.
  201. * Internal use
  202. * @param mesh The mesh to free.
  203. */
  204. public abstract _disposeMesh(mesh: Mesh): void;
  205. /**
  206. * Serializes this layer (Glow or Highlight for example)
  207. * @returns a serialized layer object
  208. */
  209. public abstract serialize?(): any;
  210. /**
  211. * Initializes the effect layer with the required options.
  212. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  213. */
  214. protected _init(options: Partial<IEffectLayerOptions>): void {
  215. // Adapt options
  216. this._effectLayerOptions = {
  217. mainTextureRatio: 0.5,
  218. alphaBlendingMode: Constants.ALPHA_COMBINE,
  219. camera: null,
  220. renderingGroupId: -1,
  221. ...options,
  222. };
  223. this._setMainTextureSize();
  224. this._createMainTexture();
  225. this._createTextureAndPostProcesses();
  226. this._mergeEffect = this._createMergeEffect();
  227. }
  228. /**
  229. * Generates the index buffer of the full screen quad blending to the main canvas.
  230. */
  231. private _generateIndexBuffer(): void {
  232. // Indices
  233. var indices = [];
  234. indices.push(0);
  235. indices.push(1);
  236. indices.push(2);
  237. indices.push(0);
  238. indices.push(2);
  239. indices.push(3);
  240. this._indexBuffer = this._engine.createIndexBuffer(indices);
  241. }
  242. /**
  243. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  244. */
  245. private _generateVertexBuffer(): void {
  246. // VBO
  247. var vertices = [];
  248. vertices.push(1, 1);
  249. vertices.push(-1, 1);
  250. vertices.push(-1, -1);
  251. vertices.push(1, -1);
  252. var vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  253. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  254. }
  255. /**
  256. * Sets the main texture desired size which is the closest power of two
  257. * of the engine canvas size.
  258. */
  259. private _setMainTextureSize(): void {
  260. if (this._effectLayerOptions.mainTextureFixedSize) {
  261. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  262. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  263. }
  264. else {
  265. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  266. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  267. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  268. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  269. }
  270. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  271. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  272. }
  273. /**
  274. * Creates the main texture for the effect layer.
  275. */
  276. protected _createMainTexture(): void {
  277. this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
  278. {
  279. width: this._mainTextureDesiredSize.width,
  280. height: this._mainTextureDesiredSize.height
  281. },
  282. this._scene,
  283. false,
  284. true,
  285. Constants.TEXTURETYPE_UNSIGNED_INT);
  286. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  287. this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  288. this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  289. this._mainTexture.anisotropicFilteringLevel = 1;
  290. this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  291. this._mainTexture.renderParticles = false;
  292. this._mainTexture.renderList = null;
  293. this._mainTexture.ignoreCameraViewport = true;
  294. // Custom render function
  295. this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  296. this.onBeforeRenderMainTextureObservable.notifyObservers(this);
  297. var index: number;
  298. let engine = this._scene.getEngine();
  299. if (depthOnlySubMeshes.length) {
  300. engine.setColorWrite(false);
  301. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  302. this._renderSubMesh(depthOnlySubMeshes.data[index]);
  303. }
  304. engine.setColorWrite(true);
  305. }
  306. for (index = 0; index < opaqueSubMeshes.length; index++) {
  307. this._renderSubMesh(opaqueSubMeshes.data[index]);
  308. }
  309. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  310. this._renderSubMesh(alphaTestSubMeshes.data[index]);
  311. }
  312. const previousAlphaMode = engine.getAlphaMode();
  313. for (index = 0; index < transparentSubMeshes.length; index++) {
  314. this._renderSubMesh(transparentSubMeshes.data[index], true);
  315. }
  316. engine.setAlphaMode(previousAlphaMode);
  317. };
  318. this._mainTexture.onClearObservable.add((engine: Engine) => {
  319. engine.clear(this.neutralColor, true, true, true);
  320. });
  321. }
  322. /**
  323. * Adds specific effects defines.
  324. * @param defines The defines to add specifics to.
  325. */
  326. protected _addCustomEffectDefines(defines: string[]): void {
  327. // Nothing to add by default.
  328. }
  329. /**
  330. * Checks for the readiness of the element composing the layer.
  331. * @param subMesh the mesh to check for
  332. * @param useInstances specify whether or not to use instances to render the mesh
  333. * @param emissiveTexture the associated emissive texture used to generate the glow
  334. * @return true if ready otherwise, false
  335. */
  336. protected _isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable<BaseTexture>): boolean {
  337. let material = subMesh.getMaterial();
  338. if (!material) {
  339. return false;
  340. }
  341. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  342. return false;
  343. }
  344. var defines: string[] = [];
  345. var attribs = [VertexBuffer.PositionKind];
  346. var mesh = subMesh.getMesh();
  347. var uv1 = false;
  348. var uv2 = false;
  349. // Diffuse
  350. if (material) {
  351. const needAlphaTest = material.needAlphaTesting();
  352. const diffuseTexture = material.getAlphaTestTexture();
  353. const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
  354. ((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
  355. if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
  356. defines.push("#define DIFFUSE");
  357. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  358. diffuseTexture.coordinatesIndex === 1) {
  359. defines.push("#define DIFFUSEUV2");
  360. uv2 = true;
  361. }
  362. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  363. defines.push("#define DIFFUSEUV1");
  364. uv1 = true;
  365. }
  366. if (needAlphaTest) {
  367. defines.push("#define ALPHATEST");
  368. defines.push("#define ALPHATESTVALUE 0.4");
  369. }
  370. }
  371. var opacityTexture = (material as any).opacityTexture;
  372. if (opacityTexture) {
  373. defines.push("#define OPACITY");
  374. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  375. opacityTexture.coordinatesIndex === 1) {
  376. defines.push("#define OPACITYUV2");
  377. uv2 = true;
  378. }
  379. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  380. defines.push("#define OPACITYUV1");
  381. uv1 = true;
  382. }
  383. }
  384. }
  385. // Emissive
  386. if (emissiveTexture) {
  387. defines.push("#define EMISSIVE");
  388. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  389. emissiveTexture.coordinatesIndex === 1) {
  390. defines.push("#define EMISSIVEUV2");
  391. uv2 = true;
  392. }
  393. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  394. defines.push("#define EMISSIVEUV1");
  395. uv1 = true;
  396. }
  397. }
  398. // Vertex
  399. if (mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha) {
  400. attribs.push(VertexBuffer.ColorKind);
  401. defines.push("#define VERTEXALPHA");
  402. }
  403. if (uv1) {
  404. attribs.push(VertexBuffer.UVKind);
  405. defines.push("#define UV1");
  406. }
  407. if (uv2) {
  408. attribs.push(VertexBuffer.UV2Kind);
  409. defines.push("#define UV2");
  410. }
  411. // Bones
  412. const fallbacks = new EffectFallbacks();
  413. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  414. attribs.push(VertexBuffer.MatricesIndicesKind);
  415. attribs.push(VertexBuffer.MatricesWeightsKind);
  416. if (mesh.numBoneInfluencers > 4) {
  417. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  418. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  419. }
  420. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  421. let skeleton = mesh.skeleton;
  422. if (skeleton && skeleton.isUsingTextureForMatrices) {
  423. defines.push("#define BONETEXTURE");
  424. } else {
  425. defines.push("#define BonesPerMesh " + (skeleton ? (skeleton.bones.length + 1) : 0));
  426. }
  427. if (mesh.numBoneInfluencers > 0) {
  428. fallbacks.addCPUSkinningFallback(0, mesh);
  429. }
  430. } else {
  431. defines.push("#define NUM_BONE_INFLUENCERS 0");
  432. }
  433. // Morph targets
  434. var manager = (<Mesh>mesh).morphTargetManager;
  435. let morphInfluencers = 0;
  436. if (manager) {
  437. if (manager.numInfluencers > 0) {
  438. defines.push("#define MORPHTARGETS");
  439. morphInfluencers = manager.numInfluencers;
  440. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  441. MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
  442. }
  443. }
  444. // Instances
  445. if (useInstances) {
  446. defines.push("#define INSTANCES");
  447. MaterialHelper.PushAttributesForInstances(attribs);
  448. }
  449. this._addCustomEffectDefines(defines);
  450. // Get correct effect
  451. var join = defines.join("\n");
  452. if (this._cachedDefines !== join) {
  453. this._cachedDefines = join;
  454. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  455. attribs,
  456. ["world", "mBones", "viewProjection",
  457. "glowColor", "morphTargetInfluences", "boneTextureWidth",
  458. "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity"],
  459. ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler"], join,
  460. fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  461. }
  462. return this._effectLayerMapGenerationEffect.isReady();
  463. }
  464. /**
  465. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  466. */
  467. public render(): void {
  468. var currentEffect = this._mergeEffect;
  469. // Check
  470. if (!currentEffect.isReady()) {
  471. return;
  472. }
  473. for (var i = 0; i < this._postProcesses.length; i++) {
  474. if (!this._postProcesses[i].isReady()) {
  475. return;
  476. }
  477. }
  478. var engine = this._scene.getEngine();
  479. this.onBeforeComposeObservable.notifyObservers(this);
  480. // Render
  481. engine.enableEffect(currentEffect);
  482. engine.setState(false);
  483. // VBOs
  484. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  485. // Cache
  486. var previousAlphaMode = engine.getAlphaMode();
  487. // Go Blend.
  488. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  489. // Blends the map on the main canvas.
  490. this._internalRender(currentEffect);
  491. // Restore Alpha
  492. engine.setAlphaMode(previousAlphaMode);
  493. this.onAfterComposeObservable.notifyObservers(this);
  494. // Handle size changes.
  495. var size = this._mainTexture.getSize();
  496. this._setMainTextureSize();
  497. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  498. // Recreate RTT and post processes on size change.
  499. this.onSizeChangedObservable.notifyObservers(this);
  500. this._disposeTextureAndPostProcesses();
  501. this._createMainTexture();
  502. this._createTextureAndPostProcesses();
  503. }
  504. }
  505. /**
  506. * Determine if a given mesh will be used in the current effect.
  507. * @param mesh mesh to test
  508. * @returns true if the mesh will be used
  509. */
  510. public hasMesh(mesh: AbstractMesh): boolean {
  511. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  512. return true;
  513. }
  514. return false;
  515. }
  516. /**
  517. * Returns true if the layer contains information to display, otherwise false.
  518. * @returns true if the glow layer should be rendered
  519. */
  520. public shouldRender(): boolean {
  521. return this.isEnabled && this._shouldRender;
  522. }
  523. /**
  524. * Returns true if the mesh should render, otherwise false.
  525. * @param mesh The mesh to render
  526. * @returns true if it should render otherwise false
  527. */
  528. protected _shouldRenderMesh(mesh: AbstractMesh): boolean {
  529. return true;
  530. }
  531. /**
  532. * Returns true if the mesh can be rendered, otherwise false.
  533. * @param mesh The mesh to render
  534. * @param material The material used on the mesh
  535. * @returns true if it can be rendered otherwise false
  536. */
  537. protected _canRenderMesh(mesh: AbstractMesh, material: Material): boolean {
  538. return !material.needAlphaBlendingForMesh(mesh);
  539. }
  540. /**
  541. * Returns true if the mesh should render, otherwise false.
  542. * @param mesh The mesh to render
  543. * @returns true if it should render otherwise false
  544. */
  545. protected _shouldRenderEmissiveTextureForMesh(): boolean {
  546. return true;
  547. }
  548. /**
  549. * Renders the submesh passed in parameter to the generation map.
  550. */
  551. protected _renderSubMesh(subMesh: SubMesh, enableAlphaMode: boolean = false): void {
  552. if (!this.shouldRender()) {
  553. return;
  554. }
  555. var material = subMesh.getMaterial();
  556. var ownerMesh = subMesh.getMesh();
  557. var replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null;
  558. var renderingMesh = subMesh.getRenderingMesh();
  559. var effectiveMesh = replacementMesh ? replacementMesh : renderingMesh;
  560. var scene = this._scene;
  561. var engine = scene.getEngine();
  562. effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
  563. if (!material) {
  564. return;
  565. }
  566. // Do not block in blend mode.
  567. if (!this._canRenderMesh(renderingMesh, material)) {
  568. return;
  569. }
  570. // Culling
  571. engine.setState(material.backFaceCulling);
  572. // Managing instances
  573. var batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);
  574. if (batch.mustReturn) {
  575. return;
  576. }
  577. // Early Exit per mesh
  578. if (!this._shouldRenderMesh(renderingMesh)) {
  579. return;
  580. }
  581. var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id];
  582. this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);
  583. this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);
  584. if (this._useMeshMaterial(renderingMesh)) {
  585. renderingMesh.render(subMesh, hardwareInstancedRendering, replacementMesh || undefined);
  586. }
  587. else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  588. engine.enableEffect(this._effectLayerMapGenerationEffect);
  589. renderingMesh._bind(subMesh, this._effectLayerMapGenerationEffect, Material.TriangleFillMode);
  590. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  591. this._effectLayerMapGenerationEffect.setFloat4("glowColor",
  592. this._emissiveTextureAndColor.color.r,
  593. this._emissiveTextureAndColor.color.g,
  594. this._emissiveTextureAndColor.color.b,
  595. this._emissiveTextureAndColor.color.a);
  596. const needAlphaTest = material.needAlphaTesting();
  597. const diffuseTexture = material.getAlphaTestTexture();
  598. const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
  599. ((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
  600. if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
  601. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", diffuseTexture);
  602. const textureMatrix = diffuseTexture.getTextureMatrix();
  603. if (textureMatrix) {
  604. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  605. }
  606. }
  607. const opacityTexture = (material as any).opacityTexture;
  608. if (opacityTexture) {
  609. this._effectLayerMapGenerationEffect.setTexture("opacitySampler", opacityTexture);
  610. this._effectLayerMapGenerationEffect.setFloat("opacityIntensity", opacityTexture.level);
  611. const textureMatrix = opacityTexture.getTextureMatrix();
  612. if (textureMatrix) {
  613. this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix", textureMatrix);
  614. }
  615. }
  616. // Glow emissive only
  617. if (this._emissiveTextureAndColor.texture) {
  618. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  619. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  620. }
  621. // Bones
  622. if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
  623. const skeleton = renderingMesh.skeleton;
  624. if (skeleton.isUsingTextureForMatrices) {
  625. const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
  626. if (!boneTexture) {
  627. return;
  628. }
  629. this._effectLayerMapGenerationEffect.setTexture("boneSampler", boneTexture);
  630. this._effectLayerMapGenerationEffect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  631. } else {
  632. this._effectLayerMapGenerationEffect.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
  633. }
  634. }
  635. // Morph targets
  636. MaterialHelper.BindMorphTargetParameters(renderingMesh, this._effectLayerMapGenerationEffect);
  637. // Alpha mode
  638. if (enableAlphaMode) {
  639. engine.setAlphaMode(material.alphaMode);
  640. }
  641. // Draw
  642. var world = effectiveMesh.getWorldMatrix();
  643. renderingMesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, material.fillMode, batch, hardwareInstancedRendering,
  644. (isInstance, w) => this._effectLayerMapGenerationEffect.setMatrix("world", world));
  645. } else {
  646. // Need to reset refresh rate of the main map
  647. this._mainTexture.resetRefreshCounter();
  648. }
  649. this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);
  650. }
  651. /**
  652. * Defines whether the current material of the mesh should be use to render the effect.
  653. * @param mesh defines the current mesh to render
  654. */
  655. protected _useMeshMaterial(mesh: AbstractMesh): boolean {
  656. return false;
  657. }
  658. /**
  659. * Rebuild the required buffers.
  660. * @hidden Internal use only.
  661. */
  662. public _rebuild(): void {
  663. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  664. if (vb) {
  665. vb._rebuild();
  666. }
  667. this._generateIndexBuffer();
  668. }
  669. /**
  670. * Dispose only the render target textures and post process.
  671. */
  672. private _disposeTextureAndPostProcesses(): void {
  673. this._mainTexture.dispose();
  674. for (var i = 0; i < this._postProcesses.length; i++) {
  675. if (this._postProcesses[i]) {
  676. this._postProcesses[i].dispose();
  677. }
  678. }
  679. this._postProcesses = [];
  680. for (var i = 0; i < this._textures.length; i++) {
  681. if (this._textures[i]) {
  682. this._textures[i].dispose();
  683. }
  684. }
  685. this._textures = [];
  686. }
  687. /**
  688. * Dispose the highlight layer and free resources.
  689. */
  690. public dispose(): void {
  691. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  692. if (vertexBuffer) {
  693. vertexBuffer.dispose();
  694. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  695. }
  696. if (this._indexBuffer) {
  697. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  698. this._indexBuffer = null;
  699. }
  700. // Clean textures and post processes
  701. this._disposeTextureAndPostProcesses();
  702. // Remove from scene
  703. var index = this._scene.effectLayers.indexOf(this, 0);
  704. if (index > -1) {
  705. this._scene.effectLayers.splice(index, 1);
  706. }
  707. // Callback
  708. this.onDisposeObservable.notifyObservers(this);
  709. this.onDisposeObservable.clear();
  710. this.onBeforeRenderMainTextureObservable.clear();
  711. this.onBeforeComposeObservable.clear();
  712. this.onBeforeRenderMeshToEffect.clear();
  713. this.onAfterRenderMeshToEffect.clear();
  714. this.onAfterComposeObservable.clear();
  715. this.onSizeChangedObservable.clear();
  716. }
  717. /**
  718. * Gets the class name of the effect layer
  719. * @returns the string with the class name of the effect layer
  720. */
  721. public getClassName(): string {
  722. return "EffectLayer";
  723. }
  724. /**
  725. * Creates an effect layer from parsed effect layer data
  726. * @param parsedEffectLayer defines effect layer data
  727. * @param scene defines the current scene
  728. * @param rootUrl defines the root URL containing the effect layer information
  729. * @returns a parsed effect Layer
  730. */
  731. public static Parse(parsedEffectLayer: any, scene: Scene, rootUrl: string): EffectLayer {
  732. var effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);
  733. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  734. }
  735. }