ArcballControls.js 78 KB

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