ArcballControls.js 79 KB

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