ArcballControls.js 85 KB

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