arcRotateCamera.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. Node.AddNodeConstructor("ArcRotateCamera", (name, scene) => {
  2. return () => new ArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene);
  3. });
  4. /**
  5. * This represents an orbital type of camera.
  6. *
  7. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  8. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  9. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  10. */
  11. export class ArcRotateCamera extends TargetCamera {
  12. /**
  13. * Defines the rotation angle of the camera along the longitudinal axis.
  14. */
  15. @serialize()
  16. public alpha: number;
  17. /**
  18. * Defines the rotation angle of the camera along the latitudinal axis.
  19. */
  20. @serialize()
  21. public beta: number;
  22. /**
  23. * Defines the radius of the camera from it s target point.
  24. */
  25. @serialize()
  26. public radius: number;
  27. @serializeAsVector3("target")
  28. protected _target: Vector3;
  29. protected _targetHost: Nullable<AbstractMesh>;
  30. /**
  31. * Defines the target point of the camera.
  32. * The camera looks towards it form the radius distance.
  33. */
  34. public get target(): Vector3 {
  35. return this._target;
  36. }
  37. public set target(value: Vector3) {
  38. this.setTarget(value);
  39. }
  40. /**
  41. * Current inertia value on the longitudinal axis.
  42. * The bigger this number the longer it will take for the camera to stop.
  43. */
  44. @serialize()
  45. public inertialAlphaOffset = 0;
  46. /**
  47. * Current inertia value on the latitudinal axis.
  48. * The bigger this number the longer it will take for the camera to stop.
  49. */
  50. @serialize()
  51. public inertialBetaOffset = 0;
  52. /**
  53. * Current inertia value on the radius axis.
  54. * The bigger this number the longer it will take for the camera to stop.
  55. */
  56. @serialize()
  57. public inertialRadiusOffset = 0;
  58. /**
  59. * Minimum allowed angle on the longitudinal axis.
  60. * This can help limiting how the Camera is able to move in the scene.
  61. */
  62. @serialize()
  63. public lowerAlphaLimit: Nullable<number> = null;
  64. /**
  65. * Maximum allowed angle on the longitudinal axis.
  66. * This can help limiting how the Camera is able to move in the scene.
  67. */
  68. @serialize()
  69. public upperAlphaLimit: Nullable<number> = null;
  70. /**
  71. * Minimum allowed angle on the latitudinal axis.
  72. * This can help limiting how the Camera is able to move in the scene.
  73. */
  74. @serialize()
  75. public lowerBetaLimit = 0.01;
  76. /**
  77. * Maximum allowed angle on the latitudinal axis.
  78. * This can help limiting how the Camera is able to move in the scene.
  79. */
  80. @serialize()
  81. public upperBetaLimit = Math.PI;
  82. /**
  83. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  84. * This can help limiting how the Camera is able to move in the scene.
  85. */
  86. @serialize()
  87. public lowerRadiusLimit: Nullable<number> = null;
  88. /**
  89. * Maximum allowed distance of the camera to the target (The camera can not get further).
  90. * This can help limiting how the Camera is able to move in the scene.
  91. */
  92. @serialize()
  93. public upperRadiusLimit: Nullable<number> = null;
  94. /**
  95. * Defines the current inertia value used during panning of the camera along the X axis.
  96. */
  97. @serialize()
  98. public inertialPanningX: number = 0;
  99. /**
  100. * Defines the current inertia value used during panning of the camera along the Y axis.
  101. */
  102. @serialize()
  103. public inertialPanningY: number = 0;
  104. /**
  105. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  106. * Basically if your fingers moves away from more than this distance you will be considered
  107. * in pinch mode.
  108. */
  109. @serialize()
  110. public pinchToPanMaxDistance: number = 20;
  111. /**
  112. * Defines the maximum distance the camera can pan.
  113. * This could help keeping the cammera always in your scene.
  114. */
  115. @serialize()
  116. public panningDistanceLimit: Nullable<number> = null;
  117. /**
  118. * Defines the target of the camera before paning.
  119. */
  120. @serializeAsVector3()
  121. public panningOriginTarget: Vector3 = Vector3.Zero();
  122. /**
  123. * Defines the value of the inertia used during panning.
  124. * 0 would mean stop inertia and one would mean no decelleration at all.
  125. */
  126. @serialize()
  127. public panningInertia = 0.9;
  128. //-- begin properties for backward compatibility for inputs
  129. /**
  130. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  131. */
  132. public get angularSensibilityX(): number {
  133. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  134. if (pointers) {
  135. return pointers.angularSensibilityX;
  136. }
  137. return 0;
  138. }
  139. public set angularSensibilityX(value: number) {
  140. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  141. if (pointers) {
  142. pointers.angularSensibilityX = value;
  143. }
  144. }
  145. /**
  146. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  147. */
  148. public get angularSensibilityY(): number {
  149. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  150. if (pointers) {
  151. return pointers.angularSensibilityY;
  152. }
  153. return 0;
  154. }
  155. public set angularSensibilityY(value: number) {
  156. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  157. if (pointers) {
  158. pointers.angularSensibilityY = value;
  159. }
  160. }
  161. /**
  162. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  163. */
  164. public get pinchPrecision(): number {
  165. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  166. if (pointers) {
  167. return pointers.pinchPrecision;
  168. }
  169. return 0;
  170. }
  171. public set pinchPrecision(value: number) {
  172. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  173. if (pointers) {
  174. pointers.pinchPrecision = value;
  175. }
  176. }
  177. /**
  178. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  179. * It will be used instead of pinchDeltaPrecision if different from 0.
  180. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  181. */
  182. public get pinchDeltaPercentage(): number {
  183. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  184. if (pointers) {
  185. return pointers.pinchDeltaPercentage;
  186. }
  187. return 0;
  188. }
  189. public set pinchDeltaPercentage(value: number) {
  190. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  191. if (pointers) {
  192. pointers.pinchDeltaPercentage = value;
  193. }
  194. }
  195. /**
  196. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  197. */
  198. public get panningSensibility(): number {
  199. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  200. if (pointers) {
  201. return pointers.panningSensibility;
  202. }
  203. return 0;
  204. }
  205. public set panningSensibility(value: number) {
  206. var pointers = <ArcRotateCameraPointersInput>this.inputs.attached["pointers"];
  207. if (pointers) {
  208. pointers.panningSensibility = value;
  209. }
  210. }
  211. /**
  212. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  213. */
  214. public get keysUp(): number[] {
  215. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  216. if (keyboard) {
  217. return keyboard.keysUp;
  218. }
  219. return [];
  220. }
  221. public set keysUp(value: number[]) {
  222. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  223. if (keyboard) {
  224. keyboard.keysUp = value;
  225. }
  226. }
  227. /**
  228. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  229. */
  230. public get keysDown(): number[] {
  231. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  232. if (keyboard) {
  233. return keyboard.keysDown;
  234. }
  235. return [];
  236. }
  237. public set keysDown(value: number[]) {
  238. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  239. if (keyboard) {
  240. keyboard.keysDown = value;
  241. }
  242. }
  243. /**
  244. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  245. */
  246. public get keysLeft(): number[] {
  247. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  248. if (keyboard) {
  249. return keyboard.keysLeft;
  250. }
  251. return [];
  252. }
  253. public set keysLeft(value: number[]) {
  254. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  255. if (keyboard) {
  256. keyboard.keysLeft = value;
  257. }
  258. }
  259. /**
  260. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  261. */
  262. public get keysRight(): number[] {
  263. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  264. if (keyboard) {
  265. return keyboard.keysRight;
  266. }
  267. return [];
  268. }
  269. public set keysRight(value: number[]) {
  270. var keyboard = <ArcRotateCameraKeyboardMoveInput>this.inputs.attached["keyboard"];
  271. if (keyboard) {
  272. keyboard.keysRight = value;
  273. }
  274. }
  275. /**
  276. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  277. */
  278. public get wheelPrecision(): number {
  279. var mousewheel = <ArcRotateCameraMouseWheelInput>this.inputs.attached["mousewheel"];
  280. if (mousewheel) {
  281. return mousewheel.wheelPrecision;
  282. }
  283. return 0;
  284. }
  285. public set wheelPrecision(value: number) {
  286. var mousewheel = <ArcRotateCameraMouseWheelInput>this.inputs.attached["mousewheel"];
  287. if (mousewheel) {
  288. mousewheel.wheelPrecision = value;
  289. }
  290. }
  291. /**
  292. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  293. * It will be used instead of pinchDeltaPrecision if different from 0.
  294. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  295. */
  296. public get wheelDeltaPercentage(): number {
  297. var mousewheel = <ArcRotateCameraMouseWheelInput>this.inputs.attached["mousewheel"];
  298. if (mousewheel) {
  299. return mousewheel.wheelDeltaPercentage;
  300. }
  301. return 0;
  302. }
  303. public set wheelDeltaPercentage(value: number) {
  304. var mousewheel = <ArcRotateCameraMouseWheelInput>this.inputs.attached["mousewheel"];
  305. if (mousewheel) {
  306. mousewheel.wheelDeltaPercentage = value;
  307. }
  308. }
  309. //-- end properties for backward compatibility for inputs
  310. /**
  311. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  312. */
  313. @serialize()
  314. public zoomOnFactor = 1;
  315. /**
  316. * Defines a screen offset for the camera position.
  317. */
  318. @serialize()
  319. public targetScreenOffset = Vector2.Zero();
  320. /**
  321. * Allows the camera to be completely reversed.
  322. * If false the camera can not arrive upside down.
  323. */
  324. @serialize()
  325. public allowUpsideDown = true;
  326. /**
  327. * Define if double tap/click is used to restore the previously saved state of the camera.
  328. */
  329. @serialize()
  330. public useInputToRestoreState = true;
  331. /** @hidden */
  332. public _viewMatrix = new Matrix();
  333. /** @hidden */
  334. public _useCtrlForPanning: boolean;
  335. /** @hidden */
  336. public _panningMouseButton: number;
  337. /**
  338. * Defines the inpute associated to the camera.
  339. */
  340. public inputs: ArcRotateCameraInputsManager;
  341. /** @hidden */
  342. public _reset: () => void;
  343. /**
  344. * Defines the allowed panning axis.
  345. */
  346. public panningAxis: Vector3 = new Vector3(1, 1, 0);
  347. protected _localDirection: Vector3;
  348. protected _transformedDirection: Vector3;
  349. // Behaviors
  350. private _bouncingBehavior: Nullable<BouncingBehavior>;
  351. /**
  352. * Gets the bouncing behavior of the camera if it has been enabled.
  353. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  354. */
  355. public get bouncingBehavior(): Nullable<BouncingBehavior> {
  356. return this._bouncingBehavior;
  357. }
  358. /**
  359. * Defines if the bouncing behavior of the camera is enabled on the camera.
  360. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  361. */
  362. public get useBouncingBehavior(): boolean {
  363. return this._bouncingBehavior != null;
  364. }
  365. public set useBouncingBehavior(value: boolean) {
  366. if (value === this.useBouncingBehavior) {
  367. return;
  368. }
  369. if (value) {
  370. this._bouncingBehavior = new BouncingBehavior();
  371. this.addBehavior(this._bouncingBehavior);
  372. } else if (this._bouncingBehavior) {
  373. this.removeBehavior(this._bouncingBehavior);
  374. this._bouncingBehavior = null;
  375. }
  376. }
  377. private _framingBehavior: Nullable<FramingBehavior>;
  378. /**
  379. * Gets the framing behavior of the camera if it has been enabled.
  380. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  381. */
  382. public get framingBehavior(): Nullable<FramingBehavior> {
  383. return this._framingBehavior;
  384. }
  385. /**
  386. * Defines if the framing behavior of the camera is enabled on the camera.
  387. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  388. */
  389. public get useFramingBehavior(): boolean {
  390. return this._framingBehavior != null;
  391. }
  392. public set useFramingBehavior(value: boolean) {
  393. if (value === this.useFramingBehavior) {
  394. return;
  395. }
  396. if (value) {
  397. this._framingBehavior = new FramingBehavior();
  398. this.addBehavior(this._framingBehavior);
  399. } else if (this._framingBehavior) {
  400. this.removeBehavior(this._framingBehavior);
  401. this._framingBehavior = null;
  402. }
  403. }
  404. private _autoRotationBehavior: Nullable<AutoRotationBehavior>;
  405. /**
  406. * Gets the auto rotation behavior of the camera if it has been enabled.
  407. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  408. */
  409. public get autoRotationBehavior(): Nullable<AutoRotationBehavior> {
  410. return this._autoRotationBehavior;
  411. }
  412. /**
  413. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  414. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  415. */
  416. public get useAutoRotationBehavior(): boolean {
  417. return this._autoRotationBehavior != null;
  418. }
  419. public set useAutoRotationBehavior(value: boolean) {
  420. if (value === this.useAutoRotationBehavior) {
  421. return;
  422. }
  423. if (value) {
  424. this._autoRotationBehavior = new AutoRotationBehavior();
  425. this.addBehavior(this._autoRotationBehavior);
  426. } else if (this._autoRotationBehavior) {
  427. this.removeBehavior(this._autoRotationBehavior);
  428. this._autoRotationBehavior = null;
  429. }
  430. }
  431. /**
  432. * Observable triggered when the mesh target has been changed on the camera.
  433. */
  434. public onMeshTargetChangedObservable = new Observable<Nullable<AbstractMesh>>();
  435. /**
  436. * Event raised when the camera is colliding with a mesh.
  437. */
  438. public onCollide: (collidedMesh: AbstractMesh) => void;
  439. /**
  440. * Defines whether the camera should check collision with the objects oh the scene.
  441. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  442. */
  443. public checkCollisions = false;
  444. /**
  445. * Defines the collision radius of the camera.
  446. * This simulates a sphere around the camera.
  447. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  448. */
  449. public collisionRadius = new Vector3(0.5, 0.5, 0.5);
  450. protected _collider: Collider;
  451. protected _previousPosition = Vector3.Zero();
  452. protected _collisionVelocity = Vector3.Zero();
  453. protected _newPosition = Vector3.Zero();
  454. protected _previousAlpha: number;
  455. protected _previousBeta: number;
  456. protected _previousRadius: number;
  457. //due to async collision inspection
  458. protected _collisionTriggered: boolean;
  459. protected _targetBoundingCenter: Nullable<Vector3>;
  460. private _computationVector: Vector3 = Vector3.Zero();
  461. /**
  462. * Instantiates a new ArcRotateCamera in a given scene
  463. * @param name Defines the name of the camera
  464. * @param alpha Defines the camera rotation along the logitudinal axis
  465. * @param beta Defines the camera rotation along the latitudinal axis
  466. * @param radius Defines the camera distance from its target
  467. * @param target Defines the camera target
  468. * @param scene Defines the scene the camera belongs to
  469. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  470. */
  471. constructor(name: string, alpha: number, beta: number, radius: number, target: Vector3, scene: Scene, setActiveOnSceneIfNoneActive = true) {
  472. super(name, Vector3.Zero(), scene, setActiveOnSceneIfNoneActive);
  473. this._target = Vector3.Zero();
  474. if (target) {
  475. this.setTarget(target);
  476. }
  477. this.alpha = alpha;
  478. this.beta = beta;
  479. this.radius = radius;
  480. this.getViewMatrix();
  481. this.inputs = new ArcRotateCameraInputsManager(this);
  482. this.inputs.addKeyboard().addMouseWheel().addPointers();
  483. }
  484. // Cache
  485. /** @hidden */
  486. public _initCache(): void {
  487. super._initCache();
  488. this._cache._target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  489. this._cache.alpha = undefined;
  490. this._cache.beta = undefined;
  491. this._cache.radius = undefined;
  492. this._cache.targetScreenOffset = Vector2.Zero();
  493. }
  494. /** @hidden */
  495. public _updateCache(ignoreParentClass?: boolean): void {
  496. if (!ignoreParentClass) {
  497. super._updateCache();
  498. }
  499. this._cache._target.copyFrom(this._getTargetPosition());
  500. this._cache.alpha = this.alpha;
  501. this._cache.beta = this.beta;
  502. this._cache.radius = this.radius;
  503. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  504. }
  505. protected _getTargetPosition(): Vector3 {
  506. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  507. var pos: Vector3 = this._targetHost.absolutePosition;
  508. if (this._targetBoundingCenter) {
  509. pos.addToRef(this._targetBoundingCenter, this._target);
  510. } else {
  511. this._target.copyFrom(pos);
  512. }
  513. }
  514. var lockedTargetPosition = this._getLockedTargetPosition();
  515. if (lockedTargetPosition) {
  516. return lockedTargetPosition;
  517. }
  518. return this._target;
  519. }
  520. private _storedAlpha: number;
  521. private _storedBeta: number;
  522. private _storedRadius: number;
  523. private _storedTarget: Vector3;
  524. /**
  525. * Stores the current state of the camera (alpha, beta, radius and target)
  526. * @returns the camera itself
  527. */
  528. public storeState(): Camera {
  529. this._storedAlpha = this.alpha;
  530. this._storedBeta = this.beta;
  531. this._storedRadius = this.radius;
  532. this._storedTarget = this._getTargetPosition().clone();
  533. return super.storeState();
  534. }
  535. /**
  536. * @hidden
  537. * Restored camera state. You must call storeState() first
  538. */
  539. public _restoreStateValues(): boolean {
  540. if (!super._restoreStateValues()) {
  541. return false;
  542. }
  543. this.alpha = this._storedAlpha;
  544. this.beta = this._storedBeta;
  545. this.radius = this._storedRadius;
  546. this.setTarget(this._storedTarget.clone());
  547. this.inertialAlphaOffset = 0;
  548. this.inertialBetaOffset = 0;
  549. this.inertialRadiusOffset = 0;
  550. this.inertialPanningX = 0;
  551. this.inertialPanningY = 0;
  552. return true;
  553. }
  554. // Synchronized
  555. /** @hidden */
  556. public _isSynchronizedViewMatrix(): boolean {
  557. if (!super._isSynchronizedViewMatrix()) {
  558. return false;
  559. }
  560. return this._cache._target.equals(this._getTargetPosition())
  561. && this._cache.alpha === this.alpha
  562. && this._cache.beta === this.beta
  563. && this._cache.radius === this.radius
  564. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  565. }
  566. /**
  567. * Attached controls to the current camera.
  568. * @param element Defines the element the controls should be listened from
  569. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  570. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  571. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  572. */
  573. public attachControl(element: HTMLElement, noPreventDefault?: boolean, useCtrlForPanning: boolean = true, panningMouseButton: number = 2): void {
  574. this._useCtrlForPanning = useCtrlForPanning;
  575. this._panningMouseButton = panningMouseButton;
  576. this.inputs.attachElement(element, noPreventDefault);
  577. this._reset = () => {
  578. this.inertialAlphaOffset = 0;
  579. this.inertialBetaOffset = 0;
  580. this.inertialRadiusOffset = 0;
  581. this.inertialPanningX = 0;
  582. this.inertialPanningY = 0;
  583. };
  584. }
  585. /**
  586. * Detach the current controls from the camera.
  587. * The camera will stop reacting to inputs.
  588. * @param element Defines the element to stop listening the inputs from
  589. */
  590. public detachControl(element: HTMLElement): void {
  591. this.inputs.detachElement(element);
  592. if (this._reset) {
  593. this._reset();
  594. }
  595. }
  596. /** @hidden */
  597. public _checkInputs(): void {
  598. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  599. if (this._collisionTriggered) {
  600. return;
  601. }
  602. this.inputs.checkInputs();
  603. // Inertia
  604. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  605. let inertialAlphaOffset = this.inertialAlphaOffset;
  606. if (this.beta <= 0) { inertialAlphaOffset *= -1; }
  607. if (this.getScene().useRightHandedSystem) { inertialAlphaOffset *= -1; }
  608. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) { inertialAlphaOffset *= -1; }
  609. this.alpha += inertialAlphaOffset;
  610. this.beta += this.inertialBetaOffset;
  611. this.radius -= this.inertialRadiusOffset;
  612. this.inertialAlphaOffset *= this.inertia;
  613. this.inertialBetaOffset *= this.inertia;
  614. this.inertialRadiusOffset *= this.inertia;
  615. if (Math.abs(this.inertialAlphaOffset) < Epsilon) {
  616. this.inertialAlphaOffset = 0;
  617. }
  618. if (Math.abs(this.inertialBetaOffset) < Epsilon) {
  619. this.inertialBetaOffset = 0;
  620. }
  621. if (Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon) {
  622. this.inertialRadiusOffset = 0;
  623. }
  624. }
  625. // Panning inertia
  626. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  627. if (!this._localDirection) {
  628. this._localDirection = Vector3.Zero();
  629. this._transformedDirection = Vector3.Zero();
  630. }
  631. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  632. this._localDirection.multiplyInPlace(this.panningAxis);
  633. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  634. Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  635. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  636. if (!this.panningAxis.y) {
  637. this._transformedDirection.y = 0;
  638. }
  639. if (!this._targetHost) {
  640. if (this.panningDistanceLimit) {
  641. this._transformedDirection.addInPlace(this._target);
  642. var distanceSquared = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  643. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  644. this._target.copyFrom(this._transformedDirection);
  645. }
  646. }
  647. else {
  648. this._target.addInPlace(this._transformedDirection);
  649. }
  650. }
  651. this.inertialPanningX *= this.panningInertia;
  652. this.inertialPanningY *= this.panningInertia;
  653. if (Math.abs(this.inertialPanningX) < this.speed * Epsilon) {
  654. this.inertialPanningX = 0;
  655. }
  656. if (Math.abs(this.inertialPanningY) < this.speed * Epsilon) {
  657. this.inertialPanningY = 0;
  658. }
  659. }
  660. // Limits
  661. this._checkLimits();
  662. super._checkInputs();
  663. }
  664. protected _checkLimits() {
  665. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  666. if (this.allowUpsideDown && this.beta > Math.PI) {
  667. this.beta = this.beta - (2 * Math.PI);
  668. }
  669. } else {
  670. if (this.beta < this.lowerBetaLimit) {
  671. this.beta = this.lowerBetaLimit;
  672. }
  673. }
  674. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  675. if (this.allowUpsideDown && this.beta < -Math.PI) {
  676. this.beta = this.beta + (2 * Math.PI);
  677. }
  678. } else {
  679. if (this.beta > this.upperBetaLimit) {
  680. this.beta = this.upperBetaLimit;
  681. }
  682. }
  683. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  684. this.alpha = this.lowerAlphaLimit;
  685. }
  686. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  687. this.alpha = this.upperAlphaLimit;
  688. }
  689. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  690. this.radius = this.lowerRadiusLimit;
  691. this.inertialRadiusOffset = 0;
  692. }
  693. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  694. this.radius = this.upperRadiusLimit;
  695. this.inertialRadiusOffset = 0;
  696. }
  697. }
  698. /**
  699. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  700. */
  701. public rebuildAnglesAndRadius(): void {
  702. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  703. this.radius = this._computationVector.length();
  704. if (this.radius === 0) {
  705. this.radius = 0.0001; // Just to avoid division by zero
  706. }
  707. // Alpha
  708. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  709. if (this._computationVector.z < 0) {
  710. this.alpha = 2 * Math.PI - this.alpha;
  711. }
  712. // Beta
  713. this.beta = Math.acos(this._computationVector.y / this.radius);
  714. this._checkLimits();
  715. }
  716. /**
  717. * Use a position to define the current camera related information like aplha, beta and radius
  718. * @param position Defines the position to set the camera at
  719. */
  720. public setPosition(position: Vector3): void {
  721. if (this.position.equals(position)) {
  722. return;
  723. }
  724. this.position.copyFrom(position);
  725. this.rebuildAnglesAndRadius();
  726. }
  727. /**
  728. * Defines the target the camera should look at.
  729. * This will automatically adapt alpha beta and radius to fit within the new target.
  730. * @param target Defines the new target as a Vector or a mesh
  731. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  732. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  733. */
  734. public setTarget(target: AbstractMesh | Vector3, toBoundingCenter = false, allowSamePosition = false): void {
  735. if ((<any>target).getBoundingInfo) {
  736. if (toBoundingCenter) {
  737. this._targetBoundingCenter = (<any>target).getBoundingInfo().boundingBox.centerWorld.clone();
  738. } else {
  739. this._targetBoundingCenter = null;
  740. }
  741. this._targetHost = <AbstractMesh>target;
  742. this._target = this._getTargetPosition();
  743. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  744. } else {
  745. var newTarget = <Vector3>target;
  746. var currentTarget = this._getTargetPosition();
  747. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  748. return;
  749. }
  750. this._targetHost = null;
  751. this._target = newTarget;
  752. this._targetBoundingCenter = null;
  753. this.onMeshTargetChangedObservable.notifyObservers(null);
  754. }
  755. this.rebuildAnglesAndRadius();
  756. }
  757. /** @hidden */
  758. public _getViewMatrix(): Matrix {
  759. // Compute
  760. var cosa = Math.cos(this.alpha);
  761. var sina = Math.sin(this.alpha);
  762. var cosb = Math.cos(this.beta);
  763. var sinb = Math.sin(this.beta);
  764. if (sinb === 0) {
  765. sinb = 0.0001;
  766. }
  767. var target = this._getTargetPosition();
  768. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  769. target.addToRef(this._computationVector, this._newPosition);
  770. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  771. if (!this._collider) {
  772. this._collider = new Collider();
  773. }
  774. this._collider._radius = this.collisionRadius;
  775. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  776. this._collisionTriggered = true;
  777. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  778. } else {
  779. this.position.copyFrom(this._newPosition);
  780. var up = this.upVector;
  781. if (this.allowUpsideDown && sinb < 0) {
  782. up = up.clone();
  783. up = up.negate();
  784. }
  785. this._computeViewMatrix(this.position, target, up);
  786. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  787. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  788. }
  789. this._currentTarget = target;
  790. return this._viewMatrix;
  791. }
  792. protected _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh> = null) => {
  793. if (this.getScene().workerCollisions && this.checkCollisions) {
  794. newPosition.multiplyInPlace(this._collider._radius);
  795. }
  796. if (!collidedMesh) {
  797. this._previousPosition.copyFrom(this.position);
  798. } else {
  799. this.setPosition(newPosition);
  800. if (this.onCollide) {
  801. this.onCollide(collidedMesh);
  802. }
  803. }
  804. // Recompute because of constraints
  805. var cosa = Math.cos(this.alpha);
  806. var sina = Math.sin(this.alpha);
  807. var cosb = Math.cos(this.beta);
  808. var sinb = Math.sin(this.beta);
  809. if (sinb === 0) {
  810. sinb = 0.0001;
  811. }
  812. var target = this._getTargetPosition();
  813. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  814. target.addToRef(this._computationVector, this._newPosition);
  815. this.position.copyFrom(this._newPosition);
  816. var up = this.upVector;
  817. if (this.allowUpsideDown && this.beta < 0) {
  818. up = up.clone();
  819. up = up.negate();
  820. }
  821. this._computeViewMatrix(this.position, target, up);
  822. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  823. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  824. this._collisionTriggered = false;
  825. }
  826. /**
  827. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  828. * @param meshes Defines the mesh to zoom on
  829. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  830. */
  831. public zoomOn(meshes?: AbstractMesh[], doNotUpdateMaxZ = false): void {
  832. meshes = meshes || this.getScene().meshes;
  833. var minMaxVector = Mesh.MinMax(meshes);
  834. var distance = Vector3.Distance(minMaxVector.min, minMaxVector.max);
  835. this.radius = distance * this.zoomOnFactor;
  836. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  837. }
  838. /**
  839. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  840. * The target will be changed but the radius
  841. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  842. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  843. */
  844. public focusOn(meshesOrMinMaxVectorAndDistance: AbstractMesh[] | { min: Vector3, max: Vector3, distance: number }, doNotUpdateMaxZ = false): void {
  845. var meshesOrMinMaxVector: { min: Vector3, max: Vector3 };
  846. var distance: number;
  847. if ((<any>meshesOrMinMaxVectorAndDistance).min === undefined) { // meshes
  848. var meshes = (<AbstractMesh[]>meshesOrMinMaxVectorAndDistance) || this.getScene().meshes;
  849. meshesOrMinMaxVector = Mesh.MinMax(meshes);
  850. distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  851. }
  852. else { //minMaxVector and distance
  853. var minMaxVectorAndDistance = <any>meshesOrMinMaxVectorAndDistance;
  854. meshesOrMinMaxVector = minMaxVectorAndDistance;
  855. distance = minMaxVectorAndDistance.distance;
  856. }
  857. this._target = Mesh.Center(meshesOrMinMaxVector);
  858. if (!doNotUpdateMaxZ) {
  859. this.maxZ = distance * 2;
  860. }
  861. }
  862. /**
  863. * @override
  864. * Override Camera.createRigCamera
  865. */
  866. public createRigCamera(name: string, cameraIndex: number): Camera {
  867. var alphaShift: number = 0;
  868. switch (this.cameraRigMode) {
  869. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  870. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  871. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  872. case Camera.RIG_MODE_VR:
  873. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  874. break;
  875. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  876. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  877. break;
  878. }
  879. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  880. rigCam._cameraRigParams = {};
  881. return rigCam;
  882. }
  883. /**
  884. * @hidden
  885. * @override
  886. * Override Camera._updateRigCameras
  887. */
  888. public _updateRigCameras() {
  889. var camLeft = <ArcRotateCamera>this._rigCameras[0];
  890. var camRight = <ArcRotateCamera>this._rigCameras[1];
  891. camLeft.beta = camRight.beta = this.beta;
  892. camLeft.radius = camRight.radius = this.radius;
  893. switch (this.cameraRigMode) {
  894. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  895. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  896. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  897. case Camera.RIG_MODE_VR:
  898. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  899. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  900. break;
  901. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  902. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  903. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  904. break;
  905. }
  906. super._updateRigCameras();
  907. }
  908. /**
  909. * Destroy the camera and release the current resources hold by it.
  910. */
  911. public dispose(): void {
  912. this.inputs.clear();
  913. super.dispose();
  914. }
  915. /**
  916. * Gets the current object class name.
  917. * @return the class name
  918. */
  919. public getClassName(): string {
  920. return "ArcRotateCamera";
  921. }
  922. }