1
0

ArcballControls.js 78 KB

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