camera.ts 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. import { serialize, SerializationHelper, serializeAsVector3 } from "../Misc/decorators";
  2. import { SmartArray } from "../Misc/smartArray";
  3. import { Tools } from "../Misc/tools";
  4. import { Observable } from "../Misc/observable";
  5. import { Nullable } from "../types";
  6. import { CameraInputsManager } from "./cameraInputsManager";
  7. import { Scene } from "../scene";
  8. import { Matrix, Vector3, Quaternion } from "../Maths/math.vector";
  9. import { Node } from "../node";
  10. import { Mesh } from "../Meshes/mesh";
  11. import { AbstractMesh } from "../Meshes/abstractMesh";
  12. import { ICullable } from "../Culling/boundingInfo";
  13. import { Logger } from "../Misc/logger";
  14. import { _TypeStore } from '../Misc/typeStore';
  15. import { _DevTools } from '../Misc/devTools';
  16. import { Viewport } from '../Maths/math.viewport';
  17. import { Frustum } from '../Maths/math.frustum';
  18. import { Plane } from '../Maths/math.plane';
  19. declare type PostProcess = import("../PostProcesses/postProcess").PostProcess;
  20. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  21. declare type FreeCamera = import("./freeCamera").FreeCamera;
  22. declare type TargetCamera = import("./targetCamera").TargetCamera;
  23. declare type Ray = import("../Culling/ray").Ray;
  24. /**
  25. * This is the base class of all the camera used in the application.
  26. * @see https://doc.babylonjs.com/features/cameras
  27. */
  28. export class Camera extends Node {
  29. /** @hidden */
  30. public static _createDefaultParsedCamera = (name: string, scene: Scene): Camera => {
  31. throw _DevTools.WarnImport("UniversalCamera");
  32. }
  33. /**
  34. * This is the default projection mode used by the cameras.
  35. * It helps recreating a feeling of perspective and better appreciate depth.
  36. * This is the best way to simulate real life cameras.
  37. */
  38. public static readonly PERSPECTIVE_CAMERA = 0;
  39. /**
  40. * This helps creating camera with an orthographic mode.
  41. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  42. */
  43. public static readonly ORTHOGRAPHIC_CAMERA = 1;
  44. /**
  45. * This is the default FOV mode for perspective cameras.
  46. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  47. */
  48. public static readonly FOVMODE_VERTICAL_FIXED = 0;
  49. /**
  50. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  51. */
  52. public static readonly FOVMODE_HORIZONTAL_FIXED = 1;
  53. /**
  54. * This specifies ther is no need for a camera rig.
  55. * Basically only one eye is rendered corresponding to the camera.
  56. */
  57. public static readonly RIG_MODE_NONE = 0;
  58. /**
  59. * Simulates a camera Rig with one blue eye and one red eye.
  60. * This can be use with 3d blue and red glasses.
  61. */
  62. public static readonly RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  63. /**
  64. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  65. */
  66. public static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  67. /**
  68. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  69. */
  70. public static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  71. /**
  72. * Defines that both eyes of the camera will be rendered over under each other.
  73. */
  74. public static readonly RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  75. /**
  76. * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.
  77. */
  78. public static readonly RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
  79. /**
  80. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  81. */
  82. public static readonly RIG_MODE_VR = 20;
  83. /**
  84. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  85. */
  86. public static readonly RIG_MODE_WEBVR = 21;
  87. /**
  88. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  89. */
  90. public static readonly RIG_MODE_CUSTOM = 22;
  91. /**
  92. * Defines if by default attaching controls should prevent the default javascript event to continue.
  93. */
  94. public static ForceAttachControlToAlwaysPreventDefault = false;
  95. /**
  96. * Define the input manager associated with the camera.
  97. */
  98. public inputs: CameraInputsManager<Camera>;
  99. /** @hidden */
  100. @serializeAsVector3("position")
  101. public _position = Vector3.Zero();
  102. /**
  103. * Define the current local position of the camera in the scene
  104. */
  105. public get position(): Vector3 {
  106. return this._position;
  107. }
  108. public set position(newPosition: Vector3) {
  109. this._position = newPosition;
  110. }
  111. @serializeAsVector3("upVector")
  112. protected _upVector = Vector3.Up();
  113. /**
  114. * The vector the camera should consider as up.
  115. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  116. */
  117. public set upVector(vec: Vector3) {
  118. this._upVector = vec;
  119. }
  120. public get upVector() {
  121. return this._upVector;
  122. }
  123. /**
  124. * Define the current limit on the left side for an orthographic camera
  125. * In scene unit
  126. */
  127. @serialize()
  128. public orthoLeft: Nullable<number> = null;
  129. /**
  130. * Define the current limit on the right side for an orthographic camera
  131. * In scene unit
  132. */
  133. @serialize()
  134. public orthoRight: Nullable<number> = null;
  135. /**
  136. * Define the current limit on the bottom side for an orthographic camera
  137. * In scene unit
  138. */
  139. @serialize()
  140. public orthoBottom: Nullable<number> = null;
  141. /**
  142. * Define the current limit on the top side for an orthographic camera
  143. * In scene unit
  144. */
  145. @serialize()
  146. public orthoTop: Nullable<number> = null;
  147. /**
  148. * Field Of View is set in Radians. (default is 0.8)
  149. */
  150. @serialize()
  151. public fov = 0.8;
  152. /**
  153. * Define the minimum distance the camera can see from.
  154. * This is important to note that the depth buffer are not infinite and the closer it starts
  155. * the more your scene might encounter depth fighting issue.
  156. */
  157. @serialize()
  158. public minZ = 1;
  159. /**
  160. * Define the maximum distance the camera can see to.
  161. * This is important to note that the depth buffer are not infinite and the further it end
  162. * the more your scene might encounter depth fighting issue.
  163. */
  164. @serialize()
  165. public maxZ = 10000.0;
  166. /**
  167. * Define the default inertia of the camera.
  168. * This helps giving a smooth feeling to the camera movement.
  169. */
  170. @serialize()
  171. public inertia = 0.9;
  172. /**
  173. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA)
  174. */
  175. @serialize()
  176. public mode = Camera.PERSPECTIVE_CAMERA;
  177. /**
  178. * Define whether the camera is intermediate.
  179. * This is useful to not present the output directly to the screen in case of rig without post process for instance
  180. */
  181. public isIntermediate = false;
  182. /**
  183. * Define the viewport of the camera.
  184. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  185. */
  186. public viewport = new Viewport(0, 0, 1.0, 1.0);
  187. /**
  188. * Restricts the camera to viewing objects with the same layerMask.
  189. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  190. */
  191. @serialize()
  192. public layerMask: number = 0x0FFFFFFF;
  193. /**
  194. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  195. */
  196. @serialize()
  197. public fovMode: number = Camera.FOVMODE_VERTICAL_FIXED;
  198. /**
  199. * Rig mode of the camera.
  200. * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  201. * This is normally controlled byt the camera themselves as internal use.
  202. */
  203. @serialize()
  204. public cameraRigMode = Camera.RIG_MODE_NONE;
  205. /**
  206. * Defines the distance between both "eyes" in case of a RIG
  207. */
  208. @serialize()
  209. public interaxialDistance: number;
  210. /**
  211. * Defines if stereoscopic rendering is done side by side or over under.
  212. */
  213. @serialize()
  214. public isStereoscopicSideBySide: boolean;
  215. /**
  216. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  217. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  218. * else in the scene. (Eg. security camera)
  219. *
  220. * To change the final output target of the camera, camera.outputRenderTarget should be used instead (eg. webXR renders to a render target corrisponding to an HMD)
  221. */
  222. public customRenderTargets = new Array<RenderTargetTexture>();
  223. /**
  224. * When set, the camera will render to this render target instead of the default canvas
  225. *
  226. * If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead
  227. */
  228. public outputRenderTarget: Nullable<RenderTargetTexture> = null;
  229. /**
  230. * Observable triggered when the camera view matrix has changed.
  231. */
  232. public onViewMatrixChangedObservable = new Observable<Camera>();
  233. /**
  234. * Observable triggered when the camera Projection matrix has changed.
  235. */
  236. public onProjectionMatrixChangedObservable = new Observable<Camera>();
  237. /**
  238. * Observable triggered when the inputs have been processed.
  239. */
  240. public onAfterCheckInputsObservable = new Observable<Camera>();
  241. /**
  242. * Observable triggered when reset has been called and applied to the camera.
  243. */
  244. public onRestoreStateObservable = new Observable<Camera>();
  245. /**
  246. * Is this camera a part of a rig system?
  247. */
  248. public isRigCamera: boolean = false;
  249. /**
  250. * If isRigCamera set to true this will be set with the parent camera.
  251. * The parent camera is not (!) necessarily the .parent of this camera (like in the case of XR)
  252. */
  253. public rigParent?: Camera;
  254. /** @hidden */
  255. public _cameraRigParams: any;
  256. /** @hidden */
  257. public _rigCameras = new Array<Camera>();
  258. /** @hidden */
  259. public _rigPostProcess: Nullable<PostProcess>;
  260. protected _webvrViewMatrix = Matrix.Identity();
  261. /** @hidden */
  262. public _skipRendering = false;
  263. /** @hidden */
  264. public _projectionMatrix = new Matrix();
  265. /** @hidden */
  266. public _postProcesses = new Array<Nullable<PostProcess>>();
  267. /** @hidden */
  268. public _activeMeshes = new SmartArray<AbstractMesh>(256);
  269. protected _globalPosition = Vector3.Zero();
  270. /** @hidden */
  271. public _computedViewMatrix = Matrix.Identity();
  272. private _doNotComputeProjectionMatrix = false;
  273. private _transformMatrix = Matrix.Zero();
  274. private _frustumPlanes: Plane[];
  275. private _refreshFrustumPlanes = true;
  276. private _storedFov: number;
  277. private _stateStored: boolean;
  278. /**
  279. * Instantiates a new camera object.
  280. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  281. * @see https://doc.babylonjs.com/features/cameras
  282. * @param name Defines the name of the camera in the scene
  283. * @param position Defines the position of the camera
  284. * @param scene Defines the scene the camera belongs too
  285. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  286. */
  287. constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive = true) {
  288. super(name, scene);
  289. this.getScene().addCamera(this);
  290. if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) {
  291. this.getScene().activeCamera = this;
  292. }
  293. this.position = position;
  294. }
  295. /**
  296. * Store current camera state (fov, position, etc..)
  297. * @returns the camera
  298. */
  299. public storeState(): Camera {
  300. this._stateStored = true;
  301. this._storedFov = this.fov;
  302. return this;
  303. }
  304. /**
  305. * Restores the camera state values if it has been stored. You must call storeState() first
  306. */
  307. protected _restoreStateValues(): boolean {
  308. if (!this._stateStored) {
  309. return false;
  310. }
  311. this.fov = this._storedFov;
  312. return true;
  313. }
  314. /**
  315. * Restored camera state. You must call storeState() first.
  316. * @returns true if restored and false otherwise
  317. */
  318. public restoreState(): boolean {
  319. if (this._restoreStateValues()) {
  320. this.onRestoreStateObservable.notifyObservers(this);
  321. return true;
  322. }
  323. return false;
  324. }
  325. /**
  326. * Gets the class name of the camera.
  327. * @returns the class name
  328. */
  329. public getClassName(): string {
  330. return "Camera";
  331. }
  332. /** @hidden */
  333. public readonly _isCamera = true;
  334. /**
  335. * Gets a string representation of the camera useful for debug purpose.
  336. * @param fullDetails Defines that a more verboe level of logging is required
  337. * @returns the string representation
  338. */
  339. public toString(fullDetails?: boolean): string {
  340. var ret = "Name: " + this.name;
  341. ret += ", type: " + this.getClassName();
  342. if (this.animations) {
  343. for (var i = 0; i < this.animations.length; i++) {
  344. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  345. }
  346. }
  347. if (fullDetails) {
  348. }
  349. return ret;
  350. }
  351. /**
  352. * Gets the current world space position of the camera.
  353. */
  354. public get globalPosition(): Vector3 {
  355. return this._globalPosition;
  356. }
  357. /**
  358. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  359. * @returns the active meshe list
  360. */
  361. public getActiveMeshes(): SmartArray<AbstractMesh> {
  362. return this._activeMeshes;
  363. }
  364. /**
  365. * Check whether a mesh is part of the current active mesh list of the camera
  366. * @param mesh Defines the mesh to check
  367. * @returns true if active, false otherwise
  368. */
  369. public isActiveMesh(mesh: Mesh): boolean {
  370. return (this._activeMeshes.indexOf(mesh) !== -1);
  371. }
  372. /**
  373. * Is this camera ready to be used/rendered
  374. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  375. * @return true if the camera is ready
  376. */
  377. public isReady(completeCheck = false): boolean {
  378. if (completeCheck) {
  379. for (var pp of this._postProcesses) {
  380. if (pp && !pp.isReady()) {
  381. return false;
  382. }
  383. }
  384. }
  385. return super.isReady(completeCheck);
  386. }
  387. /** @hidden */
  388. public _initCache() {
  389. super._initCache();
  390. this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  391. this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  392. this._cache.mode = undefined;
  393. this._cache.minZ = undefined;
  394. this._cache.maxZ = undefined;
  395. this._cache.fov = undefined;
  396. this._cache.fovMode = undefined;
  397. this._cache.aspectRatio = undefined;
  398. this._cache.orthoLeft = undefined;
  399. this._cache.orthoRight = undefined;
  400. this._cache.orthoBottom = undefined;
  401. this._cache.orthoTop = undefined;
  402. this._cache.renderWidth = undefined;
  403. this._cache.renderHeight = undefined;
  404. }
  405. /** @hidden */
  406. public _updateCache(ignoreParentClass?: boolean): void {
  407. if (!ignoreParentClass) {
  408. super._updateCache();
  409. }
  410. this._cache.position.copyFrom(this.position);
  411. this._cache.upVector.copyFrom(this.upVector);
  412. }
  413. /** @hidden */
  414. public _isSynchronized(): boolean {
  415. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  416. }
  417. /** @hidden */
  418. public _isSynchronizedViewMatrix(): boolean {
  419. if (!super._isSynchronized()) {
  420. return false;
  421. }
  422. return this._cache.position.equals(this.position)
  423. && this._cache.upVector.equals(this.upVector)
  424. && this.isSynchronizedWithParent();
  425. }
  426. /** @hidden */
  427. public _isSynchronizedProjectionMatrix(): boolean {
  428. var check = this._cache.mode === this.mode
  429. && this._cache.minZ === this.minZ
  430. && this._cache.maxZ === this.maxZ;
  431. if (!check) {
  432. return false;
  433. }
  434. var engine = this.getEngine();
  435. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  436. check = this._cache.fov === this.fov
  437. && this._cache.fovMode === this.fovMode
  438. && this._cache.aspectRatio === engine.getAspectRatio(this);
  439. }
  440. else {
  441. check = this._cache.orthoLeft === this.orthoLeft
  442. && this._cache.orthoRight === this.orthoRight
  443. && this._cache.orthoBottom === this.orthoBottom
  444. && this._cache.orthoTop === this.orthoTop
  445. && this._cache.renderWidth === engine.getRenderWidth()
  446. && this._cache.renderHeight === engine.getRenderHeight();
  447. }
  448. return check;
  449. }
  450. /**
  451. * Attach the input controls to a specific dom element to get the input from.
  452. * @param element Defines the element the controls should be listened from
  453. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  454. */
  455. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  456. }
  457. /**
  458. * Detach the current controls from the specified dom element.
  459. * @param element Defines the element to stop listening the inputs from
  460. */
  461. public detachControl(element: HTMLElement): void {
  462. }
  463. /**
  464. * Update the camera state according to the different inputs gathered during the frame.
  465. */
  466. public update(): void {
  467. this._checkInputs();
  468. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  469. this._updateRigCameras();
  470. }
  471. }
  472. /** @hidden */
  473. public _checkInputs(): void {
  474. this.onAfterCheckInputsObservable.notifyObservers(this);
  475. }
  476. /** @hidden */
  477. public get rigCameras(): Camera[] {
  478. return this._rigCameras;
  479. }
  480. /**
  481. * Gets the post process used by the rig cameras
  482. */
  483. public get rigPostProcess(): Nullable<PostProcess> {
  484. return this._rigPostProcess;
  485. }
  486. /**
  487. * Internal, gets the first post proces.
  488. * @returns the first post process to be run on this camera.
  489. */
  490. public _getFirstPostProcess(): Nullable<PostProcess> {
  491. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  492. if (this._postProcesses[ppIndex] !== null) {
  493. return this._postProcesses[ppIndex];
  494. }
  495. }
  496. return null;
  497. }
  498. private _cascadePostProcessesToRigCams(): void {
  499. // invalidate framebuffer
  500. var firstPostProcess = this._getFirstPostProcess();
  501. if (firstPostProcess) {
  502. firstPostProcess.markTextureDirty();
  503. }
  504. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  505. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  506. var cam = this._rigCameras[i];
  507. var rigPostProcess = cam._rigPostProcess;
  508. // for VR rig, there does not have to be a post process
  509. if (rigPostProcess) {
  510. var isPass = rigPostProcess.getEffectName() === "pass";
  511. if (isPass) {
  512. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  513. cam.isIntermediate = this._postProcesses.length === 0;
  514. }
  515. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  516. rigPostProcess.markTextureDirty();
  517. } else {
  518. cam._postProcesses = this._postProcesses.slice(0);
  519. }
  520. }
  521. }
  522. /**
  523. * Attach a post process to the camera.
  524. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  525. * @param postProcess The post process to attach to the camera
  526. * @param insertAt The position of the post process in case several of them are in use in the scene
  527. * @returns the position the post process has been inserted at
  528. */
  529. public attachPostProcess(postProcess: PostProcess, insertAt: Nullable<number> = null): number {
  530. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  531. Logger.Error("You're trying to reuse a post process not defined as reusable.");
  532. return 0;
  533. }
  534. if (insertAt == null || insertAt < 0) {
  535. this._postProcesses.push(postProcess);
  536. } else if (this._postProcesses[insertAt] === null) {
  537. this._postProcesses[insertAt] = postProcess;
  538. } else {
  539. this._postProcesses.splice(insertAt, 0, postProcess);
  540. }
  541. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  542. return this._postProcesses.indexOf(postProcess);
  543. }
  544. /**
  545. * Detach a post process to the camera.
  546. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  547. * @param postProcess The post process to detach from the camera
  548. */
  549. public detachPostProcess(postProcess: PostProcess): void {
  550. var idx = this._postProcesses.indexOf(postProcess);
  551. if (idx !== -1) {
  552. this._postProcesses[idx] = null;
  553. }
  554. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  555. }
  556. /**
  557. * Gets the current world matrix of the camera
  558. */
  559. public getWorldMatrix(): Matrix {
  560. if (this._isSynchronizedViewMatrix()) {
  561. return this._worldMatrix;
  562. }
  563. // Getting the the view matrix will also compute the world matrix.
  564. this.getViewMatrix();
  565. return this._worldMatrix;
  566. }
  567. /** @hidden */
  568. public _getViewMatrix(): Matrix {
  569. return Matrix.Identity();
  570. }
  571. /**
  572. * Gets the current view matrix of the camera.
  573. * @param force forces the camera to recompute the matrix without looking at the cached state
  574. * @returns the view matrix
  575. */
  576. public getViewMatrix(force?: boolean): Matrix {
  577. if (!force && this._isSynchronizedViewMatrix()) {
  578. return this._computedViewMatrix;
  579. }
  580. this.updateCache();
  581. this._computedViewMatrix = this._getViewMatrix();
  582. this._currentRenderId = this.getScene().getRenderId();
  583. this._childUpdateId++;
  584. this._refreshFrustumPlanes = true;
  585. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  586. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  587. }
  588. // Notify parent camera if rig camera is changed
  589. if (this.parent && (this.parent as Camera).onViewMatrixChangedObservable) {
  590. (this.parent as Camera).onViewMatrixChangedObservable.notifyObservers((this.parent as Camera));
  591. }
  592. this.onViewMatrixChangedObservable.notifyObservers(this);
  593. this._computedViewMatrix.invertToRef(this._worldMatrix);
  594. return this._computedViewMatrix;
  595. }
  596. /**
  597. * Freeze the projection matrix.
  598. * It will prevent the cache check of the camera projection compute and can speed up perf
  599. * if no parameter of the camera are meant to change
  600. * @param projection Defines manually a projection if necessary
  601. */
  602. public freezeProjectionMatrix(projection?: Matrix): void {
  603. this._doNotComputeProjectionMatrix = true;
  604. if (projection !== undefined) {
  605. this._projectionMatrix = projection;
  606. }
  607. }
  608. /**
  609. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  610. */
  611. public unfreezeProjectionMatrix(): void {
  612. this._doNotComputeProjectionMatrix = false;
  613. }
  614. /**
  615. * Gets the current projection matrix of the camera.
  616. * @param force forces the camera to recompute the matrix without looking at the cached state
  617. * @returns the projection matrix
  618. */
  619. public getProjectionMatrix(force?: boolean): Matrix {
  620. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  621. return this._projectionMatrix;
  622. }
  623. // Cache
  624. this._cache.mode = this.mode;
  625. this._cache.minZ = this.minZ;
  626. this._cache.maxZ = this.maxZ;
  627. // Matrix
  628. this._refreshFrustumPlanes = true;
  629. var engine = this.getEngine();
  630. var scene = this.getScene();
  631. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  632. this._cache.fov = this.fov;
  633. this._cache.fovMode = this.fovMode;
  634. this._cache.aspectRatio = engine.getAspectRatio(this);
  635. if (this.minZ <= 0) {
  636. this.minZ = 0.1;
  637. }
  638. const reverseDepth = engine.useReverseDepthBuffer;
  639. let getProjectionMatrix: (fov: number, aspect: number, znear: number, zfar: number, result: Matrix, isVerticalFovFixed: boolean) => void;
  640. if (scene.useRightHandedSystem) {
  641. getProjectionMatrix = reverseDepth ? Matrix.PerspectiveFovReverseRHToRef : Matrix.PerspectiveFovRHToRef;
  642. } else {
  643. getProjectionMatrix = reverseDepth ? Matrix.PerspectiveFovReverseLHToRef : Matrix.PerspectiveFovLHToRef;
  644. }
  645. getProjectionMatrix(this.fov,
  646. engine.getAspectRatio(this),
  647. this.minZ,
  648. this.maxZ,
  649. this._projectionMatrix,
  650. this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  651. } else {
  652. var halfWidth = engine.getRenderWidth() / 2.0;
  653. var halfHeight = engine.getRenderHeight() / 2.0;
  654. if (scene.useRightHandedSystem) {
  655. Matrix.OrthoOffCenterRHToRef(this.orthoLeft ?? -halfWidth,
  656. this.orthoRight ?? halfWidth,
  657. this.orthoBottom ?? -halfHeight,
  658. this.orthoTop ?? halfHeight,
  659. this.minZ,
  660. this.maxZ,
  661. this._projectionMatrix);
  662. } else {
  663. Matrix.OrthoOffCenterLHToRef(this.orthoLeft ?? -halfWidth,
  664. this.orthoRight ?? halfWidth,
  665. this.orthoBottom ?? -halfHeight,
  666. this.orthoTop ?? halfHeight,
  667. this.minZ,
  668. this.maxZ,
  669. this._projectionMatrix);
  670. }
  671. this._cache.orthoLeft = this.orthoLeft;
  672. this._cache.orthoRight = this.orthoRight;
  673. this._cache.orthoBottom = this.orthoBottom;
  674. this._cache.orthoTop = this.orthoTop;
  675. this._cache.renderWidth = engine.getRenderWidth();
  676. this._cache.renderHeight = engine.getRenderHeight();
  677. }
  678. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  679. return this._projectionMatrix;
  680. }
  681. /**
  682. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  683. * @returns a Matrix
  684. */
  685. public getTransformationMatrix(): Matrix {
  686. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  687. return this._transformMatrix;
  688. }
  689. private _updateFrustumPlanes(): void {
  690. if (!this._refreshFrustumPlanes) {
  691. return;
  692. }
  693. this.getTransformationMatrix();
  694. if (!this._frustumPlanes) {
  695. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  696. } else {
  697. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  698. }
  699. this._refreshFrustumPlanes = false;
  700. }
  701. /**
  702. * Checks if a cullable object (mesh...) is in the camera frustum
  703. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  704. * @param target The object to check
  705. * @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false)
  706. * @returns true if the object is in frustum otherwise false
  707. */
  708. public isInFrustum(target: ICullable, checkRigCameras = false): boolean {
  709. this._updateFrustumPlanes();
  710. if (checkRigCameras && this.rigCameras.length > 0) {
  711. var result = false;
  712. this.rigCameras.forEach((cam) => {
  713. cam._updateFrustumPlanes();
  714. result = result || target.isInFrustum(cam._frustumPlanes);
  715. });
  716. return result;
  717. } else {
  718. return target.isInFrustum(this._frustumPlanes);
  719. }
  720. }
  721. /**
  722. * Checks if a cullable object (mesh...) is in the camera frustum
  723. * Unlike isInFrustum this cheks the full bounding box
  724. * @param target The object to check
  725. * @returns true if the object is in frustum otherwise false
  726. */
  727. public isCompletelyInFrustum(target: ICullable): boolean {
  728. this._updateFrustumPlanes();
  729. return target.isCompletelyInFrustum(this._frustumPlanes);
  730. }
  731. /**
  732. * Gets a ray in the forward direction from the camera.
  733. * @param length Defines the length of the ray to create
  734. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  735. * @param origin Defines the start point of the ray which defaults to the camera position
  736. * @returns the forward ray
  737. */
  738. public getForwardRay(length = 100, transform?: Matrix, origin?: Vector3): Ray {
  739. throw _DevTools.WarnImport("Ray");
  740. }
  741. /**
  742. * Gets a ray in the forward direction from the camera.
  743. * @param refRay the ray to (re)use when setting the values
  744. * @param length Defines the length of the ray to create
  745. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  746. * @param origin Defines the start point of the ray which defaults to the camera position
  747. * @returns the forward ray
  748. */
  749. public getForwardRayToRef(refRay: Ray, length = 100, transform?: Matrix, origin?: Vector3): Ray {
  750. throw _DevTools.WarnImport("Ray");
  751. }
  752. /**
  753. * Releases resources associated with this node.
  754. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  755. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  756. */
  757. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  758. // Observables
  759. this.onViewMatrixChangedObservable.clear();
  760. this.onProjectionMatrixChangedObservable.clear();
  761. this.onAfterCheckInputsObservable.clear();
  762. this.onRestoreStateObservable.clear();
  763. // Inputs
  764. if (this.inputs) {
  765. this.inputs.clear();
  766. }
  767. // Animations
  768. this.getScene().stopAnimation(this);
  769. // Remove from scene
  770. this.getScene().removeCamera(this);
  771. while (this._rigCameras.length > 0) {
  772. let camera = this._rigCameras.pop();
  773. if (camera) {
  774. camera.dispose();
  775. }
  776. }
  777. // Postprocesses
  778. if (this._rigPostProcess) {
  779. this._rigPostProcess.dispose(this);
  780. this._rigPostProcess = null;
  781. this._postProcesses = [];
  782. }
  783. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  784. this._rigPostProcess = null;
  785. this._postProcesses = [];
  786. } else {
  787. var i = this._postProcesses.length;
  788. while (--i >= 0) {
  789. var postProcess = this._postProcesses[i];
  790. if (postProcess) {
  791. postProcess.dispose(this);
  792. }
  793. }
  794. }
  795. // Render targets
  796. var i = this.customRenderTargets.length;
  797. while (--i >= 0) {
  798. this.customRenderTargets[i].dispose();
  799. }
  800. this.customRenderTargets = [];
  801. // Active Meshes
  802. this._activeMeshes.dispose();
  803. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  804. }
  805. /** @hidden */
  806. public _isLeftCamera = false;
  807. /**
  808. * Gets the left camera of a rig setup in case of Rigged Camera
  809. */
  810. public get isLeftCamera(): boolean {
  811. return this._isLeftCamera;
  812. }
  813. /** @hidden */
  814. public _isRightCamera = false;
  815. /**
  816. * Gets the right camera of a rig setup in case of Rigged Camera
  817. */
  818. public get isRightCamera(): boolean {
  819. return this._isRightCamera;
  820. }
  821. /**
  822. * Gets the left camera of a rig setup in case of Rigged Camera
  823. */
  824. public get leftCamera(): Nullable<FreeCamera> {
  825. if (this._rigCameras.length < 1) {
  826. return null;
  827. }
  828. return (<FreeCamera>this._rigCameras[0]);
  829. }
  830. /**
  831. * Gets the right camera of a rig setup in case of Rigged Camera
  832. */
  833. public get rightCamera(): Nullable<FreeCamera> {
  834. if (this._rigCameras.length < 2) {
  835. return null;
  836. }
  837. return (<FreeCamera>this._rigCameras[1]);
  838. }
  839. /**
  840. * Gets the left camera target of a rig setup in case of Rigged Camera
  841. * @returns the target position
  842. */
  843. public getLeftTarget(): Nullable<Vector3> {
  844. if (this._rigCameras.length < 1) {
  845. return null;
  846. }
  847. return (<TargetCamera>this._rigCameras[0]).getTarget();
  848. }
  849. /**
  850. * Gets the right camera target of a rig setup in case of Rigged Camera
  851. * @returns the target position
  852. */
  853. public getRightTarget(): Nullable<Vector3> {
  854. if (this._rigCameras.length < 2) {
  855. return null;
  856. }
  857. return (<TargetCamera>this._rigCameras[1]).getTarget();
  858. }
  859. /**
  860. * @hidden
  861. */
  862. public setCameraRigMode(mode: number, rigParams: any): void {
  863. if (this.cameraRigMode === mode) {
  864. return;
  865. }
  866. while (this._rigCameras.length > 0) {
  867. let camera = this._rigCameras.pop();
  868. if (camera) {
  869. camera.dispose();
  870. }
  871. }
  872. this.cameraRigMode = mode;
  873. this._cameraRigParams = {};
  874. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  875. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  876. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  877. this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  878. // create the rig cameras, unless none
  879. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  880. let leftCamera = this.createRigCamera(this.name + "_L", 0);
  881. if (leftCamera) {
  882. leftCamera._isLeftCamera = true;
  883. }
  884. let rightCamera = this.createRigCamera(this.name + "_R", 1);
  885. if (rightCamera) {
  886. rightCamera._isRightCamera = true;
  887. }
  888. if (leftCamera && rightCamera) {
  889. this._rigCameras.push(leftCamera);
  890. this._rigCameras.push(rightCamera);
  891. }
  892. }
  893. switch (this.cameraRigMode) {
  894. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  895. Camera._setStereoscopicAnaglyphRigMode(this);
  896. break;
  897. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  898. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  899. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  900. case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:
  901. Camera._setStereoscopicRigMode(this);
  902. break;
  903. case Camera.RIG_MODE_VR:
  904. Camera._setVRRigMode(this, rigParams);
  905. break;
  906. case Camera.RIG_MODE_WEBVR:
  907. Camera._setWebVRRigMode(this, rigParams);
  908. break;
  909. }
  910. this._cascadePostProcessesToRigCams();
  911. this.update();
  912. }
  913. /** @hidden */
  914. public static _setStereoscopicRigMode(camera: Camera) {
  915. throw "Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode";
  916. }
  917. /** @hidden */
  918. public static _setStereoscopicAnaglyphRigMode(camera: Camera) {
  919. throw "Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode";
  920. }
  921. /** @hidden */
  922. public static _setVRRigMode(camera: Camera, rigParams: any) {
  923. throw "Import Cameras/RigModes/vrRigMode before using VR rig mode";
  924. }
  925. /** @hidden */
  926. public static _setWebVRRigMode(camera: Camera, rigParams: any) {
  927. throw "Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode";
  928. }
  929. /** @hidden */
  930. public _getVRProjectionMatrix(): Matrix {
  931. Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  932. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  933. return this._projectionMatrix;
  934. }
  935. protected _updateCameraRotationMatrix() {
  936. //Here for WebVR
  937. }
  938. protected _updateWebVRCameraRotationMatrix() {
  939. //Here for WebVR
  940. }
  941. /**
  942. * This function MUST be overwritten by the different WebVR cameras available.
  943. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  944. * @hidden
  945. */
  946. public _getWebVRProjectionMatrix(): Matrix {
  947. return Matrix.Identity();
  948. }
  949. /**
  950. * This function MUST be overwritten by the different WebVR cameras available.
  951. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  952. * @hidden
  953. */
  954. public _getWebVRViewMatrix(): Matrix {
  955. return Matrix.Identity();
  956. }
  957. /** @hidden */
  958. public setCameraRigParameter(name: string, value: any) {
  959. if (!this._cameraRigParams) {
  960. this._cameraRigParams = {};
  961. }
  962. this._cameraRigParams[name] = value;
  963. //provisionnally:
  964. if (name === "interaxialDistance") {
  965. this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637);
  966. }
  967. }
  968. /**
  969. * needs to be overridden by children so sub has required properties to be copied
  970. * @hidden
  971. */
  972. public createRigCamera(name: string, cameraIndex: number): Nullable<Camera> {
  973. return null;
  974. }
  975. /**
  976. * May need to be overridden by children
  977. * @hidden
  978. */
  979. public _updateRigCameras() {
  980. for (var i = 0; i < this._rigCameras.length; i++) {
  981. this._rigCameras[i].minZ = this.minZ;
  982. this._rigCameras[i].maxZ = this.maxZ;
  983. this._rigCameras[i].fov = this.fov;
  984. this._rigCameras[i].upVector.copyFrom(this.upVector);
  985. }
  986. // only update viewport when ANAGLYPH
  987. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  988. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  989. }
  990. }
  991. /** @hidden */
  992. public _setupInputs() {
  993. }
  994. /**
  995. * Serialiaze the camera setup to a json represention
  996. * @returns the JSON representation
  997. */
  998. public serialize(): any {
  999. var serializationObject = SerializationHelper.Serialize(this);
  1000. // Type
  1001. serializationObject.type = this.getClassName();
  1002. // Parent
  1003. if (this.parent) {
  1004. serializationObject.parentId = this.parent.id;
  1005. }
  1006. if (this.inputs) {
  1007. this.inputs.serialize(serializationObject);
  1008. }
  1009. // Animations
  1010. SerializationHelper.AppendSerializedAnimations(this, serializationObject);
  1011. serializationObject.ranges = this.serializeAnimationRanges();
  1012. return serializationObject;
  1013. }
  1014. /**
  1015. * Clones the current camera.
  1016. * @param name The cloned camera name
  1017. * @returns the cloned camera
  1018. */
  1019. public clone(name: string): Camera {
  1020. return SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  1021. }
  1022. /**
  1023. * Gets the direction of the camera relative to a given local axis.
  1024. * @param localAxis Defines the reference axis to provide a relative direction.
  1025. * @return the direction
  1026. */
  1027. public getDirection(localAxis: Vector3): Vector3 {
  1028. var result = Vector3.Zero();
  1029. this.getDirectionToRef(localAxis, result);
  1030. return result;
  1031. }
  1032. /**
  1033. * Returns the current camera absolute rotation
  1034. */
  1035. public get absoluteRotation(): Quaternion {
  1036. var result = Quaternion.Zero();
  1037. this.getWorldMatrix().decompose(undefined, result);
  1038. return result;
  1039. }
  1040. /**
  1041. * Gets the direction of the camera relative to a given local axis into a passed vector.
  1042. * @param localAxis Defines the reference axis to provide a relative direction.
  1043. * @param result Defines the vector to store the result in
  1044. */
  1045. public getDirectionToRef(localAxis: Vector3, result: Vector3): void {
  1046. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  1047. }
  1048. /**
  1049. * Gets a camera constructor for a given camera type
  1050. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  1051. * @param name The name of the camera the result will be able to instantiate
  1052. * @param scene The scene the result will construct the camera in
  1053. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  1054. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  1055. * @returns a factory method to construc the camera
  1056. */
  1057. static GetConstructorFromName(type: string, name: string, scene: Scene, interaxial_distance: number = 0, isStereoscopicSideBySide: boolean = true): () => Camera {
  1058. let constructorFunc = Node.Construct(type, name, scene, {
  1059. interaxial_distance: interaxial_distance,
  1060. isStereoscopicSideBySide: isStereoscopicSideBySide
  1061. });
  1062. if (constructorFunc) {
  1063. return <() => Camera>constructorFunc;
  1064. }
  1065. // Default to universal camera
  1066. return () => Camera._createDefaultParsedCamera(name, scene);
  1067. }
  1068. /**
  1069. * Compute the world matrix of the camera.
  1070. * @returns the camera world matrix
  1071. */
  1072. public computeWorldMatrix(): Matrix {
  1073. return this.getWorldMatrix();
  1074. }
  1075. /**
  1076. * Parse a JSON and creates the camera from the parsed information
  1077. * @param parsedCamera The JSON to parse
  1078. * @param scene The scene to instantiate the camera in
  1079. * @returns the newly constructed camera
  1080. */
  1081. public static Parse(parsedCamera: any, scene: Scene): Camera {
  1082. var type = parsedCamera.type;
  1083. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  1084. var camera = SerializationHelper.Parse(construct, parsedCamera, scene);
  1085. // Parent
  1086. if (parsedCamera.parentId) {
  1087. camera._waitingParentId = parsedCamera.parentId;
  1088. }
  1089. //If camera has an input manager, let it parse inputs settings
  1090. if (camera.inputs) {
  1091. camera.inputs.parse(parsedCamera);
  1092. camera._setupInputs();
  1093. }
  1094. if ((<any>camera).setPosition) { // need to force position
  1095. camera.position.copyFromFloats(0, 0, 0);
  1096. (<any>camera).setPosition(Vector3.FromArray(parsedCamera.position));
  1097. }
  1098. // Target
  1099. if (parsedCamera.target) {
  1100. if ((<any>camera).setTarget) {
  1101. (<any>camera).setTarget(Vector3.FromArray(parsedCamera.target));
  1102. }
  1103. }
  1104. // Apply 3d rig, when found
  1105. if (parsedCamera.cameraRigMode) {
  1106. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  1107. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  1108. }
  1109. // Animations
  1110. if (parsedCamera.animations) {
  1111. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  1112. var parsedAnimation = parsedCamera.animations[animationIndex];
  1113. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  1114. if (internalClass) {
  1115. camera.animations.push(internalClass.Parse(parsedAnimation));
  1116. }
  1117. }
  1118. Node.ParseAnimationRanges(camera, parsedCamera, scene);
  1119. }
  1120. if (parsedCamera.autoAnimate) {
  1121. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  1122. }
  1123. return camera;
  1124. }
  1125. }