ArcballControls.js 85 KB

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