three-render-objects.js 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305
  1. // Version 1.26.4 three-render-objects - https://github.com/vasturiano/three-render-objects
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('three')) :
  4. typeof define === 'function' && define.amd ? define(['three'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ThreeRenderObjects = factory(global.THREE));
  6. }(this, (function (three$1) { 'use strict';
  7. function styleInject(css, ref) {
  8. if ( ref === void 0 ) ref = {};
  9. var insertAt = ref.insertAt;
  10. if (!css || typeof document === 'undefined') { return; }
  11. var head = document.head || document.getElementsByTagName('head')[0];
  12. var style = document.createElement('style');
  13. style.type = 'text/css';
  14. if (insertAt === 'top') {
  15. if (head.firstChild) {
  16. head.insertBefore(style, head.firstChild);
  17. } else {
  18. head.appendChild(style);
  19. }
  20. } else {
  21. head.appendChild(style);
  22. }
  23. if (style.styleSheet) {
  24. style.styleSheet.cssText = css;
  25. } else {
  26. style.appendChild(document.createTextNode(css));
  27. }
  28. }
  29. var css_248z = ".scene-nav-info {\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n}\n\n.scene-tooltip {\n color: lavender;\n font-size: 15px;\n}\n\n.scene-nav-info, .scene-tooltip {\n position: absolute;\n font-family: sans-serif;\n pointer-events: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}";
  30. styleInject(css_248z);
  31. function _defineProperty(obj, key, value) {
  32. if (key in obj) {
  33. Object.defineProperty(obj, key, {
  34. value: value,
  35. enumerable: true,
  36. configurable: true,
  37. writable: true
  38. });
  39. } else {
  40. obj[key] = value;
  41. }
  42. return obj;
  43. }
  44. function _slicedToArray$1(arr, i) {
  45. return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$1();
  46. }
  47. function _toConsumableArray(arr) {
  48. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
  49. }
  50. function _arrayWithoutHoles(arr) {
  51. if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
  52. }
  53. function _arrayWithHoles$1(arr) {
  54. if (Array.isArray(arr)) return arr;
  55. }
  56. function _iterableToArray(iter) {
  57. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  58. }
  59. function _iterableToArrayLimit$1(arr, i) {
  60. var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  61. if (_i == null) return;
  62. var _arr = [];
  63. var _n = true;
  64. var _d = false;
  65. var _s, _e;
  66. try {
  67. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  68. _arr.push(_s.value);
  69. if (i && _arr.length === i) break;
  70. }
  71. } catch (err) {
  72. _d = true;
  73. _e = err;
  74. } finally {
  75. try {
  76. if (!_n && _i["return"] != null) _i["return"]();
  77. } finally {
  78. if (_d) throw _e;
  79. }
  80. }
  81. return _arr;
  82. }
  83. function _unsupportedIterableToArray$1(o, minLen) {
  84. if (!o) return;
  85. if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
  86. var n = Object.prototype.toString.call(o).slice(8, -1);
  87. if (n === "Object" && o.constructor) n = o.constructor.name;
  88. if (n === "Map" || n === "Set") return Array.from(o);
  89. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
  90. }
  91. function _arrayLikeToArray$1(arr, len) {
  92. if (len == null || len > arr.length) len = arr.length;
  93. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  94. return arr2;
  95. }
  96. function _nonIterableSpread() {
  97. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  98. }
  99. function _nonIterableRest$1() {
  100. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  101. }
  102. const _changeEvent$2 = { type: 'change' };
  103. const _startEvent$1 = { type: 'start' };
  104. const _endEvent$1 = { type: 'end' };
  105. class TrackballControls extends three$1.EventDispatcher {
  106. constructor( object, domElement ) {
  107. super();
  108. if ( domElement === undefined ) console.warn( 'THREE.TrackballControls: The second parameter "domElement" is now mandatory.' );
  109. if ( domElement === document ) console.error( 'THREE.TrackballControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
  110. const scope = this;
  111. const STATE = { NONE: - 1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 };
  112. this.object = object;
  113. this.domElement = domElement;
  114. // API
  115. this.enabled = true;
  116. this.screen = { left: 0, top: 0, width: 0, height: 0 };
  117. this.rotateSpeed = 1.0;
  118. this.zoomSpeed = 1.2;
  119. this.panSpeed = 0.3;
  120. this.noRotate = false;
  121. this.noZoom = false;
  122. this.noPan = false;
  123. this.staticMoving = false;
  124. this.dynamicDampingFactor = 0.2;
  125. this.minDistance = 0;
  126. this.maxDistance = Infinity;
  127. this.keys = [ 'KeyA' /*A*/, 'KeyS' /*S*/, 'KeyD' /*D*/ ];
  128. this.mouseButtons = { LEFT: three$1.MOUSE.ROTATE, MIDDLE: three$1.MOUSE.DOLLY, RIGHT: three$1.MOUSE.PAN };
  129. // internals
  130. this.target = new three$1.Vector3();
  131. const EPS = 0.000001;
  132. const lastPosition = new three$1.Vector3();
  133. let lastZoom = 1;
  134. let _state = STATE.NONE,
  135. _keyState = STATE.NONE,
  136. _touchZoomDistanceStart = 0,
  137. _touchZoomDistanceEnd = 0,
  138. _lastAngle = 0;
  139. const _eye = new three$1.Vector3(),
  140. _movePrev = new three$1.Vector2(),
  141. _moveCurr = new three$1.Vector2(),
  142. _lastAxis = new three$1.Vector3(),
  143. _zoomStart = new three$1.Vector2(),
  144. _zoomEnd = new three$1.Vector2(),
  145. _panStart = new three$1.Vector2(),
  146. _panEnd = new three$1.Vector2();
  147. // for reset
  148. this.target0 = this.target.clone();
  149. this.position0 = this.object.position.clone();
  150. this.up0 = this.object.up.clone();
  151. this.zoom0 = this.object.zoom;
  152. // methods
  153. this.handleResize = function () {
  154. const box = scope.domElement.getBoundingClientRect();
  155. // adjustments come from similar code in the jquery offset() function
  156. const d = scope.domElement.ownerDocument.documentElement;
  157. scope.screen.left = box.left + window.pageXOffset - d.clientLeft;
  158. scope.screen.top = box.top + window.pageYOffset - d.clientTop;
  159. scope.screen.width = box.width;
  160. scope.screen.height = box.height;
  161. };
  162. const getMouseOnScreen = ( function () {
  163. const vector = new three$1.Vector2();
  164. return function getMouseOnScreen( pageX, pageY ) {
  165. vector.set(
  166. ( pageX - scope.screen.left ) / scope.screen.width,
  167. ( pageY - scope.screen.top ) / scope.screen.height
  168. );
  169. return vector;
  170. };
  171. }() );
  172. const getMouseOnCircle = ( function () {
  173. const vector = new three$1.Vector2();
  174. return function getMouseOnCircle( pageX, pageY ) {
  175. vector.set(
  176. ( ( pageX - scope.screen.width * 0.5 - scope.screen.left ) / ( scope.screen.width * 0.5 ) ),
  177. ( ( scope.screen.height + 2 * ( scope.screen.top - pageY ) ) / scope.screen.width ) // screen.width intentional
  178. );
  179. return vector;
  180. };
  181. }() );
  182. this.rotateCamera = ( function () {
  183. const axis = new three$1.Vector3(),
  184. quaternion = new three$1.Quaternion(),
  185. eyeDirection = new three$1.Vector3(),
  186. objectUpDirection = new three$1.Vector3(),
  187. objectSidewaysDirection = new three$1.Vector3(),
  188. moveDirection = new three$1.Vector3();
  189. return function rotateCamera() {
  190. moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 );
  191. let angle = moveDirection.length();
  192. if ( angle ) {
  193. _eye.copy( scope.object.position ).sub( scope.target );
  194. eyeDirection.copy( _eye ).normalize();
  195. objectUpDirection.copy( scope.object.up ).normalize();
  196. objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize();
  197. objectUpDirection.setLength( _moveCurr.y - _movePrev.y );
  198. objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x );
  199. moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) );
  200. axis.crossVectors( moveDirection, _eye ).normalize();
  201. angle *= scope.rotateSpeed;
  202. quaternion.setFromAxisAngle( axis, angle );
  203. _eye.applyQuaternion( quaternion );
  204. scope.object.up.applyQuaternion( quaternion );
  205. _lastAxis.copy( axis );
  206. _lastAngle = angle;
  207. } else if ( ! scope.staticMoving && _lastAngle ) {
  208. _lastAngle *= Math.sqrt( 1.0 - scope.dynamicDampingFactor );
  209. _eye.copy( scope.object.position ).sub( scope.target );
  210. quaternion.setFromAxisAngle( _lastAxis, _lastAngle );
  211. _eye.applyQuaternion( quaternion );
  212. scope.object.up.applyQuaternion( quaternion );
  213. }
  214. _movePrev.copy( _moveCurr );
  215. };
  216. }() );
  217. this.zoomCamera = function () {
  218. let factor;
  219. if ( _state === STATE.TOUCH_ZOOM_PAN ) {
  220. factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
  221. _touchZoomDistanceStart = _touchZoomDistanceEnd;
  222. if ( scope.object.isPerspectiveCamera ) {
  223. _eye.multiplyScalar( factor );
  224. } else if ( scope.object.isOrthographicCamera ) {
  225. scope.object.zoom *= factor;
  226. scope.object.updateProjectionMatrix();
  227. } else {
  228. console.warn( 'THREE.TrackballControls: Unsupported camera type' );
  229. }
  230. } else {
  231. factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * scope.zoomSpeed;
  232. if ( factor !== 1.0 && factor > 0.0 ) {
  233. if ( scope.object.isPerspectiveCamera ) {
  234. _eye.multiplyScalar( factor );
  235. } else if ( scope.object.isOrthographicCamera ) {
  236. scope.object.zoom /= factor;
  237. scope.object.updateProjectionMatrix();
  238. } else {
  239. console.warn( 'THREE.TrackballControls: Unsupported camera type' );
  240. }
  241. }
  242. if ( scope.staticMoving ) {
  243. _zoomStart.copy( _zoomEnd );
  244. } else {
  245. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  246. }
  247. }
  248. };
  249. this.panCamera = ( function () {
  250. const mouseChange = new three$1.Vector2(),
  251. objectUp = new three$1.Vector3(),
  252. pan = new three$1.Vector3();
  253. return function panCamera() {
  254. mouseChange.copy( _panEnd ).sub( _panStart );
  255. if ( mouseChange.lengthSq() ) {
  256. if ( scope.object.isOrthographicCamera ) {
  257. const scale_x = ( scope.object.right - scope.object.left ) / scope.object.zoom / scope.domElement.clientWidth;
  258. const scale_y = ( scope.object.top - scope.object.bottom ) / scope.object.zoom / scope.domElement.clientWidth;
  259. mouseChange.x *= scale_x;
  260. mouseChange.y *= scale_y;
  261. }
  262. mouseChange.multiplyScalar( _eye.length() * scope.panSpeed );
  263. pan.copy( _eye ).cross( scope.object.up ).setLength( mouseChange.x );
  264. pan.add( objectUp.copy( scope.object.up ).setLength( mouseChange.y ) );
  265. scope.object.position.add( pan );
  266. scope.target.add( pan );
  267. if ( scope.staticMoving ) {
  268. _panStart.copy( _panEnd );
  269. } else {
  270. _panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( scope.dynamicDampingFactor ) );
  271. }
  272. }
  273. };
  274. }() );
  275. this.checkDistances = function () {
  276. if ( ! scope.noZoom || ! scope.noPan ) {
  277. if ( _eye.lengthSq() > scope.maxDistance * scope.maxDistance ) {
  278. scope.object.position.addVectors( scope.target, _eye.setLength( scope.maxDistance ) );
  279. _zoomStart.copy( _zoomEnd );
  280. }
  281. if ( _eye.lengthSq() < scope.minDistance * scope.minDistance ) {
  282. scope.object.position.addVectors( scope.target, _eye.setLength( scope.minDistance ) );
  283. _zoomStart.copy( _zoomEnd );
  284. }
  285. }
  286. };
  287. this.update = function () {
  288. _eye.subVectors( scope.object.position, scope.target );
  289. if ( ! scope.noRotate ) {
  290. scope.rotateCamera();
  291. }
  292. if ( ! scope.noZoom ) {
  293. scope.zoomCamera();
  294. }
  295. if ( ! scope.noPan ) {
  296. scope.panCamera();
  297. }
  298. scope.object.position.addVectors( scope.target, _eye );
  299. if ( scope.object.isPerspectiveCamera ) {
  300. scope.checkDistances();
  301. scope.object.lookAt( scope.target );
  302. if ( lastPosition.distanceToSquared( scope.object.position ) > EPS ) {
  303. scope.dispatchEvent( _changeEvent$2 );
  304. lastPosition.copy( scope.object.position );
  305. }
  306. } else if ( scope.object.isOrthographicCamera ) {
  307. scope.object.lookAt( scope.target );
  308. if ( lastPosition.distanceToSquared( scope.object.position ) > EPS || lastZoom !== scope.object.zoom ) {
  309. scope.dispatchEvent( _changeEvent$2 );
  310. lastPosition.copy( scope.object.position );
  311. lastZoom = scope.object.zoom;
  312. }
  313. } else {
  314. console.warn( 'THREE.TrackballControls: Unsupported camera type' );
  315. }
  316. };
  317. this.reset = function () {
  318. _state = STATE.NONE;
  319. _keyState = STATE.NONE;
  320. scope.target.copy( scope.target0 );
  321. scope.object.position.copy( scope.position0 );
  322. scope.object.up.copy( scope.up0 );
  323. scope.object.zoom = scope.zoom0;
  324. scope.object.updateProjectionMatrix();
  325. _eye.subVectors( scope.object.position, scope.target );
  326. scope.object.lookAt( scope.target );
  327. scope.dispatchEvent( _changeEvent$2 );
  328. lastPosition.copy( scope.object.position );
  329. lastZoom = scope.object.zoom;
  330. };
  331. // listeners
  332. function onPointerDown( event ) {
  333. if ( scope.enabled === false ) return;
  334. switch ( event.pointerType ) {
  335. case 'mouse':
  336. case 'pen':
  337. onMouseDown( event );
  338. break;
  339. // TODO touch
  340. }
  341. }
  342. function onPointerMove( event ) {
  343. if ( scope.enabled === false ) return;
  344. switch ( event.pointerType ) {
  345. case 'mouse':
  346. case 'pen':
  347. onMouseMove( event );
  348. break;
  349. // TODO touch
  350. }
  351. }
  352. function onPointerUp( event ) {
  353. if ( scope.enabled === false ) return;
  354. switch ( event.pointerType ) {
  355. case 'mouse':
  356. case 'pen':
  357. onMouseUp( event );
  358. break;
  359. // TODO touch
  360. }
  361. }
  362. function keydown( event ) {
  363. if ( scope.enabled === false ) return;
  364. window.removeEventListener( 'keydown', keydown );
  365. if ( _keyState !== STATE.NONE ) {
  366. return;
  367. } else if ( event.code === scope.keys[ STATE.ROTATE ] && ! scope.noRotate ) {
  368. _keyState = STATE.ROTATE;
  369. } else if ( event.code === scope.keys[ STATE.ZOOM ] && ! scope.noZoom ) {
  370. _keyState = STATE.ZOOM;
  371. } else if ( event.code === scope.keys[ STATE.PAN ] && ! scope.noPan ) {
  372. _keyState = STATE.PAN;
  373. }
  374. }
  375. function keyup() {
  376. if ( scope.enabled === false ) return;
  377. _keyState = STATE.NONE;
  378. window.addEventListener( 'keydown', keydown );
  379. }
  380. function onMouseDown( event ) {
  381. event.preventDefault();
  382. if ( _state === STATE.NONE ) {
  383. switch ( event.button ) {
  384. case scope.mouseButtons.LEFT:
  385. _state = STATE.ROTATE;
  386. break;
  387. case scope.mouseButtons.MIDDLE:
  388. _state = STATE.ZOOM;
  389. break;
  390. case scope.mouseButtons.RIGHT:
  391. _state = STATE.PAN;
  392. break;
  393. default:
  394. _state = STATE.NONE;
  395. }
  396. }
  397. const state = ( _keyState !== STATE.NONE ) ? _keyState : _state;
  398. if ( state === STATE.ROTATE && ! scope.noRotate ) {
  399. _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
  400. _movePrev.copy( _moveCurr );
  401. } else if ( state === STATE.ZOOM && ! scope.noZoom ) {
  402. _zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  403. _zoomEnd.copy( _zoomStart );
  404. } else if ( state === STATE.PAN && ! scope.noPan ) {
  405. _panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  406. _panEnd.copy( _panStart );
  407. }
  408. scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
  409. scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
  410. scope.dispatchEvent( _startEvent$1 );
  411. }
  412. function onMouseMove( event ) {
  413. if ( scope.enabled === false ) return;
  414. event.preventDefault();
  415. const state = ( _keyState !== STATE.NONE ) ? _keyState : _state;
  416. if ( state === STATE.ROTATE && ! scope.noRotate ) {
  417. _movePrev.copy( _moveCurr );
  418. _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) );
  419. } else if ( state === STATE.ZOOM && ! scope.noZoom ) {
  420. _zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  421. } else if ( state === STATE.PAN && ! scope.noPan ) {
  422. _panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) );
  423. }
  424. }
  425. function onMouseUp( event ) {
  426. if ( scope.enabled === false ) return;
  427. event.preventDefault();
  428. _state = STATE.NONE;
  429. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  430. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  431. scope.dispatchEvent( _endEvent$1 );
  432. }
  433. function mousewheel( event ) {
  434. if ( scope.enabled === false ) return;
  435. if ( scope.noZoom === true ) return;
  436. event.preventDefault();
  437. switch ( event.deltaMode ) {
  438. case 2:
  439. // Zoom in pages
  440. _zoomStart.y -= event.deltaY * 0.025;
  441. break;
  442. case 1:
  443. // Zoom in lines
  444. _zoomStart.y -= event.deltaY * 0.01;
  445. break;
  446. default:
  447. // undefined, 0, assume pixels
  448. _zoomStart.y -= event.deltaY * 0.00025;
  449. break;
  450. }
  451. scope.dispatchEvent( _startEvent$1 );
  452. scope.dispatchEvent( _endEvent$1 );
  453. }
  454. function touchstart( event ) {
  455. if ( scope.enabled === false ) return;
  456. event.preventDefault();
  457. switch ( event.touches.length ) {
  458. case 1:
  459. _state = STATE.TOUCH_ROTATE;
  460. _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
  461. _movePrev.copy( _moveCurr );
  462. break;
  463. default: // 2 or more
  464. _state = STATE.TOUCH_ZOOM_PAN;
  465. const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  466. const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  467. _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
  468. const x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
  469. const y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
  470. _panStart.copy( getMouseOnScreen( x, y ) );
  471. _panEnd.copy( _panStart );
  472. break;
  473. }
  474. scope.dispatchEvent( _startEvent$1 );
  475. }
  476. function touchmove( event ) {
  477. if ( scope.enabled === false ) return;
  478. event.preventDefault();
  479. switch ( event.touches.length ) {
  480. case 1:
  481. _movePrev.copy( _moveCurr );
  482. _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
  483. break;
  484. default: // 2 or more
  485. const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  486. const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  487. _touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy );
  488. const x = ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX ) / 2;
  489. const y = ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY ) / 2;
  490. _panEnd.copy( getMouseOnScreen( x, y ) );
  491. break;
  492. }
  493. }
  494. function touchend( event ) {
  495. if ( scope.enabled === false ) return;
  496. switch ( event.touches.length ) {
  497. case 0:
  498. _state = STATE.NONE;
  499. break;
  500. case 1:
  501. _state = STATE.TOUCH_ROTATE;
  502. _moveCurr.copy( getMouseOnCircle( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ) );
  503. _movePrev.copy( _moveCurr );
  504. break;
  505. }
  506. scope.dispatchEvent( _endEvent$1 );
  507. }
  508. function contextmenu( event ) {
  509. if ( scope.enabled === false ) return;
  510. event.preventDefault();
  511. }
  512. this.dispose = function () {
  513. scope.domElement.removeEventListener( 'contextmenu', contextmenu );
  514. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  515. scope.domElement.removeEventListener( 'wheel', mousewheel );
  516. scope.domElement.removeEventListener( 'touchstart', touchstart );
  517. scope.domElement.removeEventListener( 'touchend', touchend );
  518. scope.domElement.removeEventListener( 'touchmove', touchmove );
  519. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  520. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  521. window.removeEventListener( 'keydown', keydown );
  522. window.removeEventListener( 'keyup', keyup );
  523. };
  524. this.domElement.addEventListener( 'contextmenu', contextmenu );
  525. this.domElement.addEventListener( 'pointerdown', onPointerDown );
  526. this.domElement.addEventListener( 'wheel', mousewheel, { passive: false } );
  527. this.domElement.addEventListener( 'touchstart', touchstart, { passive: false } );
  528. this.domElement.addEventListener( 'touchend', touchend );
  529. this.domElement.addEventListener( 'touchmove', touchmove, { passive: false } );
  530. this.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
  531. this.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
  532. window.addEventListener( 'keydown', keydown );
  533. window.addEventListener( 'keyup', keyup );
  534. this.handleResize();
  535. // force an update at start
  536. this.update();
  537. }
  538. }
  539. // This set of controls performs orbiting, dollying (zooming), and panning.
  540. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  541. //
  542. // Orbit - left mouse / touch: one-finger move
  543. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  544. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  545. const _changeEvent$1 = { type: 'change' };
  546. const _startEvent = { type: 'start' };
  547. const _endEvent = { type: 'end' };
  548. class OrbitControls extends three$1.EventDispatcher {
  549. constructor( object, domElement ) {
  550. super();
  551. if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' );
  552. if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' );
  553. this.object = object;
  554. this.domElement = domElement;
  555. // Set to false to disable this control
  556. this.enabled = true;
  557. // "target" sets the location of focus, where the object orbits around
  558. this.target = new three$1.Vector3();
  559. // How far you can dolly in and out ( PerspectiveCamera only )
  560. this.minDistance = 0;
  561. this.maxDistance = Infinity;
  562. // How far you can zoom in and out ( OrthographicCamera only )
  563. this.minZoom = 0;
  564. this.maxZoom = Infinity;
  565. // How far you can orbit vertically, upper and lower limits.
  566. // Range is 0 to Math.PI radians.
  567. this.minPolarAngle = 0; // radians
  568. this.maxPolarAngle = Math.PI; // radians
  569. // How far you can orbit horizontally, upper and lower limits.
  570. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  571. this.minAzimuthAngle = - Infinity; // radians
  572. this.maxAzimuthAngle = Infinity; // radians
  573. // Set to true to enable damping (inertia)
  574. // If damping is enabled, you must call controls.update() in your animation loop
  575. this.enableDamping = false;
  576. this.dampingFactor = 0.05;
  577. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  578. // Set to false to disable zooming
  579. this.enableZoom = true;
  580. this.zoomSpeed = 1.0;
  581. // Set to false to disable rotating
  582. this.enableRotate = true;
  583. this.rotateSpeed = 1.0;
  584. // Set to false to disable panning
  585. this.enablePan = true;
  586. this.panSpeed = 1.0;
  587. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  588. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  589. // Set to true to automatically rotate around the target
  590. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  591. this.autoRotate = false;
  592. this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
  593. // The four arrow keys
  594. this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
  595. // Mouse buttons
  596. this.mouseButtons = { LEFT: three$1.MOUSE.ROTATE, MIDDLE: three$1.MOUSE.DOLLY, RIGHT: three$1.MOUSE.PAN };
  597. // Touch fingers
  598. this.touches = { ONE: three$1.TOUCH.ROTATE, TWO: three$1.TOUCH.DOLLY_PAN };
  599. // for reset
  600. this.target0 = this.target.clone();
  601. this.position0 = this.object.position.clone();
  602. this.zoom0 = this.object.zoom;
  603. // the target DOM element for key events
  604. this._domElementKeyEvents = null;
  605. //
  606. // public methods
  607. //
  608. this.getPolarAngle = function () {
  609. return spherical.phi;
  610. };
  611. this.getAzimuthalAngle = function () {
  612. return spherical.theta;
  613. };
  614. this.listenToKeyEvents = function ( domElement ) {
  615. domElement.addEventListener( 'keydown', onKeyDown );
  616. this._domElementKeyEvents = domElement;
  617. };
  618. this.saveState = function () {
  619. scope.target0.copy( scope.target );
  620. scope.position0.copy( scope.object.position );
  621. scope.zoom0 = scope.object.zoom;
  622. };
  623. this.reset = function () {
  624. scope.target.copy( scope.target0 );
  625. scope.object.position.copy( scope.position0 );
  626. scope.object.zoom = scope.zoom0;
  627. scope.object.updateProjectionMatrix();
  628. scope.dispatchEvent( _changeEvent$1 );
  629. scope.update();
  630. state = STATE.NONE;
  631. };
  632. // this method is exposed, but perhaps it would be better if we can make it private...
  633. this.update = function () {
  634. const offset = new three$1.Vector3();
  635. // so camera.up is the orbit axis
  636. const quat = new three$1.Quaternion().setFromUnitVectors( object.up, new three$1.Vector3( 0, 1, 0 ) );
  637. const quatInverse = quat.clone().invert();
  638. const lastPosition = new three$1.Vector3();
  639. const lastQuaternion = new three$1.Quaternion();
  640. const twoPI = 2 * Math.PI;
  641. return function update() {
  642. const position = scope.object.position;
  643. offset.copy( position ).sub( scope.target );
  644. // rotate offset to "y-axis-is-up" space
  645. offset.applyQuaternion( quat );
  646. // angle from z-axis around y-axis
  647. spherical.setFromVector3( offset );
  648. if ( scope.autoRotate && state === STATE.NONE ) {
  649. rotateLeft( getAutoRotationAngle() );
  650. }
  651. if ( scope.enableDamping ) {
  652. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  653. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  654. } else {
  655. spherical.theta += sphericalDelta.theta;
  656. spherical.phi += sphericalDelta.phi;
  657. }
  658. // restrict theta to be between desired limits
  659. let min = scope.minAzimuthAngle;
  660. let max = scope.maxAzimuthAngle;
  661. if ( isFinite( min ) && isFinite( max ) ) {
  662. if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
  663. if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
  664. if ( min <= max ) {
  665. spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
  666. } else {
  667. spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ?
  668. Math.max( min, spherical.theta ) :
  669. Math.min( max, spherical.theta );
  670. }
  671. }
  672. // restrict phi to be between desired limits
  673. spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
  674. spherical.makeSafe();
  675. spherical.radius *= scale;
  676. // restrict radius to be between desired limits
  677. spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
  678. // move target to panned location
  679. if ( scope.enableDamping === true ) {
  680. scope.target.addScaledVector( panOffset, scope.dampingFactor );
  681. } else {
  682. scope.target.add( panOffset );
  683. }
  684. offset.setFromSpherical( spherical );
  685. // rotate offset back to "camera-up-vector-is-up" space
  686. offset.applyQuaternion( quatInverse );
  687. position.copy( scope.target ).add( offset );
  688. scope.object.lookAt( scope.target );
  689. if ( scope.enableDamping === true ) {
  690. sphericalDelta.theta *= ( 1 - scope.dampingFactor );
  691. sphericalDelta.phi *= ( 1 - scope.dampingFactor );
  692. panOffset.multiplyScalar( 1 - scope.dampingFactor );
  693. } else {
  694. sphericalDelta.set( 0, 0, 0 );
  695. panOffset.set( 0, 0, 0 );
  696. }
  697. scale = 1;
  698. // update condition is:
  699. // min(camera displacement, camera rotation in radians)^2 > EPS
  700. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  701. if ( zoomChanged ||
  702. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  703. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
  704. scope.dispatchEvent( _changeEvent$1 );
  705. lastPosition.copy( scope.object.position );
  706. lastQuaternion.copy( scope.object.quaternion );
  707. zoomChanged = false;
  708. return true;
  709. }
  710. return false;
  711. };
  712. }();
  713. this.dispose = function () {
  714. scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
  715. scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
  716. scope.domElement.removeEventListener( 'wheel', onMouseWheel );
  717. scope.domElement.removeEventListener( 'touchstart', onTouchStart );
  718. scope.domElement.removeEventListener( 'touchend', onTouchEnd );
  719. scope.domElement.removeEventListener( 'touchmove', onTouchMove );
  720. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  721. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  722. if ( scope._domElementKeyEvents !== null ) {
  723. scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
  724. }
  725. //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  726. };
  727. //
  728. // internals
  729. //
  730. const scope = this;
  731. const STATE = {
  732. NONE: - 1,
  733. ROTATE: 0,
  734. DOLLY: 1,
  735. PAN: 2,
  736. TOUCH_ROTATE: 3,
  737. TOUCH_PAN: 4,
  738. TOUCH_DOLLY_PAN: 5,
  739. TOUCH_DOLLY_ROTATE: 6
  740. };
  741. let state = STATE.NONE;
  742. const EPS = 0.000001;
  743. // current position in spherical coordinates
  744. const spherical = new three$1.Spherical();
  745. const sphericalDelta = new three$1.Spherical();
  746. let scale = 1;
  747. const panOffset = new three$1.Vector3();
  748. let zoomChanged = false;
  749. const rotateStart = new three$1.Vector2();
  750. const rotateEnd = new three$1.Vector2();
  751. const rotateDelta = new three$1.Vector2();
  752. const panStart = new three$1.Vector2();
  753. const panEnd = new three$1.Vector2();
  754. const panDelta = new three$1.Vector2();
  755. const dollyStart = new three$1.Vector2();
  756. const dollyEnd = new three$1.Vector2();
  757. const dollyDelta = new three$1.Vector2();
  758. function getAutoRotationAngle() {
  759. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  760. }
  761. function getZoomScale() {
  762. return Math.pow( 0.95, scope.zoomSpeed );
  763. }
  764. function rotateLeft( angle ) {
  765. sphericalDelta.theta -= angle;
  766. }
  767. function rotateUp( angle ) {
  768. sphericalDelta.phi -= angle;
  769. }
  770. const panLeft = function () {
  771. const v = new three$1.Vector3();
  772. return function panLeft( distance, objectMatrix ) {
  773. v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
  774. v.multiplyScalar( - distance );
  775. panOffset.add( v );
  776. };
  777. }();
  778. const panUp = function () {
  779. const v = new three$1.Vector3();
  780. return function panUp( distance, objectMatrix ) {
  781. if ( scope.screenSpacePanning === true ) {
  782. v.setFromMatrixColumn( objectMatrix, 1 );
  783. } else {
  784. v.setFromMatrixColumn( objectMatrix, 0 );
  785. v.crossVectors( scope.object.up, v );
  786. }
  787. v.multiplyScalar( distance );
  788. panOffset.add( v );
  789. };
  790. }();
  791. // deltaX and deltaY are in pixels; right and down are positive
  792. const pan = function () {
  793. const offset = new three$1.Vector3();
  794. return function pan( deltaX, deltaY ) {
  795. const element = scope.domElement;
  796. if ( scope.object.isPerspectiveCamera ) {
  797. // perspective
  798. const position = scope.object.position;
  799. offset.copy( position ).sub( scope.target );
  800. let targetDistance = offset.length();
  801. // half of the fov is center to top of screen
  802. targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
  803. // we use only clientHeight here so aspect ratio does not distort speed
  804. panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
  805. panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
  806. } else if ( scope.object.isOrthographicCamera ) {
  807. // orthographic
  808. panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
  809. panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
  810. } else {
  811. // camera neither orthographic nor perspective
  812. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
  813. scope.enablePan = false;
  814. }
  815. };
  816. }();
  817. function dollyOut( dollyScale ) {
  818. if ( scope.object.isPerspectiveCamera ) {
  819. scale /= dollyScale;
  820. } else if ( scope.object.isOrthographicCamera ) {
  821. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
  822. scope.object.updateProjectionMatrix();
  823. zoomChanged = true;
  824. } else {
  825. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  826. scope.enableZoom = false;
  827. }
  828. }
  829. function dollyIn( dollyScale ) {
  830. if ( scope.object.isPerspectiveCamera ) {
  831. scale *= dollyScale;
  832. } else if ( scope.object.isOrthographicCamera ) {
  833. scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
  834. scope.object.updateProjectionMatrix();
  835. zoomChanged = true;
  836. } else {
  837. console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
  838. scope.enableZoom = false;
  839. }
  840. }
  841. //
  842. // event callbacks - update the object state
  843. //
  844. function handleMouseDownRotate( event ) {
  845. rotateStart.set( event.clientX, event.clientY );
  846. }
  847. function handleMouseDownDolly( event ) {
  848. dollyStart.set( event.clientX, event.clientY );
  849. }
  850. function handleMouseDownPan( event ) {
  851. panStart.set( event.clientX, event.clientY );
  852. }
  853. function handleMouseMoveRotate( event ) {
  854. rotateEnd.set( event.clientX, event.clientY );
  855. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  856. const element = scope.domElement;
  857. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  858. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  859. rotateStart.copy( rotateEnd );
  860. scope.update();
  861. }
  862. function handleMouseMoveDolly( event ) {
  863. dollyEnd.set( event.clientX, event.clientY );
  864. dollyDelta.subVectors( dollyEnd, dollyStart );
  865. if ( dollyDelta.y > 0 ) {
  866. dollyOut( getZoomScale() );
  867. } else if ( dollyDelta.y < 0 ) {
  868. dollyIn( getZoomScale() );
  869. }
  870. dollyStart.copy( dollyEnd );
  871. scope.update();
  872. }
  873. function handleMouseMovePan( event ) {
  874. panEnd.set( event.clientX, event.clientY );
  875. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  876. pan( panDelta.x, panDelta.y );
  877. panStart.copy( panEnd );
  878. scope.update();
  879. }
  880. function handleMouseWheel( event ) {
  881. if ( event.deltaY < 0 ) {
  882. dollyIn( getZoomScale() );
  883. } else if ( event.deltaY > 0 ) {
  884. dollyOut( getZoomScale() );
  885. }
  886. scope.update();
  887. }
  888. function handleKeyDown( event ) {
  889. let needsUpdate = false;
  890. switch ( event.code ) {
  891. case scope.keys.UP:
  892. pan( 0, scope.keyPanSpeed );
  893. needsUpdate = true;
  894. break;
  895. case scope.keys.BOTTOM:
  896. pan( 0, - scope.keyPanSpeed );
  897. needsUpdate = true;
  898. break;
  899. case scope.keys.LEFT:
  900. pan( scope.keyPanSpeed, 0 );
  901. needsUpdate = true;
  902. break;
  903. case scope.keys.RIGHT:
  904. pan( - scope.keyPanSpeed, 0 );
  905. needsUpdate = true;
  906. break;
  907. }
  908. if ( needsUpdate ) {
  909. // prevent the browser from scrolling on cursor keys
  910. event.preventDefault();
  911. scope.update();
  912. }
  913. }
  914. function handleTouchStartRotate( event ) {
  915. if ( event.touches.length == 1 ) {
  916. rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  917. } else {
  918. const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  919. const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  920. rotateStart.set( x, y );
  921. }
  922. }
  923. function handleTouchStartPan( event ) {
  924. if ( event.touches.length == 1 ) {
  925. panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  926. } else {
  927. const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  928. const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  929. panStart.set( x, y );
  930. }
  931. }
  932. function handleTouchStartDolly( event ) {
  933. const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  934. const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  935. const distance = Math.sqrt( dx * dx + dy * dy );
  936. dollyStart.set( 0, distance );
  937. }
  938. function handleTouchStartDollyPan( event ) {
  939. if ( scope.enableZoom ) handleTouchStartDolly( event );
  940. if ( scope.enablePan ) handleTouchStartPan( event );
  941. }
  942. function handleTouchStartDollyRotate( event ) {
  943. if ( scope.enableZoom ) handleTouchStartDolly( event );
  944. if ( scope.enableRotate ) handleTouchStartRotate( event );
  945. }
  946. function handleTouchMoveRotate( event ) {
  947. if ( event.touches.length == 1 ) {
  948. rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  949. } else {
  950. const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  951. const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  952. rotateEnd.set( x, y );
  953. }
  954. rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
  955. const element = scope.domElement;
  956. rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
  957. rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
  958. rotateStart.copy( rotateEnd );
  959. }
  960. function handleTouchMovePan( event ) {
  961. if ( event.touches.length == 1 ) {
  962. panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  963. } else {
  964. const x = 0.5 * ( event.touches[ 0 ].pageX + event.touches[ 1 ].pageX );
  965. const y = 0.5 * ( event.touches[ 0 ].pageY + event.touches[ 1 ].pageY );
  966. panEnd.set( x, y );
  967. }
  968. panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
  969. pan( panDelta.x, panDelta.y );
  970. panStart.copy( panEnd );
  971. }
  972. function handleTouchMoveDolly( event ) {
  973. const dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
  974. const dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
  975. const distance = Math.sqrt( dx * dx + dy * dy );
  976. dollyEnd.set( 0, distance );
  977. dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
  978. dollyOut( dollyDelta.y );
  979. dollyStart.copy( dollyEnd );
  980. }
  981. function handleTouchMoveDollyPan( event ) {
  982. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  983. if ( scope.enablePan ) handleTouchMovePan( event );
  984. }
  985. function handleTouchMoveDollyRotate( event ) {
  986. if ( scope.enableZoom ) handleTouchMoveDolly( event );
  987. if ( scope.enableRotate ) handleTouchMoveRotate( event );
  988. }
  989. //
  990. // event handlers - FSM: listen for events and reset state
  991. //
  992. function onPointerDown( event ) {
  993. if ( scope.enabled === false ) return;
  994. switch ( event.pointerType ) {
  995. case 'mouse':
  996. case 'pen':
  997. onMouseDown( event );
  998. break;
  999. // TODO touch
  1000. }
  1001. }
  1002. function onPointerMove( event ) {
  1003. if ( scope.enabled === false ) return;
  1004. switch ( event.pointerType ) {
  1005. case 'mouse':
  1006. case 'pen':
  1007. onMouseMove( event );
  1008. break;
  1009. // TODO touch
  1010. }
  1011. }
  1012. function onPointerUp( event ) {
  1013. switch ( event.pointerType ) {
  1014. case 'mouse':
  1015. case 'pen':
  1016. onMouseUp();
  1017. break;
  1018. // TODO touch
  1019. }
  1020. }
  1021. function onMouseDown( event ) {
  1022. // Prevent the browser from scrolling.
  1023. event.preventDefault();
  1024. // Manually set the focus since calling preventDefault above
  1025. // prevents the browser from setting it automatically.
  1026. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  1027. let mouseAction;
  1028. switch ( event.button ) {
  1029. case 0:
  1030. mouseAction = scope.mouseButtons.LEFT;
  1031. break;
  1032. case 1:
  1033. mouseAction = scope.mouseButtons.MIDDLE;
  1034. break;
  1035. case 2:
  1036. mouseAction = scope.mouseButtons.RIGHT;
  1037. break;
  1038. default:
  1039. mouseAction = - 1;
  1040. }
  1041. switch ( mouseAction ) {
  1042. case three$1.MOUSE.DOLLY:
  1043. if ( scope.enableZoom === false ) return;
  1044. handleMouseDownDolly( event );
  1045. state = STATE.DOLLY;
  1046. break;
  1047. case three$1.MOUSE.ROTATE:
  1048. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  1049. if ( scope.enablePan === false ) return;
  1050. handleMouseDownPan( event );
  1051. state = STATE.PAN;
  1052. } else {
  1053. if ( scope.enableRotate === false ) return;
  1054. handleMouseDownRotate( event );
  1055. state = STATE.ROTATE;
  1056. }
  1057. break;
  1058. case three$1.MOUSE.PAN:
  1059. if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
  1060. if ( scope.enableRotate === false ) return;
  1061. handleMouseDownRotate( event );
  1062. state = STATE.ROTATE;
  1063. } else {
  1064. if ( scope.enablePan === false ) return;
  1065. handleMouseDownPan( event );
  1066. state = STATE.PAN;
  1067. }
  1068. break;
  1069. default:
  1070. state = STATE.NONE;
  1071. }
  1072. if ( state !== STATE.NONE ) {
  1073. scope.domElement.ownerDocument.addEventListener( 'pointermove', onPointerMove );
  1074. scope.domElement.ownerDocument.addEventListener( 'pointerup', onPointerUp );
  1075. scope.dispatchEvent( _startEvent );
  1076. }
  1077. }
  1078. function onMouseMove( event ) {
  1079. if ( scope.enabled === false ) return;
  1080. event.preventDefault();
  1081. switch ( state ) {
  1082. case STATE.ROTATE:
  1083. if ( scope.enableRotate === false ) return;
  1084. handleMouseMoveRotate( event );
  1085. break;
  1086. case STATE.DOLLY:
  1087. if ( scope.enableZoom === false ) return;
  1088. handleMouseMoveDolly( event );
  1089. break;
  1090. case STATE.PAN:
  1091. if ( scope.enablePan === false ) return;
  1092. handleMouseMovePan( event );
  1093. break;
  1094. }
  1095. }
  1096. function onMouseUp( event ) {
  1097. scope.domElement.ownerDocument.removeEventListener( 'pointermove', onPointerMove );
  1098. scope.domElement.ownerDocument.removeEventListener( 'pointerup', onPointerUp );
  1099. if ( scope.enabled === false ) return;
  1100. scope.dispatchEvent( _endEvent );
  1101. state = STATE.NONE;
  1102. }
  1103. function onMouseWheel( event ) {
  1104. if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return;
  1105. event.preventDefault();
  1106. scope.dispatchEvent( _startEvent );
  1107. handleMouseWheel( event );
  1108. scope.dispatchEvent( _endEvent );
  1109. }
  1110. function onKeyDown( event ) {
  1111. if ( scope.enabled === false || scope.enablePan === false ) return;
  1112. handleKeyDown( event );
  1113. }
  1114. function onTouchStart( event ) {
  1115. if ( scope.enabled === false ) return;
  1116. event.preventDefault(); // prevent scrolling
  1117. switch ( event.touches.length ) {
  1118. case 1:
  1119. switch ( scope.touches.ONE ) {
  1120. case three$1.TOUCH.ROTATE:
  1121. if ( scope.enableRotate === false ) return;
  1122. handleTouchStartRotate( event );
  1123. state = STATE.TOUCH_ROTATE;
  1124. break;
  1125. case three$1.TOUCH.PAN:
  1126. if ( scope.enablePan === false ) return;
  1127. handleTouchStartPan( event );
  1128. state = STATE.TOUCH_PAN;
  1129. break;
  1130. default:
  1131. state = STATE.NONE;
  1132. }
  1133. break;
  1134. case 2:
  1135. switch ( scope.touches.TWO ) {
  1136. case three$1.TOUCH.DOLLY_PAN:
  1137. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  1138. handleTouchStartDollyPan( event );
  1139. state = STATE.TOUCH_DOLLY_PAN;
  1140. break;
  1141. case three$1.TOUCH.DOLLY_ROTATE:
  1142. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  1143. handleTouchStartDollyRotate( event );
  1144. state = STATE.TOUCH_DOLLY_ROTATE;
  1145. break;
  1146. default:
  1147. state = STATE.NONE;
  1148. }
  1149. break;
  1150. default:
  1151. state = STATE.NONE;
  1152. }
  1153. if ( state !== STATE.NONE ) {
  1154. scope.dispatchEvent( _startEvent );
  1155. }
  1156. }
  1157. function onTouchMove( event ) {
  1158. if ( scope.enabled === false ) return;
  1159. event.preventDefault(); // prevent scrolling
  1160. switch ( state ) {
  1161. case STATE.TOUCH_ROTATE:
  1162. if ( scope.enableRotate === false ) return;
  1163. handleTouchMoveRotate( event );
  1164. scope.update();
  1165. break;
  1166. case STATE.TOUCH_PAN:
  1167. if ( scope.enablePan === false ) return;
  1168. handleTouchMovePan( event );
  1169. scope.update();
  1170. break;
  1171. case STATE.TOUCH_DOLLY_PAN:
  1172. if ( scope.enableZoom === false && scope.enablePan === false ) return;
  1173. handleTouchMoveDollyPan( event );
  1174. scope.update();
  1175. break;
  1176. case STATE.TOUCH_DOLLY_ROTATE:
  1177. if ( scope.enableZoom === false && scope.enableRotate === false ) return;
  1178. handleTouchMoveDollyRotate( event );
  1179. scope.update();
  1180. break;
  1181. default:
  1182. state = STATE.NONE;
  1183. }
  1184. }
  1185. function onTouchEnd( event ) {
  1186. if ( scope.enabled === false ) return;
  1187. scope.dispatchEvent( _endEvent );
  1188. state = STATE.NONE;
  1189. }
  1190. function onContextMenu( event ) {
  1191. if ( scope.enabled === false ) return;
  1192. event.preventDefault();
  1193. }
  1194. //
  1195. scope.domElement.addEventListener( 'contextmenu', onContextMenu );
  1196. scope.domElement.addEventListener( 'pointerdown', onPointerDown );
  1197. scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
  1198. scope.domElement.addEventListener( 'touchstart', onTouchStart, { passive: false } );
  1199. scope.domElement.addEventListener( 'touchend', onTouchEnd );
  1200. scope.domElement.addEventListener( 'touchmove', onTouchMove, { passive: false } );
  1201. // force an update at start
  1202. this.update();
  1203. }
  1204. }
  1205. const _changeEvent = { type: 'change' };
  1206. class FlyControls extends three$1.EventDispatcher {
  1207. constructor( object, domElement ) {
  1208. super();
  1209. if ( domElement === undefined ) {
  1210. console.warn( 'THREE.FlyControls: The second parameter "domElement" is now mandatory.' );
  1211. domElement = document;
  1212. }
  1213. this.object = object;
  1214. this.domElement = domElement;
  1215. // API
  1216. this.movementSpeed = 1.0;
  1217. this.rollSpeed = 0.005;
  1218. this.dragToLook = false;
  1219. this.autoForward = false;
  1220. // disable default target object behavior
  1221. // internals
  1222. const scope = this;
  1223. const EPS = 0.000001;
  1224. const lastQuaternion = new three$1.Quaternion();
  1225. const lastPosition = new three$1.Vector3();
  1226. this.tmpQuaternion = new three$1.Quaternion();
  1227. this.mouseStatus = 0;
  1228. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  1229. this.moveVector = new three$1.Vector3( 0, 0, 0 );
  1230. this.rotationVector = new three$1.Vector3( 0, 0, 0 );
  1231. this.keydown = function ( event ) {
  1232. if ( event.altKey ) {
  1233. return;
  1234. }
  1235. //event.preventDefault();
  1236. switch ( event.code ) {
  1237. case 'ShiftLeft':
  1238. case 'ShiftRight': this.movementSpeedMultiplier = .1; break;
  1239. case 'KeyW': this.moveState.forward = 1; break;
  1240. case 'KeyS': this.moveState.back = 1; break;
  1241. case 'KeyA': this.moveState.left = 1; break;
  1242. case 'KeyD': this.moveState.right = 1; break;
  1243. case 'KeyR': this.moveState.up = 1; break;
  1244. case 'KeyF': this.moveState.down = 1; break;
  1245. case 'ArrowUp': this.moveState.pitchUp = 1; break;
  1246. case 'ArrowDown': this.moveState.pitchDown = 1; break;
  1247. case 'ArrowLeft': this.moveState.yawLeft = 1; break;
  1248. case 'ArrowRight': this.moveState.yawRight = 1; break;
  1249. case 'KeyQ': this.moveState.rollLeft = 1; break;
  1250. case 'KeyE': this.moveState.rollRight = 1; break;
  1251. }
  1252. this.updateMovementVector();
  1253. this.updateRotationVector();
  1254. };
  1255. this.keyup = function ( event ) {
  1256. switch ( event.code ) {
  1257. case 'ShiftLeft':
  1258. case 'ShiftRight': this.movementSpeedMultiplier = 1; break;
  1259. case 'KeyW': this.moveState.forward = 0; break;
  1260. case 'KeyS': this.moveState.back = 0; break;
  1261. case 'KeyA': this.moveState.left = 0; break;
  1262. case 'KeyD': this.moveState.right = 0; break;
  1263. case 'KeyR': this.moveState.up = 0; break;
  1264. case 'KeyF': this.moveState.down = 0; break;
  1265. case 'ArrowUp': this.moveState.pitchUp = 0; break;
  1266. case 'ArrowDown': this.moveState.pitchDown = 0; break;
  1267. case 'ArrowLeft': this.moveState.yawLeft = 0; break;
  1268. case 'ArrowRight': this.moveState.yawRight = 0; break;
  1269. case 'KeyQ': this.moveState.rollLeft = 0; break;
  1270. case 'KeyE': this.moveState.rollRight = 0; break;
  1271. }
  1272. this.updateMovementVector();
  1273. this.updateRotationVector();
  1274. };
  1275. this.mousedown = function ( event ) {
  1276. if ( this.domElement !== document ) {
  1277. this.domElement.focus();
  1278. }
  1279. event.preventDefault();
  1280. if ( this.dragToLook ) {
  1281. this.mouseStatus ++;
  1282. } else {
  1283. switch ( event.button ) {
  1284. case 0: this.moveState.forward = 1; break;
  1285. case 2: this.moveState.back = 1; break;
  1286. }
  1287. this.updateMovementVector();
  1288. }
  1289. };
  1290. this.mousemove = function ( event ) {
  1291. if ( ! this.dragToLook || this.mouseStatus > 0 ) {
  1292. const container = this.getContainerDimensions();
  1293. const halfWidth = container.size[ 0 ] / 2;
  1294. const halfHeight = container.size[ 1 ] / 2;
  1295. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  1296. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  1297. this.updateRotationVector();
  1298. }
  1299. };
  1300. this.mouseup = function ( event ) {
  1301. event.preventDefault();
  1302. if ( this.dragToLook ) {
  1303. this.mouseStatus --;
  1304. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  1305. } else {
  1306. switch ( event.button ) {
  1307. case 0: this.moveState.forward = 0; break;
  1308. case 2: this.moveState.back = 0; break;
  1309. }
  1310. this.updateMovementVector();
  1311. }
  1312. this.updateRotationVector();
  1313. };
  1314. this.update = function ( delta ) {
  1315. const moveMult = delta * scope.movementSpeed;
  1316. const rotMult = delta * scope.rollSpeed;
  1317. scope.object.translateX( scope.moveVector.x * moveMult );
  1318. scope.object.translateY( scope.moveVector.y * moveMult );
  1319. scope.object.translateZ( scope.moveVector.z * moveMult );
  1320. scope.tmpQuaternion.set( scope.rotationVector.x * rotMult, scope.rotationVector.y * rotMult, scope.rotationVector.z * rotMult, 1 ).normalize();
  1321. scope.object.quaternion.multiply( scope.tmpQuaternion );
  1322. if (
  1323. lastPosition.distanceToSquared( scope.object.position ) > EPS ||
  1324. 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS
  1325. ) {
  1326. scope.dispatchEvent( _changeEvent );
  1327. lastQuaternion.copy( scope.object.quaternion );
  1328. lastPosition.copy( scope.object.position );
  1329. }
  1330. };
  1331. this.updateMovementVector = function () {
  1332. const forward = ( this.moveState.forward || ( this.autoForward && ! this.moveState.back ) ) ? 1 : 0;
  1333. this.moveVector.x = ( - this.moveState.left + this.moveState.right );
  1334. this.moveVector.y = ( - this.moveState.down + this.moveState.up );
  1335. this.moveVector.z = ( - forward + this.moveState.back );
  1336. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  1337. };
  1338. this.updateRotationVector = function () {
  1339. this.rotationVector.x = ( - this.moveState.pitchDown + this.moveState.pitchUp );
  1340. this.rotationVector.y = ( - this.moveState.yawRight + this.moveState.yawLeft );
  1341. this.rotationVector.z = ( - this.moveState.rollRight + this.moveState.rollLeft );
  1342. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  1343. };
  1344. this.getContainerDimensions = function () {
  1345. if ( this.domElement != document ) {
  1346. return {
  1347. size: [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  1348. offset: [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  1349. };
  1350. } else {
  1351. return {
  1352. size: [ window.innerWidth, window.innerHeight ],
  1353. offset: [ 0, 0 ]
  1354. };
  1355. }
  1356. };
  1357. this.dispose = function () {
  1358. this.domElement.removeEventListener( 'contextmenu', contextmenu );
  1359. this.domElement.removeEventListener( 'mousedown', _mousedown );
  1360. this.domElement.removeEventListener( 'mousemove', _mousemove );
  1361. this.domElement.removeEventListener( 'mouseup', _mouseup );
  1362. window.removeEventListener( 'keydown', _keydown );
  1363. window.removeEventListener( 'keyup', _keyup );
  1364. };
  1365. const _mousemove = this.mousemove.bind( this );
  1366. const _mousedown = this.mousedown.bind( this );
  1367. const _mouseup = this.mouseup.bind( this );
  1368. const _keydown = this.keydown.bind( this );
  1369. const _keyup = this.keyup.bind( this );
  1370. this.domElement.addEventListener( 'contextmenu', contextmenu );
  1371. this.domElement.addEventListener( 'mousemove', _mousemove );
  1372. this.domElement.addEventListener( 'mousedown', _mousedown );
  1373. this.domElement.addEventListener( 'mouseup', _mouseup );
  1374. window.addEventListener( 'keydown', _keydown );
  1375. window.addEventListener( 'keyup', _keyup );
  1376. this.updateMovementVector();
  1377. this.updateRotationVector();
  1378. }
  1379. }
  1380. function contextmenu( event ) {
  1381. event.preventDefault();
  1382. }
  1383. /**
  1384. * Full-screen textured quad shader
  1385. */
  1386. var CopyShader = {
  1387. uniforms: {
  1388. 'tDiffuse': { value: null },
  1389. 'opacity': { value: 1.0 }
  1390. },
  1391. vertexShader: /* glsl */`
  1392. varying vec2 vUv;
  1393. void main() {
  1394. vUv = uv;
  1395. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  1396. }`,
  1397. fragmentShader: /* glsl */`
  1398. uniform float opacity;
  1399. uniform sampler2D tDiffuse;
  1400. varying vec2 vUv;
  1401. void main() {
  1402. vec4 texel = texture2D( tDiffuse, vUv );
  1403. gl_FragColor = opacity * texel;
  1404. }`
  1405. };
  1406. class Pass {
  1407. constructor() {
  1408. // if set to true, the pass is processed by the composer
  1409. this.enabled = true;
  1410. // if set to true, the pass indicates to swap read and write buffer after rendering
  1411. this.needsSwap = true;
  1412. // if set to true, the pass clears its buffer before rendering
  1413. this.clear = false;
  1414. // if set to true, the result of the pass is rendered to screen. This is set automatically by EffectComposer.
  1415. this.renderToScreen = false;
  1416. }
  1417. setSize( /* width, height */ ) {}
  1418. render( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  1419. console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
  1420. }
  1421. }
  1422. // Helper for passes that need to fill the viewport with a single quad.
  1423. const _camera = new three$1.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  1424. // https://github.com/mrdoob/three.js/pull/21358
  1425. const _geometry$1 = new three$1.BufferGeometry();
  1426. _geometry$1.setAttribute( 'position', new three$1.Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  1427. _geometry$1.setAttribute( 'uv', new three$1.Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  1428. class FullScreenQuad {
  1429. constructor( material ) {
  1430. this._mesh = new three$1.Mesh( _geometry$1, material );
  1431. }
  1432. dispose() {
  1433. this._mesh.geometry.dispose();
  1434. }
  1435. render( renderer ) {
  1436. renderer.render( this._mesh, _camera );
  1437. }
  1438. get material() {
  1439. return this._mesh.material;
  1440. }
  1441. set material( value ) {
  1442. this._mesh.material = value;
  1443. }
  1444. }
  1445. class ShaderPass extends Pass {
  1446. constructor( shader, textureID ) {
  1447. super();
  1448. this.textureID = ( textureID !== undefined ) ? textureID : 'tDiffuse';
  1449. if ( shader instanceof three$1.ShaderMaterial ) {
  1450. this.uniforms = shader.uniforms;
  1451. this.material = shader;
  1452. } else if ( shader ) {
  1453. this.uniforms = three$1.UniformsUtils.clone( shader.uniforms );
  1454. this.material = new three$1.ShaderMaterial( {
  1455. defines: Object.assign( {}, shader.defines ),
  1456. uniforms: this.uniforms,
  1457. vertexShader: shader.vertexShader,
  1458. fragmentShader: shader.fragmentShader
  1459. } );
  1460. }
  1461. this.fsQuad = new FullScreenQuad( this.material );
  1462. }
  1463. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  1464. if ( this.uniforms[ this.textureID ] ) {
  1465. this.uniforms[ this.textureID ].value = readBuffer.texture;
  1466. }
  1467. this.fsQuad.material = this.material;
  1468. if ( this.renderToScreen ) {
  1469. renderer.setRenderTarget( null );
  1470. this.fsQuad.render( renderer );
  1471. } else {
  1472. renderer.setRenderTarget( writeBuffer );
  1473. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  1474. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  1475. this.fsQuad.render( renderer );
  1476. }
  1477. }
  1478. }
  1479. class MaskPass extends Pass {
  1480. constructor( scene, camera ) {
  1481. super();
  1482. this.scene = scene;
  1483. this.camera = camera;
  1484. this.clear = true;
  1485. this.needsSwap = false;
  1486. this.inverse = false;
  1487. }
  1488. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  1489. const context = renderer.getContext();
  1490. const state = renderer.state;
  1491. // don't update color or depth
  1492. state.buffers.color.setMask( false );
  1493. state.buffers.depth.setMask( false );
  1494. // lock buffers
  1495. state.buffers.color.setLocked( true );
  1496. state.buffers.depth.setLocked( true );
  1497. // set up stencil
  1498. let writeValue, clearValue;
  1499. if ( this.inverse ) {
  1500. writeValue = 0;
  1501. clearValue = 1;
  1502. } else {
  1503. writeValue = 1;
  1504. clearValue = 0;
  1505. }
  1506. state.buffers.stencil.setTest( true );
  1507. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  1508. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  1509. state.buffers.stencil.setClear( clearValue );
  1510. state.buffers.stencil.setLocked( true );
  1511. // draw into the stencil buffer
  1512. renderer.setRenderTarget( readBuffer );
  1513. if ( this.clear ) renderer.clear();
  1514. renderer.render( this.scene, this.camera );
  1515. renderer.setRenderTarget( writeBuffer );
  1516. if ( this.clear ) renderer.clear();
  1517. renderer.render( this.scene, this.camera );
  1518. // unlock color and depth buffer for subsequent rendering
  1519. state.buffers.color.setLocked( false );
  1520. state.buffers.depth.setLocked( false );
  1521. // only render where stencil is set to 1
  1522. state.buffers.stencil.setLocked( false );
  1523. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  1524. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  1525. state.buffers.stencil.setLocked( true );
  1526. }
  1527. }
  1528. class ClearMaskPass extends Pass {
  1529. constructor() {
  1530. super();
  1531. this.needsSwap = false;
  1532. }
  1533. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  1534. renderer.state.buffers.stencil.setLocked( false );
  1535. renderer.state.buffers.stencil.setTest( false );
  1536. }
  1537. }
  1538. class EffectComposer {
  1539. constructor( renderer, renderTarget ) {
  1540. this.renderer = renderer;
  1541. if ( renderTarget === undefined ) {
  1542. const parameters = {
  1543. minFilter: three$1.LinearFilter,
  1544. magFilter: three$1.LinearFilter,
  1545. format: three$1.RGBAFormat
  1546. };
  1547. const size = renderer.getSize( new three$1.Vector2() );
  1548. this._pixelRatio = renderer.getPixelRatio();
  1549. this._width = size.width;
  1550. this._height = size.height;
  1551. renderTarget = new three$1.WebGLRenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, parameters );
  1552. renderTarget.texture.name = 'EffectComposer.rt1';
  1553. } else {
  1554. this._pixelRatio = 1;
  1555. this._width = renderTarget.width;
  1556. this._height = renderTarget.height;
  1557. }
  1558. this.renderTarget1 = renderTarget;
  1559. this.renderTarget2 = renderTarget.clone();
  1560. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  1561. this.writeBuffer = this.renderTarget1;
  1562. this.readBuffer = this.renderTarget2;
  1563. this.renderToScreen = true;
  1564. this.passes = [];
  1565. // dependencies
  1566. if ( CopyShader === undefined ) {
  1567. console.error( 'THREE.EffectComposer relies on CopyShader' );
  1568. }
  1569. if ( ShaderPass === undefined ) {
  1570. console.error( 'THREE.EffectComposer relies on ShaderPass' );
  1571. }
  1572. this.copyPass = new ShaderPass( CopyShader );
  1573. this.clock = new three$1.Clock();
  1574. }
  1575. swapBuffers() {
  1576. const tmp = this.readBuffer;
  1577. this.readBuffer = this.writeBuffer;
  1578. this.writeBuffer = tmp;
  1579. }
  1580. addPass( pass ) {
  1581. this.passes.push( pass );
  1582. pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
  1583. }
  1584. insertPass( pass, index ) {
  1585. this.passes.splice( index, 0, pass );
  1586. pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
  1587. }
  1588. removePass( pass ) {
  1589. const index = this.passes.indexOf( pass );
  1590. if ( index !== - 1 ) {
  1591. this.passes.splice( index, 1 );
  1592. }
  1593. }
  1594. isLastEnabledPass( passIndex ) {
  1595. for ( let i = passIndex + 1; i < this.passes.length; i ++ ) {
  1596. if ( this.passes[ i ].enabled ) {
  1597. return false;
  1598. }
  1599. }
  1600. return true;
  1601. }
  1602. render( deltaTime ) {
  1603. // deltaTime value is in seconds
  1604. if ( deltaTime === undefined ) {
  1605. deltaTime = this.clock.getDelta();
  1606. }
  1607. const currentRenderTarget = this.renderer.getRenderTarget();
  1608. let maskActive = false;
  1609. for ( let i = 0, il = this.passes.length; i < il; i ++ ) {
  1610. const pass = this.passes[ i ];
  1611. if ( pass.enabled === false ) continue;
  1612. pass.renderToScreen = ( this.renderToScreen && this.isLastEnabledPass( i ) );
  1613. pass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive );
  1614. if ( pass.needsSwap ) {
  1615. if ( maskActive ) {
  1616. const context = this.renderer.getContext();
  1617. const stencil = this.renderer.state.buffers.stencil;
  1618. //context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
  1619. stencil.setFunc( context.NOTEQUAL, 1, 0xffffffff );
  1620. this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime );
  1621. //context.stencilFunc( context.EQUAL, 1, 0xffffffff );
  1622. stencil.setFunc( context.EQUAL, 1, 0xffffffff );
  1623. }
  1624. this.swapBuffers();
  1625. }
  1626. if ( MaskPass !== undefined ) {
  1627. if ( pass instanceof MaskPass ) {
  1628. maskActive = true;
  1629. } else if ( pass instanceof ClearMaskPass ) {
  1630. maskActive = false;
  1631. }
  1632. }
  1633. }
  1634. this.renderer.setRenderTarget( currentRenderTarget );
  1635. }
  1636. reset( renderTarget ) {
  1637. if ( renderTarget === undefined ) {
  1638. const size = this.renderer.getSize( new three$1.Vector2() );
  1639. this._pixelRatio = this.renderer.getPixelRatio();
  1640. this._width = size.width;
  1641. this._height = size.height;
  1642. renderTarget = this.renderTarget1.clone();
  1643. renderTarget.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio );
  1644. }
  1645. this.renderTarget1.dispose();
  1646. this.renderTarget2.dispose();
  1647. this.renderTarget1 = renderTarget;
  1648. this.renderTarget2 = renderTarget.clone();
  1649. this.writeBuffer = this.renderTarget1;
  1650. this.readBuffer = this.renderTarget2;
  1651. }
  1652. setSize( width, height ) {
  1653. this._width = width;
  1654. this._height = height;
  1655. const effectiveWidth = this._width * this._pixelRatio;
  1656. const effectiveHeight = this._height * this._pixelRatio;
  1657. this.renderTarget1.setSize( effectiveWidth, effectiveHeight );
  1658. this.renderTarget2.setSize( effectiveWidth, effectiveHeight );
  1659. for ( let i = 0; i < this.passes.length; i ++ ) {
  1660. this.passes[ i ].setSize( effectiveWidth, effectiveHeight );
  1661. }
  1662. }
  1663. setPixelRatio( pixelRatio ) {
  1664. this._pixelRatio = pixelRatio;
  1665. this.setSize( this._width, this._height );
  1666. }
  1667. }
  1668. // Helper for passes that need to fill the viewport with a single quad.
  1669. new three$1.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  1670. // https://github.com/mrdoob/three.js/pull/21358
  1671. const _geometry = new three$1.BufferGeometry();
  1672. _geometry.setAttribute( 'position', new three$1.Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  1673. _geometry.setAttribute( 'uv', new three$1.Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  1674. class RenderPass extends Pass {
  1675. constructor( scene, camera, overrideMaterial, clearColor, clearAlpha ) {
  1676. super();
  1677. this.scene = scene;
  1678. this.camera = camera;
  1679. this.overrideMaterial = overrideMaterial;
  1680. this.clearColor = clearColor;
  1681. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  1682. this.clear = true;
  1683. this.clearDepth = false;
  1684. this.needsSwap = false;
  1685. this._oldClearColor = new three$1.Color();
  1686. }
  1687. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  1688. const oldAutoClear = renderer.autoClear;
  1689. renderer.autoClear = false;
  1690. let oldClearAlpha, oldOverrideMaterial;
  1691. if ( this.overrideMaterial !== undefined ) {
  1692. oldOverrideMaterial = this.scene.overrideMaterial;
  1693. this.scene.overrideMaterial = this.overrideMaterial;
  1694. }
  1695. if ( this.clearColor ) {
  1696. renderer.getClearColor( this._oldClearColor );
  1697. oldClearAlpha = renderer.getClearAlpha();
  1698. renderer.setClearColor( this.clearColor, this.clearAlpha );
  1699. }
  1700. if ( this.clearDepth ) {
  1701. renderer.clearDepth();
  1702. }
  1703. renderer.setRenderTarget( this.renderToScreen ? null : readBuffer );
  1704. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  1705. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  1706. renderer.render( this.scene, this.camera );
  1707. if ( this.clearColor ) {
  1708. renderer.setClearColor( this._oldClearColor, oldClearAlpha );
  1709. }
  1710. if ( this.overrideMaterial !== undefined ) {
  1711. this.scene.overrideMaterial = oldOverrideMaterial;
  1712. }
  1713. renderer.autoClear = oldAutoClear;
  1714. }
  1715. }
  1716. function _extends() {
  1717. _extends = Object.assign || function (target) {
  1718. for (var i = 1; i < arguments.length; i++) {
  1719. var source = arguments[i];
  1720. for (var key in source) {
  1721. if (Object.prototype.hasOwnProperty.call(source, key)) {
  1722. target[key] = source[key];
  1723. }
  1724. }
  1725. }
  1726. return target;
  1727. };
  1728. return _extends.apply(this, arguments);
  1729. }
  1730. function _assertThisInitialized(self) {
  1731. if (self === void 0) {
  1732. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  1733. }
  1734. return self;
  1735. }
  1736. function _setPrototypeOf(o, p) {
  1737. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  1738. o.__proto__ = p;
  1739. return o;
  1740. };
  1741. return _setPrototypeOf(o, p);
  1742. }
  1743. function _inheritsLoose(subClass, superClass) {
  1744. subClass.prototype = Object.create(superClass.prototype);
  1745. subClass.prototype.constructor = subClass;
  1746. _setPrototypeOf(subClass, superClass);
  1747. }
  1748. function _getPrototypeOf(o) {
  1749. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  1750. return o.__proto__ || Object.getPrototypeOf(o);
  1751. };
  1752. return _getPrototypeOf(o);
  1753. }
  1754. function _isNativeFunction(fn) {
  1755. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  1756. }
  1757. function _isNativeReflectConstruct() {
  1758. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  1759. if (Reflect.construct.sham) return false;
  1760. if (typeof Proxy === "function") return true;
  1761. try {
  1762. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  1763. return true;
  1764. } catch (e) {
  1765. return false;
  1766. }
  1767. }
  1768. function _construct(Parent, args, Class) {
  1769. if (_isNativeReflectConstruct()) {
  1770. _construct = Reflect.construct;
  1771. } else {
  1772. _construct = function _construct(Parent, args, Class) {
  1773. var a = [null];
  1774. a.push.apply(a, args);
  1775. var Constructor = Function.bind.apply(Parent, a);
  1776. var instance = new Constructor();
  1777. if (Class) _setPrototypeOf(instance, Class.prototype);
  1778. return instance;
  1779. };
  1780. }
  1781. return _construct.apply(null, arguments);
  1782. }
  1783. function _wrapNativeSuper(Class) {
  1784. var _cache = typeof Map === "function" ? new Map() : undefined;
  1785. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  1786. if (Class === null || !_isNativeFunction(Class)) return Class;
  1787. if (typeof Class !== "function") {
  1788. throw new TypeError("Super expression must either be null or a function");
  1789. }
  1790. if (typeof _cache !== "undefined") {
  1791. if (_cache.has(Class)) return _cache.get(Class);
  1792. _cache.set(Class, Wrapper);
  1793. }
  1794. function Wrapper() {
  1795. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  1796. }
  1797. Wrapper.prototype = Object.create(Class.prototype, {
  1798. constructor: {
  1799. value: Wrapper,
  1800. enumerable: false,
  1801. writable: true,
  1802. configurable: true
  1803. }
  1804. });
  1805. return _setPrototypeOf(Wrapper, Class);
  1806. };
  1807. return _wrapNativeSuper(Class);
  1808. }
  1809. // based on https://github.com/styled-components/styled-components/blob/fcf6f3804c57a14dd7984dfab7bc06ee2edca044/src/utils/error.js
  1810. /**
  1811. * Parse errors.md and turn it into a simple hash of code: message
  1812. * @private
  1813. */
  1814. var ERRORS = {
  1815. "1": "Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",
  1816. "2": "Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",
  1817. "3": "Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",
  1818. "4": "Couldn't generate valid rgb string from %s, it returned %s.\n\n",
  1819. "5": "Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",
  1820. "6": "Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",
  1821. "7": "Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",
  1822. "8": "Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",
  1823. "9": "Please provide a number of steps to the modularScale helper.\n\n",
  1824. "10": "Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",
  1825. "11": "Invalid value passed as base to modularScale, expected number or em string but got \"%s\"\n\n",
  1826. "12": "Expected a string ending in \"px\" or a number passed as the first argument to %s(), got \"%s\" instead.\n\n",
  1827. "13": "Expected a string ending in \"px\" or a number passed as the second argument to %s(), got \"%s\" instead.\n\n",
  1828. "14": "Passed invalid pixel value (\"%s\") to %s(), please pass a value like \"12px\" or 12.\n\n",
  1829. "15": "Passed invalid base value (\"%s\") to %s(), please pass a value like \"12px\" or 12.\n\n",
  1830. "16": "You must provide a template to this method.\n\n",
  1831. "17": "You passed an unsupported selector state to this method.\n\n",
  1832. "18": "minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",
  1833. "19": "fromSize and toSize must be provided as stringified numbers with the same units.\n\n",
  1834. "20": "expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",
  1835. "21": "expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",
  1836. "22": "expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",
  1837. "23": "fontFace expects a name of a font-family.\n\n",
  1838. "24": "fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",
  1839. "25": "fontFace expects localFonts to be an array.\n\n",
  1840. "26": "fontFace expects fileFormats to be an array.\n\n",
  1841. "27": "radialGradient requries at least 2 color-stops to properly render.\n\n",
  1842. "28": "Please supply a filename to retinaImage() as the first argument.\n\n",
  1843. "29": "Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",
  1844. "30": "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",
  1845. "31": "The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",
  1846. "32": "To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",
  1847. "33": "The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",
  1848. "34": "borderRadius expects a radius value as a string or number as the second argument.\n\n",
  1849. "35": "borderRadius expects one of \"top\", \"bottom\", \"left\" or \"right\" as the first argument.\n\n",
  1850. "36": "Property must be a string value.\n\n",
  1851. "37": "Syntax Error at %s.\n\n",
  1852. "38": "Formula contains a function that needs parentheses at %s.\n\n",
  1853. "39": "Formula is missing closing parenthesis at %s.\n\n",
  1854. "40": "Formula has too many closing parentheses at %s.\n\n",
  1855. "41": "All values in a formula must have the same unit or be unitless.\n\n",
  1856. "42": "Please provide a number of steps to the modularScale helper.\n\n",
  1857. "43": "Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",
  1858. "44": "Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",
  1859. "45": "Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",
  1860. "46": "Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",
  1861. "47": "minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",
  1862. "48": "fromSize and toSize must be provided as stringified numbers with the same units.\n\n",
  1863. "49": "Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",
  1864. "50": "Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",
  1865. "51": "Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",
  1866. "52": "fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",
  1867. "53": "fontFace expects localFonts to be an array.\n\n",
  1868. "54": "fontFace expects fileFormats to be an array.\n\n",
  1869. "55": "fontFace expects a name of a font-family.\n\n",
  1870. "56": "linearGradient requries at least 2 color-stops to properly render.\n\n",
  1871. "57": "radialGradient requries at least 2 color-stops to properly render.\n\n",
  1872. "58": "Please supply a filename to retinaImage() as the first argument.\n\n",
  1873. "59": "Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",
  1874. "60": "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",
  1875. "61": "Property must be a string value.\n\n",
  1876. "62": "borderRadius expects a radius value as a string or number as the second argument.\n\n",
  1877. "63": "borderRadius expects one of \"top\", \"bottom\", \"left\" or \"right\" as the first argument.\n\n",
  1878. "64": "The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",
  1879. "65": "To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",
  1880. "66": "The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",
  1881. "67": "You must provide a template to this method.\n\n",
  1882. "68": "You passed an unsupported selector state to this method.\n\n",
  1883. "69": "Expected a string ending in \"px\" or a number passed as the first argument to %s(), got %s instead.\n\n",
  1884. "70": "Expected a string ending in \"px\" or a number passed as the second argument to %s(), got %s instead.\n\n",
  1885. "71": "Passed invalid pixel value %s to %s(), please pass a value like \"12px\" or 12.\n\n",
  1886. "72": "Passed invalid base value %s to %s(), please pass a value like \"12px\" or 12.\n\n",
  1887. "73": "Please provide a valid CSS variable.\n\n",
  1888. "74": "CSS variable not found and no default was provided.\n\n",
  1889. "75": "important requires a valid style object, got a %s instead.\n\n",
  1890. "76": "fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",
  1891. "77": "remToPx expects a value in \"rem\" but you provided it in \"%s\".\n\n",
  1892. "78": "base must be set in \"px\" or \"%\" but you set it in \"%s\".\n"
  1893. };
  1894. /**
  1895. * super basic version of sprintf
  1896. * @private
  1897. */
  1898. function format() {
  1899. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  1900. args[_key] = arguments[_key];
  1901. }
  1902. var a = args[0];
  1903. var b = [];
  1904. var c;
  1905. for (c = 1; c < args.length; c += 1) {
  1906. b.push(args[c]);
  1907. }
  1908. b.forEach(function (d) {
  1909. a = a.replace(/%[a-z]/, d);
  1910. });
  1911. return a;
  1912. }
  1913. /**
  1914. * Create an error file out of errors.md for development and a simple web link to the full errors
  1915. * in production mode.
  1916. * @private
  1917. */
  1918. var PolishedError = /*#__PURE__*/function (_Error) {
  1919. _inheritsLoose(PolishedError, _Error);
  1920. function PolishedError(code) {
  1921. var _this;
  1922. if (process.env.NODE_ENV === 'production') {
  1923. _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#" + code + " for more information.") || this;
  1924. } else {
  1925. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  1926. args[_key2 - 1] = arguments[_key2];
  1927. }
  1928. _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(args))) || this;
  1929. }
  1930. return _assertThisInitialized(_this);
  1931. }
  1932. return PolishedError;
  1933. }( /*#__PURE__*/_wrapNativeSuper(Error));
  1934. function colorToInt(color) {
  1935. return Math.round(color * 255);
  1936. }
  1937. function convertToInt(red, green, blue) {
  1938. return colorToInt(red) + "," + colorToInt(green) + "," + colorToInt(blue);
  1939. }
  1940. function hslToRgb(hue, saturation, lightness, convert) {
  1941. if (convert === void 0) {
  1942. convert = convertToInt;
  1943. }
  1944. if (saturation === 0) {
  1945. // achromatic
  1946. return convert(lightness, lightness, lightness);
  1947. } // formulae from https://en.wikipedia.org/wiki/HSL_and_HSV
  1948. var huePrime = (hue % 360 + 360) % 360 / 60;
  1949. var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
  1950. var secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1));
  1951. var red = 0;
  1952. var green = 0;
  1953. var blue = 0;
  1954. if (huePrime >= 0 && huePrime < 1) {
  1955. red = chroma;
  1956. green = secondComponent;
  1957. } else if (huePrime >= 1 && huePrime < 2) {
  1958. red = secondComponent;
  1959. green = chroma;
  1960. } else if (huePrime >= 2 && huePrime < 3) {
  1961. green = chroma;
  1962. blue = secondComponent;
  1963. } else if (huePrime >= 3 && huePrime < 4) {
  1964. green = secondComponent;
  1965. blue = chroma;
  1966. } else if (huePrime >= 4 && huePrime < 5) {
  1967. red = secondComponent;
  1968. blue = chroma;
  1969. } else if (huePrime >= 5 && huePrime < 6) {
  1970. red = chroma;
  1971. blue = secondComponent;
  1972. }
  1973. var lightnessModification = lightness - chroma / 2;
  1974. var finalRed = red + lightnessModification;
  1975. var finalGreen = green + lightnessModification;
  1976. var finalBlue = blue + lightnessModification;
  1977. return convert(finalRed, finalGreen, finalBlue);
  1978. }
  1979. var namedColorMap = {
  1980. aliceblue: 'f0f8ff',
  1981. antiquewhite: 'faebd7',
  1982. aqua: '00ffff',
  1983. aquamarine: '7fffd4',
  1984. azure: 'f0ffff',
  1985. beige: 'f5f5dc',
  1986. bisque: 'ffe4c4',
  1987. black: '000',
  1988. blanchedalmond: 'ffebcd',
  1989. blue: '0000ff',
  1990. blueviolet: '8a2be2',
  1991. brown: 'a52a2a',
  1992. burlywood: 'deb887',
  1993. cadetblue: '5f9ea0',
  1994. chartreuse: '7fff00',
  1995. chocolate: 'd2691e',
  1996. coral: 'ff7f50',
  1997. cornflowerblue: '6495ed',
  1998. cornsilk: 'fff8dc',
  1999. crimson: 'dc143c',
  2000. cyan: '00ffff',
  2001. darkblue: '00008b',
  2002. darkcyan: '008b8b',
  2003. darkgoldenrod: 'b8860b',
  2004. darkgray: 'a9a9a9',
  2005. darkgreen: '006400',
  2006. darkgrey: 'a9a9a9',
  2007. darkkhaki: 'bdb76b',
  2008. darkmagenta: '8b008b',
  2009. darkolivegreen: '556b2f',
  2010. darkorange: 'ff8c00',
  2011. darkorchid: '9932cc',
  2012. darkred: '8b0000',
  2013. darksalmon: 'e9967a',
  2014. darkseagreen: '8fbc8f',
  2015. darkslateblue: '483d8b',
  2016. darkslategray: '2f4f4f',
  2017. darkslategrey: '2f4f4f',
  2018. darkturquoise: '00ced1',
  2019. darkviolet: '9400d3',
  2020. deeppink: 'ff1493',
  2021. deepskyblue: '00bfff',
  2022. dimgray: '696969',
  2023. dimgrey: '696969',
  2024. dodgerblue: '1e90ff',
  2025. firebrick: 'b22222',
  2026. floralwhite: 'fffaf0',
  2027. forestgreen: '228b22',
  2028. fuchsia: 'ff00ff',
  2029. gainsboro: 'dcdcdc',
  2030. ghostwhite: 'f8f8ff',
  2031. gold: 'ffd700',
  2032. goldenrod: 'daa520',
  2033. gray: '808080',
  2034. green: '008000',
  2035. greenyellow: 'adff2f',
  2036. grey: '808080',
  2037. honeydew: 'f0fff0',
  2038. hotpink: 'ff69b4',
  2039. indianred: 'cd5c5c',
  2040. indigo: '4b0082',
  2041. ivory: 'fffff0',
  2042. khaki: 'f0e68c',
  2043. lavender: 'e6e6fa',
  2044. lavenderblush: 'fff0f5',
  2045. lawngreen: '7cfc00',
  2046. lemonchiffon: 'fffacd',
  2047. lightblue: 'add8e6',
  2048. lightcoral: 'f08080',
  2049. lightcyan: 'e0ffff',
  2050. lightgoldenrodyellow: 'fafad2',
  2051. lightgray: 'd3d3d3',
  2052. lightgreen: '90ee90',
  2053. lightgrey: 'd3d3d3',
  2054. lightpink: 'ffb6c1',
  2055. lightsalmon: 'ffa07a',
  2056. lightseagreen: '20b2aa',
  2057. lightskyblue: '87cefa',
  2058. lightslategray: '789',
  2059. lightslategrey: '789',
  2060. lightsteelblue: 'b0c4de',
  2061. lightyellow: 'ffffe0',
  2062. lime: '0f0',
  2063. limegreen: '32cd32',
  2064. linen: 'faf0e6',
  2065. magenta: 'f0f',
  2066. maroon: '800000',
  2067. mediumaquamarine: '66cdaa',
  2068. mediumblue: '0000cd',
  2069. mediumorchid: 'ba55d3',
  2070. mediumpurple: '9370db',
  2071. mediumseagreen: '3cb371',
  2072. mediumslateblue: '7b68ee',
  2073. mediumspringgreen: '00fa9a',
  2074. mediumturquoise: '48d1cc',
  2075. mediumvioletred: 'c71585',
  2076. midnightblue: '191970',
  2077. mintcream: 'f5fffa',
  2078. mistyrose: 'ffe4e1',
  2079. moccasin: 'ffe4b5',
  2080. navajowhite: 'ffdead',
  2081. navy: '000080',
  2082. oldlace: 'fdf5e6',
  2083. olive: '808000',
  2084. olivedrab: '6b8e23',
  2085. orange: 'ffa500',
  2086. orangered: 'ff4500',
  2087. orchid: 'da70d6',
  2088. palegoldenrod: 'eee8aa',
  2089. palegreen: '98fb98',
  2090. paleturquoise: 'afeeee',
  2091. palevioletred: 'db7093',
  2092. papayawhip: 'ffefd5',
  2093. peachpuff: 'ffdab9',
  2094. peru: 'cd853f',
  2095. pink: 'ffc0cb',
  2096. plum: 'dda0dd',
  2097. powderblue: 'b0e0e6',
  2098. purple: '800080',
  2099. rebeccapurple: '639',
  2100. red: 'f00',
  2101. rosybrown: 'bc8f8f',
  2102. royalblue: '4169e1',
  2103. saddlebrown: '8b4513',
  2104. salmon: 'fa8072',
  2105. sandybrown: 'f4a460',
  2106. seagreen: '2e8b57',
  2107. seashell: 'fff5ee',
  2108. sienna: 'a0522d',
  2109. silver: 'c0c0c0',
  2110. skyblue: '87ceeb',
  2111. slateblue: '6a5acd',
  2112. slategray: '708090',
  2113. slategrey: '708090',
  2114. snow: 'fffafa',
  2115. springgreen: '00ff7f',
  2116. steelblue: '4682b4',
  2117. tan: 'd2b48c',
  2118. teal: '008080',
  2119. thistle: 'd8bfd8',
  2120. tomato: 'ff6347',
  2121. turquoise: '40e0d0',
  2122. violet: 'ee82ee',
  2123. wheat: 'f5deb3',
  2124. white: 'fff',
  2125. whitesmoke: 'f5f5f5',
  2126. yellow: 'ff0',
  2127. yellowgreen: '9acd32'
  2128. };
  2129. /**
  2130. * Checks if a string is a CSS named color and returns its equivalent hex value, otherwise returns the original color.
  2131. * @private
  2132. */
  2133. function nameToHex(color) {
  2134. if (typeof color !== 'string') return color;
  2135. var normalizedColorName = color.toLowerCase();
  2136. return namedColorMap[normalizedColorName] ? "#" + namedColorMap[normalizedColorName] : color;
  2137. }
  2138. var hexRegex = /^#[a-fA-F0-9]{6}$/;
  2139. var hexRgbaRegex = /^#[a-fA-F0-9]{8}$/;
  2140. var reducedHexRegex = /^#[a-fA-F0-9]{3}$/;
  2141. var reducedRgbaHexRegex = /^#[a-fA-F0-9]{4}$/;
  2142. var rgbRegex = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i;
  2143. var rgbaRegex = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i;
  2144. var hslRegex = /^hsl\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i;
  2145. var hslaRegex = /^hsla\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i;
  2146. /**
  2147. * Returns an RgbColor or RgbaColor object. This utility function is only useful
  2148. * if want to extract a color component. With the color util `toColorString` you
  2149. * can convert a RgbColor or RgbaColor object back to a string.
  2150. *
  2151. * @example
  2152. * // Assigns `{ red: 255, green: 0, blue: 0 }` to color1
  2153. * const color1 = parseToRgb('rgb(255, 0, 0)');
  2154. * // Assigns `{ red: 92, green: 102, blue: 112, alpha: 0.75 }` to color2
  2155. * const color2 = parseToRgb('hsla(210, 10%, 40%, 0.75)');
  2156. */
  2157. function parseToRgb(color) {
  2158. if (typeof color !== 'string') {
  2159. throw new PolishedError(3);
  2160. }
  2161. var normalizedColor = nameToHex(color);
  2162. if (normalizedColor.match(hexRegex)) {
  2163. return {
  2164. red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16),
  2165. green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16),
  2166. blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16)
  2167. };
  2168. }
  2169. if (normalizedColor.match(hexRgbaRegex)) {
  2170. var alpha = parseFloat((parseInt("" + normalizedColor[7] + normalizedColor[8], 16) / 255).toFixed(2));
  2171. return {
  2172. red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16),
  2173. green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16),
  2174. blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16),
  2175. alpha: alpha
  2176. };
  2177. }
  2178. if (normalizedColor.match(reducedHexRegex)) {
  2179. return {
  2180. red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16),
  2181. green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16),
  2182. blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16)
  2183. };
  2184. }
  2185. if (normalizedColor.match(reducedRgbaHexRegex)) {
  2186. var _alpha = parseFloat((parseInt("" + normalizedColor[4] + normalizedColor[4], 16) / 255).toFixed(2));
  2187. return {
  2188. red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16),
  2189. green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16),
  2190. blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16),
  2191. alpha: _alpha
  2192. };
  2193. }
  2194. var rgbMatched = rgbRegex.exec(normalizedColor);
  2195. if (rgbMatched) {
  2196. return {
  2197. red: parseInt("" + rgbMatched[1], 10),
  2198. green: parseInt("" + rgbMatched[2], 10),
  2199. blue: parseInt("" + rgbMatched[3], 10)
  2200. };
  2201. }
  2202. var rgbaMatched = rgbaRegex.exec(normalizedColor.substring(0, 50));
  2203. if (rgbaMatched) {
  2204. return {
  2205. red: parseInt("" + rgbaMatched[1], 10),
  2206. green: parseInt("" + rgbaMatched[2], 10),
  2207. blue: parseInt("" + rgbaMatched[3], 10),
  2208. alpha: parseFloat("" + rgbaMatched[4])
  2209. };
  2210. }
  2211. var hslMatched = hslRegex.exec(normalizedColor);
  2212. if (hslMatched) {
  2213. var hue = parseInt("" + hslMatched[1], 10);
  2214. var saturation = parseInt("" + hslMatched[2], 10) / 100;
  2215. var lightness = parseInt("" + hslMatched[3], 10) / 100;
  2216. var rgbColorString = "rgb(" + hslToRgb(hue, saturation, lightness) + ")";
  2217. var hslRgbMatched = rgbRegex.exec(rgbColorString);
  2218. if (!hslRgbMatched) {
  2219. throw new PolishedError(4, normalizedColor, rgbColorString);
  2220. }
  2221. return {
  2222. red: parseInt("" + hslRgbMatched[1], 10),
  2223. green: parseInt("" + hslRgbMatched[2], 10),
  2224. blue: parseInt("" + hslRgbMatched[3], 10)
  2225. };
  2226. }
  2227. var hslaMatched = hslaRegex.exec(normalizedColor.substring(0, 50));
  2228. if (hslaMatched) {
  2229. var _hue = parseInt("" + hslaMatched[1], 10);
  2230. var _saturation = parseInt("" + hslaMatched[2], 10) / 100;
  2231. var _lightness = parseInt("" + hslaMatched[3], 10) / 100;
  2232. var _rgbColorString = "rgb(" + hslToRgb(_hue, _saturation, _lightness) + ")";
  2233. var _hslRgbMatched = rgbRegex.exec(_rgbColorString);
  2234. if (!_hslRgbMatched) {
  2235. throw new PolishedError(4, normalizedColor, _rgbColorString);
  2236. }
  2237. return {
  2238. red: parseInt("" + _hslRgbMatched[1], 10),
  2239. green: parseInt("" + _hslRgbMatched[2], 10),
  2240. blue: parseInt("" + _hslRgbMatched[3], 10),
  2241. alpha: parseFloat("" + hslaMatched[4])
  2242. };
  2243. }
  2244. throw new PolishedError(5);
  2245. }
  2246. /**
  2247. * Reduces hex values if possible e.g. #ff8866 to #f86
  2248. * @private
  2249. */
  2250. var reduceHexValue = function reduceHexValue(value) {
  2251. if (value.length === 7 && value[1] === value[2] && value[3] === value[4] && value[5] === value[6]) {
  2252. return "#" + value[1] + value[3] + value[5];
  2253. }
  2254. return value;
  2255. };
  2256. function numberToHex(value) {
  2257. var hex = value.toString(16);
  2258. return hex.length === 1 ? "0" + hex : hex;
  2259. }
  2260. /**
  2261. * Returns a string value for the color. The returned result is the smallest possible hex notation.
  2262. *
  2263. * @example
  2264. * // Styles as object usage
  2265. * const styles = {
  2266. * background: rgb(255, 205, 100),
  2267. * background: rgb({ red: 255, green: 205, blue: 100 }),
  2268. * }
  2269. *
  2270. * // styled-components usage
  2271. * const div = styled.div`
  2272. * background: ${rgb(255, 205, 100)};
  2273. * background: ${rgb({ red: 255, green: 205, blue: 100 })};
  2274. * `
  2275. *
  2276. * // CSS in JS Output
  2277. *
  2278. * element {
  2279. * background: "#ffcd64";
  2280. * background: "#ffcd64";
  2281. * }
  2282. */
  2283. function rgb(value, green, blue) {
  2284. if (typeof value === 'number' && typeof green === 'number' && typeof blue === 'number') {
  2285. return reduceHexValue("#" + numberToHex(value) + numberToHex(green) + numberToHex(blue));
  2286. } else if (typeof value === 'object' && green === undefined && blue === undefined) {
  2287. return reduceHexValue("#" + numberToHex(value.red) + numberToHex(value.green) + numberToHex(value.blue));
  2288. }
  2289. throw new PolishedError(6);
  2290. }
  2291. /**
  2292. * Returns a string value for the color. The returned result is the smallest possible rgba or hex notation.
  2293. *
  2294. * Can also be used to fade a color by passing a hex value or named CSS color along with an alpha value.
  2295. *
  2296. * @example
  2297. * // Styles as object usage
  2298. * const styles = {
  2299. * background: rgba(255, 205, 100, 0.7),
  2300. * background: rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 }),
  2301. * background: rgba(255, 205, 100, 1),
  2302. * background: rgba('#ffffff', 0.4),
  2303. * background: rgba('black', 0.7),
  2304. * }
  2305. *
  2306. * // styled-components usage
  2307. * const div = styled.div`
  2308. * background: ${rgba(255, 205, 100, 0.7)};
  2309. * background: ${rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 })};
  2310. * background: ${rgba(255, 205, 100, 1)};
  2311. * background: ${rgba('#ffffff', 0.4)};
  2312. * background: ${rgba('black', 0.7)};
  2313. * `
  2314. *
  2315. * // CSS in JS Output
  2316. *
  2317. * element {
  2318. * background: "rgba(255,205,100,0.7)";
  2319. * background: "rgba(255,205,100,0.7)";
  2320. * background: "#ffcd64";
  2321. * background: "rgba(255,255,255,0.4)";
  2322. * background: "rgba(0,0,0,0.7)";
  2323. * }
  2324. */
  2325. function rgba(firstValue, secondValue, thirdValue, fourthValue) {
  2326. if (typeof firstValue === 'string' && typeof secondValue === 'number') {
  2327. var rgbValue = parseToRgb(firstValue);
  2328. return "rgba(" + rgbValue.red + "," + rgbValue.green + "," + rgbValue.blue + "," + secondValue + ")";
  2329. } else if (typeof firstValue === 'number' && typeof secondValue === 'number' && typeof thirdValue === 'number' && typeof fourthValue === 'number') {
  2330. return fourthValue >= 1 ? rgb(firstValue, secondValue, thirdValue) : "rgba(" + firstValue + "," + secondValue + "," + thirdValue + "," + fourthValue + ")";
  2331. } else if (typeof firstValue === 'object' && secondValue === undefined && thirdValue === undefined && fourthValue === undefined) {
  2332. return firstValue.alpha >= 1 ? rgb(firstValue.red, firstValue.green, firstValue.blue) : "rgba(" + firstValue.red + "," + firstValue.green + "," + firstValue.blue + "," + firstValue.alpha + ")";
  2333. }
  2334. throw new PolishedError(7);
  2335. }
  2336. // Type definitions taken from https://github.com/gcanti/flow-static-land/blob/master/src/Fun.js
  2337. // eslint-disable-next-line no-unused-vars
  2338. // eslint-disable-next-line no-unused-vars
  2339. // eslint-disable-next-line no-redeclare
  2340. function curried(f, length, acc) {
  2341. return function fn() {
  2342. // eslint-disable-next-line prefer-rest-params
  2343. var combined = acc.concat(Array.prototype.slice.call(arguments));
  2344. return combined.length >= length ? f.apply(this, combined) : curried(f, length, combined);
  2345. };
  2346. } // eslint-disable-next-line no-redeclare
  2347. function curry(f) {
  2348. // eslint-disable-line no-redeclare
  2349. return curried(f, f.length, []);
  2350. }
  2351. function guard(lowerBoundary, upperBoundary, value) {
  2352. return Math.max(lowerBoundary, Math.min(upperBoundary, value));
  2353. }
  2354. /**
  2355. * Increases the opacity of a color. Its range for the amount is between 0 to 1.
  2356. *
  2357. *
  2358. * @example
  2359. * // Styles as object usage
  2360. * const styles = {
  2361. * background: opacify(0.1, 'rgba(255, 255, 255, 0.9)');
  2362. * background: opacify(0.2, 'hsla(0, 0%, 100%, 0.5)'),
  2363. * background: opacify('0.5', 'rgba(255, 0, 0, 0.2)'),
  2364. * }
  2365. *
  2366. * // styled-components usage
  2367. * const div = styled.div`
  2368. * background: ${opacify(0.1, 'rgba(255, 255, 255, 0.9)')};
  2369. * background: ${opacify(0.2, 'hsla(0, 0%, 100%, 0.5)')},
  2370. * background: ${opacify('0.5', 'rgba(255, 0, 0, 0.2)')},
  2371. * `
  2372. *
  2373. * // CSS in JS Output
  2374. *
  2375. * element {
  2376. * background: "#fff";
  2377. * background: "rgba(255,255,255,0.7)";
  2378. * background: "rgba(255,0,0,0.7)";
  2379. * }
  2380. */
  2381. function opacify(amount, color) {
  2382. if (color === 'transparent') return color;
  2383. var parsedColor = parseToRgb(color);
  2384. var alpha = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1;
  2385. var colorWithAlpha = _extends({}, parsedColor, {
  2386. alpha: guard(0, 1, (alpha * 100 + parseFloat(amount) * 100) / 100)
  2387. });
  2388. return rgba(colorWithAlpha);
  2389. } // prettier-ignore
  2390. var curriedOpacify = /*#__PURE__*/curry
  2391. /* ::<number | string, string, string> */
  2392. (opacify);
  2393. /**
  2394. * The Ease class provides a collection of easing functions for use with tween.js.
  2395. */
  2396. var Easing = {
  2397. Linear: {
  2398. None: function (amount) {
  2399. return amount;
  2400. },
  2401. },
  2402. Quadratic: {
  2403. In: function (amount) {
  2404. return amount * amount;
  2405. },
  2406. Out: function (amount) {
  2407. return amount * (2 - amount);
  2408. },
  2409. InOut: function (amount) {
  2410. if ((amount *= 2) < 1) {
  2411. return 0.5 * amount * amount;
  2412. }
  2413. return -0.5 * (--amount * (amount - 2) - 1);
  2414. },
  2415. },
  2416. Cubic: {
  2417. In: function (amount) {
  2418. return amount * amount * amount;
  2419. },
  2420. Out: function (amount) {
  2421. return --amount * amount * amount + 1;
  2422. },
  2423. InOut: function (amount) {
  2424. if ((amount *= 2) < 1) {
  2425. return 0.5 * amount * amount * amount;
  2426. }
  2427. return 0.5 * ((amount -= 2) * amount * amount + 2);
  2428. },
  2429. },
  2430. Quartic: {
  2431. In: function (amount) {
  2432. return amount * amount * amount * amount;
  2433. },
  2434. Out: function (amount) {
  2435. return 1 - --amount * amount * amount * amount;
  2436. },
  2437. InOut: function (amount) {
  2438. if ((amount *= 2) < 1) {
  2439. return 0.5 * amount * amount * amount * amount;
  2440. }
  2441. return -0.5 * ((amount -= 2) * amount * amount * amount - 2);
  2442. },
  2443. },
  2444. Quintic: {
  2445. In: function (amount) {
  2446. return amount * amount * amount * amount * amount;
  2447. },
  2448. Out: function (amount) {
  2449. return --amount * amount * amount * amount * amount + 1;
  2450. },
  2451. InOut: function (amount) {
  2452. if ((amount *= 2) < 1) {
  2453. return 0.5 * amount * amount * amount * amount * amount;
  2454. }
  2455. return 0.5 * ((amount -= 2) * amount * amount * amount * amount + 2);
  2456. },
  2457. },
  2458. Sinusoidal: {
  2459. In: function (amount) {
  2460. return 1 - Math.cos((amount * Math.PI) / 2);
  2461. },
  2462. Out: function (amount) {
  2463. return Math.sin((amount * Math.PI) / 2);
  2464. },
  2465. InOut: function (amount) {
  2466. return 0.5 * (1 - Math.cos(Math.PI * amount));
  2467. },
  2468. },
  2469. Exponential: {
  2470. In: function (amount) {
  2471. return amount === 0 ? 0 : Math.pow(1024, amount - 1);
  2472. },
  2473. Out: function (amount) {
  2474. return amount === 1 ? 1 : 1 - Math.pow(2, -10 * amount);
  2475. },
  2476. InOut: function (amount) {
  2477. if (amount === 0) {
  2478. return 0;
  2479. }
  2480. if (amount === 1) {
  2481. return 1;
  2482. }
  2483. if ((amount *= 2) < 1) {
  2484. return 0.5 * Math.pow(1024, amount - 1);
  2485. }
  2486. return 0.5 * (-Math.pow(2, -10 * (amount - 1)) + 2);
  2487. },
  2488. },
  2489. Circular: {
  2490. In: function (amount) {
  2491. return 1 - Math.sqrt(1 - amount * amount);
  2492. },
  2493. Out: function (amount) {
  2494. return Math.sqrt(1 - --amount * amount);
  2495. },
  2496. InOut: function (amount) {
  2497. if ((amount *= 2) < 1) {
  2498. return -0.5 * (Math.sqrt(1 - amount * amount) - 1);
  2499. }
  2500. return 0.5 * (Math.sqrt(1 - (amount -= 2) * amount) + 1);
  2501. },
  2502. },
  2503. Elastic: {
  2504. In: function (amount) {
  2505. if (amount === 0) {
  2506. return 0;
  2507. }
  2508. if (amount === 1) {
  2509. return 1;
  2510. }
  2511. return -Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI);
  2512. },
  2513. Out: function (amount) {
  2514. if (amount === 0) {
  2515. return 0;
  2516. }
  2517. if (amount === 1) {
  2518. return 1;
  2519. }
  2520. return Math.pow(2, -10 * amount) * Math.sin((amount - 0.1) * 5 * Math.PI) + 1;
  2521. },
  2522. InOut: function (amount) {
  2523. if (amount === 0) {
  2524. return 0;
  2525. }
  2526. if (amount === 1) {
  2527. return 1;
  2528. }
  2529. amount *= 2;
  2530. if (amount < 1) {
  2531. return -0.5 * Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI);
  2532. }
  2533. return 0.5 * Math.pow(2, -10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI) + 1;
  2534. },
  2535. },
  2536. Back: {
  2537. In: function (amount) {
  2538. var s = 1.70158;
  2539. return amount * amount * ((s + 1) * amount - s);
  2540. },
  2541. Out: function (amount) {
  2542. var s = 1.70158;
  2543. return --amount * amount * ((s + 1) * amount + s) + 1;
  2544. },
  2545. InOut: function (amount) {
  2546. var s = 1.70158 * 1.525;
  2547. if ((amount *= 2) < 1) {
  2548. return 0.5 * (amount * amount * ((s + 1) * amount - s));
  2549. }
  2550. return 0.5 * ((amount -= 2) * amount * ((s + 1) * amount + s) + 2);
  2551. },
  2552. },
  2553. Bounce: {
  2554. In: function (amount) {
  2555. return 1 - Easing.Bounce.Out(1 - amount);
  2556. },
  2557. Out: function (amount) {
  2558. if (amount < 1 / 2.75) {
  2559. return 7.5625 * amount * amount;
  2560. }
  2561. else if (amount < 2 / 2.75) {
  2562. return 7.5625 * (amount -= 1.5 / 2.75) * amount + 0.75;
  2563. }
  2564. else if (amount < 2.5 / 2.75) {
  2565. return 7.5625 * (amount -= 2.25 / 2.75) * amount + 0.9375;
  2566. }
  2567. else {
  2568. return 7.5625 * (amount -= 2.625 / 2.75) * amount + 0.984375;
  2569. }
  2570. },
  2571. InOut: function (amount) {
  2572. if (amount < 0.5) {
  2573. return Easing.Bounce.In(amount * 2) * 0.5;
  2574. }
  2575. return Easing.Bounce.Out(amount * 2 - 1) * 0.5 + 0.5;
  2576. },
  2577. },
  2578. };
  2579. var now;
  2580. // Include a performance.now polyfill.
  2581. // In node.js, use process.hrtime.
  2582. // eslint-disable-next-line
  2583. // @ts-ignore
  2584. if (typeof self === 'undefined' && typeof process !== 'undefined' && process.hrtime) {
  2585. now = function () {
  2586. // eslint-disable-next-line
  2587. // @ts-ignore
  2588. var time = process.hrtime();
  2589. // Convert [seconds, nanoseconds] to milliseconds.
  2590. return time[0] * 1000 + time[1] / 1000000;
  2591. };
  2592. }
  2593. // In a browser, use self.performance.now if it is available.
  2594. else if (typeof self !== 'undefined' && self.performance !== undefined && self.performance.now !== undefined) {
  2595. // This must be bound, because directly assigning this function
  2596. // leads to an invocation exception in Chrome.
  2597. now = self.performance.now.bind(self.performance);
  2598. }
  2599. // Use Date.now if it is available.
  2600. else if (Date.now !== undefined) {
  2601. now = Date.now;
  2602. }
  2603. // Otherwise, use 'new Date().getTime()'.
  2604. else {
  2605. now = function () {
  2606. return new Date().getTime();
  2607. };
  2608. }
  2609. var now$1 = now;
  2610. /**
  2611. * Controlling groups of tweens
  2612. *
  2613. * Using the TWEEN singleton to manage your tweens can cause issues in large apps with many components.
  2614. * In these cases, you may want to create your own smaller groups of tween
  2615. */
  2616. var Group = /** @class */ (function () {
  2617. function Group() {
  2618. this._tweens = {};
  2619. this._tweensAddedDuringUpdate = {};
  2620. }
  2621. Group.prototype.getAll = function () {
  2622. var _this = this;
  2623. return Object.keys(this._tweens).map(function (tweenId) {
  2624. return _this._tweens[tweenId];
  2625. });
  2626. };
  2627. Group.prototype.removeAll = function () {
  2628. this._tweens = {};
  2629. };
  2630. Group.prototype.add = function (tween) {
  2631. this._tweens[tween.getId()] = tween;
  2632. this._tweensAddedDuringUpdate[tween.getId()] = tween;
  2633. };
  2634. Group.prototype.remove = function (tween) {
  2635. delete this._tweens[tween.getId()];
  2636. delete this._tweensAddedDuringUpdate[tween.getId()];
  2637. };
  2638. Group.prototype.update = function (time, preserve) {
  2639. if (time === void 0) { time = now$1(); }
  2640. if (preserve === void 0) { preserve = false; }
  2641. var tweenIds = Object.keys(this._tweens);
  2642. if (tweenIds.length === 0) {
  2643. return false;
  2644. }
  2645. // Tweens are updated in "batches". If you add a new tween during an
  2646. // update, then the new tween will be updated in the next batch.
  2647. // If you remove a tween during an update, it may or may not be updated.
  2648. // However, if the removed tween was added during the current batch,
  2649. // then it will not be updated.
  2650. while (tweenIds.length > 0) {
  2651. this._tweensAddedDuringUpdate = {};
  2652. for (var i = 0; i < tweenIds.length; i++) {
  2653. var tween = this._tweens[tweenIds[i]];
  2654. var autoStart = !preserve;
  2655. if (tween && tween.update(time, autoStart) === false && !preserve) {
  2656. delete this._tweens[tweenIds[i]];
  2657. }
  2658. }
  2659. tweenIds = Object.keys(this._tweensAddedDuringUpdate);
  2660. }
  2661. return true;
  2662. };
  2663. return Group;
  2664. }());
  2665. /**
  2666. *
  2667. */
  2668. var Interpolation = {
  2669. Linear: function (v, k) {
  2670. var m = v.length - 1;
  2671. var f = m * k;
  2672. var i = Math.floor(f);
  2673. var fn = Interpolation.Utils.Linear;
  2674. if (k < 0) {
  2675. return fn(v[0], v[1], f);
  2676. }
  2677. if (k > 1) {
  2678. return fn(v[m], v[m - 1], m - f);
  2679. }
  2680. return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
  2681. },
  2682. Bezier: function (v, k) {
  2683. var b = 0;
  2684. var n = v.length - 1;
  2685. var pw = Math.pow;
  2686. var bn = Interpolation.Utils.Bernstein;
  2687. for (var i = 0; i <= n; i++) {
  2688. b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  2689. }
  2690. return b;
  2691. },
  2692. CatmullRom: function (v, k) {
  2693. var m = v.length - 1;
  2694. var f = m * k;
  2695. var i = Math.floor(f);
  2696. var fn = Interpolation.Utils.CatmullRom;
  2697. if (v[0] === v[m]) {
  2698. if (k < 0) {
  2699. i = Math.floor((f = m * (1 + k)));
  2700. }
  2701. return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  2702. }
  2703. else {
  2704. if (k < 0) {
  2705. return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  2706. }
  2707. if (k > 1) {
  2708. return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  2709. }
  2710. return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  2711. }
  2712. },
  2713. Utils: {
  2714. Linear: function (p0, p1, t) {
  2715. return (p1 - p0) * t + p0;
  2716. },
  2717. Bernstein: function (n, i) {
  2718. var fc = Interpolation.Utils.Factorial;
  2719. return fc(n) / fc(i) / fc(n - i);
  2720. },
  2721. Factorial: (function () {
  2722. var a = [1];
  2723. return function (n) {
  2724. var s = 1;
  2725. if (a[n]) {
  2726. return a[n];
  2727. }
  2728. for (var i = n; i > 1; i--) {
  2729. s *= i;
  2730. }
  2731. a[n] = s;
  2732. return s;
  2733. };
  2734. })(),
  2735. CatmullRom: function (p0, p1, p2, p3, t) {
  2736. var v0 = (p2 - p0) * 0.5;
  2737. var v1 = (p3 - p1) * 0.5;
  2738. var t2 = t * t;
  2739. var t3 = t * t2;
  2740. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  2741. },
  2742. },
  2743. };
  2744. /**
  2745. * Utils
  2746. */
  2747. var Sequence = /** @class */ (function () {
  2748. function Sequence() {
  2749. }
  2750. Sequence.nextId = function () {
  2751. return Sequence._nextId++;
  2752. };
  2753. Sequence._nextId = 0;
  2754. return Sequence;
  2755. }());
  2756. var mainGroup = new Group();
  2757. /**
  2758. * Tween.js - Licensed under the MIT license
  2759. * https://github.com/tweenjs/tween.js
  2760. * ----------------------------------------------
  2761. *
  2762. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  2763. * Thank you all, you're awesome!
  2764. */
  2765. var Tween = /** @class */ (function () {
  2766. function Tween(_object, _group) {
  2767. if (_group === void 0) { _group = mainGroup; }
  2768. this._object = _object;
  2769. this._group = _group;
  2770. this._isPaused = false;
  2771. this._pauseStart = 0;
  2772. this._valuesStart = {};
  2773. this._valuesEnd = {};
  2774. this._valuesStartRepeat = {};
  2775. this._duration = 1000;
  2776. this._initialRepeat = 0;
  2777. this._repeat = 0;
  2778. this._yoyo = false;
  2779. this._isPlaying = false;
  2780. this._reversed = false;
  2781. this._delayTime = 0;
  2782. this._startTime = 0;
  2783. this._easingFunction = Easing.Linear.None;
  2784. this._interpolationFunction = Interpolation.Linear;
  2785. this._chainedTweens = [];
  2786. this._onStartCallbackFired = false;
  2787. this._id = Sequence.nextId();
  2788. this._isChainStopped = false;
  2789. this._goToEnd = false;
  2790. }
  2791. Tween.prototype.getId = function () {
  2792. return this._id;
  2793. };
  2794. Tween.prototype.isPlaying = function () {
  2795. return this._isPlaying;
  2796. };
  2797. Tween.prototype.isPaused = function () {
  2798. return this._isPaused;
  2799. };
  2800. Tween.prototype.to = function (properties, duration) {
  2801. // TODO? restore this, then update the 07_dynamic_to example to set fox
  2802. // tween's to on each update. That way the behavior is opt-in (there's
  2803. // currently no opt-out).
  2804. // for (const prop in properties) this._valuesEnd[prop] = properties[prop]
  2805. this._valuesEnd = Object.create(properties);
  2806. if (duration !== undefined) {
  2807. this._duration = duration;
  2808. }
  2809. return this;
  2810. };
  2811. Tween.prototype.duration = function (d) {
  2812. this._duration = d;
  2813. return this;
  2814. };
  2815. Tween.prototype.start = function (time) {
  2816. if (this._isPlaying) {
  2817. return this;
  2818. }
  2819. // eslint-disable-next-line
  2820. this._group && this._group.add(this);
  2821. this._repeat = this._initialRepeat;
  2822. if (this._reversed) {
  2823. // If we were reversed (f.e. using the yoyo feature) then we need to
  2824. // flip the tween direction back to forward.
  2825. this._reversed = false;
  2826. for (var property in this._valuesStartRepeat) {
  2827. this._swapEndStartRepeatValues(property);
  2828. this._valuesStart[property] = this._valuesStartRepeat[property];
  2829. }
  2830. }
  2831. this._isPlaying = true;
  2832. this._isPaused = false;
  2833. this._onStartCallbackFired = false;
  2834. this._isChainStopped = false;
  2835. this._startTime = time !== undefined ? (typeof time === 'string' ? now$1() + parseFloat(time) : time) : now$1();
  2836. this._startTime += this._delayTime;
  2837. this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat);
  2838. return this;
  2839. };
  2840. Tween.prototype._setupProperties = function (_object, _valuesStart, _valuesEnd, _valuesStartRepeat) {
  2841. for (var property in _valuesEnd) {
  2842. var startValue = _object[property];
  2843. var startValueIsArray = Array.isArray(startValue);
  2844. var propType = startValueIsArray ? 'array' : typeof startValue;
  2845. var isInterpolationList = !startValueIsArray && Array.isArray(_valuesEnd[property]);
  2846. // If `to()` specifies a property that doesn't exist in the source object,
  2847. // we should not set that property in the object
  2848. if (propType === 'undefined' || propType === 'function') {
  2849. continue;
  2850. }
  2851. // Check if an Array was provided as property value
  2852. if (isInterpolationList) {
  2853. var endValues = _valuesEnd[property];
  2854. if (endValues.length === 0) {
  2855. continue;
  2856. }
  2857. // handle an array of relative values
  2858. endValues = endValues.map(this._handleRelativeValue.bind(this, startValue));
  2859. // Create a local copy of the Array with the start value at the front
  2860. _valuesEnd[property] = [startValue].concat(endValues);
  2861. }
  2862. // handle the deepness of the values
  2863. if ((propType === 'object' || startValueIsArray) && startValue && !isInterpolationList) {
  2864. _valuesStart[property] = startValueIsArray ? [] : {};
  2865. // eslint-disable-next-line
  2866. for (var prop in startValue) {
  2867. // eslint-disable-next-line
  2868. // @ts-ignore FIXME?
  2869. _valuesStart[property][prop] = startValue[prop];
  2870. }
  2871. _valuesStartRepeat[property] = startValueIsArray ? [] : {}; // TODO? repeat nested values? And yoyo? And array values?
  2872. // eslint-disable-next-line
  2873. // @ts-ignore FIXME?
  2874. this._setupProperties(startValue, _valuesStart[property], _valuesEnd[property], _valuesStartRepeat[property]);
  2875. }
  2876. else {
  2877. // Save the starting value, but only once.
  2878. if (typeof _valuesStart[property] === 'undefined') {
  2879. _valuesStart[property] = startValue;
  2880. }
  2881. if (!startValueIsArray) {
  2882. // eslint-disable-next-line
  2883. // @ts-ignore FIXME?
  2884. _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  2885. }
  2886. if (isInterpolationList) {
  2887. // eslint-disable-next-line
  2888. // @ts-ignore FIXME?
  2889. _valuesStartRepeat[property] = _valuesEnd[property].slice().reverse();
  2890. }
  2891. else {
  2892. _valuesStartRepeat[property] = _valuesStart[property] || 0;
  2893. }
  2894. }
  2895. }
  2896. };
  2897. Tween.prototype.stop = function () {
  2898. if (!this._isChainStopped) {
  2899. this._isChainStopped = true;
  2900. this.stopChainedTweens();
  2901. }
  2902. if (!this._isPlaying) {
  2903. return this;
  2904. }
  2905. // eslint-disable-next-line
  2906. this._group && this._group.remove(this);
  2907. this._isPlaying = false;
  2908. this._isPaused = false;
  2909. if (this._onStopCallback) {
  2910. this._onStopCallback(this._object);
  2911. }
  2912. return this;
  2913. };
  2914. Tween.prototype.end = function () {
  2915. this._goToEnd = true;
  2916. this.update(Infinity);
  2917. return this;
  2918. };
  2919. Tween.prototype.pause = function (time) {
  2920. if (time === void 0) { time = now$1(); }
  2921. if (this._isPaused || !this._isPlaying) {
  2922. return this;
  2923. }
  2924. this._isPaused = true;
  2925. this._pauseStart = time;
  2926. // eslint-disable-next-line
  2927. this._group && this._group.remove(this);
  2928. return this;
  2929. };
  2930. Tween.prototype.resume = function (time) {
  2931. if (time === void 0) { time = now$1(); }
  2932. if (!this._isPaused || !this._isPlaying) {
  2933. return this;
  2934. }
  2935. this._isPaused = false;
  2936. this._startTime += time - this._pauseStart;
  2937. this._pauseStart = 0;
  2938. // eslint-disable-next-line
  2939. this._group && this._group.add(this);
  2940. return this;
  2941. };
  2942. Tween.prototype.stopChainedTweens = function () {
  2943. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
  2944. this._chainedTweens[i].stop();
  2945. }
  2946. return this;
  2947. };
  2948. Tween.prototype.group = function (group) {
  2949. this._group = group;
  2950. return this;
  2951. };
  2952. Tween.prototype.delay = function (amount) {
  2953. this._delayTime = amount;
  2954. return this;
  2955. };
  2956. Tween.prototype.repeat = function (times) {
  2957. this._initialRepeat = times;
  2958. this._repeat = times;
  2959. return this;
  2960. };
  2961. Tween.prototype.repeatDelay = function (amount) {
  2962. this._repeatDelayTime = amount;
  2963. return this;
  2964. };
  2965. Tween.prototype.yoyo = function (yoyo) {
  2966. this._yoyo = yoyo;
  2967. return this;
  2968. };
  2969. Tween.prototype.easing = function (easingFunction) {
  2970. this._easingFunction = easingFunction;
  2971. return this;
  2972. };
  2973. Tween.prototype.interpolation = function (interpolationFunction) {
  2974. this._interpolationFunction = interpolationFunction;
  2975. return this;
  2976. };
  2977. Tween.prototype.chain = function () {
  2978. var tweens = [];
  2979. for (var _i = 0; _i < arguments.length; _i++) {
  2980. tweens[_i] = arguments[_i];
  2981. }
  2982. this._chainedTweens = tweens;
  2983. return this;
  2984. };
  2985. Tween.prototype.onStart = function (callback) {
  2986. this._onStartCallback = callback;
  2987. return this;
  2988. };
  2989. Tween.prototype.onUpdate = function (callback) {
  2990. this._onUpdateCallback = callback;
  2991. return this;
  2992. };
  2993. Tween.prototype.onRepeat = function (callback) {
  2994. this._onRepeatCallback = callback;
  2995. return this;
  2996. };
  2997. Tween.prototype.onComplete = function (callback) {
  2998. this._onCompleteCallback = callback;
  2999. return this;
  3000. };
  3001. Tween.prototype.onStop = function (callback) {
  3002. this._onStopCallback = callback;
  3003. return this;
  3004. };
  3005. /**
  3006. * @returns true if the tween is still playing after the update, false
  3007. * otherwise (calling update on a paused tween still returns true because
  3008. * it is still playing, just paused).
  3009. */
  3010. Tween.prototype.update = function (time, autoStart) {
  3011. if (time === void 0) { time = now$1(); }
  3012. if (autoStart === void 0) { autoStart = true; }
  3013. if (this._isPaused)
  3014. return true;
  3015. var property;
  3016. var elapsed;
  3017. var endTime = this._startTime + this._duration;
  3018. if (!this._goToEnd && !this._isPlaying) {
  3019. if (time > endTime)
  3020. return false;
  3021. if (autoStart)
  3022. this.start(time);
  3023. }
  3024. this._goToEnd = false;
  3025. if (time < this._startTime) {
  3026. return true;
  3027. }
  3028. if (this._onStartCallbackFired === false) {
  3029. if (this._onStartCallback) {
  3030. this._onStartCallback(this._object);
  3031. }
  3032. this._onStartCallbackFired = true;
  3033. }
  3034. elapsed = (time - this._startTime) / this._duration;
  3035. elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed;
  3036. var value = this._easingFunction(elapsed);
  3037. // properties transformations
  3038. this._updateProperties(this._object, this._valuesStart, this._valuesEnd, value);
  3039. if (this._onUpdateCallback) {
  3040. this._onUpdateCallback(this._object, elapsed);
  3041. }
  3042. if (elapsed === 1) {
  3043. if (this._repeat > 0) {
  3044. if (isFinite(this._repeat)) {
  3045. this._repeat--;
  3046. }
  3047. // Reassign starting values, restart by making startTime = now
  3048. for (property in this._valuesStartRepeat) {
  3049. if (!this._yoyo && typeof this._valuesEnd[property] === 'string') {
  3050. this._valuesStartRepeat[property] =
  3051. // eslint-disable-next-line
  3052. // @ts-ignore FIXME?
  3053. this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]);
  3054. }
  3055. if (this._yoyo) {
  3056. this._swapEndStartRepeatValues(property);
  3057. }
  3058. this._valuesStart[property] = this._valuesStartRepeat[property];
  3059. }
  3060. if (this._yoyo) {
  3061. this._reversed = !this._reversed;
  3062. }
  3063. if (this._repeatDelayTime !== undefined) {
  3064. this._startTime = time + this._repeatDelayTime;
  3065. }
  3066. else {
  3067. this._startTime = time + this._delayTime;
  3068. }
  3069. if (this._onRepeatCallback) {
  3070. this._onRepeatCallback(this._object);
  3071. }
  3072. return true;
  3073. }
  3074. else {
  3075. if (this._onCompleteCallback) {
  3076. this._onCompleteCallback(this._object);
  3077. }
  3078. for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
  3079. // Make the chained tweens start exactly at the time they should,
  3080. // even if the `update()` method was called way past the duration of the tween
  3081. this._chainedTweens[i].start(this._startTime + this._duration);
  3082. }
  3083. this._isPlaying = false;
  3084. return false;
  3085. }
  3086. }
  3087. return true;
  3088. };
  3089. Tween.prototype._updateProperties = function (_object, _valuesStart, _valuesEnd, value) {
  3090. for (var property in _valuesEnd) {
  3091. // Don't update properties that do not exist in the source object
  3092. if (_valuesStart[property] === undefined) {
  3093. continue;
  3094. }
  3095. var start = _valuesStart[property] || 0;
  3096. var end = _valuesEnd[property];
  3097. var startIsArray = Array.isArray(_object[property]);
  3098. var endIsArray = Array.isArray(end);
  3099. var isInterpolationList = !startIsArray && endIsArray;
  3100. if (isInterpolationList) {
  3101. _object[property] = this._interpolationFunction(end, value);
  3102. }
  3103. else if (typeof end === 'object' && end) {
  3104. // eslint-disable-next-line
  3105. // @ts-ignore FIXME?
  3106. this._updateProperties(_object[property], start, end, value);
  3107. }
  3108. else {
  3109. // Parses relative end values with start as base (e.g.: +10, -3)
  3110. end = this._handleRelativeValue(start, end);
  3111. // Protect against non numeric properties.
  3112. if (typeof end === 'number') {
  3113. // eslint-disable-next-line
  3114. // @ts-ignore FIXME?
  3115. _object[property] = start + (end - start) * value;
  3116. }
  3117. }
  3118. }
  3119. };
  3120. Tween.prototype._handleRelativeValue = function (start, end) {
  3121. if (typeof end !== 'string') {
  3122. return end;
  3123. }
  3124. if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  3125. return start + parseFloat(end);
  3126. }
  3127. else {
  3128. return parseFloat(end);
  3129. }
  3130. };
  3131. Tween.prototype._swapEndStartRepeatValues = function (property) {
  3132. var tmp = this._valuesStartRepeat[property];
  3133. var endValue = this._valuesEnd[property];
  3134. if (typeof endValue === 'string') {
  3135. this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(endValue);
  3136. }
  3137. else {
  3138. this._valuesStartRepeat[property] = this._valuesEnd[property];
  3139. }
  3140. this._valuesEnd[property] = tmp;
  3141. };
  3142. return Tween;
  3143. }());
  3144. var VERSION = '18.6.4';
  3145. /**
  3146. * Tween.js - Licensed under the MIT license
  3147. * https://github.com/tweenjs/tween.js
  3148. * ----------------------------------------------
  3149. *
  3150. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  3151. * Thank you all, you're awesome!
  3152. */
  3153. var nextId = Sequence.nextId;
  3154. /**
  3155. * Controlling groups of tweens
  3156. *
  3157. * Using the TWEEN singleton to manage your tweens can cause issues in large apps with many components.
  3158. * In these cases, you may want to create your own smaller groups of tweens.
  3159. */
  3160. var TWEEN = mainGroup;
  3161. // This is the best way to export things in a way that's compatible with both ES
  3162. // Modules and CommonJS, without build hacks, and so as not to break the
  3163. // existing API.
  3164. // https://github.com/rollup/rollup/issues/1961#issuecomment-423037881
  3165. var getAll = TWEEN.getAll.bind(TWEEN);
  3166. var removeAll = TWEEN.removeAll.bind(TWEEN);
  3167. var add = TWEEN.add.bind(TWEEN);
  3168. var remove = TWEEN.remove.bind(TWEEN);
  3169. var update = TWEEN.update.bind(TWEEN);
  3170. var exports$1 = {
  3171. Easing: Easing,
  3172. Group: Group,
  3173. Interpolation: Interpolation,
  3174. now: now$1,
  3175. Sequence: Sequence,
  3176. nextId: nextId,
  3177. Tween: Tween,
  3178. VERSION: VERSION,
  3179. getAll: getAll,
  3180. removeAll: removeAll,
  3181. add: add,
  3182. remove: remove,
  3183. update: update,
  3184. };
  3185. var index$1 = (function (p) {
  3186. return p instanceof Function ? p // fn
  3187. : typeof p === 'string' ? function (obj) {
  3188. return obj[p];
  3189. } // property name
  3190. : function (obj) {
  3191. return p;
  3192. };
  3193. }); // constant
  3194. /**
  3195. * Returns a function, that, as long as it continues to be invoked, will not
  3196. * be triggered. The function will be called after it stops being called for
  3197. * N milliseconds. If `immediate` is passed, trigger the function on the
  3198. * leading edge, instead of the trailing. The function also has a property 'clear'
  3199. * that is a function which will clear the timer to prevent previously scheduled executions.
  3200. *
  3201. * @source underscore.js
  3202. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  3203. * @param {Function} function to wrap
  3204. * @param {Number} timeout in ms (`100`)
  3205. * @param {Boolean} whether to execute at the beginning (`false`)
  3206. * @api public
  3207. */
  3208. function debounce(func, wait, immediate){
  3209. var timeout, args, context, timestamp, result;
  3210. if (null == wait) wait = 100;
  3211. function later() {
  3212. var last = Date.now() - timestamp;
  3213. if (last < wait && last >= 0) {
  3214. timeout = setTimeout(later, wait - last);
  3215. } else {
  3216. timeout = null;
  3217. if (!immediate) {
  3218. result = func.apply(context, args);
  3219. context = args = null;
  3220. }
  3221. }
  3222. }
  3223. var debounced = function(){
  3224. context = this;
  3225. args = arguments;
  3226. timestamp = Date.now();
  3227. var callNow = immediate && !timeout;
  3228. if (!timeout) timeout = setTimeout(later, wait);
  3229. if (callNow) {
  3230. result = func.apply(context, args);
  3231. context = args = null;
  3232. }
  3233. return result;
  3234. };
  3235. debounced.clear = function() {
  3236. if (timeout) {
  3237. clearTimeout(timeout);
  3238. timeout = null;
  3239. }
  3240. };
  3241. debounced.flush = function() {
  3242. if (timeout) {
  3243. result = func.apply(context, args);
  3244. context = args = null;
  3245. clearTimeout(timeout);
  3246. timeout = null;
  3247. }
  3248. };
  3249. return debounced;
  3250. }
  3251. // Adds compatibility for ES modules
  3252. debounce.debounce = debounce;
  3253. var debounce_1 = debounce;
  3254. function _classCallCheck(instance, Constructor) {
  3255. if (!(instance instanceof Constructor)) {
  3256. throw new TypeError("Cannot call a class as a function");
  3257. }
  3258. }
  3259. function _slicedToArray(arr, i) {
  3260. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  3261. }
  3262. function _arrayWithHoles(arr) {
  3263. if (Array.isArray(arr)) return arr;
  3264. }
  3265. function _iterableToArrayLimit(arr, i) {
  3266. var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]);
  3267. if (_i == null) return;
  3268. var _arr = [];
  3269. var _n = true;
  3270. var _d = false;
  3271. var _s, _e;
  3272. try {
  3273. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  3274. _arr.push(_s.value);
  3275. if (i && _arr.length === i) break;
  3276. }
  3277. } catch (err) {
  3278. _d = true;
  3279. _e = err;
  3280. } finally {
  3281. try {
  3282. if (!_n && _i["return"] != null) _i["return"]();
  3283. } finally {
  3284. if (_d) throw _e;
  3285. }
  3286. }
  3287. return _arr;
  3288. }
  3289. function _unsupportedIterableToArray(o, minLen) {
  3290. if (!o) return;
  3291. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  3292. var n = Object.prototype.toString.call(o).slice(8, -1);
  3293. if (n === "Object" && o.constructor) n = o.constructor.name;
  3294. if (n === "Map" || n === "Set") return Array.from(o);
  3295. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  3296. }
  3297. function _arrayLikeToArray(arr, len) {
  3298. if (len == null || len > arr.length) len = arr.length;
  3299. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  3300. return arr2;
  3301. }
  3302. function _nonIterableRest() {
  3303. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  3304. }
  3305. var Prop = function Prop(name, _ref) {
  3306. var _ref$default = _ref["default"],
  3307. defaultVal = _ref$default === void 0 ? null : _ref$default,
  3308. _ref$triggerUpdate = _ref.triggerUpdate,
  3309. triggerUpdate = _ref$triggerUpdate === void 0 ? true : _ref$triggerUpdate,
  3310. _ref$onChange = _ref.onChange,
  3311. onChange = _ref$onChange === void 0 ? function (newVal, state) {} : _ref$onChange;
  3312. _classCallCheck(this, Prop);
  3313. this.name = name;
  3314. this.defaultVal = defaultVal;
  3315. this.triggerUpdate = triggerUpdate;
  3316. this.onChange = onChange;
  3317. };
  3318. function index (_ref2) {
  3319. var _ref2$stateInit = _ref2.stateInit,
  3320. stateInit = _ref2$stateInit === void 0 ? function () {
  3321. return {};
  3322. } : _ref2$stateInit,
  3323. _ref2$props = _ref2.props,
  3324. rawProps = _ref2$props === void 0 ? {} : _ref2$props,
  3325. _ref2$methods = _ref2.methods,
  3326. methods = _ref2$methods === void 0 ? {} : _ref2$methods,
  3327. _ref2$aliases = _ref2.aliases,
  3328. aliases = _ref2$aliases === void 0 ? {} : _ref2$aliases,
  3329. _ref2$init = _ref2.init,
  3330. initFn = _ref2$init === void 0 ? function () {} : _ref2$init,
  3331. _ref2$update = _ref2.update,
  3332. updateFn = _ref2$update === void 0 ? function () {} : _ref2$update;
  3333. // Parse props into Prop instances
  3334. var props = Object.keys(rawProps).map(function (propName) {
  3335. return new Prop(propName, rawProps[propName]);
  3336. });
  3337. return function () {
  3338. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  3339. // Holds component state
  3340. var state = Object.assign({}, stateInit instanceof Function ? stateInit(options) : stateInit, // Support plain objects for backwards compatibility
  3341. {
  3342. initialised: false
  3343. }); // keeps track of which props triggered an update
  3344. var changedProps = {}; // Component constructor
  3345. function comp(nodeElement) {
  3346. initStatic(nodeElement, options);
  3347. digest();
  3348. return comp;
  3349. }
  3350. var initStatic = function initStatic(nodeElement, options) {
  3351. initFn.call(comp, nodeElement, state, options);
  3352. state.initialised = true;
  3353. };
  3354. var digest = debounce_1(function () {
  3355. if (!state.initialised) {
  3356. return;
  3357. }
  3358. updateFn.call(comp, state, changedProps);
  3359. changedProps = {};
  3360. }, 1); // Getter/setter methods
  3361. props.forEach(function (prop) {
  3362. comp[prop.name] = getSetProp(prop);
  3363. function getSetProp(_ref3) {
  3364. var prop = _ref3.name,
  3365. _ref3$triggerUpdate = _ref3.triggerUpdate,
  3366. redigest = _ref3$triggerUpdate === void 0 ? false : _ref3$triggerUpdate,
  3367. _ref3$onChange = _ref3.onChange,
  3368. onChange = _ref3$onChange === void 0 ? function (newVal, state) {} : _ref3$onChange,
  3369. _ref3$defaultVal = _ref3.defaultVal,
  3370. defaultVal = _ref3$defaultVal === void 0 ? null : _ref3$defaultVal;
  3371. return function (_) {
  3372. var curVal = state[prop];
  3373. if (!arguments.length) {
  3374. return curVal;
  3375. } // Getter mode
  3376. var val = _ === undefined ? defaultVal : _; // pick default if value passed is undefined
  3377. state[prop] = val;
  3378. onChange.call(comp, val, state, curVal); // track changed props
  3379. !changedProps.hasOwnProperty(prop) && (changedProps[prop] = curVal);
  3380. if (redigest) {
  3381. digest();
  3382. }
  3383. return comp;
  3384. };
  3385. }
  3386. }); // Other methods
  3387. Object.keys(methods).forEach(function (methodName) {
  3388. comp[methodName] = function () {
  3389. var _methods$methodName;
  3390. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3391. args[_key] = arguments[_key];
  3392. }
  3393. return (_methods$methodName = methods[methodName]).call.apply(_methods$methodName, [comp, state].concat(args));
  3394. };
  3395. }); // Link aliases
  3396. Object.entries(aliases).forEach(function (_ref4) {
  3397. var _ref5 = _slicedToArray(_ref4, 2),
  3398. alias = _ref5[0],
  3399. target = _ref5[1];
  3400. return comp[alias] = comp[target];
  3401. }); // Reset all component props to their default value
  3402. comp.resetProps = function () {
  3403. props.forEach(function (prop) {
  3404. comp[prop.name](prop.defaultVal);
  3405. });
  3406. return comp;
  3407. }; //
  3408. comp.resetProps(); // Apply all prop defaults
  3409. state._rerender = digest; // Expose digest method
  3410. return comp;
  3411. };
  3412. }
  3413. var three = window.THREE ? window.THREE // Prefer consumption from global THREE, if exists
  3414. : {
  3415. WebGLRenderer: three$1.WebGLRenderer,
  3416. Scene: three$1.Scene,
  3417. PerspectiveCamera: three$1.PerspectiveCamera,
  3418. Raycaster: three$1.Raycaster,
  3419. TextureLoader: three$1.TextureLoader,
  3420. Vector2: three$1.Vector2,
  3421. Vector3: three$1.Vector3,
  3422. Box3: three$1.Box3,
  3423. Color: three$1.Color,
  3424. Mesh: three$1.Mesh,
  3425. SphereGeometry: three$1.SphereGeometry,
  3426. MeshBasicMaterial: three$1.MeshBasicMaterial,
  3427. BackSide: three$1.BackSide,
  3428. EventDispatcher: three$1.EventDispatcher,
  3429. MOUSE: three$1.MOUSE,
  3430. Quaternion: three$1.Quaternion,
  3431. Spherical: three$1.Spherical,
  3432. Clock: three$1.Clock
  3433. };
  3434. var threeRenderObjects = index({
  3435. props: {
  3436. width: {
  3437. "default": window.innerWidth,
  3438. onChange: function onChange(width, state, prevWidth) {
  3439. isNaN(width) && (state.width = prevWidth);
  3440. }
  3441. },
  3442. height: {
  3443. "default": window.innerHeight,
  3444. onChange: function onChange(height, state, prevHeight) {
  3445. isNaN(height) && (state.height = prevHeight);
  3446. }
  3447. },
  3448. backgroundColor: {
  3449. "default": '#000011'
  3450. },
  3451. backgroundImageUrl: {},
  3452. onBackgroundImageLoaded: {},
  3453. showNavInfo: {
  3454. "default": true
  3455. },
  3456. skyRadius: {
  3457. "default": 50000
  3458. },
  3459. objects: {
  3460. "default": []
  3461. },
  3462. enablePointerInteraction: {
  3463. "default": true,
  3464. onChange: function onChange(_, state) {
  3465. // Reset hover state
  3466. state.hoverObj = null;
  3467. if (state.toolTipElem) state.toolTipElem.innerHTML = '';
  3468. },
  3469. triggerUpdate: false
  3470. },
  3471. lineHoverPrecision: {
  3472. "default": 1,
  3473. triggerUpdate: false
  3474. },
  3475. hoverOrderComparator: {
  3476. "default": function _default() {
  3477. return -1;
  3478. },
  3479. triggerUpdate: false
  3480. },
  3481. // keep existing order by default
  3482. hoverFilter: {
  3483. "default": function _default() {
  3484. return true;
  3485. },
  3486. triggerUpdate: false
  3487. },
  3488. // exclude objects from interaction
  3489. tooltipContent: {
  3490. triggerUpdate: false
  3491. },
  3492. hoverDuringDrag: {
  3493. "default": false,
  3494. triggerUpdate: false
  3495. },
  3496. clickAfterDrag: {
  3497. "default": false,
  3498. triggerUpdate: false
  3499. },
  3500. onHover: {
  3501. "default": function _default() {},
  3502. triggerUpdate: false
  3503. },
  3504. onClick: {
  3505. "default": function _default() {},
  3506. triggerUpdate: false
  3507. },
  3508. onRightClick: {
  3509. triggerUpdate: false
  3510. }
  3511. },
  3512. methods: {
  3513. tick: function tick(state) {
  3514. if (state.initialised) {
  3515. state.controls.update && state.controls.update(state.clock.getDelta()); // timedelta is required for fly controls
  3516. state.postProcessingComposer ? state.postProcessingComposer.render() // if using postprocessing, switch the output to it
  3517. : state.renderer.render(state.scene, state.camera);
  3518. state.extraRenderers.forEach(function (r) {
  3519. return r.render(state.scene, state.camera);
  3520. });
  3521. if (state.enablePointerInteraction) {
  3522. // Update tooltip and trigger onHover events
  3523. var topObject = null;
  3524. if (state.hoverDuringDrag || !state.isPointerDragging) {
  3525. var intersects = this.intersectingObjects(state.pointerPos.x, state.pointerPos.y).filter(function (d) {
  3526. return state.hoverFilter(d.object);
  3527. }).sort(function (a, b) {
  3528. return state.hoverOrderComparator(a.object, b.object);
  3529. });
  3530. var topIntersect = intersects.length ? intersects[0] : null;
  3531. topObject = topIntersect ? topIntersect.object : null;
  3532. state.intersectionPoint = topIntersect ? topIntersect.point : null;
  3533. }
  3534. if (topObject !== state.hoverObj) {
  3535. state.onHover(topObject, state.hoverObj);
  3536. state.toolTipElem.innerHTML = topObject ? index$1(state.tooltipContent)(topObject) || '' : '';
  3537. state.hoverObj = topObject;
  3538. }
  3539. }
  3540. exports$1.update(); // update camera animation tweens
  3541. }
  3542. return this;
  3543. },
  3544. getPointerPos: function getPointerPos(state) {
  3545. var _state$pointerPos = state.pointerPos,
  3546. x = _state$pointerPos.x,
  3547. y = _state$pointerPos.y;
  3548. return {
  3549. x: x,
  3550. y: y
  3551. };
  3552. },
  3553. cameraPosition: function cameraPosition(state, position, lookAt, transitionDuration) {
  3554. var camera = state.camera; // Setter
  3555. if (position && state.initialised) {
  3556. var finalPos = position;
  3557. var finalLookAt = lookAt || {
  3558. x: 0,
  3559. y: 0,
  3560. z: 0
  3561. };
  3562. if (!transitionDuration) {
  3563. // no animation
  3564. setCameraPos(finalPos);
  3565. setLookAt(finalLookAt);
  3566. } else {
  3567. var camPos = Object.assign({}, camera.position);
  3568. var camLookAt = getLookAt();
  3569. new exports$1.Tween(camPos).to(finalPos, transitionDuration).easing(exports$1.Easing.Quadratic.Out).onUpdate(setCameraPos).start(); // Face direction in 1/3rd of time
  3570. new exports$1.Tween(camLookAt).to(finalLookAt, transitionDuration / 3).easing(exports$1.Easing.Quadratic.Out).onUpdate(setLookAt).start();
  3571. }
  3572. return this;
  3573. } // Getter
  3574. return Object.assign({}, camera.position, {
  3575. lookAt: getLookAt()
  3576. }); //
  3577. function setCameraPos(pos) {
  3578. var x = pos.x,
  3579. y = pos.y,
  3580. z = pos.z;
  3581. if (x !== undefined) camera.position.x = x;
  3582. if (y !== undefined) camera.position.y = y;
  3583. if (z !== undefined) camera.position.z = z;
  3584. }
  3585. function setLookAt(lookAt) {
  3586. state.controls.target = new three.Vector3(lookAt.x, lookAt.y, lookAt.z);
  3587. }
  3588. function getLookAt() {
  3589. return Object.assign(new three.Vector3(0, 0, -1000).applyQuaternion(camera.quaternion).add(camera.position));
  3590. }
  3591. },
  3592. zoomToFit: function zoomToFit(state) {
  3593. var transitionDuration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3594. var padding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
  3595. for (var _len = arguments.length, bboxArgs = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
  3596. bboxArgs[_key - 3] = arguments[_key];
  3597. }
  3598. return this.fitToBbox(this.getBbox.apply(this, bboxArgs), transitionDuration, padding);
  3599. },
  3600. fitToBbox: function fitToBbox(state, bbox) {
  3601. var transitionDuration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  3602. var padding = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10;
  3603. // based on https://discourse.threejs.org/t/camera-zoom-to-fit-object/936/24
  3604. var camera = state.camera;
  3605. if (bbox) {
  3606. var center = new three.Vector3(0, 0, 0); // reset camera aim to center
  3607. var maxBoxSide = Math.max.apply(Math, _toConsumableArray(Object.entries(bbox).map(function (_ref) {
  3608. var _ref2 = _slicedToArray$1(_ref, 2),
  3609. coordType = _ref2[0],
  3610. coords = _ref2[1];
  3611. return Math.max.apply(Math, _toConsumableArray(coords.map(function (c) {
  3612. return Math.abs(center[coordType] - c);
  3613. })));
  3614. }))) * 2; // find distance that fits whole bbox within padded fov
  3615. var paddedFov = (1 - padding * 2 / state.height) * camera.fov;
  3616. var fitHeightDistance = maxBoxSide / Math.atan(paddedFov * Math.PI / 180);
  3617. var fitWidthDistance = fitHeightDistance / camera.aspect;
  3618. var distance = Math.max(fitHeightDistance, fitWidthDistance);
  3619. if (distance > 0) {
  3620. var newCameraPosition = center.clone().sub(camera.position).normalize().multiplyScalar(-distance);
  3621. this.cameraPosition(newCameraPosition, center, transitionDuration);
  3622. }
  3623. }
  3624. return this;
  3625. },
  3626. getBbox: function getBbox(state) {
  3627. var objFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
  3628. return true;
  3629. };
  3630. var box = new three.Box3(new three.Vector3(0, 0, 0), new three.Vector3(0, 0, 0));
  3631. var objs = state.objects.filter(objFilter);
  3632. if (!objs.length) return null;
  3633. objs.forEach(function (obj) {
  3634. return box.expandByObject(obj);
  3635. }); // extract global x,y,z min/max
  3636. return Object.assign.apply(Object, _toConsumableArray(['x', 'y', 'z'].map(function (c) {
  3637. return _defineProperty({}, c, [box.min[c], box.max[c]]);
  3638. })));
  3639. },
  3640. getScreenCoords: function getScreenCoords(state, x, y, z) {
  3641. var vec = new three.Vector3(x, y, z);
  3642. vec.project(this.camera()); // project to the camera plane
  3643. return {
  3644. // align relative pos to canvas dimensions
  3645. x: (vec.x + 1) * state.width / 2,
  3646. y: -(vec.y - 1) * state.height / 2
  3647. };
  3648. },
  3649. getSceneCoords: function getSceneCoords(state, screenX, screenY) {
  3650. var distance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  3651. var relCoords = new three.Vector2(screenX / state.width * 2 - 1, -(screenY / state.height) * 2 + 1);
  3652. var raycaster = new three.Raycaster();
  3653. raycaster.setFromCamera(relCoords, state.camera);
  3654. return Object.assign({}, raycaster.ray.at(distance, new three.Vector3()));
  3655. },
  3656. intersectingObjects: function intersectingObjects(state, x, y) {
  3657. var relCoords = new three.Vector2(x / state.width * 2 - 1, -(y / state.height) * 2 + 1);
  3658. var raycaster = new three.Raycaster();
  3659. raycaster.params.Line.threshold = state.lineHoverPrecision; // set linePrecision
  3660. raycaster.setFromCamera(relCoords, state.camera);
  3661. return raycaster.intersectObjects(state.objects, true);
  3662. },
  3663. renderer: function renderer(state) {
  3664. return state.renderer;
  3665. },
  3666. scene: function scene(state) {
  3667. return state.scene;
  3668. },
  3669. camera: function camera(state) {
  3670. return state.camera;
  3671. },
  3672. postProcessingComposer: function postProcessingComposer(state) {
  3673. return state.postProcessingComposer;
  3674. },
  3675. controls: function controls(state) {
  3676. return state.controls;
  3677. },
  3678. tbControls: function tbControls(state) {
  3679. return state.controls;
  3680. } // to be deprecated
  3681. },
  3682. stateInit: function stateInit() {
  3683. return {
  3684. scene: new three.Scene(),
  3685. camera: new three.PerspectiveCamera(),
  3686. clock: new three.Clock()
  3687. };
  3688. },
  3689. init: function init(domNode, state) {
  3690. var _ref4 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  3691. _ref4$controlType = _ref4.controlType,
  3692. controlType = _ref4$controlType === void 0 ? 'trackball' : _ref4$controlType,
  3693. _ref4$rendererConfig = _ref4.rendererConfig,
  3694. rendererConfig = _ref4$rendererConfig === void 0 ? {} : _ref4$rendererConfig,
  3695. _ref4$extraRenderers = _ref4.extraRenderers,
  3696. extraRenderers = _ref4$extraRenderers === void 0 ? [] : _ref4$extraRenderers,
  3697. _ref4$waitForLoadComp = _ref4.waitForLoadComplete,
  3698. waitForLoadComplete = _ref4$waitForLoadComp === void 0 ? true : _ref4$waitForLoadComp;
  3699. // Wipe DOM
  3700. domNode.innerHTML = ''; // Add relative container
  3701. domNode.appendChild(state.container = document.createElement('div'));
  3702. state.container.className = 'scene-container';
  3703. state.container.style.position = 'relative'; // Add nav info section
  3704. state.container.appendChild(state.navInfo = document.createElement('div'));
  3705. state.navInfo.className = 'scene-nav-info';
  3706. state.navInfo.textContent = {
  3707. orbit: 'Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan',
  3708. trackball: 'Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan',
  3709. fly: 'WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw'
  3710. }[controlType] || '';
  3711. state.navInfo.style.display = state.showNavInfo ? null : 'none'; // Setup tooltip
  3712. state.toolTipElem = document.createElement('div');
  3713. state.toolTipElem.classList.add('scene-tooltip');
  3714. state.container.appendChild(state.toolTipElem); // Capture pointer coords on move or touchstart
  3715. state.pointerPos = new three.Vector2();
  3716. state.pointerPos.x = -2; // Initialize off canvas
  3717. state.pointerPos.y = -2;
  3718. ['pointermove', 'pointerdown'].forEach(function (evType) {
  3719. return state.container.addEventListener(evType, function (ev) {
  3720. // track click state
  3721. evType === 'pointerdown' && (state.isPointerPressed = true); // detect point drag
  3722. !state.isPointerDragging && ev.type === 'pointermove' && (ev.pressure > 0 || state.isPointerPressed) // ev.pressure always 0 on Safari, so we used the isPointerPressed tracker
  3723. && (ev.pointerType !== 'touch' || ev.movementX === undefined || [ev.movementX, ev.movementY].some(function (m) {
  3724. return Math.abs(m) > 1;
  3725. })) // relax drag trigger sensitivity on touch events
  3726. && (state.isPointerDragging = true);
  3727. if (state.enablePointerInteraction) {
  3728. // update the pointer pos
  3729. var offset = getOffset(state.container);
  3730. state.pointerPos.x = ev.pageX - offset.left;
  3731. state.pointerPos.y = ev.pageY - offset.top; // Move tooltip
  3732. state.toolTipElem.style.top = "".concat(state.pointerPos.y, "px");
  3733. state.toolTipElem.style.left = "".concat(state.pointerPos.x, "px");
  3734. state.toolTipElem.style.transform = "translate(-".concat(state.pointerPos.x / state.width * 100, "%, 21px)"); // adjust horizontal position to not exceed canvas boundaries
  3735. }
  3736. function getOffset(el) {
  3737. var rect = el.getBoundingClientRect(),
  3738. scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  3739. scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  3740. return {
  3741. top: rect.top + scrollTop,
  3742. left: rect.left + scrollLeft
  3743. };
  3744. }
  3745. }, {
  3746. passive: true
  3747. });
  3748. }); // Handle click events on objs
  3749. state.container.addEventListener('pointerup', function (ev) {
  3750. state.isPointerPressed = false;
  3751. if (state.isPointerDragging) {
  3752. state.isPointerDragging = false;
  3753. if (!state.clickAfterDrag) return; // don't trigger onClick after pointer drag (camera motion via controls)
  3754. }
  3755. requestAnimationFrame(function () {
  3756. // trigger click events asynchronously, to allow hoverObj to be set (on frame)
  3757. if (ev.button === 0) {
  3758. // left-click
  3759. state.onClick(state.hoverObj || null, ev, state.intersectionPoint); // trigger background clicks with null
  3760. }
  3761. if (ev.button === 2 && state.onRightClick) {
  3762. // right-click
  3763. state.onRightClick(state.hoverObj || null, ev, state.intersectionPoint);
  3764. }
  3765. });
  3766. }, {
  3767. passive: true,
  3768. capture: true
  3769. }); // use capture phase to prevent propagation blocking from controls (specifically for fly)
  3770. state.container.addEventListener('contextmenu', function (ev) {
  3771. if (state.onRightClick) ev.preventDefault(); // prevent default contextmenu behavior and allow pointerup to fire instead
  3772. }); // Setup renderer, camera and controls
  3773. state.renderer = new three.WebGLRenderer(Object.assign({
  3774. antialias: true,
  3775. alpha: true
  3776. }, rendererConfig));
  3777. state.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio)); // clamp device pixel ratio
  3778. state.container.appendChild(state.renderer.domElement); // Setup extra renderers
  3779. state.extraRenderers = extraRenderers;
  3780. state.extraRenderers.forEach(function (r) {
  3781. // overlay them on top of main renderer
  3782. r.domElement.style.position = 'absolute';
  3783. r.domElement.style.top = '0px';
  3784. r.domElement.style.pointerEvents = 'none';
  3785. state.container.appendChild(r.domElement);
  3786. }); // configure post-processing composer
  3787. state.postProcessingComposer = new EffectComposer(state.renderer);
  3788. state.postProcessingComposer.addPass(new RenderPass(state.scene, state.camera)); // render scene as first pass
  3789. // configure controls
  3790. state.controls = new {
  3791. trackball: TrackballControls,
  3792. orbit: OrbitControls,
  3793. fly: FlyControls
  3794. }[controlType](state.camera, state.renderer.domElement);
  3795. if (controlType === 'fly') {
  3796. state.controls.movementSpeed = 300;
  3797. state.controls.rollSpeed = Math.PI / 6;
  3798. state.controls.dragToLook = true;
  3799. }
  3800. if (controlType === 'trackball' || controlType === 'orbit') {
  3801. state.controls.minDistance = 0.1;
  3802. state.controls.maxDistance = state.skyRadius;
  3803. state.controls.addEventListener('start', function () {
  3804. state.controlsEngaged = true;
  3805. });
  3806. state.controls.addEventListener('change', function () {
  3807. if (state.controlsEngaged) {
  3808. state.controlsDragging = true;
  3809. }
  3810. });
  3811. state.controls.addEventListener('end', function () {
  3812. state.controlsEngaged = false;
  3813. state.controlsDragging = false;
  3814. });
  3815. }
  3816. [state.renderer, state.postProcessingComposer].concat(_toConsumableArray(state.extraRenderers)).forEach(function (r) {
  3817. return r.setSize(state.width, state.height);
  3818. });
  3819. state.camera.aspect = state.width / state.height;
  3820. state.camera.updateProjectionMatrix();
  3821. state.camera.position.z = 1000; // add sky
  3822. state.scene.add(state.skysphere = new three.Mesh());
  3823. state.skysphere.visible = false;
  3824. state.loadComplete = state.scene.visible = !waitForLoadComplete;
  3825. window.scene = state.scene;
  3826. },
  3827. update: function update(state, changedProps) {
  3828. // resize canvas
  3829. if (state.width && state.height && (changedProps.hasOwnProperty('width') || changedProps.hasOwnProperty('height'))) {
  3830. state.container.style.width = state.width;
  3831. state.container.style.height = state.height;
  3832. [state.renderer, state.postProcessingComposer].concat(_toConsumableArray(state.extraRenderers)).forEach(function (r) {
  3833. return r.setSize(state.width, state.height);
  3834. });
  3835. state.camera.aspect = state.width / state.height;
  3836. state.camera.updateProjectionMatrix();
  3837. }
  3838. if (changedProps.hasOwnProperty('skyRadius') && state.skyRadius) {
  3839. state.controls.hasOwnProperty('maxDistance') && changedProps.skyRadius && (state.controls.maxDistance = state.skyRadius);
  3840. state.camera.far = state.skyRadius * 2.5;
  3841. state.camera.updateProjectionMatrix();
  3842. state.skysphere.geometry = new three.SphereGeometry(state.skyRadius);
  3843. }
  3844. if (changedProps.hasOwnProperty('backgroundColor')) {
  3845. var alpha = parseToRgb(state.backgroundColor).alpha;
  3846. if (alpha === undefined) alpha = 1;
  3847. state.renderer.setClearColor(new three.Color(curriedOpacify(1, state.backgroundColor)), alpha);
  3848. }
  3849. if (changedProps.hasOwnProperty('backgroundImageUrl')) {
  3850. if (!state.backgroundImageUrl) {
  3851. state.skysphere.visible = false;
  3852. state.skysphere.material.map = null;
  3853. !state.loadComplete && finishLoad();
  3854. } else {
  3855. new three.TextureLoader().load(state.backgroundImageUrl, function (texture) {
  3856. state.skysphere.material = new three.MeshBasicMaterial({
  3857. map: texture,
  3858. side: three.BackSide
  3859. });
  3860. state.skysphere.visible = true; // triggered when background image finishes loading (asynchronously to allow 1 frame to load texture)
  3861. state.onBackgroundImageLoaded && setTimeout(state.onBackgroundImageLoaded);
  3862. !state.loadComplete && finishLoad();
  3863. });
  3864. }
  3865. }
  3866. changedProps.hasOwnProperty('showNavInfo') && (state.navInfo.style.display = state.showNavInfo ? null : 'none');
  3867. if (changedProps.hasOwnProperty('objects')) {
  3868. (changedProps.objects || []).forEach(function (obj) {
  3869. return state.scene.remove(obj);
  3870. }); // Clear the place
  3871. state.objects.forEach(function (obj) {
  3872. return state.scene.add(obj);
  3873. }); // Add to scene
  3874. } //
  3875. function finishLoad() {
  3876. state.loadComplete = state.scene.visible = true;
  3877. }
  3878. }
  3879. });
  3880. return threeRenderObjects;
  3881. })));
  3882. //# sourceMappingURL=three-render-objects.js.map