ArcballControls.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224
  1. import {
  2. GridHelper,
  3. EllipseCurve,
  4. BufferGeometry,
  5. Line,
  6. LineBasicMaterial,
  7. Raycaster,
  8. Group,
  9. Box3,
  10. Sphere,
  11. Quaternion,
  12. Vector2,
  13. Vector3,
  14. Matrix4,
  15. MathUtils,
  16. EventDispatcher
  17. } from 'three';
  18. //trackball state
  19. const STATE = {
  20. IDLE: Symbol(),
  21. ROTATE: Symbol(),
  22. PAN: Symbol(),
  23. SCALE: Symbol(),
  24. FOV: Symbol(),
  25. FOCUS: Symbol(),
  26. ZROTATE: Symbol(),
  27. TOUCH_MULTI: Symbol(),
  28. ANIMATION_FOCUS: Symbol(),
  29. ANIMATION_ROTATE: Symbol()
  30. };
  31. const INPUT = {
  32. NONE: Symbol(),
  33. ONE_FINGER: Symbol(),
  34. ONE_FINGER_SWITCHED: Symbol(),
  35. TWO_FINGER: Symbol(),
  36. MULT_FINGER: Symbol(),
  37. CURSOR: Symbol()
  38. };
  39. //cursor center coordinates
  40. const _center = {
  41. x: 0,
  42. y: 0
  43. };
  44. //transformation matrices for gizmos and camera
  45. const _transformation = {
  46. camera: new Matrix4(),
  47. gizmos: new Matrix4()
  48. };
  49. //events
  50. const _changeEvent = { type: 'change' };
  51. const _startEvent = { type: 'start' };
  52. const _endEvent = { type: 'end' };
  53. const _raycaster = new Raycaster();
  54. const _offset = new Vector3();
  55. const _gizmoMatrixStateTemp = new Matrix4();
  56. const _cameraMatrixStateTemp = new Matrix4();
  57. const _scalePointTemp = new Vector3();
  58. /**
  59. *
  60. * @param {Camera} camera Virtual camera used in the scene
  61. * @param {HTMLElement} domElement Renderer's dom element
  62. * @param {Scene} scene The scene to be rendered
  63. */
  64. class ArcballControls extends EventDispatcher {
  65. constructor( camera, domElement, scene = null ) {
  66. super();
  67. this.camera = null;
  68. this.domElement = domElement;
  69. this.scene = scene;
  70. this.target = new Vector3();
  71. this._currentTarget = new Vector3();
  72. this.radiusFactor = 0.67;
  73. this.mouseActions = [];
  74. this._mouseOp = null;
  75. //global vectors and matrices that are used in some operations to avoid creating new objects every time (e.g. every time cursor moves)
  76. this._v2_1 = new Vector2();
  77. this._v3_1 = new Vector3();
  78. this._v3_2 = new Vector3();
  79. this._m4_1 = new Matrix4();
  80. this._m4_2 = new Matrix4();
  81. this._quat = new Quaternion();
  82. //transformation matrices
  83. this._translationMatrix = new Matrix4(); //matrix for translation operation
  84. this._rotationMatrix = new Matrix4(); //matrix for rotation operation
  85. this._scaleMatrix = new Matrix4(); //matrix for scaling operation
  86. this._rotationAxis = new Vector3(); //axis for rotate operation
  87. //camera state
  88. this._cameraMatrixState = new Matrix4();
  89. this._cameraProjectionState = new Matrix4();
  90. this._fovState = 1;
  91. this._upState = new Vector3();
  92. this._zoomState = 1;
  93. this._nearPos = 0;
  94. this._farPos = 0;
  95. this._gizmoMatrixState = new Matrix4();
  96. //initial values
  97. this._up0 = new Vector3();
  98. this._zoom0 = 1;
  99. this._fov0 = 0;
  100. this._initialNear = 0;
  101. this._nearPos0 = 0;
  102. this._initialFar = 0;
  103. this._farPos0 = 0;
  104. this._cameraMatrixState0 = new Matrix4();
  105. this._gizmoMatrixState0 = new Matrix4();
  106. //pointers array
  107. this._button = - 1;
  108. this._touchStart = [];
  109. this._touchCurrent = [];
  110. this._input = INPUT.NONE;
  111. //two fingers touch interaction
  112. this._switchSensibility = 32; //minimum movement to be performed to fire single pan start after the second finger has been released
  113. this._startFingerDistance = 0; //distance between two fingers
  114. this._currentFingerDistance = 0;
  115. this._startFingerRotation = 0; //amount of rotation performed with two fingers
  116. this._currentFingerRotation = 0;
  117. //double tap
  118. this._devPxRatio = 0;
  119. this._downValid = true;
  120. this._nclicks = 0;
  121. this._downEvents = [];
  122. this._downStart = 0; //pointerDown time
  123. this._clickStart = 0; //first click time
  124. this._maxDownTime = 250;
  125. this._maxInterval = 300;
  126. this._posThreshold = 24;
  127. this._movementThreshold = 24;
  128. //cursor positions
  129. this._currentCursorPosition = new Vector3();
  130. this._startCursorPosition = new Vector3();
  131. //grid
  132. this._grid = null; //grid to be visualized during pan operation
  133. this._gridPosition = new Vector3();
  134. //gizmos
  135. this._gizmos = new Group();
  136. this._curvePts = 128;
  137. //animations
  138. this._timeStart = - 1; //initial time
  139. this._animationId = - 1;
  140. //focus animation
  141. this.focusAnimationTime = 500; //duration of focus animation in ms
  142. //rotate animation
  143. this._timePrev = 0; //time at which previous rotate operation has been detected
  144. this._timeCurrent = 0; //time at which current rotate operation has been detected
  145. this._anglePrev = 0; //angle of previous rotation
  146. this._angleCurrent = 0; //angle of current rotation
  147. this._cursorPosPrev = new Vector3(); //cursor position when previous rotate operation has been detected
  148. this._cursorPosCurr = new Vector3();//cursor position when current rotate operation has been detected
  149. this._wPrev = 0; //angular velocity of the previous rotate operation
  150. this._wCurr = 0; //angular velocity of the current rotate operation
  151. //parameters
  152. this.adjustNearFar = false;
  153. this.scaleFactor = 1.1; //zoom/distance multiplier
  154. this.dampingFactor = 25;
  155. this.wMax = 20; //maximum angular velocity allowed
  156. this.enableAnimations = true; //if animations should be performed
  157. this.enableGrid = false; //if grid should be showed during pan operation
  158. this.cursorZoom = false; //if wheel zoom should be cursor centered
  159. this.minFov = 5;
  160. this.maxFov = 90;
  161. this.rotateSpeed = 1;
  162. this.enabled = true;
  163. this.enablePan = true;
  164. this.enableRotate = true;
  165. this.enableZoom = true;
  166. this.enableGizmos = true;
  167. this.minDistance = 0;
  168. this.maxDistance = Infinity;
  169. this.minZoom = 0;
  170. this.maxZoom = Infinity;
  171. //trackball parameters
  172. this._tbRadius = 1;
  173. //FSA
  174. this._state = STATE.IDLE;
  175. this.setCamera( camera );
  176. if ( this.scene != null ) {
  177. this.scene.add( this._gizmos );
  178. }
  179. this.domElement.style.touchAction = 'none';
  180. this._devPxRatio = window.devicePixelRatio;
  181. this.initializeMouseActions();
  182. this._onContextMenu = onContextMenu.bind( this );
  183. this._onWheel = onWheel.bind( this );
  184. this._onPointerUp = onPointerUp.bind( this );
  185. this._onPointerMove = onPointerMove.bind( this );
  186. this._onPointerDown = onPointerDown.bind( this );
  187. this._onPointerCancel = onPointerCancel.bind( this );
  188. this._onWindowResize = onWindowResize.bind( this );
  189. this.domElement.addEventListener( 'contextmenu', this._onContextMenu );
  190. this.domElement.addEventListener( 'wheel', this._onWheel );
  191. this.domElement.addEventListener( 'pointerdown', this._onPointerDown );
  192. this.domElement.addEventListener( 'pointercancel', this._onPointerCancel );
  193. window.addEventListener( 'resize', this._onWindowResize );
  194. }
  195. onSinglePanStart( event, operation ) {
  196. if ( this.enabled ) {
  197. this.dispatchEvent( _startEvent );
  198. this.setCenter( event.clientX, event.clientY );
  199. switch ( operation ) {
  200. case 'PAN':
  201. if ( ! this.enablePan ) {
  202. return;
  203. }
  204. if ( this._animationId != - 1 ) {
  205. cancelAnimationFrame( this._animationId );
  206. this._animationId = - 1;
  207. this._timeStart = - 1;
  208. this.activateGizmos( false );
  209. this.dispatchEvent( _changeEvent );
  210. }
  211. this.updateTbState( STATE.PAN, true );
  212. this._startCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) );
  213. if ( this.enableGrid ) {
  214. this.drawGrid();
  215. this.dispatchEvent( _changeEvent );
  216. }
  217. break;
  218. case 'ROTATE':
  219. if ( ! this.enableRotate ) {
  220. return;
  221. }
  222. if ( this._animationId != - 1 ) {
  223. cancelAnimationFrame( this._animationId );
  224. this._animationId = - 1;
  225. this._timeStart = - 1;
  226. }
  227. this.updateTbState( STATE.ROTATE, true );
  228. this._startCursorPosition.copy( this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ) );
  229. this.activateGizmos( true );
  230. if ( this.enableAnimations ) {
  231. this._timePrev = this._timeCurrent = performance.now();
  232. this._angleCurrent = this._anglePrev = 0;
  233. this._cursorPosPrev.copy( this._startCursorPosition );
  234. this._cursorPosCurr.copy( this._cursorPosPrev );
  235. this._wCurr = 0;
  236. this._wPrev = this._wCurr;
  237. }
  238. this.dispatchEvent( _changeEvent );
  239. break;
  240. case 'FOV':
  241. if ( ! this.camera.isPerspectiveCamera || ! this.enableZoom ) {
  242. return;
  243. }
  244. if ( this._animationId != - 1 ) {
  245. cancelAnimationFrame( this._animationId );
  246. this._animationId = - 1;
  247. this._timeStart = - 1;
  248. this.activateGizmos( false );
  249. this.dispatchEvent( _changeEvent );
  250. }
  251. this.updateTbState( STATE.FOV, true );
  252. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  253. this._currentCursorPosition.copy( this._startCursorPosition );
  254. break;
  255. case 'ZOOM':
  256. if ( ! this.enableZoom ) {
  257. return;
  258. }
  259. if ( this._animationId != - 1 ) {
  260. cancelAnimationFrame( this._animationId );
  261. this._animationId = - 1;
  262. this._timeStart = - 1;
  263. this.activateGizmos( false );
  264. this.dispatchEvent( _changeEvent );
  265. }
  266. this.updateTbState( STATE.SCALE, true );
  267. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  268. this._currentCursorPosition.copy( this._startCursorPosition );
  269. break;
  270. }
  271. }
  272. }
  273. onSinglePanMove( event, opState ) {
  274. if ( this.enabled ) {
  275. const restart = opState != this._state;
  276. this.setCenter( event.clientX, event.clientY );
  277. switch ( opState ) {
  278. case STATE.PAN:
  279. if ( this.enablePan ) {
  280. if ( restart ) {
  281. //switch to pan operation
  282. this.dispatchEvent( _endEvent );
  283. this.dispatchEvent( _startEvent );
  284. this.updateTbState( opState, true );
  285. this._startCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) );
  286. if ( this.enableGrid ) {
  287. this.drawGrid();
  288. }
  289. this.activateGizmos( false );
  290. } else {
  291. //continue with pan operation
  292. this._currentCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ) );
  293. this.applyTransformMatrix( this.pan( this._startCursorPosition, this._currentCursorPosition ) );
  294. }
  295. }
  296. break;
  297. case STATE.ROTATE:
  298. if ( this.enableRotate ) {
  299. if ( restart ) {
  300. //switch to rotate operation
  301. this.dispatchEvent( _endEvent );
  302. this.dispatchEvent( _startEvent );
  303. this.updateTbState( opState, true );
  304. this._startCursorPosition.copy( this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ) );
  305. if ( this.enableGrid ) {
  306. this.disposeGrid();
  307. }
  308. this.activateGizmos( true );
  309. } else {
  310. //continue with rotate operation
  311. this._currentCursorPosition.copy( this.unprojectOnTbSurface( this.camera, _center.x, _center.y, this.domElement, this._tbRadius ) );
  312. const distance = this._startCursorPosition.distanceTo( this._currentCursorPosition );
  313. const angle = this._startCursorPosition.angleTo( this._currentCursorPosition );
  314. const amount = Math.max( distance / this._tbRadius, angle ) * this.rotateSpeed; //effective rotation angle
  315. this.applyTransformMatrix( this.rotate( this.calculateRotationAxis( this._startCursorPosition, this._currentCursorPosition ), amount ) );
  316. if ( this.enableAnimations ) {
  317. this._timePrev = this._timeCurrent;
  318. this._timeCurrent = performance.now();
  319. this._anglePrev = this._angleCurrent;
  320. this._angleCurrent = amount;
  321. this._cursorPosPrev.copy( this._cursorPosCurr );
  322. this._cursorPosCurr.copy( this._currentCursorPosition );
  323. this._wPrev = this._wCurr;
  324. this._wCurr = this.calculateAngularSpeed( this._anglePrev, this._angleCurrent, this._timePrev, this._timeCurrent );
  325. }
  326. }
  327. }
  328. break;
  329. case STATE.SCALE:
  330. if ( this.enableZoom ) {
  331. if ( restart ) {
  332. //switch to zoom operation
  333. this.dispatchEvent( _endEvent );
  334. this.dispatchEvent( _startEvent );
  335. this.updateTbState( opState, true );
  336. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  337. this._currentCursorPosition.copy( this._startCursorPosition );
  338. if ( this.enableGrid ) {
  339. this.disposeGrid();
  340. }
  341. this.activateGizmos( false );
  342. } else {
  343. //continue with zoom operation
  344. const screenNotches = 8; //how many wheel notches corresponds to a full screen pan
  345. this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  346. const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
  347. let size = 1;
  348. if ( movement < 0 ) {
  349. size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) );
  350. } else if ( movement > 0 ) {
  351. size = Math.pow( this.scaleFactor, movement * screenNotches );
  352. }
  353. this._v3_1.setFromMatrixPosition( this._gizmoMatrixState );
  354. this.applyTransformMatrix( this.scale( size, this._v3_1 ) );
  355. }
  356. }
  357. break;
  358. case STATE.FOV:
  359. if ( this.enableZoom && this.camera.isPerspectiveCamera ) {
  360. if ( restart ) {
  361. //switch to fov operation
  362. this.dispatchEvent( _endEvent );
  363. this.dispatchEvent( _startEvent );
  364. this.updateTbState( opState, true );
  365. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  366. this._currentCursorPosition.copy( this._startCursorPosition );
  367. if ( this.enableGrid ) {
  368. this.disposeGrid();
  369. }
  370. this.activateGizmos( false );
  371. } else {
  372. //continue with fov operation
  373. const screenNotches = 8; //how many wheel notches corresponds to a full screen pan
  374. this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  375. const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
  376. let size = 1;
  377. if ( movement < 0 ) {
  378. size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) );
  379. } else if ( movement > 0 ) {
  380. size = Math.pow( this.scaleFactor, movement * screenNotches );
  381. }
  382. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  383. const x = this._v3_1.distanceTo( this._gizmos.position );
  384. let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
  385. //check min and max distance
  386. xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance );
  387. const y = x * Math.tan( MathUtils.DEG2RAD * this._fovState * 0.5 );
  388. //calculate new fov
  389. let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 );
  390. //check min and max fov
  391. newFov = MathUtils.clamp( newFov, this.minFov, this.maxFov );
  392. const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) );
  393. size = x / newDistance;
  394. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  395. this.setFov( newFov );
  396. this.applyTransformMatrix( this.scale( size, this._v3_2, false ) );
  397. //adjusting distance
  398. _offset.copy( this._gizmos.position ).sub( this.camera.position ).normalize().multiplyScalar( newDistance / x );
  399. this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z );
  400. }
  401. }
  402. break;
  403. }
  404. this.dispatchEvent( _changeEvent );
  405. }
  406. }
  407. onSinglePanEnd() {
  408. if ( this._state == STATE.ROTATE ) {
  409. if ( ! this.enableRotate ) {
  410. return;
  411. }
  412. if ( this.enableAnimations ) {
  413. //perform rotation animation
  414. const deltaTime = ( performance.now() - this._timeCurrent );
  415. if ( deltaTime < 120 ) {
  416. const w = Math.abs( ( this._wPrev + this._wCurr ) / 2 );
  417. const self = this;
  418. this._animationId = window.requestAnimationFrame( function ( t ) {
  419. self.updateTbState( STATE.ANIMATION_ROTATE, true );
  420. const rotationAxis = self.calculateRotationAxis( self._cursorPosPrev, self._cursorPosCurr );
  421. self.onRotationAnim( t, rotationAxis, Math.min( w, self.wMax ) );
  422. } );
  423. } else {
  424. //cursor has been standing still for over 120 ms since last movement
  425. this.updateTbState( STATE.IDLE, false );
  426. this.activateGizmos( false );
  427. this.dispatchEvent( _changeEvent );
  428. }
  429. } else {
  430. this.updateTbState( STATE.IDLE, false );
  431. this.activateGizmos( false );
  432. this.dispatchEvent( _changeEvent );
  433. }
  434. } else if ( this._state == STATE.PAN || this._state == STATE.IDLE ) {
  435. this.updateTbState( STATE.IDLE, false );
  436. if ( this.enableGrid ) {
  437. this.disposeGrid();
  438. }
  439. this.activateGizmos( false );
  440. this.dispatchEvent( _changeEvent );
  441. }
  442. this.dispatchEvent( _endEvent );
  443. }
  444. onDoubleTap( event ) {
  445. if ( this.enabled && this.enablePan && this.scene != null ) {
  446. this.dispatchEvent( _startEvent );
  447. this.setCenter( event.clientX, event.clientY );
  448. const hitP = this.unprojectOnObj( this.getCursorNDC( _center.x, _center.y, this.domElement ), this.camera );
  449. if ( hitP != null && this.enableAnimations ) {
  450. const self = this;
  451. if ( this._animationId != - 1 ) {
  452. window.cancelAnimationFrame( this._animationId );
  453. }
  454. this._timeStart = - 1;
  455. this._animationId = window.requestAnimationFrame( function ( t ) {
  456. self.updateTbState( STATE.ANIMATION_FOCUS, true );
  457. self.onFocusAnim( t, hitP, self._cameraMatrixState, self._gizmoMatrixState );
  458. } );
  459. } else if ( hitP != null && ! this.enableAnimations ) {
  460. this.updateTbState( STATE.FOCUS, true );
  461. this.focus( hitP, this.scaleFactor );
  462. this.updateTbState( STATE.IDLE, false );
  463. this.dispatchEvent( _changeEvent );
  464. }
  465. }
  466. this.dispatchEvent( _endEvent );
  467. }
  468. onDoublePanStart() {
  469. if ( this.enabled && this.enablePan ) {
  470. this.dispatchEvent( _startEvent );
  471. this.updateTbState( STATE.PAN, true );
  472. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  473. this._startCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement, true ) );
  474. this._currentCursorPosition.copy( this._startCursorPosition );
  475. this.activateGizmos( false );
  476. }
  477. }
  478. onDoublePanMove() {
  479. if ( this.enabled && this.enablePan ) {
  480. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  481. if ( this._state != STATE.PAN ) {
  482. this.updateTbState( STATE.PAN, true );
  483. this._startCursorPosition.copy( this._currentCursorPosition );
  484. }
  485. this._currentCursorPosition.copy( this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement, true ) );
  486. this.applyTransformMatrix( this.pan( this._startCursorPosition, this._currentCursorPosition, true ) );
  487. this.dispatchEvent( _changeEvent );
  488. }
  489. }
  490. onDoublePanEnd() {
  491. this.updateTbState( STATE.IDLE, false );
  492. this.dispatchEvent( _endEvent );
  493. }
  494. onRotateStart() {
  495. if ( this.enabled && this.enableRotate ) {
  496. this.dispatchEvent( _startEvent );
  497. this.updateTbState( STATE.ZROTATE, true );
  498. //this._startFingerRotation = event.rotation;
  499. this._startFingerRotation = this.getAngle( this._touchCurrent[ 1 ], this._touchCurrent[ 0 ] ) + this.getAngle( this._touchStart[ 1 ], this._touchStart[ 0 ] );
  500. this._currentFingerRotation = this._startFingerRotation;
  501. this.camera.getWorldDirection( this._rotationAxis ); //rotation axis
  502. if ( ! this.enablePan && ! this.enableZoom ) {
  503. this.activateGizmos( true );
  504. }
  505. }
  506. }
  507. onRotateMove() {
  508. if ( this.enabled && this.enableRotate ) {
  509. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  510. let rotationPoint;
  511. if ( this._state != STATE.ZROTATE ) {
  512. this.updateTbState( STATE.ZROTATE, true );
  513. this._startFingerRotation = this._currentFingerRotation;
  514. }
  515. //this._currentFingerRotation = event.rotation;
  516. this._currentFingerRotation = this.getAngle( this._touchCurrent[ 1 ], this._touchCurrent[ 0 ] ) + this.getAngle( this._touchStart[ 1 ], this._touchStart[ 0 ] );
  517. if ( ! this.enablePan ) {
  518. rotationPoint = new Vector3().setFromMatrixPosition( this._gizmoMatrixState );
  519. } else {
  520. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  521. rotationPoint = this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement ).applyQuaternion( this.camera.quaternion ).multiplyScalar( 1 / this.camera.zoom ).add( this._v3_2 );
  522. }
  523. const amount = MathUtils.DEG2RAD * ( this._startFingerRotation - this._currentFingerRotation );
  524. this.applyTransformMatrix( this.zRotate( rotationPoint, amount ) );
  525. this.dispatchEvent( _changeEvent );
  526. }
  527. }
  528. onRotateEnd() {
  529. this.updateTbState( STATE.IDLE, false );
  530. this.activateGizmos( false );
  531. this.dispatchEvent( _endEvent );
  532. }
  533. onPinchStart() {
  534. if ( this.enabled && this.enableZoom ) {
  535. this.dispatchEvent( _startEvent );
  536. this.updateTbState( STATE.SCALE, true );
  537. this._startFingerDistance = this.calculatePointersDistance( this._touchCurrent[ 0 ], this._touchCurrent[ 1 ] );
  538. this._currentFingerDistance = this._startFingerDistance;
  539. this.activateGizmos( false );
  540. }
  541. }
  542. onPinchMove() {
  543. if ( this.enabled && this.enableZoom ) {
  544. this.setCenter( ( this._touchCurrent[ 0 ].clientX + this._touchCurrent[ 1 ].clientX ) / 2, ( this._touchCurrent[ 0 ].clientY + this._touchCurrent[ 1 ].clientY ) / 2 );
  545. const minDistance = 12; //minimum distance between fingers (in css pixels)
  546. if ( this._state != STATE.SCALE ) {
  547. this._startFingerDistance = this._currentFingerDistance;
  548. this.updateTbState( STATE.SCALE, true );
  549. }
  550. this._currentFingerDistance = Math.max( this.calculatePointersDistance( this._touchCurrent[ 0 ], this._touchCurrent[ 1 ] ), minDistance * this._devPxRatio );
  551. const amount = this._currentFingerDistance / this._startFingerDistance;
  552. let scalePoint;
  553. if ( ! this.enablePan ) {
  554. scalePoint = this._gizmos.position;
  555. } else {
  556. if ( this.camera.isOrthographicCamera ) {
  557. scalePoint = this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement )
  558. .applyQuaternion( this.camera.quaternion )
  559. .multiplyScalar( 1 / this.camera.zoom )
  560. .add( this._gizmos.position );
  561. } else if ( this.camera.isPerspectiveCamera ) {
  562. scalePoint = this.unprojectOnTbPlane( this.camera, _center.x, _center.y, this.domElement )
  563. .applyQuaternion( this.camera.quaternion )
  564. .add( this._gizmos.position );
  565. }
  566. }
  567. this.applyTransformMatrix( this.scale( amount, scalePoint ) );
  568. this.dispatchEvent( _changeEvent );
  569. }
  570. }
  571. onPinchEnd() {
  572. this.updateTbState( STATE.IDLE, false );
  573. this.dispatchEvent( _endEvent );
  574. }
  575. onTriplePanStart() {
  576. if ( this.enabled && this.enableZoom ) {
  577. this.dispatchEvent( _startEvent );
  578. this.updateTbState( STATE.SCALE, true );
  579. //const center = event.center;
  580. let clientX = 0;
  581. let clientY = 0;
  582. const nFingers = this._touchCurrent.length;
  583. for ( let i = 0; i < nFingers; i ++ ) {
  584. clientX += this._touchCurrent[ i ].clientX;
  585. clientY += this._touchCurrent[ i ].clientY;
  586. }
  587. this.setCenter( clientX / nFingers, clientY / nFingers );
  588. this._startCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  589. this._currentCursorPosition.copy( this._startCursorPosition );
  590. }
  591. }
  592. onTriplePanMove() {
  593. if ( this.enabled && this.enableZoom ) {
  594. // fov / 2
  595. // |\
  596. // | \
  597. // | \
  598. // x | \
  599. // | \
  600. // | \
  601. // | _ _ _\
  602. // y
  603. //const center = event.center;
  604. let clientX = 0;
  605. let clientY = 0;
  606. const nFingers = this._touchCurrent.length;
  607. for ( let i = 0; i < nFingers; i ++ ) {
  608. clientX += this._touchCurrent[ i ].clientX;
  609. clientY += this._touchCurrent[ i ].clientY;
  610. }
  611. this.setCenter( clientX / nFingers, clientY / nFingers );
  612. const screenNotches = 8; //how many wheel notches corresponds to a full screen pan
  613. this._currentCursorPosition.setY( this.getCursorNDC( _center.x, _center.y, this.domElement ).y * 0.5 );
  614. const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
  615. let size = 1;
  616. if ( movement < 0 ) {
  617. size = 1 / ( Math.pow( this.scaleFactor, - movement * screenNotches ) );
  618. } else if ( movement > 0 ) {
  619. size = Math.pow( this.scaleFactor, movement * screenNotches );
  620. }
  621. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  622. const x = this._v3_1.distanceTo( this._gizmos.position );
  623. let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
  624. //check min and max distance
  625. xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance );
  626. const y = x * Math.tan( MathUtils.DEG2RAD * this._fovState * 0.5 );
  627. //calculate new fov
  628. let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 );
  629. //check min and max fov
  630. newFov = MathUtils.clamp( newFov, this.minFov, this.maxFov );
  631. const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) );
  632. size = x / newDistance;
  633. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  634. this.setFov( newFov );
  635. this.applyTransformMatrix( this.scale( size, this._v3_2, false ) );
  636. //adjusting distance
  637. _offset.copy( this._gizmos.position ).sub( this.camera.position ).normalize().multiplyScalar( newDistance / x );
  638. this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z );
  639. this.dispatchEvent( _changeEvent );
  640. }
  641. }
  642. onTriplePanEnd() {
  643. this.updateTbState( STATE.IDLE, false );
  644. this.dispatchEvent( _endEvent );
  645. //this.dispatchEvent( _changeEvent );
  646. }
  647. /**
  648. * Set _center's x/y coordinates
  649. * @param {Number} clientX
  650. * @param {Number} clientY
  651. */
  652. setCenter( clientX, clientY ) {
  653. _center.x = clientX;
  654. _center.y = clientY;
  655. }
  656. /**
  657. * Set default mouse actions
  658. */
  659. initializeMouseActions() {
  660. this.setMouseAction( 'PAN', 0, 'CTRL' );
  661. this.setMouseAction( 'PAN', 2 );
  662. this.setMouseAction( 'ROTATE', 0 );
  663. this.setMouseAction( 'ZOOM', 'WHEEL' );
  664. this.setMouseAction( 'ZOOM', 1 );
  665. this.setMouseAction( 'FOV', 'WHEEL', 'SHIFT' );
  666. this.setMouseAction( 'FOV', 1, 'SHIFT' );
  667. }
  668. /**
  669. * Compare two mouse actions
  670. * @param {Object} action1
  671. * @param {Object} action2
  672. * @returns {Boolean} True if action1 and action 2 are the same mouse action, false otherwise
  673. */
  674. compareMouseAction( action1, action2 ) {
  675. if ( action1.operation == action2.operation ) {
  676. if ( action1.mouse == action2.mouse && action1.key == action2.key ) {
  677. return true;
  678. } else {
  679. return false;
  680. }
  681. } else {
  682. return false;
  683. }
  684. }
  685. /**
  686. * Set a new mouse action by specifying the operation to be performed and a mouse/key combination. In case of conflict, replaces the existing one
  687. * @param {String} operation The operation to be performed ('PAN', 'ROTATE', 'ZOOM', 'FOV)
  688. * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches
  689. * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed
  690. * @returns {Boolean} True if the mouse action has been successfully added, false otherwise
  691. */
  692. setMouseAction( operation, mouse, key = null ) {
  693. const operationInput = [ 'PAN', 'ROTATE', 'ZOOM', 'FOV' ];
  694. const mouseInput = [ 0, 1, 2, 'WHEEL' ];
  695. const keyInput = [ 'CTRL', 'SHIFT', null ];
  696. let state;
  697. if ( ! operationInput.includes( operation ) || ! mouseInput.includes( mouse ) || ! keyInput.includes( key ) ) {
  698. //invalid parameters
  699. return false;
  700. }
  701. if ( mouse == 'WHEEL' ) {
  702. if ( operation != 'ZOOM' && operation != 'FOV' ) {
  703. //cannot associate 2D operation to 1D input
  704. return false;
  705. }
  706. }
  707. switch ( operation ) {
  708. case 'PAN':
  709. state = STATE.PAN;
  710. break;
  711. case 'ROTATE':
  712. state = STATE.ROTATE;
  713. break;
  714. case 'ZOOM':
  715. state = STATE.SCALE;
  716. break;
  717. case 'FOV':
  718. state = STATE.FOV;
  719. break;
  720. }
  721. const action = {
  722. operation: operation,
  723. mouse: mouse,
  724. key: key,
  725. state: state
  726. };
  727. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  728. if ( this.mouseActions[ i ].mouse == action.mouse && this.mouseActions[ i ].key == action.key ) {
  729. this.mouseActions.splice( i, 1, action );
  730. return true;
  731. }
  732. }
  733. this.mouseActions.push( action );
  734. return true;
  735. }
  736. /**
  737. * Remove a mouse action by specifying its mouse/key combination
  738. * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches
  739. * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed
  740. * @returns {Boolean} True if the operation has been succesfully removed, false otherwise
  741. */
  742. unsetMouseAction( mouse, key = null ) {
  743. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  744. if ( this.mouseActions[ i ].mouse == mouse && this.mouseActions[ i ].key == key ) {
  745. this.mouseActions.splice( i, 1 );
  746. return true;
  747. }
  748. }
  749. return false;
  750. }
  751. /**
  752. * Return the operation associated to a mouse/keyboard combination
  753. * @param {*} mouse A mouse button (0, 1, 2) or 'WHEEL' for wheel notches
  754. * @param {*} key The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed
  755. * @returns The operation if it has been found, null otherwise
  756. */
  757. getOpFromAction( mouse, key ) {
  758. let action;
  759. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  760. action = this.mouseActions[ i ];
  761. if ( action.mouse == mouse && action.key == key ) {
  762. return action.operation;
  763. }
  764. }
  765. if ( key != null ) {
  766. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  767. action = this.mouseActions[ i ];
  768. if ( action.mouse == mouse && action.key == null ) {
  769. return action.operation;
  770. }
  771. }
  772. }
  773. return null;
  774. }
  775. /**
  776. * Get the operation associated to mouse and key combination and returns the corresponding FSA state
  777. * @param {Number} mouse Mouse button
  778. * @param {String} key Keyboard modifier
  779. * @returns The FSA state obtained from the operation associated to mouse/keyboard combination
  780. */
  781. getOpStateFromAction( mouse, key ) {
  782. let action;
  783. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  784. action = this.mouseActions[ i ];
  785. if ( action.mouse == mouse && action.key == key ) {
  786. return action.state;
  787. }
  788. }
  789. if ( key != null ) {
  790. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  791. action = this.mouseActions[ i ];
  792. if ( action.mouse == mouse && action.key == null ) {
  793. return action.state;
  794. }
  795. }
  796. }
  797. return null;
  798. }
  799. /**
  800. * Calculate the angle between two pointers
  801. * @param {PointerEvent} p1
  802. * @param {PointerEvent} p2
  803. * @returns {Number} The angle between two pointers in degrees
  804. */
  805. getAngle( p1, p2 ) {
  806. return Math.atan2( p2.clientY - p1.clientY, p2.clientX - p1.clientX ) * 180 / Math.PI;
  807. }
  808. /**
  809. * Update a PointerEvent inside current pointerevents array
  810. * @param {PointerEvent} event
  811. */
  812. updateTouchEvent( event ) {
  813. for ( let i = 0; i < this._touchCurrent.length; i ++ ) {
  814. if ( this._touchCurrent[ i ].pointerId == event.pointerId ) {
  815. this._touchCurrent.splice( i, 1, event );
  816. break;
  817. }
  818. }
  819. }
  820. /**
  821. * Apply a transformation matrix, to the camera and gizmos
  822. * @param {Object} transformation Object containing matrices to apply to camera and gizmos
  823. */
  824. applyTransformMatrix( transformation ) {
  825. if ( transformation.camera != null ) {
  826. this._m4_1.copy( this._cameraMatrixState ).premultiply( transformation.camera );
  827. this._m4_1.decompose( this.camera.position, this.camera.quaternion, this.camera.scale );
  828. this.camera.updateMatrix();
  829. //update camera up vector
  830. if ( this._state == STATE.ROTATE || this._state == STATE.ZROTATE || this._state == STATE.ANIMATION_ROTATE ) {
  831. this.camera.up.copy( this._upState ).applyQuaternion( this.camera.quaternion );
  832. }
  833. }
  834. if ( transformation.gizmos != null ) {
  835. this._m4_1.copy( this._gizmoMatrixState ).premultiply( transformation.gizmos );
  836. this._m4_1.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  837. this._gizmos.updateMatrix();
  838. }
  839. if ( this._state == STATE.SCALE || this._state == STATE.FOCUS || this._state == STATE.ANIMATION_FOCUS ) {
  840. this._tbRadius = this.calculateTbRadius( this.camera );
  841. if ( this.adjustNearFar ) {
  842. const cameraDistance = this.camera.position.distanceTo( this._gizmos.position );
  843. const bb = new Box3();
  844. bb.setFromObject( this._gizmos );
  845. const sphere = new Sphere();
  846. bb.getBoundingSphere( sphere );
  847. const adjustedNearPosition = Math.max( this._nearPos0, sphere.radius + sphere.center.length() );
  848. const regularNearPosition = cameraDistance - this._initialNear;
  849. const minNearPos = Math.min( adjustedNearPosition, regularNearPosition );
  850. this.camera.near = cameraDistance - minNearPos;
  851. const adjustedFarPosition = Math.min( this._farPos0, - sphere.radius + sphere.center.length() );
  852. const regularFarPosition = cameraDistance - this._initialFar;
  853. const minFarPos = Math.min( adjustedFarPosition, regularFarPosition );
  854. this.camera.far = cameraDistance - minFarPos;
  855. this.camera.updateProjectionMatrix();
  856. } else {
  857. let update = false;
  858. if ( this.camera.near != this._initialNear ) {
  859. this.camera.near = this._initialNear;
  860. update = true;
  861. }
  862. if ( this.camera.far != this._initialFar ) {
  863. this.camera.far = this._initialFar;
  864. update = true;
  865. }
  866. if ( update ) {
  867. this.camera.updateProjectionMatrix();
  868. }
  869. }
  870. }
  871. }
  872. /**
  873. * Calculate the angular speed
  874. * @param {Number} p0 Position at t0
  875. * @param {Number} p1 Position at t1
  876. * @param {Number} t0 Initial time in milliseconds
  877. * @param {Number} t1 Ending time in milliseconds
  878. */
  879. calculateAngularSpeed( p0, p1, t0, t1 ) {
  880. const s = p1 - p0;
  881. const t = ( t1 - t0 ) / 1000;
  882. if ( t == 0 ) {
  883. return 0;
  884. }
  885. return s / t;
  886. }
  887. /**
  888. * Calculate the distance between two pointers
  889. * @param {PointerEvent} p0 The first pointer
  890. * @param {PointerEvent} p1 The second pointer
  891. * @returns {number} The distance between the two pointers
  892. */
  893. calculatePointersDistance( p0, p1 ) {
  894. return Math.sqrt( Math.pow( p1.clientX - p0.clientX, 2 ) + Math.pow( p1.clientY - p0.clientY, 2 ) );
  895. }
  896. /**
  897. * Calculate the rotation axis as the vector perpendicular between two vectors
  898. * @param {Vector3} vec1 The first vector
  899. * @param {Vector3} vec2 The second vector
  900. * @returns {Vector3} The normalized rotation axis
  901. */
  902. calculateRotationAxis( vec1, vec2 ) {
  903. this._rotationMatrix.extractRotation( this._cameraMatrixState );
  904. this._quat.setFromRotationMatrix( this._rotationMatrix );
  905. this._rotationAxis.crossVectors( vec1, vec2 ).applyQuaternion( this._quat );
  906. return this._rotationAxis.normalize().clone();
  907. }
  908. /**
  909. * Calculate the trackball radius so that gizmo's diamater will be 2/3 of the minimum side of the camera frustum
  910. * @param {Camera} camera
  911. * @returns {Number} The trackball radius
  912. */
  913. calculateTbRadius( camera ) {
  914. const distance = camera.position.distanceTo( this._gizmos.position );
  915. if ( camera.type == 'PerspectiveCamera' ) {
  916. const halfFovV = MathUtils.DEG2RAD * camera.fov * 0.5; //vertical fov/2 in radians
  917. const halfFovH = Math.atan( ( camera.aspect ) * Math.tan( halfFovV ) ); //horizontal fov/2 in radians
  918. return Math.tan( Math.min( halfFovV, halfFovH ) ) * distance * this.radiusFactor;
  919. } else if ( camera.type == 'OrthographicCamera' ) {
  920. return Math.min( camera.top, camera.right ) * this.radiusFactor;
  921. }
  922. }
  923. /**
  924. * Focus operation consist of positioning the point of interest in front of the camera and a slightly zoom in
  925. * @param {Vector3} point The point of interest
  926. * @param {Number} size Scale factor
  927. * @param {Number} amount Amount of operation to be completed (used for focus animations, default is complete full operation)
  928. */
  929. focus( point, size, amount = 1 ) {
  930. //move center of camera (along with gizmos) towards point of interest
  931. _offset.copy( point ).sub( this._gizmos.position ).multiplyScalar( amount );
  932. this._translationMatrix.makeTranslation( _offset.x, _offset.y, _offset.z );
  933. _gizmoMatrixStateTemp.copy( this._gizmoMatrixState );
  934. this._gizmoMatrixState.premultiply( this._translationMatrix );
  935. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  936. _cameraMatrixStateTemp.copy( this._cameraMatrixState );
  937. this._cameraMatrixState.premultiply( this._translationMatrix );
  938. this._cameraMatrixState.decompose( this.camera.position, this.camera.quaternion, this.camera.scale );
  939. //apply zoom
  940. if ( this.enableZoom ) {
  941. this.applyTransformMatrix( this.scale( size, this._gizmos.position ) );
  942. }
  943. this._gizmoMatrixState.copy( _gizmoMatrixStateTemp );
  944. this._cameraMatrixState.copy( _cameraMatrixStateTemp );
  945. }
  946. /**
  947. * Draw a grid and add it to the scene
  948. */
  949. drawGrid() {
  950. if ( this.scene != null ) {
  951. const color = 0x888888;
  952. const multiplier = 3;
  953. let size, divisions, maxLength, tick;
  954. if ( this.camera.isOrthographicCamera ) {
  955. const width = this.camera.right - this.camera.left;
  956. const height = this.camera.bottom - this.camera.top;
  957. maxLength = Math.max( width, height );
  958. tick = maxLength / 20;
  959. size = maxLength / this.camera.zoom * multiplier;
  960. divisions = size / tick * this.camera.zoom;
  961. } else if ( this.camera.isPerspectiveCamera ) {
  962. const distance = this.camera.position.distanceTo( this._gizmos.position );
  963. const halfFovV = MathUtils.DEG2RAD * this.camera.fov * 0.5;
  964. const halfFovH = Math.atan( ( this.camera.aspect ) * Math.tan( halfFovV ) );
  965. maxLength = Math.tan( Math.max( halfFovV, halfFovH ) ) * distance * 2;
  966. tick = maxLength / 20;
  967. size = maxLength * multiplier;
  968. divisions = size / tick;
  969. }
  970. if ( this._grid == null ) {
  971. this._grid = new GridHelper( size, divisions, color, color );
  972. this._grid.position.copy( this._gizmos.position );
  973. this._gridPosition.copy( this._grid.position );
  974. this._grid.quaternion.copy( this.camera.quaternion );
  975. this._grid.rotateX( Math.PI * 0.5 );
  976. this.scene.add( this._grid );
  977. }
  978. }
  979. }
  980. /**
  981. * Remove all listeners, stop animations and clean scene
  982. */
  983. dispose() {
  984. if ( this._animationId != - 1 ) {
  985. window.cancelAnimationFrame( this._animationId );
  986. }
  987. this.domElement.removeEventListener( 'pointerdown', this._onPointerDown );
  988. this.domElement.removeEventListener( 'pointercancel', this._onPointerCancel );
  989. this.domElement.removeEventListener( 'wheel', this._onWheel );
  990. this.domElement.removeEventListener( 'contextmenu', this._onContextMenu );
  991. window.removeEventListener( 'pointermove', this._onPointerMove );
  992. window.removeEventListener( 'pointerup', this._onPointerUp );
  993. window.removeEventListener( 'resize', this._onWindowResize );
  994. if ( this.scene !== null ) this.scene.remove( this._gizmos );
  995. this.disposeGrid();
  996. }
  997. /**
  998. * remove the grid from the scene
  999. */
  1000. disposeGrid() {
  1001. if ( this._grid != null && this.scene != null ) {
  1002. this.scene.remove( this._grid );
  1003. this._grid = null;
  1004. }
  1005. }
  1006. /**
  1007. * Compute the easing out cubic function for ease out effect in animation
  1008. * @param {Number} t The absolute progress of the animation in the bound of 0 (beginning of the) and 1 (ending of animation)
  1009. * @returns {Number} Result of easing out cubic at time t
  1010. */
  1011. easeOutCubic( t ) {
  1012. return 1 - Math.pow( 1 - t, 3 );
  1013. }
  1014. /**
  1015. * Make rotation gizmos more or less visible
  1016. * @param {Boolean} isActive If true, make gizmos more visible
  1017. */
  1018. activateGizmos( isActive ) {
  1019. const gizmoX = this._gizmos.children[ 0 ];
  1020. const gizmoY = this._gizmos.children[ 1 ];
  1021. const gizmoZ = this._gizmos.children[ 2 ];
  1022. if ( isActive ) {
  1023. gizmoX.material.setValues( { opacity: 1 } );
  1024. gizmoY.material.setValues( { opacity: 1 } );
  1025. gizmoZ.material.setValues( { opacity: 1 } );
  1026. } else {
  1027. gizmoX.material.setValues( { opacity: 0.6 } );
  1028. gizmoY.material.setValues( { opacity: 0.6 } );
  1029. gizmoZ.material.setValues( { opacity: 0.6 } );
  1030. }
  1031. }
  1032. /**
  1033. * Calculate the cursor position in NDC
  1034. * @param {number} x Cursor horizontal coordinate within the canvas
  1035. * @param {number} y Cursor vertical coordinate within the canvas
  1036. * @param {HTMLElement} canvas The canvas where the renderer draws its output
  1037. * @returns {Vector2} Cursor normalized position inside the canvas
  1038. */
  1039. getCursorNDC( cursorX, cursorY, canvas ) {
  1040. const canvasRect = canvas.getBoundingClientRect();
  1041. this._v2_1.setX( ( ( cursorX - canvasRect.left ) / canvasRect.width ) * 2 - 1 );
  1042. this._v2_1.setY( ( ( canvasRect.bottom - cursorY ) / canvasRect.height ) * 2 - 1 );
  1043. return this._v2_1.clone();
  1044. }
  1045. /**
  1046. * Calculate the cursor position inside the canvas x/y coordinates with the origin being in the center of the canvas
  1047. * @param {Number} x Cursor horizontal coordinate within the canvas
  1048. * @param {Number} y Cursor vertical coordinate within the canvas
  1049. * @param {HTMLElement} canvas The canvas where the renderer draws its output
  1050. * @returns {Vector2} Cursor position inside the canvas
  1051. */
  1052. getCursorPosition( cursorX, cursorY, canvas ) {
  1053. this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) );
  1054. this._v2_1.x *= ( this.camera.right - this.camera.left ) * 0.5;
  1055. this._v2_1.y *= ( this.camera.top - this.camera.bottom ) * 0.5;
  1056. return this._v2_1.clone();
  1057. }
  1058. /**
  1059. * Set the camera to be controlled
  1060. * @param {Camera} camera The virtual camera to be controlled
  1061. */
  1062. setCamera( camera ) {
  1063. camera.lookAt( this.target );
  1064. camera.updateMatrix();
  1065. //setting state
  1066. if ( camera.type == 'PerspectiveCamera' ) {
  1067. this._fov0 = camera.fov;
  1068. this._fovState = camera.fov;
  1069. }
  1070. this._cameraMatrixState0.copy( camera.matrix );
  1071. this._cameraMatrixState.copy( this._cameraMatrixState0 );
  1072. this._cameraProjectionState.copy( camera.projectionMatrix );
  1073. this._zoom0 = camera.zoom;
  1074. this._zoomState = this._zoom0;
  1075. this._initialNear = camera.near;
  1076. this._nearPos0 = camera.position.distanceTo( this.target ) - camera.near;
  1077. this._nearPos = this._initialNear;
  1078. this._initialFar = camera.far;
  1079. this._farPos0 = camera.position.distanceTo( this.target ) - camera.far;
  1080. this._farPos = this._initialFar;
  1081. this._up0.copy( camera.up );
  1082. this._upState.copy( camera.up );
  1083. this.camera = camera;
  1084. this.camera.updateProjectionMatrix();
  1085. //making gizmos
  1086. this._tbRadius = this.calculateTbRadius( camera );
  1087. this.makeGizmos( this.target, this._tbRadius );
  1088. }
  1089. /**
  1090. * Set gizmos visibility
  1091. * @param {Boolean} value Value of gizmos visibility
  1092. */
  1093. setGizmosVisible( value ) {
  1094. this._gizmos.visible = value;
  1095. this.dispatchEvent( _changeEvent );
  1096. }
  1097. /**
  1098. * Set gizmos radius factor and redraws gizmos
  1099. * @param {Float} value Value of radius factor
  1100. */
  1101. setTbRadius( value ) {
  1102. this.radiusFactor = value;
  1103. this._tbRadius = this.calculateTbRadius( this.camera );
  1104. const curve = new EllipseCurve( 0, 0, this._tbRadius, this._tbRadius );
  1105. const points = curve.getPoints( this._curvePts );
  1106. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1107. for ( const gizmo in this._gizmos.children ) {
  1108. this._gizmos.children[ gizmo ].geometry = curveGeometry;
  1109. }
  1110. this.dispatchEvent( _changeEvent );
  1111. }
  1112. /**
  1113. * Creates the rotation gizmos matching trackball center and radius
  1114. * @param {Vector3} tbCenter The trackball center
  1115. * @param {number} tbRadius The trackball radius
  1116. */
  1117. makeGizmos( tbCenter, tbRadius ) {
  1118. const curve = new EllipseCurve( 0, 0, tbRadius, tbRadius );
  1119. const points = curve.getPoints( this._curvePts );
  1120. //geometry
  1121. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1122. //material
  1123. const curveMaterialX = new LineBasicMaterial( { color: 0xff8080, fog: false, transparent: true, opacity: 0.6 } );
  1124. const curveMaterialY = new LineBasicMaterial( { color: 0x80ff80, fog: false, transparent: true, opacity: 0.6 } );
  1125. const curveMaterialZ = new LineBasicMaterial( { color: 0x8080ff, fog: false, transparent: true, opacity: 0.6 } );
  1126. //line
  1127. const gizmoX = new Line( curveGeometry, curveMaterialX );
  1128. const gizmoY = new Line( curveGeometry, curveMaterialY );
  1129. const gizmoZ = new Line( curveGeometry, curveMaterialZ );
  1130. const rotation = Math.PI * 0.5;
  1131. gizmoX.rotation.x = rotation;
  1132. gizmoY.rotation.y = rotation;
  1133. //setting state
  1134. this._gizmoMatrixState0.identity().setPosition( tbCenter );
  1135. this._gizmoMatrixState.copy( this._gizmoMatrixState0 );
  1136. if ( this.camera.zoom !== 1 ) {
  1137. //adapt gizmos size to camera zoom
  1138. const size = 1 / this.camera.zoom;
  1139. this._scaleMatrix.makeScale( size, size, size );
  1140. this._translationMatrix.makeTranslation( - tbCenter.x, - tbCenter.y, - tbCenter.z );
  1141. this._gizmoMatrixState.premultiply( this._translationMatrix ).premultiply( this._scaleMatrix );
  1142. this._translationMatrix.makeTranslation( tbCenter.x, tbCenter.y, tbCenter.z );
  1143. this._gizmoMatrixState.premultiply( this._translationMatrix );
  1144. }
  1145. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1146. //
  1147. this._gizmos.traverse( function ( object ) {
  1148. if ( object.isLine ) {
  1149. object.geometry.dispose();
  1150. object.material.dispose();
  1151. }
  1152. } );
  1153. this._gizmos.clear();
  1154. //
  1155. this._gizmos.add( gizmoX );
  1156. this._gizmos.add( gizmoY );
  1157. this._gizmos.add( gizmoZ );
  1158. }
  1159. /**
  1160. * Perform animation for focus operation
  1161. * @param {Number} time Instant in which this function is called as performance.now()
  1162. * @param {Vector3} point Point of interest for focus operation
  1163. * @param {Matrix4} cameraMatrix Camera matrix
  1164. * @param {Matrix4} gizmoMatrix Gizmos matrix
  1165. */
  1166. onFocusAnim( time, point, cameraMatrix, gizmoMatrix ) {
  1167. if ( this._timeStart == - 1 ) {
  1168. //animation start
  1169. this._timeStart = time;
  1170. }
  1171. if ( this._state == STATE.ANIMATION_FOCUS ) {
  1172. const deltaTime = time - this._timeStart;
  1173. const animTime = deltaTime / this.focusAnimationTime;
  1174. this._gizmoMatrixState.copy( gizmoMatrix );
  1175. if ( animTime >= 1 ) {
  1176. //animation end
  1177. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1178. this.focus( point, this.scaleFactor );
  1179. this._timeStart = - 1;
  1180. this.updateTbState( STATE.IDLE, false );
  1181. this.activateGizmos( false );
  1182. this.dispatchEvent( _changeEvent );
  1183. } else {
  1184. const amount = this.easeOutCubic( animTime );
  1185. const size = ( ( 1 - amount ) + ( this.scaleFactor * amount ) );
  1186. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1187. this.focus( point, size, amount );
  1188. this.dispatchEvent( _changeEvent );
  1189. const self = this;
  1190. this._animationId = window.requestAnimationFrame( function ( t ) {
  1191. self.onFocusAnim( t, point, cameraMatrix, gizmoMatrix.clone() );
  1192. } );
  1193. }
  1194. } else {
  1195. //interrupt animation
  1196. this._animationId = - 1;
  1197. this._timeStart = - 1;
  1198. }
  1199. }
  1200. /**
  1201. * Perform animation for rotation operation
  1202. * @param {Number} time Instant in which this function is called as performance.now()
  1203. * @param {Vector3} rotationAxis Rotation axis
  1204. * @param {number} w0 Initial angular velocity
  1205. */
  1206. onRotationAnim( time, rotationAxis, w0 ) {
  1207. if ( this._timeStart == - 1 ) {
  1208. //animation start
  1209. this._anglePrev = 0;
  1210. this._angleCurrent = 0;
  1211. this._timeStart = time;
  1212. }
  1213. if ( this._state == STATE.ANIMATION_ROTATE ) {
  1214. //w = w0 + alpha * t
  1215. const deltaTime = ( time - this._timeStart ) / 1000;
  1216. const w = w0 + ( ( - this.dampingFactor ) * deltaTime );
  1217. if ( w > 0 ) {
  1218. //tetha = 0.5 * alpha * t^2 + w0 * t + tetha0
  1219. this._angleCurrent = 0.5 * ( - this.dampingFactor ) * Math.pow( deltaTime, 2 ) + w0 * deltaTime + 0;
  1220. this.applyTransformMatrix( this.rotate( rotationAxis, this._angleCurrent ) );
  1221. this.dispatchEvent( _changeEvent );
  1222. const self = this;
  1223. this._animationId = window.requestAnimationFrame( function ( t ) {
  1224. self.onRotationAnim( t, rotationAxis, w0 );
  1225. } );
  1226. } else {
  1227. this._animationId = - 1;
  1228. this._timeStart = - 1;
  1229. this.updateTbState( STATE.IDLE, false );
  1230. this.activateGizmos( false );
  1231. this.dispatchEvent( _changeEvent );
  1232. }
  1233. } else {
  1234. //interrupt animation
  1235. this._animationId = - 1;
  1236. this._timeStart = - 1;
  1237. if ( this._state != STATE.ROTATE ) {
  1238. this.activateGizmos( false );
  1239. this.dispatchEvent( _changeEvent );
  1240. }
  1241. }
  1242. }
  1243. /**
  1244. * Perform pan operation moving camera between two points
  1245. * @param {Vector3} p0 Initial point
  1246. * @param {Vector3} p1 Ending point
  1247. * @param {Boolean} adjust If movement should be adjusted considering camera distance (Perspective only)
  1248. */
  1249. pan( p0, p1, adjust = false ) {
  1250. const movement = p0.clone().sub( p1 );
  1251. if ( this.camera.isOrthographicCamera ) {
  1252. //adjust movement amount
  1253. movement.multiplyScalar( 1 / this.camera.zoom );
  1254. } else if ( this.camera.isPerspectiveCamera && adjust ) {
  1255. //adjust movement amount
  1256. this._v3_1.setFromMatrixPosition( this._cameraMatrixState0 ); //camera's initial position
  1257. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState0 ); //gizmo's initial position
  1258. const distanceFactor = this._v3_1.distanceTo( this._v3_2 ) / this.camera.position.distanceTo( this._gizmos.position );
  1259. movement.multiplyScalar( 1 / distanceFactor );
  1260. }
  1261. this._v3_1.set( movement.x, movement.y, 0 ).applyQuaternion( this.camera.quaternion );
  1262. this._m4_1.makeTranslation( this._v3_1.x, this._v3_1.y, this._v3_1.z );
  1263. this.setTransformationMatrices( this._m4_1, this._m4_1 );
  1264. return _transformation;
  1265. }
  1266. /**
  1267. * Reset trackball
  1268. */
  1269. reset() {
  1270. this.camera.zoom = this._zoom0;
  1271. if ( this.camera.isPerspectiveCamera ) {
  1272. this.camera.fov = this._fov0;
  1273. }
  1274. this.camera.near = this._nearPos;
  1275. this.camera.far = this._farPos;
  1276. this._cameraMatrixState.copy( this._cameraMatrixState0 );
  1277. this._cameraMatrixState.decompose( this.camera.position, this.camera.quaternion, this.camera.scale );
  1278. this.camera.up.copy( this._up0 );
  1279. this.camera.updateMatrix();
  1280. this.camera.updateProjectionMatrix();
  1281. this._gizmoMatrixState.copy( this._gizmoMatrixState0 );
  1282. this._gizmoMatrixState0.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1283. this._gizmos.updateMatrix();
  1284. this._tbRadius = this.calculateTbRadius( this.camera );
  1285. this.makeGizmos( this._gizmos.position, this._tbRadius );
  1286. this.camera.lookAt( this._gizmos.position );
  1287. this.updateTbState( STATE.IDLE, false );
  1288. this.dispatchEvent( _changeEvent );
  1289. }
  1290. /**
  1291. * Rotate the camera around an axis passing by trackball's center
  1292. * @param {Vector3} axis Rotation axis
  1293. * @param {number} angle Angle in radians
  1294. * @returns {Object} Object with 'camera' field containing transformation matrix resulting from the operation to be applied to the camera
  1295. */
  1296. rotate( axis, angle ) {
  1297. const point = this._gizmos.position; //rotation center
  1298. this._translationMatrix.makeTranslation( - point.x, - point.y, - point.z );
  1299. this._rotationMatrix.makeRotationAxis( axis, - angle );
  1300. //rotate camera
  1301. this._m4_1.makeTranslation( point.x, point.y, point.z );
  1302. this._m4_1.multiply( this._rotationMatrix );
  1303. this._m4_1.multiply( this._translationMatrix );
  1304. this.setTransformationMatrices( this._m4_1 );
  1305. return _transformation;
  1306. }
  1307. copyState() {
  1308. let state;
  1309. if ( this.camera.isOrthographicCamera ) {
  1310. state = JSON.stringify( { arcballState: {
  1311. cameraFar: this.camera.far,
  1312. cameraMatrix: this.camera.matrix,
  1313. cameraNear: this.camera.near,
  1314. cameraUp: this.camera.up,
  1315. cameraZoom: this.camera.zoom,
  1316. gizmoMatrix: this._gizmos.matrix
  1317. } } );
  1318. } else if ( this.camera.isPerspectiveCamera ) {
  1319. state = JSON.stringify( { arcballState: {
  1320. cameraFar: this.camera.far,
  1321. cameraFov: this.camera.fov,
  1322. cameraMatrix: this.camera.matrix,
  1323. cameraNear: this.camera.near,
  1324. cameraUp: this.camera.up,
  1325. cameraZoom: this.camera.zoom,
  1326. gizmoMatrix: this._gizmos.matrix
  1327. } } );
  1328. }
  1329. navigator.clipboard.writeText( state );
  1330. }
  1331. pasteState() {
  1332. const self = this;
  1333. navigator.clipboard.readText().then( function resolved( value ) {
  1334. self.setStateFromJSON( value );
  1335. } );
  1336. }
  1337. /**
  1338. * Save the current state of the control. This can later be recover with .reset
  1339. */
  1340. saveState() {
  1341. this._cameraMatrixState0.copy( this.camera.matrix );
  1342. this._gizmoMatrixState0.copy( this._gizmos.matrix );
  1343. this._nearPos = this.camera.near;
  1344. this._farPos = this.camera.far;
  1345. this._zoom0 = this.camera.zoom;
  1346. this._up0.copy( this.camera.up );
  1347. if ( this.camera.isPerspectiveCamera ) {
  1348. this._fov0 = this.camera.fov;
  1349. }
  1350. }
  1351. /**
  1352. * Perform uniform scale operation around a given point
  1353. * @param {Number} size Scale factor
  1354. * @param {Vector3} point Point around which scale
  1355. * @param {Boolean} scaleGizmos If gizmos should be scaled (Perspective only)
  1356. * @returns {Object} Object with 'camera' and 'gizmo' fields containing transformation matrices resulting from the operation to be applied to the camera and gizmos
  1357. */
  1358. scale( size, point, scaleGizmos = true ) {
  1359. _scalePointTemp.copy( point );
  1360. let sizeInverse = 1 / size;
  1361. if ( this.camera.isOrthographicCamera ) {
  1362. //camera zoom
  1363. this.camera.zoom = this._zoomState;
  1364. this.camera.zoom *= size;
  1365. //check min and max zoom
  1366. if ( this.camera.zoom > this.maxZoom ) {
  1367. this.camera.zoom = this.maxZoom;
  1368. sizeInverse = this._zoomState / this.maxZoom;
  1369. } else if ( this.camera.zoom < this.minZoom ) {
  1370. this.camera.zoom = this.minZoom;
  1371. sizeInverse = this._zoomState / this.minZoom;
  1372. }
  1373. this.camera.updateProjectionMatrix();
  1374. this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ); //gizmos position
  1375. //scale gizmos so they appear in the same spot having the same dimension
  1376. this._scaleMatrix.makeScale( sizeInverse, sizeInverse, sizeInverse );
  1377. this._translationMatrix.makeTranslation( - this._v3_1.x, - this._v3_1.y, - this._v3_1.z );
  1378. this._m4_2.makeTranslation( this._v3_1.x, this._v3_1.y, this._v3_1.z ).multiply( this._scaleMatrix );
  1379. this._m4_2.multiply( this._translationMatrix );
  1380. //move camera and gizmos to obtain pinch effect
  1381. _scalePointTemp.sub( this._v3_1 );
  1382. const amount = _scalePointTemp.clone().multiplyScalar( sizeInverse );
  1383. _scalePointTemp.sub( amount );
  1384. this._m4_1.makeTranslation( _scalePointTemp.x, _scalePointTemp.y, _scalePointTemp.z );
  1385. this._m4_2.premultiply( this._m4_1 );
  1386. this.setTransformationMatrices( this._m4_1, this._m4_2 );
  1387. return _transformation;
  1388. } else if ( this.camera.isPerspectiveCamera ) {
  1389. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  1390. this._v3_2.setFromMatrixPosition( this._gizmoMatrixState );
  1391. //move camera
  1392. let distance = this._v3_1.distanceTo( _scalePointTemp );
  1393. let amount = distance - ( distance * sizeInverse );
  1394. //check min and max distance
  1395. const newDistance = distance - amount;
  1396. if ( newDistance < this.minDistance ) {
  1397. sizeInverse = this.minDistance / distance;
  1398. amount = distance - ( distance * sizeInverse );
  1399. } else if ( newDistance > this.maxDistance ) {
  1400. sizeInverse = this.maxDistance / distance;
  1401. amount = distance - ( distance * sizeInverse );
  1402. }
  1403. _offset.copy( _scalePointTemp ).sub( this._v3_1 ).normalize().multiplyScalar( amount );
  1404. this._m4_1.makeTranslation( _offset.x, _offset.y, _offset.z );
  1405. if ( scaleGizmos ) {
  1406. //scale gizmos so they appear in the same spot having the same dimension
  1407. const pos = this._v3_2;
  1408. distance = pos.distanceTo( _scalePointTemp );
  1409. amount = distance - ( distance * sizeInverse );
  1410. _offset.copy( _scalePointTemp ).sub( this._v3_2 ).normalize().multiplyScalar( amount );
  1411. this._translationMatrix.makeTranslation( pos.x, pos.y, pos.z );
  1412. this._scaleMatrix.makeScale( sizeInverse, sizeInverse, sizeInverse );
  1413. this._m4_2.makeTranslation( _offset.x, _offset.y, _offset.z ).multiply( this._translationMatrix );
  1414. this._m4_2.multiply( this._scaleMatrix );
  1415. this._translationMatrix.makeTranslation( - pos.x, - pos.y, - pos.z );
  1416. this._m4_2.multiply( this._translationMatrix );
  1417. this.setTransformationMatrices( this._m4_1, this._m4_2 );
  1418. } else {
  1419. this.setTransformationMatrices( this._m4_1 );
  1420. }
  1421. return _transformation;
  1422. }
  1423. }
  1424. /**
  1425. * Set camera fov
  1426. * @param {Number} value fov to be setted
  1427. */
  1428. setFov( value ) {
  1429. if ( this.camera.isPerspectiveCamera ) {
  1430. this.camera.fov = MathUtils.clamp( value, this.minFov, this.maxFov );
  1431. this.camera.updateProjectionMatrix();
  1432. }
  1433. }
  1434. /**
  1435. * Set values in transformation object
  1436. * @param {Matrix4} camera Transformation to be applied to the camera
  1437. * @param {Matrix4} gizmos Transformation to be applied to gizmos
  1438. */
  1439. setTransformationMatrices( camera = null, gizmos = null ) {
  1440. if ( camera != null ) {
  1441. if ( _transformation.camera != null ) {
  1442. _transformation.camera.copy( camera );
  1443. } else {
  1444. _transformation.camera = camera.clone();
  1445. }
  1446. } else {
  1447. _transformation.camera = null;
  1448. }
  1449. if ( gizmos != null ) {
  1450. if ( _transformation.gizmos != null ) {
  1451. _transformation.gizmos.copy( gizmos );
  1452. } else {
  1453. _transformation.gizmos = gizmos.clone();
  1454. }
  1455. } else {
  1456. _transformation.gizmos = null;
  1457. }
  1458. }
  1459. /**
  1460. * Rotate camera around its direction axis passing by a given point by a given angle
  1461. * @param {Vector3} point The point where the rotation axis is passing trough
  1462. * @param {Number} angle Angle in radians
  1463. * @returns The computed transormation matix
  1464. */
  1465. zRotate( point, angle ) {
  1466. this._rotationMatrix.makeRotationAxis( this._rotationAxis, angle );
  1467. this._translationMatrix.makeTranslation( - point.x, - point.y, - point.z );
  1468. this._m4_1.makeTranslation( point.x, point.y, point.z );
  1469. this._m4_1.multiply( this._rotationMatrix );
  1470. this._m4_1.multiply( this._translationMatrix );
  1471. this._v3_1.setFromMatrixPosition( this._gizmoMatrixState ).sub( point ); //vector from rotation center to gizmos position
  1472. this._v3_2.copy( this._v3_1 ).applyAxisAngle( this._rotationAxis, angle ); //apply rotation
  1473. this._v3_2.sub( this._v3_1 );
  1474. this._m4_2.makeTranslation( this._v3_2.x, this._v3_2.y, this._v3_2.z );
  1475. this.setTransformationMatrices( this._m4_1, this._m4_2 );
  1476. return _transformation;
  1477. }
  1478. getRaycaster() {
  1479. return _raycaster;
  1480. }
  1481. /**
  1482. * Unproject the cursor on the 3D object surface
  1483. * @param {Vector2} cursor Cursor coordinates in NDC
  1484. * @param {Camera} camera Virtual camera
  1485. * @returns {Vector3} The point of intersection with the model, if exist, null otherwise
  1486. */
  1487. unprojectOnObj( cursor, camera ) {
  1488. const raycaster = this.getRaycaster();
  1489. raycaster.near = camera.near;
  1490. raycaster.far = camera.far;
  1491. raycaster.setFromCamera( cursor, camera );
  1492. const intersect = raycaster.intersectObjects( this.scene.children, true );
  1493. for ( let i = 0; i < intersect.length; i ++ ) {
  1494. if ( intersect[ i ].object.uuid != this._gizmos.uuid && intersect[ i ].face != null ) {
  1495. return intersect[ i ].point.clone();
  1496. }
  1497. }
  1498. return null;
  1499. }
  1500. /**
  1501. * Unproject the cursor on the trackball surface
  1502. * @param {Camera} camera The virtual camera
  1503. * @param {Number} cursorX Cursor horizontal coordinate on screen
  1504. * @param {Number} cursorY Cursor vertical coordinate on screen
  1505. * @param {HTMLElement} canvas The canvas where the renderer draws its output
  1506. * @param {number} tbRadius The trackball radius
  1507. * @returns {Vector3} The unprojected point on the trackball surface
  1508. */
  1509. unprojectOnTbSurface( camera, cursorX, cursorY, canvas, tbRadius ) {
  1510. if ( camera.type == 'OrthographicCamera' ) {
  1511. this._v2_1.copy( this.getCursorPosition( cursorX, cursorY, canvas ) );
  1512. this._v3_1.set( this._v2_1.x, this._v2_1.y, 0 );
  1513. const x2 = Math.pow( this._v2_1.x, 2 );
  1514. const y2 = Math.pow( this._v2_1.y, 2 );
  1515. const r2 = Math.pow( this._tbRadius, 2 );
  1516. if ( x2 + y2 <= r2 * 0.5 ) {
  1517. //intersection with sphere
  1518. this._v3_1.setZ( Math.sqrt( r2 - ( x2 + y2 ) ) );
  1519. } else {
  1520. //intersection with hyperboloid
  1521. this._v3_1.setZ( ( r2 * 0.5 ) / ( Math.sqrt( x2 + y2 ) ) );
  1522. }
  1523. return this._v3_1;
  1524. } else if ( camera.type == 'PerspectiveCamera' ) {
  1525. //unproject cursor on the near plane
  1526. this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) );
  1527. this._v3_1.set( this._v2_1.x, this._v2_1.y, - 1 );
  1528. this._v3_1.applyMatrix4( camera.projectionMatrixInverse );
  1529. const rayDir = this._v3_1.clone().normalize(); //unprojected ray direction
  1530. const cameraGizmoDistance = camera.position.distanceTo( this._gizmos.position );
  1531. const radius2 = Math.pow( tbRadius, 2 );
  1532. // camera
  1533. // |\
  1534. // | \
  1535. // | \
  1536. // h | \
  1537. // | \
  1538. // | \
  1539. // _ _ | _ _ _\ _ _ near plane
  1540. // l
  1541. const h = this._v3_1.z;
  1542. const l = Math.sqrt( Math.pow( this._v3_1.x, 2 ) + Math.pow( this._v3_1.y, 2 ) );
  1543. if ( l == 0 ) {
  1544. //ray aligned with camera
  1545. rayDir.set( this._v3_1.x, this._v3_1.y, tbRadius );
  1546. return rayDir;
  1547. }
  1548. const m = h / l;
  1549. const q = cameraGizmoDistance;
  1550. /*
  1551. * calculate intersection point between unprojected ray and trackball surface
  1552. *|y = m * x + q
  1553. *|x^2 + y^2 = r^2
  1554. *
  1555. * (m^2 + 1) * x^2 + (2 * m * q) * x + q^2 - r^2 = 0
  1556. */
  1557. let a = Math.pow( m, 2 ) + 1;
  1558. let b = 2 * m * q;
  1559. let c = Math.pow( q, 2 ) - radius2;
  1560. let delta = Math.pow( b, 2 ) - ( 4 * a * c );
  1561. if ( delta >= 0 ) {
  1562. //intersection with sphere
  1563. this._v2_1.setX( ( - b - Math.sqrt( delta ) ) / ( 2 * a ) );
  1564. this._v2_1.setY( m * this._v2_1.x + q );
  1565. const angle = MathUtils.RAD2DEG * this._v2_1.angle();
  1566. if ( angle >= 45 ) {
  1567. //if angle between intersection point and X' axis is >= 45°, return that point
  1568. //otherwise, calculate intersection point with hyperboloid
  1569. const rayLength = Math.sqrt( Math.pow( this._v2_1.x, 2 ) + Math.pow( ( cameraGizmoDistance - this._v2_1.y ), 2 ) );
  1570. rayDir.multiplyScalar( rayLength );
  1571. rayDir.z += cameraGizmoDistance;
  1572. return rayDir;
  1573. }
  1574. }
  1575. //intersection with hyperboloid
  1576. /*
  1577. *|y = m * x + q
  1578. *|y = (1 / x) * (r^2 / 2)
  1579. *
  1580. * m * x^2 + q * x - r^2 / 2 = 0
  1581. */
  1582. a = m;
  1583. b = q;
  1584. c = - radius2 * 0.5;
  1585. delta = Math.pow( b, 2 ) - ( 4 * a * c );
  1586. this._v2_1.setX( ( - b - Math.sqrt( delta ) ) / ( 2 * a ) );
  1587. this._v2_1.setY( m * this._v2_1.x + q );
  1588. const rayLength = Math.sqrt( Math.pow( this._v2_1.x, 2 ) + Math.pow( ( cameraGizmoDistance - this._v2_1.y ), 2 ) );
  1589. rayDir.multiplyScalar( rayLength );
  1590. rayDir.z += cameraGizmoDistance;
  1591. return rayDir;
  1592. }
  1593. }
  1594. /**
  1595. * Unproject the cursor on the plane passing through the center of the trackball orthogonal to the camera
  1596. * @param {Camera} camera The virtual camera
  1597. * @param {Number} cursorX Cursor horizontal coordinate on screen
  1598. * @param {Number} cursorY Cursor vertical coordinate on screen
  1599. * @param {HTMLElement} canvas The canvas where the renderer draws its output
  1600. * @param {Boolean} initialDistance If initial distance between camera and gizmos should be used for calculations instead of current (Perspective only)
  1601. * @returns {Vector3} The unprojected point on the trackball plane
  1602. */
  1603. unprojectOnTbPlane( camera, cursorX, cursorY, canvas, initialDistance = false ) {
  1604. if ( camera.type == 'OrthographicCamera' ) {
  1605. this._v2_1.copy( this.getCursorPosition( cursorX, cursorY, canvas ) );
  1606. this._v3_1.set( this._v2_1.x, this._v2_1.y, 0 );
  1607. return this._v3_1.clone();
  1608. } else if ( camera.type == 'PerspectiveCamera' ) {
  1609. this._v2_1.copy( this.getCursorNDC( cursorX, cursorY, canvas ) );
  1610. //unproject cursor on the near plane
  1611. this._v3_1.set( this._v2_1.x, this._v2_1.y, - 1 );
  1612. this._v3_1.applyMatrix4( camera.projectionMatrixInverse );
  1613. const rayDir = this._v3_1.clone().normalize(); //unprojected ray direction
  1614. // camera
  1615. // |\
  1616. // | \
  1617. // | \
  1618. // h | \
  1619. // | \
  1620. // | \
  1621. // _ _ | _ _ _\ _ _ near plane
  1622. // l
  1623. const h = this._v3_1.z;
  1624. const l = Math.sqrt( Math.pow( this._v3_1.x, 2 ) + Math.pow( this._v3_1.y, 2 ) );
  1625. let cameraGizmoDistance;
  1626. if ( initialDistance ) {
  1627. cameraGizmoDistance = this._v3_1.setFromMatrixPosition( this._cameraMatrixState0 ).distanceTo( this._v3_2.setFromMatrixPosition( this._gizmoMatrixState0 ) );
  1628. } else {
  1629. cameraGizmoDistance = camera.position.distanceTo( this._gizmos.position );
  1630. }
  1631. /*
  1632. * calculate intersection point between unprojected ray and the plane
  1633. *|y = mx + q
  1634. *|y = 0
  1635. *
  1636. * x = -q/m
  1637. */
  1638. if ( l == 0 ) {
  1639. //ray aligned with camera
  1640. rayDir.set( 0, 0, 0 );
  1641. return rayDir;
  1642. }
  1643. const m = h / l;
  1644. const q = cameraGizmoDistance;
  1645. const x = - q / m;
  1646. const rayLength = Math.sqrt( Math.pow( q, 2 ) + Math.pow( x, 2 ) );
  1647. rayDir.multiplyScalar( rayLength );
  1648. rayDir.z = 0;
  1649. return rayDir;
  1650. }
  1651. }
  1652. /**
  1653. * Update camera and gizmos state
  1654. */
  1655. updateMatrixState() {
  1656. //update camera and gizmos state
  1657. this._cameraMatrixState.copy( this.camera.matrix );
  1658. this._gizmoMatrixState.copy( this._gizmos.matrix );
  1659. if ( this.camera.isOrthographicCamera ) {
  1660. this._cameraProjectionState.copy( this.camera.projectionMatrix );
  1661. this.camera.updateProjectionMatrix();
  1662. this._zoomState = this.camera.zoom;
  1663. } else if ( this.camera.isPerspectiveCamera ) {
  1664. this._fovState = this.camera.fov;
  1665. }
  1666. }
  1667. /**
  1668. * Update the trackball FSA
  1669. * @param {STATE} newState New state of the FSA
  1670. * @param {Boolean} updateMatrices If matriices state should be updated
  1671. */
  1672. updateTbState( newState, updateMatrices ) {
  1673. this._state = newState;
  1674. if ( updateMatrices ) {
  1675. this.updateMatrixState();
  1676. }
  1677. }
  1678. update() {
  1679. const EPS = 0.000001;
  1680. if ( this.target.equals( this._currentTarget ) === false ) {
  1681. this._gizmos.position.copy( this.target ); //for correct radius calculation
  1682. this._tbRadius = this.calculateTbRadius( this.camera );
  1683. this.makeGizmos( this.target, this._tbRadius );
  1684. this._currentTarget.copy( this.target );
  1685. }
  1686. //check min/max parameters
  1687. if ( this.camera.isOrthographicCamera ) {
  1688. //check zoom
  1689. if ( this.camera.zoom > this.maxZoom || this.camera.zoom < this.minZoom ) {
  1690. const newZoom = MathUtils.clamp( this.camera.zoom, this.minZoom, this.maxZoom );
  1691. this.applyTransformMatrix( this.scale( newZoom / this.camera.zoom, this._gizmos.position, true ) );
  1692. }
  1693. } else if ( this.camera.isPerspectiveCamera ) {
  1694. //check distance
  1695. const distance = this.camera.position.distanceTo( this._gizmos.position );
  1696. if ( distance > this.maxDistance + EPS || distance < this.minDistance - EPS ) {
  1697. const newDistance = MathUtils.clamp( distance, this.minDistance, this.maxDistance );
  1698. this.applyTransformMatrix( this.scale( newDistance / distance, this._gizmos.position ) );
  1699. this.updateMatrixState();
  1700. }
  1701. //check fov
  1702. if ( this.camera.fov < this.minFov || this.camera.fov > this.maxFov ) {
  1703. this.camera.fov = MathUtils.clamp( this.camera.fov, this.minFov, this.maxFov );
  1704. this.camera.updateProjectionMatrix();
  1705. }
  1706. const oldRadius = this._tbRadius;
  1707. this._tbRadius = this.calculateTbRadius( this.camera );
  1708. if ( oldRadius < this._tbRadius - EPS || oldRadius > this._tbRadius + EPS ) {
  1709. const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3;
  1710. const newRadius = this._tbRadius / scale;
  1711. const curve = new EllipseCurve( 0, 0, newRadius, newRadius );
  1712. const points = curve.getPoints( this._curvePts );
  1713. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1714. for ( const gizmo in this._gizmos.children ) {
  1715. this._gizmos.children[ gizmo ].geometry = curveGeometry;
  1716. }
  1717. }
  1718. }
  1719. this.camera.lookAt( this._gizmos.position );
  1720. }
  1721. setStateFromJSON( json ) {
  1722. const state = JSON.parse( json );
  1723. if ( state.arcballState != undefined ) {
  1724. this._cameraMatrixState.fromArray( state.arcballState.cameraMatrix.elements );
  1725. this._cameraMatrixState.decompose( this.camera.position, this.camera.quaternion, this.camera.scale );
  1726. this.camera.up.copy( state.arcballState.cameraUp );
  1727. this.camera.near = state.arcballState.cameraNear;
  1728. this.camera.far = state.arcballState.cameraFar;
  1729. this.camera.zoom = state.arcballState.cameraZoom;
  1730. if ( this.camera.isPerspectiveCamera ) {
  1731. this.camera.fov = state.arcballState.cameraFov;
  1732. }
  1733. this._gizmoMatrixState.fromArray( state.arcballState.gizmoMatrix.elements );
  1734. this._gizmoMatrixState.decompose( this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale );
  1735. this.camera.updateMatrix();
  1736. this.camera.updateProjectionMatrix();
  1737. this._gizmos.updateMatrix();
  1738. this._tbRadius = this.calculateTbRadius( this.camera );
  1739. const gizmoTmp = new Matrix4().copy( this._gizmoMatrixState0 );
  1740. this.makeGizmos( this._gizmos.position, this._tbRadius );
  1741. this._gizmoMatrixState0.copy( gizmoTmp );
  1742. this.camera.lookAt( this._gizmos.position );
  1743. this.updateTbState( STATE.IDLE, false );
  1744. this.dispatchEvent( _changeEvent );
  1745. }
  1746. }
  1747. }
  1748. //listeners
  1749. function onWindowResize() {
  1750. const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3;
  1751. this._tbRadius = this.calculateTbRadius( this.camera );
  1752. const newRadius = this._tbRadius / scale;
  1753. const curve = new EllipseCurve( 0, 0, newRadius, newRadius );
  1754. const points = curve.getPoints( this._curvePts );
  1755. const curveGeometry = new BufferGeometry().setFromPoints( points );
  1756. for ( const gizmo in this._gizmos.children ) {
  1757. this._gizmos.children[ gizmo ].geometry = curveGeometry;
  1758. }
  1759. this.dispatchEvent( _changeEvent );
  1760. }
  1761. function onContextMenu( event ) {
  1762. if ( ! this.enabled ) {
  1763. return;
  1764. }
  1765. for ( let i = 0; i < this.mouseActions.length; i ++ ) {
  1766. if ( this.mouseActions[ i ].mouse == 2 ) {
  1767. //prevent only if button 2 is actually used
  1768. event.preventDefault();
  1769. break;
  1770. }
  1771. }
  1772. }
  1773. function onPointerCancel() {
  1774. this._touchStart.splice( 0, this._touchStart.length );
  1775. this._touchCurrent.splice( 0, this._touchCurrent.length );
  1776. this._input = INPUT.NONE;
  1777. }
  1778. function onPointerDown( event ) {
  1779. if ( event.button == 0 && event.isPrimary ) {
  1780. this._downValid = true;
  1781. this._downEvents.push( event );
  1782. this._downStart = performance.now();
  1783. } else {
  1784. this._downValid = false;
  1785. }
  1786. if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) {
  1787. this._touchStart.push( event );
  1788. this._touchCurrent.push( event );
  1789. switch ( this._input ) {
  1790. case INPUT.NONE:
  1791. //singleStart
  1792. this._input = INPUT.ONE_FINGER;
  1793. this.onSinglePanStart( event, 'ROTATE' );
  1794. window.addEventListener( 'pointermove', this._onPointerMove );
  1795. window.addEventListener( 'pointerup', this._onPointerUp );
  1796. break;
  1797. case INPUT.ONE_FINGER:
  1798. case INPUT.ONE_FINGER_SWITCHED:
  1799. //doubleStart
  1800. this._input = INPUT.TWO_FINGER;
  1801. this.onRotateStart();
  1802. this.onPinchStart();
  1803. this.onDoublePanStart();
  1804. break;
  1805. case INPUT.TWO_FINGER:
  1806. //multipleStart
  1807. this._input = INPUT.MULT_FINGER;
  1808. this.onTriplePanStart( event );
  1809. break;
  1810. }
  1811. } else if ( event.pointerType != 'touch' && this._input == INPUT.NONE ) {
  1812. let modifier = null;
  1813. if ( event.ctrlKey || event.metaKey ) {
  1814. modifier = 'CTRL';
  1815. } else if ( event.shiftKey ) {
  1816. modifier = 'SHIFT';
  1817. }
  1818. this._mouseOp = this.getOpFromAction( event.button, modifier );
  1819. if ( this._mouseOp != null ) {
  1820. window.addEventListener( 'pointermove', this._onPointerMove );
  1821. window.addEventListener( 'pointerup', this._onPointerUp );
  1822. //singleStart
  1823. this._input = INPUT.CURSOR;
  1824. this._button = event.button;
  1825. this.onSinglePanStart( event, this._mouseOp );
  1826. }
  1827. }
  1828. }
  1829. function onPointerMove( event ) {
  1830. if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) {
  1831. switch ( this._input ) {
  1832. case INPUT.ONE_FINGER:
  1833. //singleMove
  1834. this.updateTouchEvent( event );
  1835. this.onSinglePanMove( event, STATE.ROTATE );
  1836. break;
  1837. case INPUT.ONE_FINGER_SWITCHED:
  1838. const movement = this.calculatePointersDistance( this._touchCurrent[ 0 ], event ) * this._devPxRatio;
  1839. if ( movement >= this._switchSensibility ) {
  1840. //singleMove
  1841. this._input = INPUT.ONE_FINGER;
  1842. this.updateTouchEvent( event );
  1843. this.onSinglePanStart( event, 'ROTATE' );
  1844. break;
  1845. }
  1846. break;
  1847. case INPUT.TWO_FINGER:
  1848. //rotate/pan/pinchMove
  1849. this.updateTouchEvent( event );
  1850. this.onRotateMove();
  1851. this.onPinchMove();
  1852. this.onDoublePanMove();
  1853. break;
  1854. case INPUT.MULT_FINGER:
  1855. //multMove
  1856. this.updateTouchEvent( event );
  1857. this.onTriplePanMove( event );
  1858. break;
  1859. }
  1860. } else if ( event.pointerType != 'touch' && this._input == INPUT.CURSOR ) {
  1861. let modifier = null;
  1862. if ( event.ctrlKey || event.metaKey ) {
  1863. modifier = 'CTRL';
  1864. } else if ( event.shiftKey ) {
  1865. modifier = 'SHIFT';
  1866. }
  1867. const mouseOpState = this.getOpStateFromAction( this._button, modifier );
  1868. if ( mouseOpState != null ) {
  1869. this.onSinglePanMove( event, mouseOpState );
  1870. }
  1871. }
  1872. //checkDistance
  1873. if ( this._downValid ) {
  1874. const movement = this.calculatePointersDistance( this._downEvents[ this._downEvents.length - 1 ], event ) * this._devPxRatio;
  1875. if ( movement > this._movementThreshold ) {
  1876. this._downValid = false;
  1877. }
  1878. }
  1879. }
  1880. function onPointerUp( event ) {
  1881. if ( event.pointerType == 'touch' && this._input != INPUT.CURSOR ) {
  1882. const nTouch = this._touchCurrent.length;
  1883. for ( let i = 0; i < nTouch; i ++ ) {
  1884. if ( this._touchCurrent[ i ].pointerId == event.pointerId ) {
  1885. this._touchCurrent.splice( i, 1 );
  1886. this._touchStart.splice( i, 1 );
  1887. break;
  1888. }
  1889. }
  1890. switch ( this._input ) {
  1891. case INPUT.ONE_FINGER:
  1892. case INPUT.ONE_FINGER_SWITCHED:
  1893. //singleEnd
  1894. window.removeEventListener( 'pointermove', this._onPointerMove );
  1895. window.removeEventListener( 'pointerup', this._onPointerUp );
  1896. this._input = INPUT.NONE;
  1897. this.onSinglePanEnd();
  1898. break;
  1899. case INPUT.TWO_FINGER:
  1900. //doubleEnd
  1901. this.onDoublePanEnd( event );
  1902. this.onPinchEnd( event );
  1903. this.onRotateEnd( event );
  1904. //switching to singleStart
  1905. this._input = INPUT.ONE_FINGER_SWITCHED;
  1906. break;
  1907. case INPUT.MULT_FINGER:
  1908. if ( this._touchCurrent.length == 0 ) {
  1909. window.removeEventListener( 'pointermove', this._onPointerMove );
  1910. window.removeEventListener( 'pointerup', this._onPointerUp );
  1911. //multCancel
  1912. this._input = INPUT.NONE;
  1913. this.onTriplePanEnd();
  1914. }
  1915. break;
  1916. }
  1917. } else if ( event.pointerType != 'touch' && this._input == INPUT.CURSOR ) {
  1918. window.removeEventListener( 'pointermove', this._onPointerMove );
  1919. window.removeEventListener( 'pointerup', this._onPointerUp );
  1920. this._input = INPUT.NONE;
  1921. this.onSinglePanEnd();
  1922. this._button = - 1;
  1923. }
  1924. if ( event.isPrimary ) {
  1925. if ( this._downValid ) {
  1926. const downTime = event.timeStamp - this._downEvents[ this._downEvents.length - 1 ].timeStamp;
  1927. if ( downTime <= this._maxDownTime ) {
  1928. if ( this._nclicks == 0 ) {
  1929. //first valid click detected
  1930. this._nclicks = 1;
  1931. this._clickStart = performance.now();
  1932. } else {
  1933. const clickInterval = event.timeStamp - this._clickStart;
  1934. const movement = this.calculatePointersDistance( this._downEvents[ 1 ], this._downEvents[ 0 ] ) * this._devPxRatio;
  1935. if ( clickInterval <= this._maxInterval && movement <= this._posThreshold ) {
  1936. //second valid click detected
  1937. //fire double tap and reset values
  1938. this._nclicks = 0;
  1939. this._downEvents.splice( 0, this._downEvents.length );
  1940. this.onDoubleTap( event );
  1941. } else {
  1942. //new 'first click'
  1943. this._nclicks = 1;
  1944. this._downEvents.shift();
  1945. this._clickStart = performance.now();
  1946. }
  1947. }
  1948. } else {
  1949. this._downValid = false;
  1950. this._nclicks = 0;
  1951. this._downEvents.splice( 0, this._downEvents.length );
  1952. }
  1953. } else {
  1954. this._nclicks = 0;
  1955. this._downEvents.splice( 0, this._downEvents.length );
  1956. }
  1957. }
  1958. }
  1959. function onWheel( event ) {
  1960. if ( this.enabled && this.enableZoom ) {
  1961. let modifier = null;
  1962. if ( event.ctrlKey || event.metaKey ) {
  1963. modifier = 'CTRL';
  1964. } else if ( event.shiftKey ) {
  1965. modifier = 'SHIFT';
  1966. }
  1967. const mouseOp = this.getOpFromAction( 'WHEEL', modifier );
  1968. if ( mouseOp != null ) {
  1969. event.preventDefault();
  1970. this.dispatchEvent( _startEvent );
  1971. const notchDeltaY = 125; //distance of one notch of mouse wheel
  1972. let sgn = event.deltaY / notchDeltaY;
  1973. let size = 1;
  1974. if ( sgn > 0 ) {
  1975. size = 1 / this.scaleFactor;
  1976. } else if ( sgn < 0 ) {
  1977. size = this.scaleFactor;
  1978. }
  1979. switch ( mouseOp ) {
  1980. case 'ZOOM':
  1981. this.updateTbState( STATE.SCALE, true );
  1982. if ( sgn > 0 ) {
  1983. size = 1 / ( Math.pow( this.scaleFactor, sgn ) );
  1984. } else if ( sgn < 0 ) {
  1985. size = Math.pow( this.scaleFactor, - sgn );
  1986. }
  1987. if ( this.cursorZoom && this.enablePan ) {
  1988. let scalePoint;
  1989. if ( this.camera.isOrthographicCamera ) {
  1990. scalePoint = this.unprojectOnTbPlane( this.camera, event.clientX, event.clientY, this.domElement ).applyQuaternion( this.camera.quaternion ).multiplyScalar( 1 / this.camera.zoom ).add( this._gizmos.position );
  1991. } else if ( this.camera.isPerspectiveCamera ) {
  1992. scalePoint = this.unprojectOnTbPlane( this.camera, event.clientX, event.clientY, this.domElement ).applyQuaternion( this.camera.quaternion ).add( this._gizmos.position );
  1993. }
  1994. this.applyTransformMatrix( this.scale( size, scalePoint ) );
  1995. } else {
  1996. this.applyTransformMatrix( this.scale( size, this._gizmos.position ) );
  1997. }
  1998. if ( this._grid != null ) {
  1999. this.disposeGrid();
  2000. this.drawGrid();
  2001. }
  2002. this.updateTbState( STATE.IDLE, false );
  2003. this.dispatchEvent( _changeEvent );
  2004. this.dispatchEvent( _endEvent );
  2005. break;
  2006. case 'FOV':
  2007. if ( this.camera.isPerspectiveCamera ) {
  2008. this.updateTbState( STATE.FOV, true );
  2009. //Vertigo effect
  2010. // fov / 2
  2011. // |\
  2012. // | \
  2013. // | \
  2014. // x | \
  2015. // | \
  2016. // | \
  2017. // | _ _ _\
  2018. // y
  2019. //check for iOs shift shortcut
  2020. if ( event.deltaX != 0 ) {
  2021. sgn = event.deltaX / notchDeltaY;
  2022. size = 1;
  2023. if ( sgn > 0 ) {
  2024. size = 1 / ( Math.pow( this.scaleFactor, sgn ) );
  2025. } else if ( sgn < 0 ) {
  2026. size = Math.pow( this.scaleFactor, - sgn );
  2027. }
  2028. }
  2029. this._v3_1.setFromMatrixPosition( this._cameraMatrixState );
  2030. const x = this._v3_1.distanceTo( this._gizmos.position );
  2031. let xNew = x / size; //distance between camera and gizmos if scale(size, scalepoint) would be performed
  2032. //check min and max distance
  2033. xNew = MathUtils.clamp( xNew, this.minDistance, this.maxDistance );
  2034. const y = x * Math.tan( MathUtils.DEG2RAD * this.camera.fov * 0.5 );
  2035. //calculate new fov
  2036. let newFov = MathUtils.RAD2DEG * ( Math.atan( y / xNew ) * 2 );
  2037. //check min and max fov
  2038. if ( newFov > this.maxFov ) {
  2039. newFov = this.maxFov;
  2040. } else if ( newFov < this.minFov ) {
  2041. newFov = this.minFov;
  2042. }
  2043. const newDistance = y / Math.tan( MathUtils.DEG2RAD * ( newFov / 2 ) );
  2044. size = x / newDistance;
  2045. this.setFov( newFov );
  2046. this.applyTransformMatrix( this.scale( size, this._gizmos.position, false ) );
  2047. }
  2048. if ( this._grid != null ) {
  2049. this.disposeGrid();
  2050. this.drawGrid();
  2051. }
  2052. this.updateTbState( STATE.IDLE, false );
  2053. this.dispatchEvent( _changeEvent );
  2054. this.dispatchEvent( _endEvent );
  2055. break;
  2056. }
  2057. }
  2058. }
  2059. }
  2060. export { ArcballControls };