ArcballControls.js 78 KB

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