babylon.arcRotateCamera.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 pinchPrecision = 2.0;
  16. public keysUp = [38];
  17. public keysDown = [40];
  18. public keysLeft = [37];
  19. public keysRight = [39];
  20. public zoomOnFactor = 1;
  21. public targetScreenOffset = Vector2.Zero();
  22. public pinchInwards = true;
  23. public allowUpsideDown = true;
  24. private _keys = [];
  25. private _viewMatrix = new Matrix();
  26. private _attachedElement: HTMLElement;
  27. private _onPointerDown: (e: PointerEvent) => void;
  28. private _onPointerUp: (e: PointerEvent) => void;
  29. private _onPointerMove: (e: PointerEvent) => void;
  30. private _wheel: (e: MouseWheelEvent) => void;
  31. private _onMouseMove: (e: MouseEvent) => any;
  32. private _onKeyDown: (e: KeyboardEvent) => any;
  33. private _onKeyUp: (e: KeyboardEvent) => any;
  34. private _onLostFocus: (e: FocusEvent) => any;
  35. private _reset: () => void;
  36. private _onGestureStart: (e: PointerEvent) => void;
  37. private _onGesture: (e: MSGestureEvent) => void;
  38. private _MSGestureHandler: MSGesture;
  39. // Collisions
  40. public onCollide: (collidedMesh: AbstractMesh) => void;
  41. public checkCollisions = false;
  42. public collisionRadius = new Vector3(0.5, 0.5, 0.5);
  43. private _collider = new Collider();
  44. private _previousPosition = Vector3.Zero();
  45. private _collisionVelocity = Vector3.Zero();
  46. private _newPosition = Vector3.Zero();
  47. private _previousAlpha: number;
  48. private _previousBeta: number;
  49. private _previousRadius: number;
  50. //due to async collision inspection
  51. private _collisionTriggered: boolean;
  52. constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
  53. super(name, Vector3.Zero(), scene);
  54. if (!this.target) {
  55. this.target = Vector3.Zero();
  56. }
  57. this.getViewMatrix();
  58. }
  59. public _getTargetPosition(): Vector3 {
  60. return this.target.position || this.target;
  61. }
  62. // Cache
  63. public _initCache(): void {
  64. super._initCache();
  65. this._cache.target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66. this._cache.alpha = undefined;
  67. this._cache.beta = undefined;
  68. this._cache.radius = undefined;
  69. this._cache.targetScreenOffset = undefined;
  70. }
  71. public _updateCache(ignoreParentClass?: boolean): void {
  72. if (!ignoreParentClass) {
  73. super._updateCache();
  74. }
  75. this._cache.target.copyFrom(this._getTargetPosition());
  76. this._cache.alpha = this.alpha;
  77. this._cache.beta = this.beta;
  78. this._cache.radius = this.radius;
  79. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  80. }
  81. // Synchronized
  82. public _isSynchronizedViewMatrix(): boolean {
  83. if (!super._isSynchronizedViewMatrix())
  84. return false;
  85. return this._cache.target.equals(this._getTargetPosition())
  86. && this._cache.alpha === this.alpha
  87. && this._cache.beta === this.beta
  88. && this._cache.radius === this.radius
  89. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  90. }
  91. // Methods
  92. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  93. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  94. var previousPinchDistance = 0;
  95. var pointers = new SmartCollection();
  96. if (this._attachedElement) {
  97. return;
  98. }
  99. this._attachedElement = element;
  100. var engine = this.getEngine();
  101. if (this._onPointerDown === undefined) {
  102. this._onPointerDown = evt => {
  103. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  104. cacheSoloPointer = pointers.item(evt.pointerId);
  105. if (!noPreventDefault) {
  106. evt.preventDefault();
  107. }
  108. };
  109. this._onPointerUp = evt => {
  110. cacheSoloPointer = null;
  111. previousPinchDistance = 0;
  112. pointers.remove(evt.pointerId);
  113. if (!noPreventDefault) {
  114. evt.preventDefault();
  115. }
  116. };
  117. this._onPointerMove = evt => {
  118. if (!noPreventDefault) {
  119. evt.preventDefault();
  120. }
  121. switch (pointers.count) {
  122. case 1: //normal camera rotation
  123. var offsetX = evt.clientX - cacheSoloPointer.x;
  124. var offsetY = evt.clientY - cacheSoloPointer.y;
  125. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  126. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  127. cacheSoloPointer.x = evt.clientX;
  128. cacheSoloPointer.y = evt.clientY;
  129. break;
  130. case 2: //pinch
  131. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  132. pointers.item(evt.pointerId).x = evt.clientX;
  133. pointers.item(evt.pointerId).y = evt.clientY;
  134. var direction = this.pinchInwards ? 1 : -1;
  135. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  136. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  137. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  138. if (previousPinchDistance === 0) {
  139. previousPinchDistance = pinchSquaredDistance;
  140. return;
  141. }
  142. if (pinchSquaredDistance !== previousPinchDistance) {
  143. this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (this.pinchPrecision * this.wheelPrecision * this.angularSensibility * direction);
  144. previousPinchDistance = pinchSquaredDistance;
  145. }
  146. break;
  147. default:
  148. if (pointers.item(evt.pointerId)) {
  149. pointers.item(evt.pointerId).x = evt.clientX;
  150. pointers.item(evt.pointerId).y = evt.clientY;
  151. }
  152. }
  153. };
  154. this._onMouseMove = evt => {
  155. if (!engine.isPointerLock) {
  156. return;
  157. }
  158. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  159. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  160. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  161. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  162. if (!noPreventDefault) {
  163. evt.preventDefault();
  164. }
  165. };
  166. this._wheel = event => {
  167. var delta = 0;
  168. if (event.wheelDelta) {
  169. delta = event.wheelDelta / (this.wheelPrecision * 40);
  170. } else if (event.detail) {
  171. delta = -event.detail / this.wheelPrecision;
  172. }
  173. if (delta)
  174. this.inertialRadiusOffset += delta;
  175. if (event.preventDefault) {
  176. if (!noPreventDefault) {
  177. event.preventDefault();
  178. }
  179. }
  180. };
  181. this._onKeyDown = evt => {
  182. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  183. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  184. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  185. this.keysRight.indexOf(evt.keyCode) !== -1) {
  186. var index = this._keys.indexOf(evt.keyCode);
  187. if (index === -1) {
  188. this._keys.push(evt.keyCode);
  189. }
  190. if (evt.preventDefault) {
  191. if (!noPreventDefault) {
  192. evt.preventDefault();
  193. }
  194. }
  195. }
  196. };
  197. this._onKeyUp = evt => {
  198. if (this.keysUp.indexOf(evt.keyCode) !== -1 ||
  199. this.keysDown.indexOf(evt.keyCode) !== -1 ||
  200. this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  201. this.keysRight.indexOf(evt.keyCode) !== -1) {
  202. var index = this._keys.indexOf(evt.keyCode);
  203. if (index >= 0) {
  204. this._keys.splice(index, 1);
  205. }
  206. if (evt.preventDefault) {
  207. if (!noPreventDefault) {
  208. evt.preventDefault();
  209. }
  210. }
  211. }
  212. };
  213. this._onLostFocus = () => {
  214. this._keys = [];
  215. pointers.empty();
  216. previousPinchDistance = 0;
  217. cacheSoloPointer = null;
  218. };
  219. this._onGestureStart = e => {
  220. if (window.MSGesture === undefined) {
  221. return;
  222. }
  223. if (!this._MSGestureHandler) {
  224. this._MSGestureHandler = new MSGesture();
  225. this._MSGestureHandler.target = element;
  226. }
  227. this._MSGestureHandler.addPointer(e.pointerId);
  228. };
  229. this._onGesture = e => {
  230. this.radius *= e.scale;
  231. if (e.preventDefault) {
  232. if (!noPreventDefault) {
  233. e.stopPropagation();
  234. e.preventDefault();
  235. }
  236. }
  237. };
  238. this._reset = () => {
  239. this._keys = [];
  240. this.inertialAlphaOffset = 0;
  241. this.inertialBetaOffset = 0;
  242. this.inertialRadiusOffset = 0;
  243. pointers.empty();
  244. previousPinchDistance = 0;
  245. cacheSoloPointer = null;
  246. };
  247. }
  248. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  249. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  250. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  251. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  252. element.addEventListener("mousemove", this._onMouseMove, false);
  253. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  254. element.addEventListener("MSGestureChange", this._onGesture, false);
  255. element.addEventListener('mousewheel', this._wheel, false);
  256. element.addEventListener('DOMMouseScroll', this._wheel, false);
  257. Tools.RegisterTopRootEvents([
  258. { name: "keydown", handler: this._onKeyDown },
  259. { name: "keyup", handler: this._onKeyUp },
  260. { name: "blur", handler: this._onLostFocus }
  261. ]);
  262. }
  263. public detachControl(element: HTMLElement): void {
  264. if (this._attachedElement !== element) {
  265. return;
  266. }
  267. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  268. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  269. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  270. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  271. element.removeEventListener("mousemove", this._onMouseMove);
  272. element.removeEventListener("MSPointerDown", this._onGestureStart);
  273. element.removeEventListener("MSGestureChange", this._onGesture);
  274. element.removeEventListener('mousewheel', this._wheel);
  275. element.removeEventListener('DOMMouseScroll', this._wheel);
  276. Tools.UnregisterTopRootEvents([
  277. { name: "keydown", handler: this._onKeyDown },
  278. { name: "keyup", handler: this._onKeyUp },
  279. { name: "blur", handler: this._onLostFocus }
  280. ]);
  281. this._MSGestureHandler = null;
  282. this._attachedElement = null;
  283. if (this._reset) {
  284. this._reset();
  285. }
  286. }
  287. public _checkInputs(): void {
  288. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  289. if (this._collisionTriggered) {
  290. return;
  291. }
  292. // Keyboard
  293. for (var index = 0; index < this._keys.length; index++) {
  294. var keyCode = this._keys[index];
  295. if (this.keysLeft.indexOf(keyCode) !== -1) {
  296. this.inertialAlphaOffset -= 0.01;
  297. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  298. this.inertialBetaOffset -= 0.01;
  299. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  300. this.inertialAlphaOffset += 0.01;
  301. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  302. this.inertialBetaOffset += 0.01;
  303. }
  304. }
  305. // Inertia
  306. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  307. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  308. this.beta += this.inertialBetaOffset;
  309. this.radius -= this.inertialRadiusOffset;
  310. this.inertialAlphaOffset *= this.inertia;
  311. this.inertialBetaOffset *= this.inertia;
  312. this.inertialRadiusOffset *= this.inertia;
  313. if (Math.abs(this.inertialAlphaOffset) < Engine.Epsilon)
  314. this.inertialAlphaOffset = 0;
  315. if (Math.abs(this.inertialBetaOffset) < Engine.Epsilon)
  316. this.inertialBetaOffset = 0;
  317. if (Math.abs(this.inertialRadiusOffset) < Engine.Epsilon)
  318. this.inertialRadiusOffset = 0;
  319. }
  320. // Limits
  321. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  322. if (this.allowUpsideDown && this.beta > Math.PI) {
  323. this.beta = this.beta - (2 * Math.PI);
  324. }
  325. } else {
  326. if (this.beta < this.lowerBetaLimit) {
  327. this.beta = this.lowerBetaLimit;
  328. }
  329. }
  330. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  331. if (this.allowUpsideDown && this.beta < -Math.PI) {
  332. this.beta = this.beta + (2 * Math.PI);
  333. }
  334. } else {
  335. if (this.beta > this.upperBetaLimit) {
  336. this.beta = this.upperBetaLimit;
  337. }
  338. }
  339. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  340. this.alpha = this.lowerAlphaLimit;
  341. }
  342. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  343. this.alpha = this.upperAlphaLimit;
  344. }
  345. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  346. this.radius = this.lowerRadiusLimit;
  347. }
  348. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  349. this.radius = this.upperRadiusLimit;
  350. }
  351. super._checkInputs();
  352. }
  353. public setPosition(position: Vector3): void {
  354. var radiusv3 = position.subtract(this._getTargetPosition());
  355. this.radius = radiusv3.length();
  356. // Alpha
  357. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  358. if (radiusv3.z < 0) {
  359. this.alpha = 2 * Math.PI - this.alpha;
  360. }
  361. // Beta
  362. this.beta = Math.acos(radiusv3.y / this.radius);
  363. }
  364. public _getViewMatrix(): Matrix {
  365. // Compute
  366. var cosa = Math.cos(this.alpha);
  367. var sina = Math.sin(this.alpha);
  368. var cosb = Math.cos(this.beta);
  369. var sinb = Math.sin(this.beta);
  370. var target = this._getTargetPosition();
  371. target.addToRef(new Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  372. if (this.checkCollisions) {
  373. this._collider.radius = this.collisionRadius;
  374. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  375. this._collisionTriggered = true;
  376. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  377. }
  378. var up = this.upVector;
  379. if (this.allowUpsideDown && this.beta < 0) {
  380. var up = up.clone();
  381. up = up.negate();
  382. }
  383. Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  384. this._previousAlpha = this.alpha;
  385. this._previousBeta = this.beta;
  386. this._previousRadius = this.radius;
  387. this._previousPosition.copyFrom(this.position);
  388. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  389. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  390. return this._viewMatrix;
  391. }
  392. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: AbstractMesh = null) => {
  393. if (this.getScene().workerCollisions && this.checkCollisions) {
  394. newPosition.multiplyInPlace(this._collider.radius);
  395. }
  396. if (!collidedMesh) {
  397. this._previousPosition.copyFrom(this.position);
  398. this.setPosition(this._newPosition);
  399. this.position.copyFrom(this._newPosition);
  400. } else {
  401. this.setPosition(this._previousPosition);
  402. this.position.copyFrom(this._previousPosition);
  403. if (this.onCollide) {
  404. this.onCollide(collidedMesh);
  405. }
  406. }
  407. Matrix.LookAtLHToRef(this.position, this._getTargetPosition(), this.upVector, this._viewMatrix);
  408. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  409. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  410. this._collisionTriggered = false;
  411. }
  412. public zoomOn(meshes?: AbstractMesh[]): void {
  413. meshes = meshes || this.getScene().meshes;
  414. var minMaxVector = Mesh.MinMax(meshes);
  415. var distance = Vector3.Distance(minMaxVector.min, minMaxVector.max);
  416. this.radius = distance * this.zoomOnFactor;
  417. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  418. }
  419. public focusOn(meshesOrMinMaxVectorAndDistance): void {
  420. var meshesOrMinMaxVector;
  421. var distance;
  422. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  423. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  424. meshesOrMinMaxVector = Mesh.MinMax(meshesOrMinMaxVector);
  425. distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  426. }
  427. else { //minMaxVector and distance
  428. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  429. distance = meshesOrMinMaxVectorAndDistance.distance;
  430. }
  431. this.target = Mesh.Center(meshesOrMinMaxVector);
  432. this.maxZ = distance * 2;
  433. }
  434. /**
  435. * @override
  436. * needs to be overridden, so sub has required properties to be copied
  437. */
  438. public getSubCamera(name: string, isA: boolean): Camera {
  439. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  440. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  441. }
  442. /**
  443. * @override
  444. * needs to be overridden, adding copy of alpha, beta & radius
  445. */
  446. public _updateSubCameras() {
  447. var camA = <ArcRotateCamera> this.subCameras[Camera.SUB_CAMERAID_A];
  448. var camB = <ArcRotateCamera> this.subCameras[Camera.SUB_CAMERAID_B];
  449. camA.alpha = this.alpha - this._subCamHalfSpace;
  450. camB.alpha = this.alpha + this._subCamHalfSpace;
  451. camA.beta = camB.beta = this.beta;
  452. camA.radius = camB.radius = this.radius;
  453. super._updateSubCameras();
  454. }
  455. }
  456. }