lensFlareSystem.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import { Tools } from "../Misc/tools";
  2. import { Nullable } from "../types";
  3. import { Scene } from "../scene";
  4. import { Matrix, Vector3 } from "../Maths/math.vector";
  5. import { Scalar } from "../Maths/math.scalar";
  6. import { EngineStore } from "../Engines/engineStore";
  7. import { AbstractMesh } from "../Meshes/abstractMesh";
  8. import { VertexBuffer } from "../Meshes/buffer";
  9. import { Ray } from "../Culling/ray";
  10. import { Effect } from "../Materials/effect";
  11. import { Material } from "../Materials/material";
  12. import { LensFlare } from "./lensFlare";
  13. import { Constants } from "../Engines/constants";
  14. import "../Shaders/lensFlare.fragment";
  15. import "../Shaders/lensFlare.vertex";
  16. import { _DevTools } from '../Misc/devTools';
  17. import { DataBuffer } from '../Meshes/dataBuffer';
  18. import { Color3 } from '../Maths/math.color';
  19. import { Viewport } from '../Maths/math.viewport';
  20. /**
  21. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  22. * It is usually composed of several `lensFlare`.
  23. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24. */
  25. export class LensFlareSystem {
  26. /**
  27. * List of lens flares used in this system.
  28. */
  29. public lensFlares = new Array<LensFlare>();
  30. /**
  31. * Define a limit from the border the lens flare can be visible.
  32. */
  33. public borderLimit = 300;
  34. /**
  35. * Define a viewport border we do not want to see the lens flare in.
  36. */
  37. public viewportBorder = 0;
  38. /**
  39. * Define a predicate which could limit the list of meshes able to occlude the effect.
  40. */
  41. public meshesSelectionPredicate: (mesh: AbstractMesh) => boolean;
  42. /**
  43. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  44. */
  45. public layerMask: number = 0x0FFFFFFF;
  46. /**
  47. * Define the id of the lens flare system in the scene.
  48. * (equal to name by default)
  49. */
  50. public id: string;
  51. private _scene: Scene;
  52. private _emitter: any;
  53. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  54. private _indexBuffer: Nullable<DataBuffer>;
  55. private _effect: Effect;
  56. private _positionX: number;
  57. private _positionY: number;
  58. private _isEnabled = true;
  59. /** @hidden */
  60. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  61. throw _DevTools.WarnImport("LensFlareSystemSceneComponent");
  62. }
  63. /**
  64. * Instantiates a lens flare system.
  65. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  66. * It is usually composed of several `lensFlare`.
  67. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  68. * @param name Define the name of the lens flare system in the scene
  69. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  70. * @param scene Define the scene the lens flare system belongs to
  71. */
  72. constructor(
  73. /**
  74. * Define the name of the lens flare system
  75. */
  76. public name: string,
  77. emitter: any,
  78. scene: Scene) {
  79. this._scene = scene || EngineStore.LastCreatedScene;
  80. LensFlareSystem._SceneComponentInitialization(this._scene);
  81. this._emitter = emitter;
  82. this.id = name;
  83. scene.lensFlareSystems.push(this);
  84. this.meshesSelectionPredicate = (m) => <boolean>(scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0));
  85. var engine = scene.getEngine();
  86. // VBO
  87. var vertices = [];
  88. vertices.push(1, 1);
  89. vertices.push(-1, 1);
  90. vertices.push(-1, -1);
  91. vertices.push(1, -1);
  92. this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  93. // Indices
  94. var indices = [];
  95. indices.push(0);
  96. indices.push(1);
  97. indices.push(2);
  98. indices.push(0);
  99. indices.push(2);
  100. indices.push(3);
  101. this._indexBuffer = engine.createIndexBuffer(indices);
  102. // Effects
  103. this._effect = engine.createEffect("lensFlare",
  104. [VertexBuffer.PositionKind],
  105. ["color", "viewportMatrix"],
  106. ["textureSampler"], "");
  107. }
  108. /**
  109. * Define if the lens flare system is enabled.
  110. */
  111. public get isEnabled(): boolean {
  112. return this._isEnabled;
  113. }
  114. public set isEnabled(value: boolean) {
  115. this._isEnabled = value;
  116. }
  117. /**
  118. * Get the scene the effects belongs to.
  119. * @returns the scene holding the lens flare system
  120. */
  121. public getScene(): Scene {
  122. return this._scene;
  123. }
  124. /**
  125. * Get the emitter of the lens flare system.
  126. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  127. * @returns the emitter of the lens flare system
  128. */
  129. public getEmitter(): any {
  130. return this._emitter;
  131. }
  132. /**
  133. * Set the emitter of the lens flare system.
  134. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  135. * @param newEmitter Define the new emitter of the system
  136. */
  137. public setEmitter(newEmitter: any): void {
  138. this._emitter = newEmitter;
  139. }
  140. /**
  141. * Get the lens flare system emitter position.
  142. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  143. * @returns the position
  144. */
  145. public getEmitterPosition(): Vector3 {
  146. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  147. }
  148. /**
  149. * @hidden
  150. */
  151. public computeEffectivePosition(globalViewport: Viewport): boolean {
  152. var position = this.getEmitterPosition();
  153. position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  154. this._positionX = position.x;
  155. this._positionY = position.y;
  156. position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  157. if (this.viewportBorder > 0) {
  158. globalViewport.x -= this.viewportBorder;
  159. globalViewport.y -= this.viewportBorder;
  160. globalViewport.width += this.viewportBorder * 2;
  161. globalViewport.height += this.viewportBorder * 2;
  162. position.x += this.viewportBorder;
  163. position.y += this.viewportBorder;
  164. this._positionX += this.viewportBorder;
  165. this._positionY += this.viewportBorder;
  166. }
  167. if (position.z > 0) {
  168. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  169. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  170. return true;
  171. }
  172. }
  173. return true;
  174. }
  175. return false;
  176. }
  177. /** @hidden */
  178. public _isVisible(): boolean {
  179. if (!this._isEnabled || !this._scene.activeCamera) {
  180. return false;
  181. }
  182. var emitterPosition = this.getEmitterPosition();
  183. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  184. var distance = direction.length();
  185. direction.normalize();
  186. var ray = new Ray(this._scene.activeCamera.globalPosition, direction);
  187. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  188. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  189. }
  190. /**
  191. * @hidden
  192. */
  193. public render(): boolean {
  194. if (!this._effect.isReady() || !this._scene.activeCamera) {
  195. return false;
  196. }
  197. var engine = this._scene.getEngine();
  198. var viewport = this._scene.activeCamera.viewport;
  199. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  200. // Position
  201. if (!this.computeEffectivePosition(globalViewport)) {
  202. return false;
  203. }
  204. // Visibility
  205. if (!this._isVisible()) {
  206. return false;
  207. }
  208. // Intensity
  209. var awayX;
  210. var awayY;
  211. if (this._positionX < this.borderLimit + globalViewport.x) {
  212. awayX = this.borderLimit + globalViewport.x - this._positionX;
  213. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  214. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  215. } else {
  216. awayX = 0;
  217. }
  218. if (this._positionY < this.borderLimit + globalViewport.y) {
  219. awayY = this.borderLimit + globalViewport.y - this._positionY;
  220. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  221. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  222. } else {
  223. awayY = 0;
  224. }
  225. var away = (awayX > awayY) ? awayX : awayY;
  226. away -= this.viewportBorder;
  227. if (away > this.borderLimit) {
  228. away = this.borderLimit;
  229. }
  230. var intensity = 1.0 - Scalar.Clamp(away / this.borderLimit, 0, 1);
  231. if (intensity < 0) {
  232. return false;
  233. }
  234. if (intensity > 1.0) {
  235. intensity = 1.0;
  236. }
  237. if (this.viewportBorder > 0) {
  238. globalViewport.x += this.viewportBorder;
  239. globalViewport.y += this.viewportBorder;
  240. globalViewport.width -= this.viewportBorder * 2;
  241. globalViewport.height -= this.viewportBorder * 2;
  242. this._positionX -= this.viewportBorder;
  243. this._positionY -= this.viewportBorder;
  244. }
  245. // Position
  246. var centerX = globalViewport.x + globalViewport.width / 2;
  247. var centerY = globalViewport.y + globalViewport.height / 2;
  248. var distX = centerX - this._positionX;
  249. var distY = centerY - this._positionY;
  250. // Effects
  251. engine.enableEffect(this._effect);
  252. engine.setState(false);
  253. engine.setDepthBuffer(false);
  254. // VBOs
  255. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  256. // Flares
  257. for (var index = 0; index < this.lensFlares.length; index++) {
  258. var flare = this.lensFlares[index];
  259. if (flare.texture && !flare.texture.isReady()) {
  260. continue;
  261. }
  262. engine.setAlphaMode(flare.alphaMode);
  263. var x = centerX - (distX * flare.position);
  264. var y = centerY - (distY * flare.position);
  265. var cw = flare.size;
  266. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  267. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  268. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  269. var viewportMatrix = Matrix.FromValues(
  270. cw / 2, 0, 0, 0,
  271. 0, ch / 2, 0, 0,
  272. 0, 0, 1, 0,
  273. cx, cy, 0, 1);
  274. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  275. // Texture
  276. this._effect.setTexture("textureSampler", flare.texture);
  277. // Color
  278. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  279. // Draw order
  280. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  281. }
  282. engine.setDepthBuffer(true);
  283. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  284. return true;
  285. }
  286. /**
  287. * Dispose and release the lens flare with its associated resources.
  288. */
  289. public dispose(): void {
  290. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  291. if (vertexBuffer) {
  292. vertexBuffer.dispose();
  293. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  294. }
  295. if (this._indexBuffer) {
  296. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  297. this._indexBuffer = null;
  298. }
  299. while (this.lensFlares.length) {
  300. this.lensFlares[0].dispose();
  301. }
  302. // Remove from scene
  303. var index = this._scene.lensFlareSystems.indexOf(this);
  304. this._scene.lensFlareSystems.splice(index, 1);
  305. }
  306. /**
  307. * Parse a lens flare system from a JSON repressentation
  308. * @param parsedLensFlareSystem Define the JSON to parse
  309. * @param scene Define the scene the parsed system should be instantiated in
  310. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  311. * @returns the parsed system
  312. */
  313. public static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem {
  314. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  315. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  316. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  317. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  318. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  319. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  320. var parsedFlare = parsedLensFlareSystem.flares[index];
  321. LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  322. }
  323. return lensFlareSystem;
  324. }
  325. /**
  326. * Serialize the current Lens Flare System into a JSON representation.
  327. * @returns the serialized JSON
  328. */
  329. public serialize(): any {
  330. var serializationObject: any = {};
  331. serializationObject.id = this.id;
  332. serializationObject.name = this.name;
  333. serializationObject.emitterId = this.getEmitter().id;
  334. serializationObject.borderLimit = this.borderLimit;
  335. serializationObject.flares = [];
  336. for (var index = 0; index < this.lensFlares.length; index++) {
  337. var flare = this.lensFlares[index];
  338. serializationObject.flares.push({
  339. size: flare.size,
  340. position: flare.position,
  341. color: flare.color.asArray(),
  342. textureName: Tools.GetFilename(flare.texture ? flare.texture.name : "")
  343. });
  344. }
  345. return serializationObject;
  346. }
  347. }