OrbitControls.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. import {
  2. EventDispatcher,
  3. MOUSE,
  4. Quaternion,
  5. Spherical,
  6. TOUCH,
  7. Vector2,
  8. Vector3,
  9. Plane,
  10. Ray,
  11. MathUtils
  12. } from 'three';
  13. // OrbitControls performs orbiting, dollying (zooming), and panning.
  14. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  15. //
  16. // Orbit - left mouse / touch: one-finger move
  17. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  18. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  19. const _changeEvent = { type: 'change' };
  20. const _startEvent = { type: 'start' };
  21. const _endEvent = { type: 'end' };
  22. const _ray = new Ray();
  23. const _plane = new Plane();
  24. const TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
  25. class OrbitControls extends EventDispatcher {
  26. constructor( object, domElement ) {
  27. super();
  28. this.object = object;
  29. this.domElement = domElement;
  30. this.domElement.style.touchAction = 'none'; // disable touch scroll
  31. // Set to false to disable this control
  32. this.enabled = true;
  33. // "target" sets the location of focus, where the object orbits around
  34. this.target = new Vector3();
  35. // Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect
  36. this.cursor = new Vector3();
  37. // How far you can dolly in and out ( PerspectiveCamera only )
  38. this.minDistance = 0;
  39. this.maxDistance = Infinity;
  40. // How far you can zoom in and out ( OrthographicCamera only )
  41. this.minZoom = 0;
  42. this.maxZoom = Infinity;
  43. // Limit camera target within a spherical area around the cursor
  44. this.minTargetRadius = 0;
  45. this.maxTargetRadius = Infinity;
  46. // How far you can orbit vertically, upper and lower limits.
  47. // Range is 0 to Math.PI radians.
  48. this.minPolarAngle = 0; // radians
  49. this.maxPolarAngle = Math.PI; // radians
  50. // How far you can orbit horizontally, upper and lower limits.
  51. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  52. this.minAzimuthAngle = - Infinity; // radians
  53. this.maxAzimuthAngle = Infinity; // radians
  54. // Set to true to enable damping (inertia)
  55. // If damping is enabled, you must call controls.update() in your animation loop
  56. this.enableDamping = false;
  57. this.dampingFactor = 0.05;
  58. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  59. // Set to false to disable zooming
  60. this.enableZoom = true;
  61. this.zoomSpeed = 1.0;
  62. // Set to false to disable rotating
  63. this.enableRotate = true;
  64. this.rotateSpeed = 1.0;
  65. // Set to false to disable panning
  66. this.enablePan = true;
  67. this.panSpeed = 1.0;
  68. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  69. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  70. this.zoomToCursor = false;
  71. // Set to true to automatically rotate around the target
  72. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  73. this.autoRotate = false;
  74. this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
  75. // The four arrow keys
  76. this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
  77. // Mouse buttons
  78. this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
  79. // Touch fingers
  80. this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
  81. // for reset
  82. this.target0 = this.target.clone();
  83. this.position0 = this.object.position.clone();
  84. this.zoom0 = this.object.zoom;
  85. // the target DOM element for key events
  86. this._domElementKeyEvents = null;
  87. //
  88. // public methods
  89. //
  90. this.getPolarAngle = function () {
  91. return spherical.phi;
  92. };
  93. this.getAzimuthalAngle = function () {
  94. return spherical.theta;
  95. };
  96. this.getDistance = function () {
  97. return this.object.position.distanceTo( this.target );
  98. };
  99. this.listenToKeyEvents = function ( domElement ) {
  100. domElement.addEventListener( 'keydown', onKeyDown );
  101. this._domElementKeyEvents = domElement;
  102. };
  103. this.stopListenToKeyEvents = function () {
  104. this._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  105. this._domElementKeyEvents = null;
  106. };
  107. this.saveState = function () {
  108. scope.target0.copy( scope.target );
  109. scope.position0.copy( scope.object.position );
  110. scope.zoom0 = scope.object.zoom;
  111. };
  112. this.reset = function () {
  113. scope.target.copy( scope.target0 );
  114. scope.object.position.copy( scope.position0 );
  115. scope.object.zoom = scope.zoom0;
  116. scope.object.updateProjectionMatrix();
  117. scope.dispatchEvent( _changeEvent );
  118. scope.update();
  119. state = STATE.NONE;
  120. };
  121. // this method is exposed, but perhaps it would be better if we can make it private...
  122. this.update = function () {
  123. const offset = new Vector3();
  124. // so camera.up is the orbit axis
  125. const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
  126. const quatInverse = quat.clone().invert();
  127. const lastPosition = new Vector3();
  128. const lastQuaternion = new Quaternion();
  129. const lastTargetPosition = new Vector3();
  130. const twoPI = 2 * Math.PI;
  131. return function update( deltaTime = null ) {
  132. const position = scope.object.position;
  133. offset.copy( position ).sub( scope.target );
  134. // rotate offset to "y-axis-is-up" space
  135. offset.applyQuaternion( quat );
  136. // angle from z-axis around y-axis
  137. spherical.setFromVector3( offset );
  138. if ( scope.autoRotate && state === STATE.NONE ) {
  139. rotateLeft( getAutoRotationAngle( deltaTime ) );
  140. }
  141. if ( scope.enableDamping ) {
  142. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  143. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  144. } else {
  145. spherical.theta += sphericalDelta.theta;
  146. spherical.phi += sphericalDelta.phi;
  147. }
  148. // restrict theta to be between desired limits
  149. let min = scope.minAzimuthAngle;
  150. let max = scope.maxAzimuthAngle;
  151. if ( isFinite( min ) && isFinite( max ) ) {
  152. if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
  153. if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
  154. if ( min <= max ) {
  155. spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
  156. } else {
  157. spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?
  158. Math.max( min, spherical.theta ) :
  159. Math.min( max, spherical.theta );
  160. }
  161. }
  162. // restrict phi to be between desired limits
  163. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  164. spherical.makeSafe();
  165. // move target to panned location
  166. if ( scope.enableDamping === true ) {
  167. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  168. } else {
  169. scope.target.add( panOffset );
  170. }
  171. // Limit the target distance from the cursor to create a sphere around the center of interest
  172. scope.target.sub( scope.cursor );
  173. scope.target.clampLength( scope.minTargetRadius, scope.maxTargetRadius );
  174. scope.target.add( scope.cursor );
  175. let zoomChanged = false;
  176. // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
  177. // we adjust zoom later in these cases
  178. if ( scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera ) {
  179. spherical.radius = clampDistance( spherical.radius );
  180. } else {
  181. const prevRadius = spherical.radius;
  182. spherical.radius = clampDistance( spherical.radius * scale );
  183. zoomChanged = prevRadius != spherical.radius;
  184. }
  185. offset.setFromSpherical( spherical );
  186. // rotate offset back to "camera-up-vector-is-up" space
  187. offset.applyQuaternion( quatInverse );
  188. position.copy( scope.target ).add( offset );
  189. scope.object.lookAt( scope.target );
  190. if ( scope.enableDamping === true ) {
  191. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  192. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  193. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  194. } else {
  195. sphericalDelta.set( 0, 0, 0 );
  196. panOffset.set( 0, 0, 0 );
  197. }
  198. // adjust camera position
  199. if ( scope.zoomToCursor && performCursorZoom ) {
  200. let newRadius = null;
  201. if ( scope.object.isPerspectiveCamera ) {
  202. // move the camera down the pointer ray
  203. // this method avoids floating point error
  204. const prevRadius = offset.length();
  205. newRadius = clampDistance( prevRadius * scale );
  206. const radiusDelta = prevRadius - newRadius;
  207. scope.object.position.addScaledVector( dollyDirection, radiusDelta );
  208. scope.object.updateMatrixWorld();
  209. zoomChanged = !! radiusDelta;
  210. } else if ( scope.object.isOrthographicCamera ) {
  211. // adjust the ortho camera position based on zoom changes
  212. const mouseBefore = new Vector3( mouse.x, mouse.y, 0 );
  213. mouseBefore.unproject( scope.object );
  214. const prevZoom = scope.object.zoom;
  215. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  216. scope.object.updateProjectionMatrix();
  217. zoomChanged = prevZoom !== scope.object.zoom;
  218. const mouseAfter = new Vector3( mouse.x, mouse.y, 0 );
  219. mouseAfter.unproject( scope.object );
  220. scope.object.position.sub( mouseAfter ).add( mouseBefore );
  221. scope.object.updateMatrixWorld();
  222. newRadius = offset.length();
  223. } else {
  224. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
  225. scope.zoomToCursor = false;
  226. }
  227. // handle the placement of the target
  228. if ( newRadius !== null ) {
  229. if ( this.screenSpacePanning ) {
  230. // position the orbit target in front of the new camera position
  231. scope.target.set( 0, 0, - 1 )
  232. .transformDirection( scope.object.matrix )
  233. .multiplyScalar( newRadius )
  234. .add( scope.object.position );
  235. } else {
  236. // get the ray and translation plane to compute target
  237. _ray.origin.copy( scope.object.position );
  238. _ray.direction.set( 0, 0, - 1 ).transformDirection( scope.object.matrix );
  239. // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
  240. // extremely large values
  241. if ( Math.abs( scope.object.up.dot( _ray.direction ) ) < TILT_LIMIT ) {
  242. object.lookAt( scope.target );
  243. } else {
  244. _plane.setFromNormalAndCoplanarPoint( scope.object.up, scope.target );
  245. _ray.intersectPlane( _plane, scope.target );
  246. }
  247. }
  248. }
  249. } else if ( scope.object.isOrthographicCamera ) {
  250. const prevZoom = scope.object.zoom;
  251. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) );
  252. if ( prevZoom !== scope.object.zoom ) {
  253. scope.object.updateProjectionMatrix();
  254. zoomChanged = true;
  255. }
  256. }
  257. scale = 1;
  258. performCursorZoom = false;
  259. // update condition is:
  260. // min(camera displacement, camera rotation in radians)^2 > EPS
  261. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  262. if ( zoomChanged ||
  263. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  264. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ||
  265. lastTargetPosition.distanceToSquared( scope.target ) > EPS ) {
  266. scope.dispatchEvent( _changeEvent );
  267. lastPosition.copy( scope.object.position );
  268. lastQuaternion.copy( scope.object.quaternion );
  269. lastTargetPosition.copy( scope.target );
  270. return true;
  271. }
  272. return false;
  273. };
  274. }();
  275. this.dispose = function () {
  276. scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
  277. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  278. scope.domElement.removeEventListener( 'pointercancel', onPointerUp );
  279. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  280. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  281. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  282. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  283. document.removeEventListener( 'keydown', interceptControlDown, { capture: true } );
  284. if ( scope._domElementKeyEvents !== null ) {
  285. scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  286. scope._domElementKeyEvents = null;
  287. }
  288. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  289. };
  290. //
  291. // internals
  292. //
  293. const scope = this;
  294. const STATE = {
  295. NONE: - 1,
  296. ROTATE: 0,
  297. DOLLY: 1,
  298. PAN: 2,
  299. TOUCH_ROTATE: 3,
  300. TOUCH_PAN: 4,
  301. TOUCH_DOLLY_PAN: 5,
  302. TOUCH_DOLLY_ROTATE: 6
  303. };
  304. let state = STATE.NONE;
  305. const EPS = 0.000001;
  306. // current position in spherical coordinates
  307. const spherical = new Spherical();
  308. const sphericalDelta = new Spherical();
  309. let scale = 1;
  310. const panOffset = new Vector3();
  311. const rotateStart = new Vector2();
  312. const rotateEnd = new Vector2();
  313. const rotateDelta = new Vector2();
  314. const panStart = new Vector2();
  315. const panEnd = new Vector2();
  316. const panDelta = new Vector2();
  317. const dollyStart = new Vector2();
  318. const dollyEnd = new Vector2();
  319. const dollyDelta = new Vector2();
  320. const dollyDirection = new Vector3();
  321. const mouse = new Vector2();
  322. let performCursorZoom = false;
  323. const pointers = [];
  324. const pointerPositions = {};
  325. let controlActive = false;
  326. function getAutoRotationAngle( deltaTime ) {
  327. if ( deltaTime !== null ) {
  328. return ( 2 * Math.PI / 60 * scope.autoRotateSpeed ) * deltaTime;
  329. } else {
  330. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  331. }
  332. }
  333. function getZoomScale( delta ) {
  334. const normalizedDelta = Math.abs( delta * 0.01 );
  335. return Math.pow( 0.95, scope.zoomSpeed * normalizedDelta );
  336. }
  337. function rotateLeft( angle ) {
  338. sphericalDelta.theta -= angle;
  339. }
  340. function rotateUp( angle ) {
  341. sphericalDelta.phi -= angle;
  342. }
  343. const panLeft = function () {
  344. const v = new Vector3();
  345. return function panLeft( distance, objectMatrix ) {
  346. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  347. v.multiplyScalar( - distance );
  348. panOffset.add( v );
  349. };
  350. }();
  351. const panUp = function () {
  352. const v = new Vector3();
  353. return function panUp( distance, objectMatrix ) {
  354. if ( scope.screenSpacePanning === true ) {
  355. v.setFromMatrixColumn( objectMatrix, 1 );
  356. } else {
  357. v.setFromMatrixColumn( objectMatrix, 0 );
  358. v.crossVectors( scope.object.up, v );
  359. }
  360. v.multiplyScalar( distance );
  361. panOffset.add( v );
  362. };
  363. }();
  364. // deltaX and deltaY are in pixels; right and down are positive
  365. const pan = function () {
  366. const offset = new Vector3();
  367. return function pan( deltaX, deltaY ) {
  368. const element = scope.domElement;
  369. if ( scope.object.isPerspectiveCamera ) {
  370. // perspective
  371. const position = scope.object.position;
  372. offset.copy( position ).sub( scope.target );
  373. let targetDistance = offset.length();
  374. // half of the fov is center to top of screen
  375. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  376. // we use only clientHeight here so aspect ratio does not distort speed
  377. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  378. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  379. } else if ( scope.object.isOrthographicCamera ) {
  380. // orthographic
  381. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  382. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  383. } else {
  384. // camera neither orthographic nor perspective
  385. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  386. scope.enablePan = false;
  387. }
  388. };
  389. }();
  390. function dollyOut( dollyScale ) {
  391. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  392. scale /= dollyScale;
  393. } else {
  394. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  395. scope.enableZoom = false;
  396. }
  397. }
  398. function dollyIn( dollyScale ) {
  399. if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
  400. scale *= dollyScale;
  401. } else {
  402. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  403. scope.enableZoom = false;
  404. }
  405. }
  406. function updateZoomParameters( x, y ) {
  407. if ( ! scope.zoomToCursor ) {
  408. return;
  409. }
  410. performCursorZoom = true;
  411. const rect = scope.domElement.getBoundingClientRect();
  412. const dx = x - rect.left;
  413. const dy = y - rect.top;
  414. const w = rect.width;
  415. const h = rect.height;
  416. mouse.x = ( dx / w ) * 2 - 1;
  417. mouse.y = - ( dy / h ) * 2 + 1;
  418. dollyDirection.set( mouse.x, mouse.y, 1 ).unproject( scope.object ).sub( scope.object.position ).normalize();
  419. }
  420. function clampDistance( dist ) {
  421. return Math.max( scope.minDistance, Math.min( scope.maxDistance, dist ) );
  422. }
  423. //
  424. // event callbacks - update the object state
  425. //
  426. function handleMouseDownRotate( event ) {
  427. rotateStart.set( event.clientX, event.clientY );
  428. }
  429. function handleMouseDownDolly( event ) {
  430. updateZoomParameters( event.clientX, event.clientX );
  431. dollyStart.set( event.clientX, event.clientY );
  432. }
  433. function handleMouseDownPan( event ) {
  434. panStart.set( event.clientX, event.clientY );
  435. }
  436. function handleMouseMoveRotate( event ) {
  437. rotateEnd.set( event.clientX, event.clientY );
  438. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  439. const element = scope.domElement;
  440. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  441. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  442. rotateStart.copy( rotateEnd );
  443. scope.update();
  444. }
  445. function handleMouseMoveDolly( event ) {
  446. dollyEnd.set( event.clientX, event.clientY );
  447. dollyDelta.subVectors( dollyEnd, dollyStart );
  448. if ( dollyDelta.y > 0 ) {
  449. dollyOut( getZoomScale( dollyDelta.y ) );
  450. } else if ( dollyDelta.y < 0 ) {
  451. dollyIn( getZoomScale( dollyDelta.y ) );
  452. }
  453. dollyStart.copy( dollyEnd );
  454. scope.update();
  455. }
  456. function handleMouseMovePan( event ) {
  457. panEnd.set( event.clientX, event.clientY );
  458. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  459. pan( panDelta.x, panDelta.y );
  460. panStart.copy( panEnd );
  461. scope.update();
  462. }
  463. function handleMouseWheel( event ) {
  464. updateZoomParameters( event.clientX, event.clientY );
  465. if ( event.deltaY < 0 ) {
  466. dollyIn( getZoomScale( event.deltaY ) );
  467. } else if ( event.deltaY > 0 ) {
  468. dollyOut( getZoomScale( event.deltaY ) );
  469. }
  470. scope.update();
  471. }
  472. function handleKeyDown( event ) {
  473. let needsUpdate = false;
  474. switch ( event.code ) {
  475. case scope.keys.UP:
  476. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  477. rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  478. } else {
  479. pan( 0, scope.keyPanSpeed );
  480. }
  481. needsUpdate = true;
  482. break;
  483. case scope.keys.BOTTOM:
  484. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  485. rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  486. } else {
  487. pan( 0, - scope.keyPanSpeed );
  488. }
  489. needsUpdate = true;
  490. break;
  491. case scope.keys.LEFT:
  492. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  493. rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  494. } else {
  495. pan( scope.keyPanSpeed, 0 );
  496. }
  497. needsUpdate = true;
  498. break;
  499. case scope.keys.RIGHT:
  500. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  501. rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
  502. } else {
  503. pan( - scope.keyPanSpeed, 0 );
  504. }
  505. needsUpdate = true;
  506. break;
  507. }
  508. if ( needsUpdate ) {
  509. // prevent the browser from scrolling on cursor keys
  510. event.preventDefault();
  511. scope.update();
  512. }
  513. }
  514. function handleTouchStartRotate( event ) {
  515. if ( pointers.length === 1 ) {
  516. rotateStart.set( event.pageX, event.pageY );
  517. } else {
  518. const position = getSecondPointerPosition( event );
  519. const x = 0.5 * ( event.pageX + position.x );
  520. const y = 0.5 * ( event.pageY + position.y );
  521. rotateStart.set( x, y );
  522. }
  523. }
  524. function handleTouchStartPan( event ) {
  525. if ( pointers.length === 1 ) {
  526. panStart.set( event.pageX, event.pageY );
  527. } else {
  528. const position = getSecondPointerPosition( event );
  529. const x = 0.5 * ( event.pageX + position.x );
  530. const y = 0.5 * ( event.pageY + position.y );
  531. panStart.set( x, y );
  532. }
  533. }
  534. function handleTouchStartDolly( event ) {
  535. const position = getSecondPointerPosition( event );
  536. const dx = event.pageX - position.x;
  537. const dy = event.pageY - position.y;
  538. const distance = Math.sqrt( dx * dx + dy * dy );
  539. dollyStart.set( 0, distance );
  540. }
  541. function handleTouchStartDollyPan( event ) {
  542. if ( scope.enableZoom ) handleTouchStartDolly( event );
  543. if ( scope.enablePan ) handleTouchStartPan( event );
  544. }
  545. function handleTouchStartDollyRotate( event ) {
  546. if ( scope.enableZoom ) handleTouchStartDolly( event );
  547. if ( scope.enableRotate ) handleTouchStartRotate( event );
  548. }
  549. function handleTouchMoveRotate( event ) {
  550. if ( pointers.length == 1 ) {
  551. rotateEnd.set( event.pageX, event.pageY );
  552. } else {
  553. const position = getSecondPointerPosition( event );
  554. const x = 0.5 * ( event.pageX + position.x );
  555. const y = 0.5 * ( event.pageY + position.y );
  556. rotateEnd.set( x, y );
  557. }
  558. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  559. const element = scope.domElement;
  560. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  561. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  562. rotateStart.copy( rotateEnd );
  563. }
  564. function handleTouchMovePan( event ) {
  565. if ( pointers.length === 1 ) {
  566. panEnd.set( event.pageX, event.pageY );
  567. } else {
  568. const position = getSecondPointerPosition( event );
  569. const x = 0.5 * ( event.pageX + position.x );
  570. const y = 0.5 * ( event.pageY + position.y );
  571. panEnd.set( x, y );
  572. }
  573. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  574. pan( panDelta.x, panDelta.y );
  575. panStart.copy( panEnd );
  576. }
  577. function handleTouchMoveDolly( event ) {
  578. const position = getSecondPointerPosition( event );
  579. const dx = event.pageX - position.x;
  580. const dy = event.pageY - position.y;
  581. const distance = Math.sqrt( dx * dx + dy * dy );
  582. dollyEnd.set( 0, distance );
  583. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  584. dollyOut( dollyDelta.y );
  585. dollyStart.copy( dollyEnd );
  586. const centerX = ( event.pageX + position.x ) * 0.5;
  587. const centerY = ( event.pageY + position.y ) * 0.5;
  588. updateZoomParameters( centerX, centerY );
  589. }
  590. function handleTouchMoveDollyPan( event ) {
  591. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  592. if ( scope.enablePan ) handleTouchMovePan( event );
  593. }
  594. function handleTouchMoveDollyRotate( event ) {
  595. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  596. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  597. }
  598. //
  599. // event handlers - FSM: listen for events and reset state
  600. //
  601. function onPointerDown( event ) {
  602. if ( scope.enabled === false ) return;
  603. if ( pointers.length === 0 ) {
  604. scope.domElement.setPointerCapture( event.pointerId );
  605. scope.domElement.addEventListener( 'pointermove', onPointerMove );
  606. scope.domElement.addEventListener( 'pointerup', onPointerUp );
  607. }
  608. //
  609. if ( isTrackingPointer( event ) ) return;
  610. //
  611. addPointer( event );
  612. if ( event.pointerType === 'touch' ) {
  613. onTouchStart( event );
  614. } else {
  615. onMouseDown( event );
  616. }
  617. }
  618. function onPointerMove( event ) {
  619. if ( scope.enabled === false ) return;
  620. if ( event.pointerType === 'touch' ) {
  621. onTouchMove( event );
  622. } else {
  623. onMouseMove( event );
  624. }
  625. }
  626. function onPointerUp( event ) {
  627. removePointer( event );
  628. switch ( pointers.length ) {
  629. case 0:
  630. scope.domElement.releasePointerCapture( event.pointerId );
  631. scope.domElement.removeEventListener( 'pointermove', onPointerMove );
  632. scope.domElement.removeEventListener( 'pointerup', onPointerUp );
  633. scope.dispatchEvent( _endEvent );
  634. state = STATE.NONE;
  635. break;
  636. case 1:
  637. const pointerId = pointers[ 0 ];
  638. const position = pointerPositions[ pointerId ];
  639. // minimal placeholder event - allows state correction on pointer-up
  640. onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } );
  641. break;
  642. }
  643. }
  644. function onMouseDown( event ) {
  645. let mouseAction;
  646. switch ( event.button ) {
  647. case 0:
  648. mouseAction = scope.mouseButtons.LEFT;
  649. break;
  650. case 1:
  651. mouseAction = scope.mouseButtons.MIDDLE;
  652. break;
  653. case 2:
  654. mouseAction = scope.mouseButtons.RIGHT;
  655. break;
  656. default:
  657. mouseAction = - 1;
  658. }
  659. switch ( mouseAction ) {
  660. case MOUSE.DOLLY:
  661. if ( scope.enableZoom === false ) return;
  662. handleMouseDownDolly( event );
  663. state = STATE.DOLLY;
  664. break;
  665. case MOUSE.ROTATE:
  666. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  667. if ( scope.enablePan === false ) return;
  668. handleMouseDownPan( event );
  669. state = STATE.PAN;
  670. } else {
  671. if ( scope.enableRotate === false ) return;
  672. handleMouseDownRotate( event );
  673. state = STATE.ROTATE;
  674. }
  675. break;
  676. case MOUSE.PAN:
  677. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  678. if ( scope.enableRotate === false ) return;
  679. handleMouseDownRotate( event );
  680. state = STATE.ROTATE;
  681. } else {
  682. if ( scope.enablePan === false ) return;
  683. handleMouseDownPan( event );
  684. state = STATE.PAN;
  685. }
  686. break;
  687. default:
  688. state = STATE.NONE;
  689. }
  690. if ( state !== STATE.NONE ) {
  691. scope.dispatchEvent( _startEvent );
  692. }
  693. }
  694. function onMouseMove( event ) {
  695. switch ( state ) {
  696. case STATE.ROTATE:
  697. if ( scope.enableRotate === false ) return;
  698. handleMouseMoveRotate( event );
  699. break;
  700. case STATE.DOLLY:
  701. if ( scope.enableZoom === false ) return;
  702. handleMouseMoveDolly( event );
  703. break;
  704. case STATE.PAN:
  705. if ( scope.enablePan === false ) return;
  706. handleMouseMovePan( event );
  707. break;
  708. }
  709. }
  710. function onMouseWheel( event ) {
  711. if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
  712. event.preventDefault();
  713. scope.dispatchEvent( _startEvent );
  714. handleMouseWheel( customWheelEvent( event ) );
  715. scope.dispatchEvent( _endEvent );
  716. }
  717. function customWheelEvent( event ) {
  718. const mode = event.deltaMode;
  719. // minimal wheel event altered to meet delta-zoom demand
  720. const newEvent = {
  721. clientX: event.clientX,
  722. clientY: event.clientY,
  723. deltaY: event.deltaY,
  724. };
  725. switch ( mode ) {
  726. case 1: // LINE_MODE
  727. newEvent.deltaY *= 16;
  728. break;
  729. case 2: // PAGE_MODE
  730. newEvent.deltaY *= 100;
  731. break;
  732. }
  733. // detect if event was triggered by pinching
  734. if ( event.ctrlKey && ! controlActive ) {
  735. newEvent.deltaY *= 10;
  736. }
  737. return newEvent;
  738. }
  739. function interceptControlDown( event ) {
  740. if ( event.key === 'Control' ) {
  741. controlActive = true;
  742. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  743. document.addEventListener( 'keyup', interceptControlUp, { passive: true, capture: true } );
  744. }
  745. }
  746. function interceptControlUp( event ) {
  747. if ( event.key === 'Control' ) {
  748. controlActive = false;
  749. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  750. document.removeEventListener( 'keyup', interceptControlUp, { passive: true, capture: true } );
  751. }
  752. }
  753. function onKeyDown( event ) {
  754. if ( scope.enabled === false || scope.enablePan === false ) return;
  755. handleKeyDown( event );
  756. }
  757. function onTouchStart( event ) {
  758. trackPointer( event );
  759. switch ( pointers.length ) {
  760. case 1:
  761. switch ( scope.touches.ONE ) {
  762. case TOUCH.ROTATE:
  763. if ( scope.enableRotate === false ) return;
  764. handleTouchStartRotate( event );
  765. state = STATE.TOUCH_ROTATE;
  766. break;
  767. case TOUCH.PAN:
  768. if ( scope.enablePan === false ) return;
  769. handleTouchStartPan( event );
  770. state = STATE.TOUCH_PAN;
  771. break;
  772. default:
  773. state = STATE.NONE;
  774. }
  775. break;
  776. case 2:
  777. switch ( scope.touches.TWO ) {
  778. case TOUCH.DOLLY_PAN:
  779. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  780. handleTouchStartDollyPan( event );
  781. state = STATE.TOUCH_DOLLY_PAN;
  782. break;
  783. case TOUCH.DOLLY_ROTATE:
  784. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  785. handleTouchStartDollyRotate( event );
  786. state = STATE.TOUCH_DOLLY_ROTATE;
  787. break;
  788. default:
  789. state = STATE.NONE;
  790. }
  791. break;
  792. default:
  793. state = STATE.NONE;
  794. }
  795. if ( state !== STATE.NONE ) {
  796. scope.dispatchEvent( _startEvent );
  797. }
  798. }
  799. function onTouchMove( event ) {
  800. trackPointer( event );
  801. switch ( state ) {
  802. case STATE.TOUCH_ROTATE:
  803. if ( scope.enableRotate === false ) return;
  804. handleTouchMoveRotate( event );
  805. scope.update();
  806. break;
  807. case STATE.TOUCH_PAN:
  808. if ( scope.enablePan === false ) return;
  809. handleTouchMovePan( event );
  810. scope.update();
  811. break;
  812. case STATE.TOUCH_DOLLY_PAN:
  813. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  814. handleTouchMoveDollyPan( event );
  815. scope.update();
  816. break;
  817. case STATE.TOUCH_DOLLY_ROTATE:
  818. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  819. handleTouchMoveDollyRotate( event );
  820. scope.update();
  821. break;
  822. default:
  823. state = STATE.NONE;
  824. }
  825. }
  826. function onContextMenu( event ) {
  827. if ( scope.enabled === false ) return;
  828. event.preventDefault();
  829. }
  830. function addPointer( event ) {
  831. pointers.push( event.pointerId );
  832. }
  833. function removePointer( event ) {
  834. delete pointerPositions[ event.pointerId ];
  835. for ( let i = 0; i < pointers.length; i ++ ) {
  836. if ( pointers[ i ] == event.pointerId ) {
  837. pointers.splice( i, 1 );
  838. return;
  839. }
  840. }
  841. }
  842. function isTrackingPointer( event ) {
  843. for ( let i = 0; i < pointers.length; i ++ ) {
  844. if ( pointers[ i ] == event.pointerId ) return true;
  845. }
  846. return false;
  847. }
  848. function trackPointer( event ) {
  849. let position = pointerPositions[ event.pointerId ];
  850. if ( position === undefined ) {
  851. position = new Vector2();
  852. pointerPositions[ event.pointerId ] = position;
  853. }
  854. position.set( event.pageX, event.pageY );
  855. }
  856. function getSecondPointerPosition( event ) {
  857. const pointerId = ( event.pointerId === pointers[ 0 ] ) ? pointers[ 1 ] : pointers[ 0 ];
  858. return pointerPositions[ pointerId ];
  859. }
  860. //
  861. scope.domElement.addEventListener( 'contextmenu', onContextMenu );
  862. scope.domElement.addEventListener( 'pointerdown', onPointerDown );
  863. scope.domElement.addEventListener( 'pointercancel', onPointerUp );
  864. scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  865. const document = scope.domElement.getRootNode(); // offscreen canvas compatibility
  866. document.addEventListener( 'keydown', interceptControlDown, { passive: true, capture: true } );
  867. // force an update at start
  868. this.update();
  869. }
  870. }
  871. export { OrbitControls };