babylon.arcRotateCamera.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. private _keys = [];
  23. private _viewMatrix = new BABYLON.Matrix();
  24. private _attachedElement: HTMLElement;
  25. private _onPointerDown: (e: PointerEvent) => void;
  26. private _onPointerUp: (e: PointerEvent) => void;
  27. private _onPointerMove: (e: PointerEvent) => void;
  28. private _wheel: (e: MouseWheelEvent) => void;
  29. private _onMouseMove: (e: MouseEvent) => any;
  30. private _onKeyDown: (e: KeyboardEvent) => any;
  31. private _onKeyUp: (e: KeyboardEvent) => any;
  32. private _onLostFocus: (e: FocusEvent) => any;
  33. private _reset: () => void;
  34. private _onGestureStart: (e: PointerEvent) => void;
  35. private _onGesture: (e: MSGestureEvent) => void;
  36. private _MSGestureHandler: MSGesture;
  37. // Collisions
  38. public onCollide: (collidedMesh: AbstractMesh) => void;
  39. public checkCollisions = false;
  40. public collisionRadius = new Vector3(0.5, 0.5, 0.5);
  41. private _collider = new Collider();
  42. private _previousPosition = Vector3.Zero();
  43. private _collisionVelocity = Vector3.Zero();
  44. private _newPosition = Vector3.Zero();
  45. private _previousAlpha: number;
  46. private _previousBeta: number;
  47. private _previousRadius: number;
  48. constructor(name: string, public alpha: number, public beta: number, public radius: number, public target: any, scene: Scene) {
  49. super(name, BABYLON.Vector3.Zero(), scene);
  50. this.getViewMatrix();
  51. }
  52. public _getTargetPosition(): Vector3 {
  53. return this.target.position || this.target;
  54. }
  55. // Cache
  56. public _initCache(): void {
  57. super._initCache();
  58. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59. this._cache.alpha = undefined;
  60. this._cache.beta = undefined;
  61. this._cache.radius = undefined;
  62. this._cache.targetScreenOffset = undefined;
  63. }
  64. public _updateCache(ignoreParentClass?: boolean): void {
  65. if (!ignoreParentClass) {
  66. super._updateCache();
  67. }
  68. this._cache.target.copyFrom(this._getTargetPosition());
  69. this._cache.alpha = this.alpha;
  70. this._cache.beta = this.beta;
  71. this._cache.radius = this.radius;
  72. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  73. }
  74. // Synchronized
  75. public _isSynchronizedViewMatrix(): boolean {
  76. if (!super._isSynchronizedViewMatrix())
  77. return false;
  78. return this._cache.target.equals(this._getTargetPosition())
  79. && this._cache.alpha === this.alpha
  80. && this._cache.beta === this.beta
  81. && this._cache.radius === this.radius
  82. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  83. }
  84. // Methods
  85. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  86. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  87. var previousPinchDistance = 0;
  88. var pointers = new BABYLON.SmartCollection();
  89. if (this._attachedElement) {
  90. return;
  91. }
  92. this._attachedElement = element;
  93. var engine = this.getEngine();
  94. if (this._onPointerDown === undefined) {
  95. this._onPointerDown = evt => {
  96. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  97. cacheSoloPointer = pointers.item(evt.pointerId);
  98. if (!noPreventDefault) {
  99. evt.preventDefault();
  100. }
  101. };
  102. this._onPointerUp = evt => {
  103. cacheSoloPointer = null;
  104. previousPinchDistance = 0;
  105. pointers.remove(evt.pointerId);
  106. if (!noPreventDefault) {
  107. evt.preventDefault();
  108. }
  109. };
  110. this._onPointerMove = evt => {
  111. if (!noPreventDefault) {
  112. evt.preventDefault();
  113. }
  114. switch (pointers.count) {
  115. case 1: //normal camera rotation
  116. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  117. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  118. var offsetX = evt.clientX - cacheSoloPointer.x;
  119. var offsetY = evt.clientY - cacheSoloPointer.y;
  120. this.inertialAlphaOffset -= offsetX / this.angularSensibility;
  121. this.inertialBetaOffset -= offsetY / this.angularSensibility;
  122. //pointers.item(evt.pointerId).x = evt.clientX;
  123. //pointers.item(evt.pointerId).y = evt.clientY;
  124. cacheSoloPointer.x = evt.clientX;
  125. cacheSoloPointer.y = evt.clientY;
  126. break;
  127. case 2: //pinch
  128. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  129. pointers.item(evt.pointerId).x = evt.clientX;
  130. pointers.item(evt.pointerId).y = evt.clientY;
  131. var direction = 1;
  132. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  133. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  134. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  135. if (previousPinchDistance === 0) {
  136. previousPinchDistance = pinchSquaredDistance;
  137. return;
  138. }
  139. if (pinchSquaredDistance != previousPinchDistance) {
  140. if (pinchSquaredDistance > previousPinchDistance) {
  141. direction = -1;
  142. }
  143. this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (this.pinchPrecision * this.wheelPrecision * this.angularSensibility);
  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 _update(): void {
  288. // Keyboard
  289. for (var index = 0; index < this._keys.length; index++) {
  290. var keyCode = this._keys[index];
  291. if (this.keysLeft.indexOf(keyCode) !== -1) {
  292. this.inertialAlphaOffset -= 0.01;
  293. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  294. this.inertialBetaOffset -= 0.01;
  295. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  296. this.inertialAlphaOffset += 0.01;
  297. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  298. this.inertialBetaOffset += 0.01;
  299. }
  300. }
  301. // Inertia
  302. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  303. this.alpha += this.inertialAlphaOffset;
  304. this.beta += this.inertialBetaOffset;
  305. this.radius -= this.inertialRadiusOffset;
  306. this.inertialAlphaOffset *= this.inertia;
  307. this.inertialBetaOffset *= this.inertia;
  308. this.inertialRadiusOffset *= this.inertia;
  309. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  310. this.inertialAlphaOffset = 0;
  311. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  312. this.inertialBetaOffset = 0;
  313. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  314. this.inertialRadiusOffset = 0;
  315. }
  316. // Limits
  317. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  318. this.alpha = this.lowerAlphaLimit;
  319. }
  320. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  321. this.alpha = this.upperAlphaLimit;
  322. }
  323. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  324. this.beta = this.lowerBetaLimit;
  325. }
  326. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  327. this.beta = this.upperBetaLimit;
  328. }
  329. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  330. this.radius = this.lowerRadiusLimit;
  331. }
  332. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  333. this.radius = this.upperRadiusLimit;
  334. }
  335. }
  336. public setPosition(position: Vector3): void {
  337. var radiusv3 = position.subtract(this._getTargetPosition());
  338. this.radius = radiusv3.length();
  339. // Alpha
  340. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  341. if (radiusv3.z < 0) {
  342. this.alpha = 2 * Math.PI - this.alpha;
  343. }
  344. // Beta
  345. this.beta = Math.acos(radiusv3.y / this.radius);
  346. }
  347. public _getViewMatrix(): Matrix {
  348. // Compute
  349. var cosa = Math.cos(this.alpha);
  350. var sina = Math.sin(this.alpha);
  351. var cosb = Math.cos(this.beta);
  352. var sinb = Math.sin(this.beta);
  353. var target = this._getTargetPosition();
  354. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  355. if (this.checkCollisions) {
  356. this._collider.radius = this.collisionRadius;
  357. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  358. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  359. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  360. this.position.copyFrom(this._previousPosition);
  361. this.alpha = this._previousAlpha;
  362. this.beta = this._previousBeta;
  363. this.radius = this._previousRadius;
  364. if (this.onCollide) {
  365. this.onCollide(this._collider.collidedMesh);
  366. }
  367. }
  368. }
  369. Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  370. this._previousAlpha = this.alpha;
  371. this._previousBeta = this.beta;
  372. this._previousRadius = this.radius;
  373. this._previousPosition.copyFrom(this.position);
  374. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  375. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  376. return this._viewMatrix;
  377. }
  378. public zoomOn(meshes?: AbstractMesh[]): void {
  379. meshes = meshes || this.getScene().meshes;
  380. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  381. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  382. this.radius = distance * this.zoomOnFactor;
  383. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  384. }
  385. public focusOn(meshesOrMinMaxVectorAndDistance): void {
  386. var meshesOrMinMaxVector;
  387. var distance;
  388. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  389. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  390. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  391. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  392. }
  393. else { //minMaxVector and distance
  394. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  395. distance = meshesOrMinMaxVectorAndDistance.distance;
  396. }
  397. this.target = Mesh.Center(meshesOrMinMaxVector);
  398. this.maxZ = distance * 2;
  399. }
  400. }
  401. }