effectLayer.ts 31 KB

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