babylon.light.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. module BABYLON {
  2. export class Light extends Node {
  3. //lightmapMode Consts
  4. private static _LIGHTMAP_DEFAULT = 0;
  5. private static _LIGHTMAP_SPECULAR = 1;
  6. private static _LIGHTMAP_SHADOWSONLY = 2;
  7. /**
  8. * If every light affecting the material is in this lightmapMode,
  9. * material.lightmapTexture adds or multiplies
  10. * (depends on material.useLightmapAsShadowmap)
  11. * after every other light calculations.
  12. */
  13. public static get LIGHTMAP_DEFAULT(): number {
  14. return Light._LIGHTMAP_DEFAULT;
  15. }
  16. /**
  17. * material.lightmapTexture as only diffuse lighting from this light
  18. * adds only specular lighting from this light
  19. * adds dynamic shadows
  20. */
  21. public static get LIGHTMAP_SPECULAR(): number {
  22. return Light._LIGHTMAP_SPECULAR;
  23. }
  24. /**
  25. * material.lightmapTexture as only lighting
  26. * no light calculation from this light
  27. * only adds dynamic shadows from this light
  28. */
  29. public static get LIGHTMAP_SHADOWSONLY(): number {
  30. return Light._LIGHTMAP_SHADOWSONLY;
  31. }
  32. // Intensity Mode Consts
  33. private static _INTENSITYMODE_AUTOMATIC = 0;
  34. private static _INTENSITYMODE_LUMINOUSPOWER = 1;
  35. private static _INTENSITYMODE_LUMINOUSINTENSITY = 2;
  36. private static _INTENSITYMODE_ILLUMINANCE = 3;
  37. private static _INTENSITYMODE_LUMINANCE = 4;
  38. /**
  39. * Each light type uses the default quantity according to its type:
  40. * point/spot lights use luminous intensity
  41. * directional lights use illuminance
  42. */
  43. public static get INTENSITYMODE_AUTOMATIC(): number {
  44. return Light._INTENSITYMODE_AUTOMATIC;
  45. }
  46. /**
  47. * lumen (lm)
  48. */
  49. public static get INTENSITYMODE_LUMINOUSPOWER(): number {
  50. return Light._INTENSITYMODE_LUMINOUSPOWER;
  51. }
  52. /**
  53. * candela (lm/sr)
  54. */
  55. public static get INTENSITYMODE_LUMINOUSINTENSITY(): number {
  56. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  57. }
  58. /**
  59. * lux (lm/m^2)
  60. */
  61. public static get INTENSITYMODE_ILLUMINANCE(): number {
  62. return Light._INTENSITYMODE_ILLUMINANCE;
  63. }
  64. /**
  65. * nit (cd/m^2)
  66. */
  67. public static get INTENSITYMODE_LUMINANCE(): number {
  68. return Light._INTENSITYMODE_LUMINANCE;
  69. }
  70. // Light types ids const.
  71. private static _LIGHTTYPEID_POINTLIGHT = 0;
  72. private static _LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  73. private static _LIGHTTYPEID_SPOTLIGHT = 2;
  74. private static _LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  75. /**
  76. * Light type const id of the point light.
  77. */
  78. public static get LIGHTTYPEID_POINTLIGHT(): number {
  79. return Light._LIGHTTYPEID_POINTLIGHT;
  80. }
  81. /**
  82. * Light type const id of the directional light.
  83. */
  84. public static get LIGHTTYPEID_DIRECTIONALLIGHT(): number {
  85. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  86. }
  87. /**
  88. * Light type const id of the spot light.
  89. */
  90. public static get LIGHTTYPEID_SPOTLIGHT(): number {
  91. return Light._LIGHTTYPEID_SPOTLIGHT;
  92. }
  93. /**
  94. * Light type const id of the hemispheric light.
  95. */
  96. public static get LIGHTTYPEID_HEMISPHERICLIGHT(): number {
  97. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  98. }
  99. @serializeAsColor3()
  100. public diffuse = new Color3(1.0, 1.0, 1.0);
  101. @serializeAsColor3()
  102. public specular = new Color3(1.0, 1.0, 1.0);
  103. @serialize()
  104. public intensity = 1.0;
  105. @serialize()
  106. public range = Number.MAX_VALUE;
  107. /**
  108. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  109. * of light.
  110. */
  111. private _photometricScale = 1.0;
  112. private _intensityMode: number = Light.INTENSITYMODE_AUTOMATIC;
  113. /**
  114. * Gets the photometric scale used to interpret the intensity.
  115. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  116. */
  117. @serialize()
  118. public get intensityMode(): number {
  119. return this._intensityMode;
  120. };
  121. /**
  122. * Sets the photometric scale used to interpret the intensity.
  123. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  124. */
  125. public set intensityMode(value: number) {
  126. this._intensityMode = value;
  127. this._computePhotometricScale();
  128. };
  129. private _radius = 0.00001;
  130. /**
  131. * Gets the light radius used by PBR Materials to simulate soft area lights.
  132. */
  133. @serialize()
  134. public get radius(): number {
  135. return this._radius;
  136. };
  137. /**
  138. * sets the light radius used by PBR Materials to simulate soft area lights.
  139. */
  140. public set radius(value: number) {
  141. this._radius = value;
  142. this._computePhotometricScale();
  143. };
  144. /**
  145. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  146. * exceeding the number allowed of the materials.
  147. */
  148. @serialize()
  149. private _renderPriority: number;
  150. @expandToProperty("_reorderLightsInScene")
  151. public renderPriority: number = 0;
  152. /**
  153. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  154. * the current shadow generator.
  155. */
  156. @serialize()
  157. public shadowEnabled: boolean = true;
  158. private _includedOnlyMeshes: AbstractMesh[];
  159. public get includedOnlyMeshes(): AbstractMesh[] {
  160. return this._includedOnlyMeshes;
  161. }
  162. public set includedOnlyMeshes(value: AbstractMesh[]) {
  163. this._includedOnlyMeshes = value;
  164. this._hookArrayForIncludedOnly(value);
  165. }
  166. private _excludedMeshes: AbstractMesh[];
  167. public get excludedMeshes(): AbstractMesh[] {
  168. return this._excludedMeshes;
  169. }
  170. public set excludedMeshes(value: AbstractMesh[]) {
  171. this._excludedMeshes = value;
  172. this._hookArrayForExcluded(value);
  173. }
  174. @serialize("excludeWithLayerMask")
  175. private _excludeWithLayerMask = 0;
  176. public get excludeWithLayerMask(): number {
  177. return this._excludeWithLayerMask;
  178. }
  179. public set excludeWithLayerMask(value: number) {
  180. this._excludeWithLayerMask = value;
  181. this._resyncMeshes();
  182. }
  183. @serialize("includeOnlyWithLayerMask")
  184. private _includeOnlyWithLayerMask = 0;
  185. public get includeOnlyWithLayerMask(): number {
  186. return this._includeOnlyWithLayerMask;
  187. }
  188. public set includeOnlyWithLayerMask(value: number) {
  189. this._includeOnlyWithLayerMask = value;
  190. this._resyncMeshes();
  191. }
  192. @serialize("lightmapMode")
  193. private _lightmapMode = 0;
  194. public get lightmapMode(): number {
  195. return this._lightmapMode;
  196. }
  197. public set lightmapMode(value: number) {
  198. if (this._lightmapMode === value) {
  199. return;
  200. }
  201. this._lightmapMode = value;
  202. this._markMeshesAsLightDirty();
  203. }
  204. private _parentedWorldMatrix: Matrix;
  205. public _shadowGenerator: Nullable<IShadowGenerator>;
  206. public _excludedMeshesIds = new Array<string>();
  207. public _includedOnlyMeshesIds = new Array<string>();
  208. // Light uniform buffer
  209. public _uniformBuffer: UniformBuffer;
  210. /**
  211. * Creates a Light object in the scene.
  212. * Documentation : http://doc.babylonjs.com/tutorials/lights
  213. */
  214. constructor(name: string, scene: Scene) {
  215. super(name, scene);
  216. this.getScene().addLight(this);
  217. this._uniformBuffer = new UniformBuffer(this.getScene().getEngine());
  218. this._buildUniformLayout();
  219. this.includedOnlyMeshes = new Array<AbstractMesh>();
  220. this.excludedMeshes = new Array<AbstractMesh>();
  221. this._resyncMeshes();
  222. }
  223. protected _buildUniformLayout(): void {
  224. // Overridden
  225. }
  226. /**
  227. * Returns the string "Light".
  228. */
  229. public getClassName(): string {
  230. return "Light";
  231. }
  232. /**
  233. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  234. */
  235. public toString(fullDetails?: boolean): string {
  236. var ret = "Name: " + this.name;
  237. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  238. if (this.animations) {
  239. for (var i = 0; i < this.animations.length; i++) {
  240. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  241. }
  242. }
  243. if (fullDetails) {
  244. }
  245. return ret;
  246. }
  247. /**
  248. * Set the enabled state of this node.
  249. * @param {boolean} value - the new enabled state
  250. * @see isEnabled
  251. */
  252. public setEnabled(value: boolean): void {
  253. super.setEnabled(value);
  254. this._resyncMeshes();
  255. }
  256. /**
  257. * Returns the Light associated shadow generator.
  258. */
  259. public getShadowGenerator(): Nullable<IShadowGenerator> {
  260. return this._shadowGenerator;
  261. }
  262. /**
  263. * Returns a Vector3, the absolute light position in the World.
  264. */
  265. public getAbsolutePosition(): Vector3 {
  266. return Vector3.Zero();
  267. }
  268. public transferToEffect(effect: Effect, lightIndex: string): void {
  269. }
  270. public _getWorldMatrix(): Matrix {
  271. return Matrix.Identity();
  272. }
  273. /**
  274. * Boolean : True if the light will affect the passed mesh.
  275. */
  276. public canAffectMesh(mesh: AbstractMesh): boolean {
  277. if (!mesh) {
  278. return true;
  279. }
  280. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  281. return false;
  282. }
  283. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  284. return false;
  285. }
  286. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  287. return false;
  288. }
  289. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  290. return false;
  291. }
  292. return true;
  293. }
  294. /**
  295. * Returns the light World matrix.
  296. */
  297. public getWorldMatrix(): Matrix {
  298. this._currentRenderId = this.getScene().getRenderId();
  299. var worldMatrix = this._getWorldMatrix();
  300. if (this.parent && this.parent.getWorldMatrix) {
  301. if (!this._parentedWorldMatrix) {
  302. this._parentedWorldMatrix = Matrix.Identity();
  303. }
  304. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  305. this._markSyncedWithParent();
  306. return this._parentedWorldMatrix;
  307. }
  308. return worldMatrix;
  309. }
  310. /**
  311. * Sort function to order lights for rendering.
  312. * @param a First Light object to compare to second.
  313. * @param b Second Light object to compare first.
  314. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  315. */
  316. public static compareLightsPriority(a: Light, b: Light): number {
  317. //shadow-casting lights have priority over non-shadow-casting lights
  318. //the renderPrioirty is a secondary sort criterion
  319. if (a.shadowEnabled !== b.shadowEnabled) {
  320. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  321. }
  322. return b.renderPriority - a.renderPriority;
  323. }
  324. /**
  325. * Disposes the light.
  326. */
  327. public dispose(): void {
  328. if (this._shadowGenerator) {
  329. this._shadowGenerator.dispose();
  330. this._shadowGenerator = null;
  331. }
  332. // Animations
  333. this.getScene().stopAnimation(this);
  334. // Remove from meshes
  335. for (var mesh of this.getScene().meshes) {
  336. mesh._removeLightSource(this);
  337. }
  338. this._uniformBuffer.dispose();
  339. // Remove from scene
  340. this.getScene().removeLight(this);
  341. super.dispose();
  342. }
  343. /**
  344. * Returns the light type ID (integer).
  345. */
  346. public getTypeID(): number {
  347. return 0;
  348. }
  349. /**
  350. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  351. */
  352. public getScaledIntensity() {
  353. return this._photometricScale * this.intensity;
  354. }
  355. /**
  356. * Returns a new Light object, named "name", from the current one.
  357. */
  358. public clone(name: string): Nullable<Light> {
  359. let constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  360. if (!constructor) {
  361. return null;
  362. }
  363. return SerializationHelper.Clone(constructor, this);
  364. }
  365. /**
  366. * Serializes the current light into a Serialization object.
  367. * Returns the serialized object.
  368. */
  369. public serialize(): any {
  370. var serializationObject = SerializationHelper.Serialize(this);
  371. // Type
  372. serializationObject.type = this.getTypeID();
  373. // Parent
  374. if (this.parent) {
  375. serializationObject.parentId = this.parent.id;
  376. }
  377. // Inclusion / exclusions
  378. if (this.excludedMeshes.length > 0) {
  379. serializationObject.excludedMeshesIds = [];
  380. this.excludedMeshes.forEach((mesh: AbstractMesh) => {
  381. serializationObject.excludedMeshesIds.push(mesh.id);
  382. });
  383. }
  384. if (this.includedOnlyMeshes.length > 0) {
  385. serializationObject.includedOnlyMeshesIds = [];
  386. this.includedOnlyMeshes.forEach((mesh: AbstractMesh) => {
  387. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  388. });
  389. }
  390. // Animations
  391. Animation.AppendSerializedAnimations(this, serializationObject);
  392. serializationObject.ranges = this.serializeAnimationRanges();
  393. return serializationObject;
  394. }
  395. /**
  396. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  397. * This new light is named "name" and added to the passed scene.
  398. */
  399. static GetConstructorFromName(type: number, name: string, scene: Scene): Nullable<() => Light> {
  400. switch (type) {
  401. case 0:
  402. return () => new PointLight(name, Vector3.Zero(), scene);
  403. case 1:
  404. return () => new DirectionalLight(name, Vector3.Zero(), scene);
  405. case 2:
  406. return () => new SpotLight(name, Vector3.Zero(), Vector3.Zero(), 0, 0, scene);
  407. case 3:
  408. return () => new HemisphericLight(name, Vector3.Zero(), scene);
  409. }
  410. return null;
  411. }
  412. /**
  413. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  414. */
  415. public static Parse(parsedLight: any, scene: Scene): Nullable<Light> {
  416. let constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  417. if (!constructor) {
  418. return null;
  419. }
  420. var light = SerializationHelper.Parse(constructor, parsedLight, scene);
  421. // Inclusion / exclusions
  422. if (parsedLight.excludedMeshesIds) {
  423. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  424. }
  425. if (parsedLight.includedOnlyMeshesIds) {
  426. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  427. }
  428. // Parent
  429. if (parsedLight.parentId) {
  430. light._waitingParentId = parsedLight.parentId;
  431. }
  432. // Animations
  433. if (parsedLight.animations) {
  434. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  435. var parsedAnimation = parsedLight.animations[animationIndex];
  436. light.animations.push(Animation.Parse(parsedAnimation));
  437. }
  438. Node.ParseAnimationRanges(light, parsedLight, scene);
  439. }
  440. if (parsedLight.autoAnimate) {
  441. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  442. }
  443. return light;
  444. }
  445. private _hookArrayForExcluded(array: AbstractMesh[]): void {
  446. var oldPush = array.push;
  447. array.push = (...items: AbstractMesh[]) => {
  448. var result = oldPush.apply(array, items);
  449. for (var item of items) {
  450. item._resyncLighSource(this);
  451. }
  452. return result;
  453. }
  454. var oldSplice = array.splice;
  455. array.splice = (index: number, deleteCount?: number) => {
  456. var deleted = oldSplice.apply(array, [index, deleteCount]);
  457. for (var item of deleted) {
  458. item._resyncLighSource(this);
  459. }
  460. return deleted;
  461. }
  462. for (var item of array) {
  463. item._resyncLighSource(this);
  464. }
  465. }
  466. private _hookArrayForIncludedOnly(array: AbstractMesh[]): void {
  467. var oldPush = array.push;
  468. array.push = (...items: AbstractMesh[]) => {
  469. var result = oldPush.apply(array, items);
  470. this._resyncMeshes();
  471. return result;
  472. }
  473. var oldSplice = array.splice;
  474. array.splice = (index: number, deleteCount?: number) => {
  475. var deleted = oldSplice.apply(array, [index, deleteCount]);
  476. this._resyncMeshes();
  477. return deleted;
  478. }
  479. this._resyncMeshes();
  480. }
  481. private _resyncMeshes() {
  482. for (var mesh of this.getScene().meshes) {
  483. mesh._resyncLighSource(this);
  484. }
  485. }
  486. public _markMeshesAsLightDirty() {
  487. for (var mesh of this.getScene().meshes) {
  488. if (mesh._lightSources.indexOf(this) !== -1) {
  489. mesh._markSubMeshesAsLightDirty();
  490. }
  491. }
  492. }
  493. /**
  494. * Recomputes the cached photometric scale if needed.
  495. */
  496. private _computePhotometricScale(): void {
  497. this._photometricScale = this._getPhotometricScale();
  498. this.getScene().resetCachedMaterial();
  499. }
  500. /**
  501. * Returns the Photometric Scale according to the light type and intensity mode.
  502. */
  503. private _getPhotometricScale() {
  504. let photometricScale = 0.0;
  505. let lightTypeID = this.getTypeID();
  506. //get photometric mode
  507. let photometricMode = this.intensityMode;
  508. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  509. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  510. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  511. } else {
  512. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  513. }
  514. }
  515. //compute photometric scale
  516. switch (lightTypeID) {
  517. case Light.LIGHTTYPEID_POINTLIGHT:
  518. case Light.LIGHTTYPEID_SPOTLIGHT:
  519. switch (photometricMode) {
  520. case Light.INTENSITYMODE_LUMINOUSPOWER:
  521. photometricScale = 1.0 / (4.0 * Math.PI);
  522. break;
  523. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  524. photometricScale = 1.0;
  525. break;
  526. case Light.INTENSITYMODE_LUMINANCE:
  527. photometricScale = this.radius * this.radius;
  528. break;
  529. }
  530. break;
  531. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  532. switch (photometricMode) {
  533. case Light.INTENSITYMODE_ILLUMINANCE:
  534. photometricScale = 1.0;
  535. break;
  536. case Light.INTENSITYMODE_LUMINANCE:
  537. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  538. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  539. let apexAngleRadians = this.radius;
  540. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  541. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  542. let solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  543. photometricScale = solidAngle;
  544. break;
  545. }
  546. break;
  547. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  548. // No fall off in hemisperic light.
  549. photometricScale = 1.0;
  550. break;
  551. }
  552. return photometricScale;
  553. }
  554. public _reorderLightsInScene(): void {
  555. var scene = this.getScene();
  556. if (this._renderPriority != 0) {
  557. scene.requireLightSorting = true;
  558. }
  559. this.getScene().sortLightsByPriority();
  560. }
  561. }
  562. }