ArcballControls.js 82 KB

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