babylon.arcRotateCamera.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. module BABYLON {
  2. var eventPrefix = Tools.GetPointerPrefix();
  3. export class ArcRotateCamera extends Camera {
  4. public inertialAlphaOffset = 0;
  5. public inertialBetaOffset = 0;
  6. public inertialRadiusOffset = 0;
  7. public lowerAlphaLimit = null;
  8. public upperAlphaLimit = null;
  9. public lowerBetaLimit = 0.01;
  10. public upperBetaLimit = Math.PI;
  11. public lowerRadiusLimit = null;
  12. public upperRadiusLimit = null;
  13. public angularSensibility = 1000.0;
  14. public wheelPrecision = 3.0;
  15. public keysUp = [38];
  16. public keysDown = [40];
  17. public keysLeft = [37];
  18. public keysRight = [39];
  19. public zoomOnFactor = 1;
  20. public targetScreenOffset = Vector3.Zero();
  21. private _keys = [];
  22. private _viewMatrix = new BABYLON.Matrix();
  23. private _attachedElement: HTMLElement;
  24. private _onPointerDown: (e: PointerEvent) => void;
  25. private _onPointerUp: (e: PointerEvent) => void;
  26. private _onPointerMove: (e: PointerEvent) => void;
  27. private _wheel: (e: MouseWheelEvent) => void;
  28. private _onMouseMove: (e: MouseEvent) => any;
  29. private _onKeyDown: (e: KeyboardEvent) => any;
  30. private _onKeyUp: (e: KeyboardEvent) => any;
  31. private _onLostFocus: (e: FocusEvent) => any;
  32. private _reset: () => void;
  33. private _onGestureStart: (e: PointerEvent) => void;
  34. private _onGesture: (e: MSGestureEvent) => void;
  35. private _MSGestureHandler: MSGesture;
  36. // Collisions
  37. public onCollide: (collidedMesh: AbstractMesh) => void;
  38. public checkCollisions = false;
  39. public collisionRadius = new Vector3(0.5, 0.5, 0.5);
  40. private _collider = new Collider();
  41. private _previousPosition = Vector3.Zero();
  42. private _collisionVelocity = Vector3.Zero();
  43. private _newPosition = Vector3.Zero();
  44. private _previousAlpha: number;
  45. private _previousBeta: number;
  46. private _previousRadius: number;
  47. // Pinch
  48. // value for pinch step scaling
  49. // set to 20 by default
  50. public pinchPrecision = 20;
  51. // Event for pinch
  52. private _touchStart: (e: any) => void;
  53. private _touchMove: (e: any) => void;
  54. private _touchEnd: (e: any) => void;
  55. // Method for pinch
  56. private _pinchStart: (e: any) => void;
  57. private _pinchMove: (e: any) => void;
  58. private _pinchEnd: (e: any) => void;
  59. constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
  60. super(name, BABYLON.Vector3.Zero(), scene);
  61. this.getViewMatrix();
  62. }
  63. public _getTargetPosition(): Vector3 {
  64. return this.target.position || this.target;
  65. }
  66. // Cache
  67. public _initCache(): void {
  68. super._initCache();
  69. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70. this._cache.alpha = undefined;
  71. this._cache.beta = undefined;
  72. this._cache.radius = undefined;
  73. this._cache.targetScreenOffset = undefined;
  74. }
  75. public _updateCache(ignoreParentClass?: boolean): void {
  76. if (!ignoreParentClass) {
  77. super._updateCache();
  78. }
  79. this._cache.target.copyFrom(this._getTargetPosition());
  80. this._cache.alpha = this.alpha;
  81. this._cache.beta = this.beta;
  82. this._cache.radius = this.radius;
  83. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  84. }
  85. // Synchronized
  86. public _isSynchronizedViewMatrix(): boolean {
  87. if (!super._isSynchronizedViewMatrix())
  88. return false;
  89. return this._cache.target.equals(this._getTargetPosition())
  90. && this._cache.alpha === this.alpha
  91. && this._cache.beta === this.beta
  92. && this._cache.radius === this.radius
  93. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  94. }
  95. // Methods
  96. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  97. var previousPosition;
  98. var pointerId;
  99. // to know if pinch started
  100. var pinchStarted = false;
  101. // two pinch point on X
  102. // that will use for find if user action is pinch open or pinch close
  103. var pinchPointX1, pinchPointX2;
  104. if (this._attachedElement) {
  105. return;
  106. }
  107. this._attachedElement = element;
  108. var engine = this.getEngine();
  109. if (this._onPointerDown === undefined) {
  110. this._onPointerDown = evt => {
  111. if (pointerId) {
  112. return;
  113. }
  114. pointerId = evt.pointerId;
  115. previousPosition = {
  116. x: evt.clientX,
  117. y: evt.clientY
  118. };
  119. if (!noPreventDefault) {
  120. evt.preventDefault();
  121. }
  122. };
  123. this._onPointerUp = evt => {
  124. previousPosition = null;
  125. pointerId = null;
  126. if (!noPreventDefault) {
  127. evt.preventDefault();
  128. }
  129. };
  130. this._onPointerMove = evt => {
  131. if (!previousPosition) {
  132. return;
  133. }
  134. if (pointerId !== evt.pointerId) {
  135. return;
  136. }
  137. // return pinch is started
  138. if (pinchStarted) {
  139. return;
  140. }
  141. var offsetX = evt.clientX - previousPosition.x;
  142. var offsetY = evt.clientY - previousPosition.y;
  143. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  144. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  145. previousPosition = {
  146. x: evt.clientX,
  147. y: evt.clientY
  148. };
  149. if (!noPreventDefault) {
  150. evt.preventDefault();
  151. }
  152. };
  153. this._onMouseMove = evt => {
  154. if (!engine.isPointerLock) {
  155. return;
  156. }
  157. // return pinch is started
  158. if (pinchStarted) {
  159. return;
  160. }
  161. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  162. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  163. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  164. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  165. if (!noPreventDefault) {
  166. evt.preventDefault();
  167. }
  168. };
  169. this._wheel = event => {
  170. var delta = 0;
  171. if (event.wheelDelta) {
  172. delta = event.wheelDelta / (this.wheelPrecision * 40);
  173. } else if (event.detail) {
  174. delta = -event.detail / this.wheelPrecision;
  175. }
  176. if (delta)
  177. this.inertialRadiusOffset += delta;
  178. if (event.preventDefault) {
  179. if (!noPreventDefault) {
  180. event.preventDefault();
  181. }
  182. }
  183. };
  184. this._onKeyDown = evt => {
  185. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  186. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  187. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  188. this.keysRight.indexOf(evt.keyCode) !== -1) {
  189. var index = this._keys.indexOf(evt.keyCode);
  190. if (index === -1) {
  191. this._keys.push(evt.keyCode);
  192. }
  193. if (evt.preventDefault) {
  194. if (!noPreventDefault) {
  195. evt.preventDefault();
  196. }
  197. }
  198. }
  199. };
  200. this._onKeyUp = evt => {
  201. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  202. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  203. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  204. this.keysRight.indexOf(evt.keyCode) !== -1) {
  205. var index = this._keys.indexOf(evt.keyCode);
  206. if (index >= 0) {
  207. this._keys.splice(index, 1);
  208. }
  209. if (evt.preventDefault) {
  210. if (!noPreventDefault) {
  211. evt.preventDefault();
  212. }
  213. }
  214. }
  215. };
  216. this._onLostFocus = () => {
  217. this._keys = [];
  218. pointerId = null;
  219. };
  220. this._onGestureStart = e => {
  221. if (window.MSGesture === undefined) {
  222. return;
  223. }
  224. if (!this._MSGestureHandler) {
  225. this._MSGestureHandler = new MSGesture();
  226. this._MSGestureHandler.target = element;
  227. }
  228. this._MSGestureHandler.addPointer(e.pointerId);
  229. };
  230. this._onGesture = e => {
  231. this.radius *= e.scale;
  232. if (e.preventDefault) {
  233. if (!noPreventDefault) {
  234. e.stopPropagation();
  235. e.preventDefault();
  236. }
  237. }
  238. };
  239. this._reset = () => {
  240. this._keys = [];
  241. this.inertialAlphaOffset = 0;
  242. this.inertialBetaOffset = 0;
  243. this.inertialRadiusOffset = 0;
  244. previousPosition = null;
  245. pointerId = null;
  246. };
  247. this._touchStart = event => {
  248. if (event.touches.length == 2) {
  249. //-- start pinch if two fingers on the screen
  250. pinchStarted = true;
  251. this._pinchStart(event);
  252. }
  253. };
  254. this._touchMove = event => {
  255. if (pinchStarted) {
  256. //-- make scaling
  257. this._pinchMove(event);
  258. }
  259. };
  260. this._touchEnd = event => {
  261. if (pinchStarted) {
  262. //-- end of pinch
  263. this._pinchEnd(event);
  264. }
  265. };
  266. this._pinchStart = event => {
  267. // save origin touch point
  268. pinchPointX1 = event.touches[0].clientX;
  269. pinchPointX2 = event.touches[1].clientX;
  270. // block the camera
  271. // if not it rotate around target during pinch
  272. pinchStarted = true;
  273. };
  274. this._pinchMove = event => {
  275. // variable for new camera's radius
  276. var delta = 0;
  277. // variables to know if pinch open or pinch close
  278. var direction = 1;
  279. var distanceXOrigine, distanceXNow;
  280. if (event.touches.length != 2)
  281. return;
  282. // calculate absolute distances of the two fingers
  283. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  284. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  285. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  286. if (distanceXNow < distanceXOrigine) {
  287. direction = -1;
  288. }
  289. // calculate new radius
  290. delta = (this.pinchPrecision / (this.wheelPrecision * 40)) * direction;
  291. // set new radius
  292. this.inertialRadiusOffset += delta;
  293. // save origin touch point
  294. pinchPointX1 = event.touches[0].clientX;
  295. pinchPointX2 = event.touches[1].clientX;
  296. };
  297. this._pinchEnd = event => {
  298. // cancel pinch and deblock camera rotation
  299. pinchStarted = false;
  300. };
  301. }
  302. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  303. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  304. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  305. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  306. element.addEventListener("mousemove", this._onMouseMove, false);
  307. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  308. element.addEventListener("MSGestureChange", this._onGesture, false);
  309. element.addEventListener('mousewheel', this._wheel, false);
  310. element.addEventListener('DOMMouseScroll', this._wheel, false);
  311. // pinch
  312. element.addEventListener('touchstart', this._touchStart, false);
  313. element.addEventListener('touchmove', this._touchMove, false);
  314. element.addEventListener('touchend', this._touchEnd, false);
  315. Tools.RegisterTopRootEvents([
  316. { name: "keydown", handler: this._onKeyDown },
  317. { name: "keyup", handler: this._onKeyUp },
  318. { name: "blur", handler: this._onLostFocus }
  319. ]);
  320. }
  321. public detachControl(element: HTMLElement): void {
  322. if (this._attachedElement != element) {
  323. return;
  324. }
  325. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  326. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  327. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  328. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  329. element.removeEventListener("mousemove", this._onMouseMove);
  330. element.removeEventListener("MSPointerDown", this._onGestureStart);
  331. element.removeEventListener("MSGestureChange", this._onGesture);
  332. element.removeEventListener('mousewheel', this._wheel);
  333. element.removeEventListener('DOMMouseScroll', this._wheel);
  334. // pinch
  335. element.removeEventListener('touchstart', this._touchStart);
  336. element.removeEventListener('touchmove', this._touchMove);
  337. element.removeEventListener('touchend', this._touchEnd);
  338. Tools.UnregisterTopRootEvents([
  339. { name: "keydown", handler: this._onKeyDown },
  340. { name: "keyup", handler: this._onKeyUp },
  341. { name: "blur", handler: this._onLostFocus }
  342. ]);
  343. this._MSGestureHandler = null;
  344. this._attachedElement = null;
  345. if (this._reset) {
  346. this._reset();
  347. }
  348. }
  349. public _update(): void {
  350. // Keyboard
  351. for (var index = 0; index < this._keys.length; index++) {
  352. var keyCode = this._keys[index];
  353. if (this.keysLeft.indexOf(keyCode) !== -1) {
  354. this.inertialAlphaOffset -= 0.01;
  355. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  356. this.inertialBetaOffset -= 0.01;
  357. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  358. this.inertialAlphaOffset += 0.01;
  359. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  360. this.inertialBetaOffset += 0.01;
  361. }
  362. }
  363. // Inertia
  364. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  365. this.alpha += this.inertialAlphaOffset;
  366. this.beta += this.inertialBetaOffset;
  367. this.radius -= this.inertialRadiusOffset;
  368. this.inertialAlphaOffset *= this.inertia;
  369. this.inertialBetaOffset *= this.inertia;
  370. this.inertialRadiusOffset *= this.inertia;
  371. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  372. this.inertialAlphaOffset = 0;
  373. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  374. this.inertialBetaOffset = 0;
  375. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  376. this.inertialRadiusOffset = 0;
  377. }
  378. // Limits
  379. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  380. this.alpha = this.lowerAlphaLimit;
  381. }
  382. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  383. this.alpha = this.upperAlphaLimit;
  384. }
  385. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  386. this.beta = this.lowerBetaLimit;
  387. }
  388. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  389. this.beta = this.upperBetaLimit;
  390. }
  391. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  392. this.radius = this.lowerRadiusLimit;
  393. }
  394. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  395. this.radius = this.upperRadiusLimit;
  396. }
  397. }
  398. public setPosition(position: Vector3): void {
  399. var radiusv3 = position.subtract(this._getTargetPosition());
  400. this.radius = radiusv3.length();
  401. // Alpha
  402. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  403. if (radiusv3.z < 0) {
  404. this.alpha = 2 * Math.PI - this.alpha;
  405. }
  406. // Beta
  407. this.beta = Math.acos(radiusv3.y / this.radius);
  408. }
  409. public _getViewMatrix(): Matrix {
  410. // Compute
  411. var cosa = Math.cos(this.alpha);
  412. var sina = Math.sin(this.alpha);
  413. var cosb = Math.cos(this.beta);
  414. var sinb = Math.sin(this.beta);
  415. var target = this._getTargetPosition();
  416. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  417. if (this.checkCollisions) {
  418. this._collider.radius = this.collisionRadius;
  419. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  420. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  421. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  422. this.position.copyFrom(this._previousPosition);
  423. this.alpha = this._previousAlpha;
  424. this.beta = this._previousBeta;
  425. this.radius = this._previousRadius;
  426. if (this.onCollide) {
  427. this.onCollide(this._collider.collidedMesh);
  428. }
  429. }
  430. }
  431. Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  432. this._previousAlpha = this.alpha;
  433. this._previousBeta = this.beta;
  434. this._previousRadius = this.radius;
  435. this._previousPosition.copyFrom(this.position);
  436. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  437. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  438. return this._viewMatrix;
  439. }
  440. public zoomOn(meshes?: AbstractMesh[]): void {
  441. meshes = meshes || this.getScene().meshes;
  442. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  443. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  444. this.radius = distance * this.zoomOnFactor;
  445. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  446. }
  447. public focusOn(meshesOrMinMaxVectorAndDistance): void {
  448. var meshesOrMinMaxVector;
  449. var distance;
  450. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  451. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  452. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  453. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  454. }
  455. else { //minMaxVector and distance
  456. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  457. distance = meshesOrMinMaxVectorAndDistance.distance;
  458. }
  459. this.target = Mesh.Center(meshesOrMinMaxVector);
  460. this.maxZ = distance * 2;
  461. }
  462. }
  463. }