effectLayer.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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. if (subMesh.getRenderingMesh().hasThinInstances) {
  449. defines.push("#define THIN_INSTANCES");
  450. }
  451. }
  452. this._addCustomEffectDefines(defines);
  453. // Get correct effect
  454. var join = defines.join("\n");
  455. if (this._cachedDefines !== join) {
  456. this._cachedDefines = join;
  457. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  458. attribs,
  459. ["world", "mBones", "viewProjection",
  460. "glowColor", "morphTargetInfluences", "boneTextureWidth",
  461. "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity"],
  462. ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler"], join,
  463. fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  464. }
  465. return this._effectLayerMapGenerationEffect.isReady();
  466. }
  467. /**
  468. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  469. */
  470. public render(): void {
  471. var currentEffect = this._mergeEffect;
  472. // Check
  473. if (!currentEffect.isReady()) {
  474. return;
  475. }
  476. for (var i = 0; i < this._postProcesses.length; i++) {
  477. if (!this._postProcesses[i].isReady()) {
  478. return;
  479. }
  480. }
  481. var engine = this._scene.getEngine();
  482. this.onBeforeComposeObservable.notifyObservers(this);
  483. // Render
  484. engine.enableEffect(currentEffect);
  485. engine.setState(false);
  486. // VBOs
  487. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  488. // Cache
  489. var previousAlphaMode = engine.getAlphaMode();
  490. // Go Blend.
  491. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  492. // Blends the map on the main canvas.
  493. this._internalRender(currentEffect);
  494. // Restore Alpha
  495. engine.setAlphaMode(previousAlphaMode);
  496. this.onAfterComposeObservable.notifyObservers(this);
  497. // Handle size changes.
  498. var size = this._mainTexture.getSize();
  499. this._setMainTextureSize();
  500. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  501. // Recreate RTT and post processes on size change.
  502. this.onSizeChangedObservable.notifyObservers(this);
  503. this._disposeTextureAndPostProcesses();
  504. this._createMainTexture();
  505. this._createTextureAndPostProcesses();
  506. }
  507. }
  508. /**
  509. * Determine if a given mesh will be used in the current effect.
  510. * @param mesh mesh to test
  511. * @returns true if the mesh will be used
  512. */
  513. public hasMesh(mesh: AbstractMesh): boolean {
  514. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  515. return true;
  516. }
  517. return false;
  518. }
  519. /**
  520. * Returns true if the layer contains information to display, otherwise false.
  521. * @returns true if the glow layer should be rendered
  522. */
  523. public shouldRender(): boolean {
  524. return this.isEnabled && this._shouldRender;
  525. }
  526. /**
  527. * Returns true if the mesh should render, otherwise false.
  528. * @param mesh The mesh to render
  529. * @returns true if it should render otherwise false
  530. */
  531. protected _shouldRenderMesh(mesh: AbstractMesh): boolean {
  532. return true;
  533. }
  534. /**
  535. * Returns true if the mesh can be rendered, otherwise false.
  536. * @param mesh The mesh to render
  537. * @param material The material used on the mesh
  538. * @returns true if it can be rendered otherwise false
  539. */
  540. protected _canRenderMesh(mesh: AbstractMesh, material: Material): boolean {
  541. return !material.needAlphaBlendingForMesh(mesh);
  542. }
  543. /**
  544. * Returns true if the mesh should render, otherwise false.
  545. * @param mesh The mesh to render
  546. * @returns true if it should render otherwise false
  547. */
  548. protected _shouldRenderEmissiveTextureForMesh(): boolean {
  549. return true;
  550. }
  551. /**
  552. * Renders the submesh passed in parameter to the generation map.
  553. */
  554. protected _renderSubMesh(subMesh: SubMesh, enableAlphaMode: boolean = false): void {
  555. if (!this.shouldRender()) {
  556. return;
  557. }
  558. var material = subMesh.getMaterial();
  559. var ownerMesh = subMesh.getMesh();
  560. var replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null;
  561. var renderingMesh = subMesh.getRenderingMesh();
  562. var effectiveMesh = replacementMesh ? replacementMesh : renderingMesh;
  563. var scene = this._scene;
  564. var engine = scene.getEngine();
  565. effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
  566. if (!material) {
  567. return;
  568. }
  569. // Do not block in blend mode.
  570. if (!this._canRenderMesh(renderingMesh, material)) {
  571. return;
  572. }
  573. // Culling
  574. engine.setState(material.backFaceCulling);
  575. // Managing instances
  576. var batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);
  577. if (batch.mustReturn) {
  578. return;
  579. }
  580. // Early Exit per mesh
  581. if (!this._shouldRenderMesh(renderingMesh)) {
  582. return;
  583. }
  584. var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;
  585. this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);
  586. this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);
  587. if (this._useMeshMaterial(renderingMesh)) {
  588. renderingMesh.render(subMesh, hardwareInstancedRendering, replacementMesh || undefined);
  589. }
  590. else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  591. engine.enableEffect(this._effectLayerMapGenerationEffect);
  592. renderingMesh._bind(subMesh, this._effectLayerMapGenerationEffect, Material.TriangleFillMode);
  593. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  594. this._effectLayerMapGenerationEffect.setFloat4("glowColor",
  595. this._emissiveTextureAndColor.color.r,
  596. this._emissiveTextureAndColor.color.g,
  597. this._emissiveTextureAndColor.color.b,
  598. this._emissiveTextureAndColor.color.a);
  599. const needAlphaTest = material.needAlphaTesting();
  600. const diffuseTexture = material.getAlphaTestTexture();
  601. const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
  602. ((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
  603. if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
  604. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", diffuseTexture);
  605. const textureMatrix = diffuseTexture.getTextureMatrix();
  606. if (textureMatrix) {
  607. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  608. }
  609. }
  610. const opacityTexture = (material as any).opacityTexture;
  611. if (opacityTexture) {
  612. this._effectLayerMapGenerationEffect.setTexture("opacitySampler", opacityTexture);
  613. this._effectLayerMapGenerationEffect.setFloat("opacityIntensity", opacityTexture.level);
  614. const textureMatrix = opacityTexture.getTextureMatrix();
  615. if (textureMatrix) {
  616. this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix", textureMatrix);
  617. }
  618. }
  619. // Glow emissive only
  620. if (this._emissiveTextureAndColor.texture) {
  621. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  622. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  623. }
  624. // Bones
  625. if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
  626. const skeleton = renderingMesh.skeleton;
  627. if (skeleton.isUsingTextureForMatrices) {
  628. const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
  629. if (!boneTexture) {
  630. return;
  631. }
  632. this._effectLayerMapGenerationEffect.setTexture("boneSampler", boneTexture);
  633. this._effectLayerMapGenerationEffect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  634. } else {
  635. this._effectLayerMapGenerationEffect.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
  636. }
  637. }
  638. // Morph targets
  639. MaterialHelper.BindMorphTargetParameters(renderingMesh, this._effectLayerMapGenerationEffect);
  640. // Alpha mode
  641. if (enableAlphaMode) {
  642. engine.setAlphaMode(material.alphaMode);
  643. }
  644. // Draw
  645. renderingMesh._processRendering(effectiveMesh, subMesh, this._effectLayerMapGenerationEffect, material.fillMode, batch, hardwareInstancedRendering,
  646. (isInstance, world) => this._effectLayerMapGenerationEffect.setMatrix("world", world));
  647. } else {
  648. // Need to reset refresh rate of the main map
  649. this._mainTexture.resetRefreshCounter();
  650. }
  651. this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);
  652. }
  653. /**
  654. * Defines whether the current material of the mesh should be use to render the effect.
  655. * @param mesh defines the current mesh to render
  656. */
  657. protected _useMeshMaterial(mesh: AbstractMesh): boolean {
  658. return false;
  659. }
  660. /**
  661. * Rebuild the required buffers.
  662. * @hidden Internal use only.
  663. */
  664. public _rebuild(): void {
  665. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  666. if (vb) {
  667. vb._rebuild();
  668. }
  669. this._generateIndexBuffer();
  670. }
  671. /**
  672. * Dispose only the render target textures and post process.
  673. */
  674. private _disposeTextureAndPostProcesses(): void {
  675. this._mainTexture.dispose();
  676. for (var i = 0; i < this._postProcesses.length; i++) {
  677. if (this._postProcesses[i]) {
  678. this._postProcesses[i].dispose();
  679. }
  680. }
  681. this._postProcesses = [];
  682. for (var i = 0; i < this._textures.length; i++) {
  683. if (this._textures[i]) {
  684. this._textures[i].dispose();
  685. }
  686. }
  687. this._textures = [];
  688. }
  689. /**
  690. * Dispose the highlight layer and free resources.
  691. */
  692. public dispose(): void {
  693. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  694. if (vertexBuffer) {
  695. vertexBuffer.dispose();
  696. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  697. }
  698. if (this._indexBuffer) {
  699. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  700. this._indexBuffer = null;
  701. }
  702. // Clean textures and post processes
  703. this._disposeTextureAndPostProcesses();
  704. // Remove from scene
  705. var index = this._scene.effectLayers.indexOf(this, 0);
  706. if (index > -1) {
  707. this._scene.effectLayers.splice(index, 1);
  708. }
  709. // Callback
  710. this.onDisposeObservable.notifyObservers(this);
  711. this.onDisposeObservable.clear();
  712. this.onBeforeRenderMainTextureObservable.clear();
  713. this.onBeforeComposeObservable.clear();
  714. this.onBeforeRenderMeshToEffect.clear();
  715. this.onAfterRenderMeshToEffect.clear();
  716. this.onAfterComposeObservable.clear();
  717. this.onSizeChangedObservable.clear();
  718. }
  719. /**
  720. * Gets the class name of the effect layer
  721. * @returns the string with the class name of the effect layer
  722. */
  723. public getClassName(): string {
  724. return "EffectLayer";
  725. }
  726. /**
  727. * Creates an effect layer from parsed effect layer data
  728. * @param parsedEffectLayer defines effect layer data
  729. * @param scene defines the current scene
  730. * @param rootUrl defines the root URL containing the effect layer information
  731. * @returns a parsed effect Layer
  732. */
  733. public static Parse(parsedEffectLayer: any, scene: Scene, rootUrl: string): EffectLayer {
  734. var effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);
  735. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  736. }
  737. }