ArcballControls.js 85 KB

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