ArcballControls.js 85 KB

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