ArcballControls.js 78 KB

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