Transforms-273eeb44.js 491 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657
  1. /**
  2. * @license
  3. * Cesium - https://github.com/CesiumGS/cesium
  4. * Version 1.95
  5. *
  6. * Copyright 2011-2022 Cesium Contributors
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. *
  20. * Columbus View (Pat. Pend.)
  21. *
  22. * Portions licensed separately.
  23. * See https://github.com/CesiumGS/cesium/blob/main/LICENSE.md for full licensing details.
  24. */
  25. define(['exports', './Matrix2-9e1c22e2', './RuntimeError-4f8ec8a2', './defaultValue-97284df2', './ComponentDatatype-4eeb6d9b', './_commonjsHelpers-3aae1032-65601a27', './combine-d11b1f00'], (function (exports, Matrix2, RuntimeError, defaultValue, ComponentDatatype, _commonjsHelpers3aae1032, combine) { 'use strict';
  26. /**
  27. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  28. * them by the {@link Ellipsoid#maximumRadius}. This projection
  29. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  30. * is also known as EPSG:4326.
  31. *
  32. * @alias GeographicProjection
  33. * @constructor
  34. *
  35. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  36. *
  37. * @see WebMercatorProjection
  38. */
  39. function GeographicProjection(ellipsoid) {
  40. this._ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  41. this._semimajorAxis = this._ellipsoid.maximumRadius;
  42. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  43. }
  44. Object.defineProperties(GeographicProjection.prototype, {
  45. /**
  46. * Gets the {@link Ellipsoid}.
  47. *
  48. * @memberof GeographicProjection.prototype
  49. *
  50. * @type {Ellipsoid}
  51. * @readonly
  52. */
  53. ellipsoid: {
  54. get: function () {
  55. return this._ellipsoid;
  56. },
  57. },
  58. });
  59. /**
  60. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  61. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  62. * ellipsoid. Z is the unmodified height.
  63. *
  64. * @param {Cartographic} cartographic The coordinates to project.
  65. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  66. * undefined, a new instance is created and returned.
  67. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  68. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  69. * created and returned.
  70. */
  71. GeographicProjection.prototype.project = function (cartographic, result) {
  72. // Actually this is the special case of equidistant cylindrical called the plate carree
  73. const semimajorAxis = this._semimajorAxis;
  74. const x = cartographic.longitude * semimajorAxis;
  75. const y = cartographic.latitude * semimajorAxis;
  76. const z = cartographic.height;
  77. if (!defaultValue.defined(result)) {
  78. return new Matrix2.Cartesian3(x, y, z);
  79. }
  80. result.x = x;
  81. result.y = y;
  82. result.z = z;
  83. return result;
  84. };
  85. /**
  86. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  87. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  88. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  89. *
  90. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  91. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  92. * undefined, a new instance is created and returned.
  93. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  94. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  95. * created and returned.
  96. */
  97. GeographicProjection.prototype.unproject = function (cartesian, result) {
  98. //>>includeStart('debug', pragmas.debug);
  99. if (!defaultValue.defined(cartesian)) {
  100. throw new RuntimeError.DeveloperError("cartesian is required");
  101. }
  102. //>>includeEnd('debug');
  103. const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  104. const longitude = cartesian.x * oneOverEarthSemimajorAxis;
  105. const latitude = cartesian.y * oneOverEarthSemimajorAxis;
  106. const height = cartesian.z;
  107. if (!defaultValue.defined(result)) {
  108. return new Matrix2.Cartographic(longitude, latitude, height);
  109. }
  110. result.longitude = longitude;
  111. result.latitude = latitude;
  112. result.height = height;
  113. return result;
  114. };
  115. /**
  116. * This enumerated type is used in determining where, relative to the frustum, an
  117. * object is located. The object can either be fully contained within the frustum (INSIDE),
  118. * partially inside the frustum and partially outside (INTERSECTING), or somewhere entirely
  119. * outside of the frustum's 6 planes (OUTSIDE).
  120. *
  121. * @enum {Number}
  122. */
  123. const Intersect = {
  124. /**
  125. * Represents that an object is not contained within the frustum.
  126. *
  127. * @type {Number}
  128. * @constant
  129. */
  130. OUTSIDE: -1,
  131. /**
  132. * Represents that an object intersects one of the frustum's planes.
  133. *
  134. * @type {Number}
  135. * @constant
  136. */
  137. INTERSECTING: 0,
  138. /**
  139. * Represents that an object is fully within the frustum.
  140. *
  141. * @type {Number}
  142. * @constant
  143. */
  144. INSIDE: 1,
  145. };
  146. var Intersect$1 = Object.freeze(Intersect);
  147. /**
  148. * Represents the closed interval [start, stop].
  149. * @alias Interval
  150. * @constructor
  151. *
  152. * @param {Number} [start=0.0] The beginning of the interval.
  153. * @param {Number} [stop=0.0] The end of the interval.
  154. */
  155. function Interval(start, stop) {
  156. /**
  157. * The beginning of the interval.
  158. * @type {Number}
  159. * @default 0.0
  160. */
  161. this.start = defaultValue.defaultValue(start, 0.0);
  162. /**
  163. * The end of the interval.
  164. * @type {Number}
  165. * @default 0.0
  166. */
  167. this.stop = defaultValue.defaultValue(stop, 0.0);
  168. }
  169. /**
  170. * A bounding sphere with a center and a radius.
  171. * @alias BoundingSphere
  172. * @constructor
  173. *
  174. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  175. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  176. *
  177. * @see AxisAlignedBoundingBox
  178. * @see BoundingRectangle
  179. * @see Packable
  180. */
  181. function BoundingSphere(center, radius) {
  182. /**
  183. * The center point of the sphere.
  184. * @type {Cartesian3}
  185. * @default {@link Cartesian3.ZERO}
  186. */
  187. this.center = Matrix2.Cartesian3.clone(defaultValue.defaultValue(center, Matrix2.Cartesian3.ZERO));
  188. /**
  189. * The radius of the sphere.
  190. * @type {Number}
  191. * @default 0.0
  192. */
  193. this.radius = defaultValue.defaultValue(radius, 0.0);
  194. }
  195. const fromPointsXMin = new Matrix2.Cartesian3();
  196. const fromPointsYMin = new Matrix2.Cartesian3();
  197. const fromPointsZMin = new Matrix2.Cartesian3();
  198. const fromPointsXMax = new Matrix2.Cartesian3();
  199. const fromPointsYMax = new Matrix2.Cartesian3();
  200. const fromPointsZMax = new Matrix2.Cartesian3();
  201. const fromPointsCurrentPos = new Matrix2.Cartesian3();
  202. const fromPointsScratch = new Matrix2.Cartesian3();
  203. const fromPointsRitterCenter = new Matrix2.Cartesian3();
  204. const fromPointsMinBoxPt = new Matrix2.Cartesian3();
  205. const fromPointsMaxBoxPt = new Matrix2.Cartesian3();
  206. const fromPointsNaiveCenterScratch = new Matrix2.Cartesian3();
  207. const volumeConstant = (4.0 / 3.0) * ComponentDatatype.CesiumMath.PI;
  208. /**
  209. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  210. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  211. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  212. *
  213. * @param {Cartesian3[]} [positions] An array of points that the bounding sphere will enclose. Each point must have <code>x</code>, <code>y</code>, and <code>z</code> properties.
  214. * @param {BoundingSphere} [result] The object onto which to store the result.
  215. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  216. *
  217. * @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
  218. */
  219. BoundingSphere.fromPoints = function (positions, result) {
  220. if (!defaultValue.defined(result)) {
  221. result = new BoundingSphere();
  222. }
  223. if (!defaultValue.defined(positions) || positions.length === 0) {
  224. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  225. result.radius = 0.0;
  226. return result;
  227. }
  228. const currentPos = Matrix2.Cartesian3.clone(positions[0], fromPointsCurrentPos);
  229. const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
  230. const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
  231. const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
  232. const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
  233. const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
  234. const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
  235. const numPositions = positions.length;
  236. let i;
  237. for (i = 1; i < numPositions; i++) {
  238. Matrix2.Cartesian3.clone(positions[i], currentPos);
  239. const x = currentPos.x;
  240. const y = currentPos.y;
  241. const z = currentPos.z;
  242. // Store points containing the the smallest and largest components
  243. if (x < xMin.x) {
  244. Matrix2.Cartesian3.clone(currentPos, xMin);
  245. }
  246. if (x > xMax.x) {
  247. Matrix2.Cartesian3.clone(currentPos, xMax);
  248. }
  249. if (y < yMin.y) {
  250. Matrix2.Cartesian3.clone(currentPos, yMin);
  251. }
  252. if (y > yMax.y) {
  253. Matrix2.Cartesian3.clone(currentPos, yMax);
  254. }
  255. if (z < zMin.z) {
  256. Matrix2.Cartesian3.clone(currentPos, zMin);
  257. }
  258. if (z > zMax.z) {
  259. Matrix2.Cartesian3.clone(currentPos, zMax);
  260. }
  261. }
  262. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  263. const xSpan = Matrix2.Cartesian3.magnitudeSquared(
  264. Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  265. );
  266. const ySpan = Matrix2.Cartesian3.magnitudeSquared(
  267. Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  268. );
  269. const zSpan = Matrix2.Cartesian3.magnitudeSquared(
  270. Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  271. );
  272. // Set the diameter endpoints to the largest span.
  273. let diameter1 = xMin;
  274. let diameter2 = xMax;
  275. let maxSpan = xSpan;
  276. if (ySpan > maxSpan) {
  277. maxSpan = ySpan;
  278. diameter1 = yMin;
  279. diameter2 = yMax;
  280. }
  281. if (zSpan > maxSpan) {
  282. maxSpan = zSpan;
  283. diameter1 = zMin;
  284. diameter2 = zMax;
  285. }
  286. // Calculate the center of the initial sphere found by Ritter's algorithm
  287. const ritterCenter = fromPointsRitterCenter;
  288. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  289. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  290. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  291. // Calculate the radius of the initial sphere found by Ritter's algorithm
  292. let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
  293. Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  294. );
  295. let ritterRadius = Math.sqrt(radiusSquared);
  296. // Find the center of the sphere found using the Naive method.
  297. const minBoxPt = fromPointsMinBoxPt;
  298. minBoxPt.x = xMin.x;
  299. minBoxPt.y = yMin.y;
  300. minBoxPt.z = zMin.z;
  301. const maxBoxPt = fromPointsMaxBoxPt;
  302. maxBoxPt.x = xMax.x;
  303. maxBoxPt.y = yMax.y;
  304. maxBoxPt.z = zMax.z;
  305. const naiveCenter = Matrix2.Cartesian3.midpoint(
  306. minBoxPt,
  307. maxBoxPt,
  308. fromPointsNaiveCenterScratch
  309. );
  310. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  311. let naiveRadius = 0;
  312. for (i = 0; i < numPositions; i++) {
  313. Matrix2.Cartesian3.clone(positions[i], currentPos);
  314. // Find the furthest point from the naive center to calculate the naive radius.
  315. const r = Matrix2.Cartesian3.magnitude(
  316. Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  317. );
  318. if (r > naiveRadius) {
  319. naiveRadius = r;
  320. }
  321. // Make adjustments to the Ritter Sphere to include all points.
  322. const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
  323. Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  324. );
  325. if (oldCenterToPointSquared > radiusSquared) {
  326. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  327. // Calculate new radius to include the point that lies outside
  328. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  329. radiusSquared = ritterRadius * ritterRadius;
  330. // Calculate center of new Ritter sphere
  331. const oldToNew = oldCenterToPoint - ritterRadius;
  332. ritterCenter.x =
  333. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  334. oldCenterToPoint;
  335. ritterCenter.y =
  336. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  337. oldCenterToPoint;
  338. ritterCenter.z =
  339. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  340. oldCenterToPoint;
  341. }
  342. }
  343. if (ritterRadius < naiveRadius) {
  344. Matrix2.Cartesian3.clone(ritterCenter, result.center);
  345. result.radius = ritterRadius;
  346. } else {
  347. Matrix2.Cartesian3.clone(naiveCenter, result.center);
  348. result.radius = naiveRadius;
  349. }
  350. return result;
  351. };
  352. const defaultProjection = new GeographicProjection();
  353. const fromRectangle2DLowerLeft = new Matrix2.Cartesian3();
  354. const fromRectangle2DUpperRight = new Matrix2.Cartesian3();
  355. const fromRectangle2DSouthwest = new Matrix2.Cartographic();
  356. const fromRectangle2DNortheast = new Matrix2.Cartographic();
  357. /**
  358. * Computes a bounding sphere from a rectangle projected in 2D.
  359. *
  360. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  361. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  362. * @param {BoundingSphere} [result] The object onto which to store the result.
  363. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  364. */
  365. BoundingSphere.fromRectangle2D = function (rectangle, projection, result) {
  366. return BoundingSphere.fromRectangleWithHeights2D(
  367. rectangle,
  368. projection,
  369. 0.0,
  370. 0.0,
  371. result
  372. );
  373. };
  374. /**
  375. * Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
  376. * object's minimum and maximum heights over the rectangle.
  377. *
  378. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  379. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  380. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  381. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  382. * @param {BoundingSphere} [result] The object onto which to store the result.
  383. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  384. */
  385. BoundingSphere.fromRectangleWithHeights2D = function (
  386. rectangle,
  387. projection,
  388. minimumHeight,
  389. maximumHeight,
  390. result
  391. ) {
  392. if (!defaultValue.defined(result)) {
  393. result = new BoundingSphere();
  394. }
  395. if (!defaultValue.defined(rectangle)) {
  396. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  397. result.radius = 0.0;
  398. return result;
  399. }
  400. projection = defaultValue.defaultValue(projection, defaultProjection);
  401. Matrix2.Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  402. fromRectangle2DSouthwest.height = minimumHeight;
  403. Matrix2.Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  404. fromRectangle2DNortheast.height = maximumHeight;
  405. const lowerLeft = projection.project(
  406. fromRectangle2DSouthwest,
  407. fromRectangle2DLowerLeft
  408. );
  409. const upperRight = projection.project(
  410. fromRectangle2DNortheast,
  411. fromRectangle2DUpperRight
  412. );
  413. const width = upperRight.x - lowerLeft.x;
  414. const height = upperRight.y - lowerLeft.y;
  415. const elevation = upperRight.z - lowerLeft.z;
  416. result.radius =
  417. Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  418. const center = result.center;
  419. center.x = lowerLeft.x + width * 0.5;
  420. center.y = lowerLeft.y + height * 0.5;
  421. center.z = lowerLeft.z + elevation * 0.5;
  422. return result;
  423. };
  424. const fromRectangle3DScratch = [];
  425. /**
  426. * Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
  427. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  428. *
  429. * @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
  430. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  431. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  432. * @param {BoundingSphere} [result] The object onto which to store the result.
  433. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  434. */
  435. BoundingSphere.fromRectangle3D = function (
  436. rectangle,
  437. ellipsoid,
  438. surfaceHeight,
  439. result
  440. ) {
  441. ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  442. surfaceHeight = defaultValue.defaultValue(surfaceHeight, 0.0);
  443. if (!defaultValue.defined(result)) {
  444. result = new BoundingSphere();
  445. }
  446. if (!defaultValue.defined(rectangle)) {
  447. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  448. result.radius = 0.0;
  449. return result;
  450. }
  451. const positions = Matrix2.Rectangle.subsample(
  452. rectangle,
  453. ellipsoid,
  454. surfaceHeight,
  455. fromRectangle3DScratch
  456. );
  457. return BoundingSphere.fromPoints(positions, result);
  458. };
  459. /**
  460. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  461. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  462. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  463. * ensure a tight fit.
  464. *
  465. * @param {Number[]} [positions] An array of points that the bounding sphere will enclose. Each point
  466. * is formed from three elements in the array in the order X, Y, Z.
  467. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  468. * origin of the coordinate system. This is useful when the positions are to be used for
  469. * relative-to-center (RTC) rendering.
  470. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  471. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  472. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  473. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  474. * the stride is 5, however, two array elements are skipped and the next position begins at array
  475. * index 5.
  476. * @param {BoundingSphere} [result] The object onto which to store the result.
  477. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  478. *
  479. * @example
  480. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  481. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  482. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  483. * const center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  484. * const points = [1.0, 2.0, 3.0, 0.1, 0.2,
  485. * 4.0, 5.0, 6.0, 0.1, 0.2,
  486. * 7.0, 8.0, 9.0, 0.1, 0.2];
  487. * const sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  488. *
  489. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  490. */
  491. BoundingSphere.fromVertices = function (positions, center, stride, result) {
  492. if (!defaultValue.defined(result)) {
  493. result = new BoundingSphere();
  494. }
  495. if (!defaultValue.defined(positions) || positions.length === 0) {
  496. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  497. result.radius = 0.0;
  498. return result;
  499. }
  500. center = defaultValue.defaultValue(center, Matrix2.Cartesian3.ZERO);
  501. stride = defaultValue.defaultValue(stride, 3);
  502. //>>includeStart('debug', pragmas.debug);
  503. RuntimeError.Check.typeOf.number.greaterThanOrEquals("stride", stride, 3);
  504. //>>includeEnd('debug');
  505. const currentPos = fromPointsCurrentPos;
  506. currentPos.x = positions[0] + center.x;
  507. currentPos.y = positions[1] + center.y;
  508. currentPos.z = positions[2] + center.z;
  509. const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
  510. const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
  511. const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
  512. const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
  513. const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
  514. const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
  515. const numElements = positions.length;
  516. let i;
  517. for (i = 0; i < numElements; i += stride) {
  518. const x = positions[i] + center.x;
  519. const y = positions[i + 1] + center.y;
  520. const z = positions[i + 2] + center.z;
  521. currentPos.x = x;
  522. currentPos.y = y;
  523. currentPos.z = z;
  524. // Store points containing the the smallest and largest components
  525. if (x < xMin.x) {
  526. Matrix2.Cartesian3.clone(currentPos, xMin);
  527. }
  528. if (x > xMax.x) {
  529. Matrix2.Cartesian3.clone(currentPos, xMax);
  530. }
  531. if (y < yMin.y) {
  532. Matrix2.Cartesian3.clone(currentPos, yMin);
  533. }
  534. if (y > yMax.y) {
  535. Matrix2.Cartesian3.clone(currentPos, yMax);
  536. }
  537. if (z < zMin.z) {
  538. Matrix2.Cartesian3.clone(currentPos, zMin);
  539. }
  540. if (z > zMax.z) {
  541. Matrix2.Cartesian3.clone(currentPos, zMax);
  542. }
  543. }
  544. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  545. const xSpan = Matrix2.Cartesian3.magnitudeSquared(
  546. Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  547. );
  548. const ySpan = Matrix2.Cartesian3.magnitudeSquared(
  549. Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  550. );
  551. const zSpan = Matrix2.Cartesian3.magnitudeSquared(
  552. Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  553. );
  554. // Set the diameter endpoints to the largest span.
  555. let diameter1 = xMin;
  556. let diameter2 = xMax;
  557. let maxSpan = xSpan;
  558. if (ySpan > maxSpan) {
  559. maxSpan = ySpan;
  560. diameter1 = yMin;
  561. diameter2 = yMax;
  562. }
  563. if (zSpan > maxSpan) {
  564. maxSpan = zSpan;
  565. diameter1 = zMin;
  566. diameter2 = zMax;
  567. }
  568. // Calculate the center of the initial sphere found by Ritter's algorithm
  569. const ritterCenter = fromPointsRitterCenter;
  570. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  571. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  572. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  573. // Calculate the radius of the initial sphere found by Ritter's algorithm
  574. let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
  575. Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  576. );
  577. let ritterRadius = Math.sqrt(radiusSquared);
  578. // Find the center of the sphere found using the Naive method.
  579. const minBoxPt = fromPointsMinBoxPt;
  580. minBoxPt.x = xMin.x;
  581. minBoxPt.y = yMin.y;
  582. minBoxPt.z = zMin.z;
  583. const maxBoxPt = fromPointsMaxBoxPt;
  584. maxBoxPt.x = xMax.x;
  585. maxBoxPt.y = yMax.y;
  586. maxBoxPt.z = zMax.z;
  587. const naiveCenter = Matrix2.Cartesian3.midpoint(
  588. minBoxPt,
  589. maxBoxPt,
  590. fromPointsNaiveCenterScratch
  591. );
  592. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  593. let naiveRadius = 0;
  594. for (i = 0; i < numElements; i += stride) {
  595. currentPos.x = positions[i] + center.x;
  596. currentPos.y = positions[i + 1] + center.y;
  597. currentPos.z = positions[i + 2] + center.z;
  598. // Find the furthest point from the naive center to calculate the naive radius.
  599. const r = Matrix2.Cartesian3.magnitude(
  600. Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  601. );
  602. if (r > naiveRadius) {
  603. naiveRadius = r;
  604. }
  605. // Make adjustments to the Ritter Sphere to include all points.
  606. const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
  607. Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  608. );
  609. if (oldCenterToPointSquared > radiusSquared) {
  610. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  611. // Calculate new radius to include the point that lies outside
  612. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  613. radiusSquared = ritterRadius * ritterRadius;
  614. // Calculate center of new Ritter sphere
  615. const oldToNew = oldCenterToPoint - ritterRadius;
  616. ritterCenter.x =
  617. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  618. oldCenterToPoint;
  619. ritterCenter.y =
  620. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  621. oldCenterToPoint;
  622. ritterCenter.z =
  623. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  624. oldCenterToPoint;
  625. }
  626. }
  627. if (ritterRadius < naiveRadius) {
  628. Matrix2.Cartesian3.clone(ritterCenter, result.center);
  629. result.radius = ritterRadius;
  630. } else {
  631. Matrix2.Cartesian3.clone(naiveCenter, result.center);
  632. result.radius = naiveRadius;
  633. }
  634. return result;
  635. };
  636. /**
  637. * Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
  638. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  639. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  640. * ensure a tight fit.
  641. *
  642. * @param {Number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  643. * is formed from three elements in the array in the order X, Y, Z.
  644. * @param {Number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  645. * is formed from three elements in the array in the order X, Y, Z.
  646. * @param {BoundingSphere} [result] The object onto which to store the result.
  647. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  648. *
  649. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  650. */
  651. BoundingSphere.fromEncodedCartesianVertices = function (
  652. positionsHigh,
  653. positionsLow,
  654. result
  655. ) {
  656. if (!defaultValue.defined(result)) {
  657. result = new BoundingSphere();
  658. }
  659. if (
  660. !defaultValue.defined(positionsHigh) ||
  661. !defaultValue.defined(positionsLow) ||
  662. positionsHigh.length !== positionsLow.length ||
  663. positionsHigh.length === 0
  664. ) {
  665. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  666. result.radius = 0.0;
  667. return result;
  668. }
  669. const currentPos = fromPointsCurrentPos;
  670. currentPos.x = positionsHigh[0] + positionsLow[0];
  671. currentPos.y = positionsHigh[1] + positionsLow[1];
  672. currentPos.z = positionsHigh[2] + positionsLow[2];
  673. const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
  674. const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
  675. const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
  676. const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
  677. const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
  678. const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
  679. const numElements = positionsHigh.length;
  680. let i;
  681. for (i = 0; i < numElements; i += 3) {
  682. const x = positionsHigh[i] + positionsLow[i];
  683. const y = positionsHigh[i + 1] + positionsLow[i + 1];
  684. const z = positionsHigh[i + 2] + positionsLow[i + 2];
  685. currentPos.x = x;
  686. currentPos.y = y;
  687. currentPos.z = z;
  688. // Store points containing the the smallest and largest components
  689. if (x < xMin.x) {
  690. Matrix2.Cartesian3.clone(currentPos, xMin);
  691. }
  692. if (x > xMax.x) {
  693. Matrix2.Cartesian3.clone(currentPos, xMax);
  694. }
  695. if (y < yMin.y) {
  696. Matrix2.Cartesian3.clone(currentPos, yMin);
  697. }
  698. if (y > yMax.y) {
  699. Matrix2.Cartesian3.clone(currentPos, yMax);
  700. }
  701. if (z < zMin.z) {
  702. Matrix2.Cartesian3.clone(currentPos, zMin);
  703. }
  704. if (z > zMax.z) {
  705. Matrix2.Cartesian3.clone(currentPos, zMax);
  706. }
  707. }
  708. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  709. const xSpan = Matrix2.Cartesian3.magnitudeSquared(
  710. Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  711. );
  712. const ySpan = Matrix2.Cartesian3.magnitudeSquared(
  713. Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  714. );
  715. const zSpan = Matrix2.Cartesian3.magnitudeSquared(
  716. Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  717. );
  718. // Set the diameter endpoints to the largest span.
  719. let diameter1 = xMin;
  720. let diameter2 = xMax;
  721. let maxSpan = xSpan;
  722. if (ySpan > maxSpan) {
  723. maxSpan = ySpan;
  724. diameter1 = yMin;
  725. diameter2 = yMax;
  726. }
  727. if (zSpan > maxSpan) {
  728. maxSpan = zSpan;
  729. diameter1 = zMin;
  730. diameter2 = zMax;
  731. }
  732. // Calculate the center of the initial sphere found by Ritter's algorithm
  733. const ritterCenter = fromPointsRitterCenter;
  734. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  735. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  736. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  737. // Calculate the radius of the initial sphere found by Ritter's algorithm
  738. let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
  739. Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  740. );
  741. let ritterRadius = Math.sqrt(radiusSquared);
  742. // Find the center of the sphere found using the Naive method.
  743. const minBoxPt = fromPointsMinBoxPt;
  744. minBoxPt.x = xMin.x;
  745. minBoxPt.y = yMin.y;
  746. minBoxPt.z = zMin.z;
  747. const maxBoxPt = fromPointsMaxBoxPt;
  748. maxBoxPt.x = xMax.x;
  749. maxBoxPt.y = yMax.y;
  750. maxBoxPt.z = zMax.z;
  751. const naiveCenter = Matrix2.Cartesian3.midpoint(
  752. minBoxPt,
  753. maxBoxPt,
  754. fromPointsNaiveCenterScratch
  755. );
  756. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  757. let naiveRadius = 0;
  758. for (i = 0; i < numElements; i += 3) {
  759. currentPos.x = positionsHigh[i] + positionsLow[i];
  760. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  761. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  762. // Find the furthest point from the naive center to calculate the naive radius.
  763. const r = Matrix2.Cartesian3.magnitude(
  764. Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  765. );
  766. if (r > naiveRadius) {
  767. naiveRadius = r;
  768. }
  769. // Make adjustments to the Ritter Sphere to include all points.
  770. const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
  771. Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  772. );
  773. if (oldCenterToPointSquared > radiusSquared) {
  774. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  775. // Calculate new radius to include the point that lies outside
  776. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  777. radiusSquared = ritterRadius * ritterRadius;
  778. // Calculate center of new Ritter sphere
  779. const oldToNew = oldCenterToPoint - ritterRadius;
  780. ritterCenter.x =
  781. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  782. oldCenterToPoint;
  783. ritterCenter.y =
  784. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  785. oldCenterToPoint;
  786. ritterCenter.z =
  787. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  788. oldCenterToPoint;
  789. }
  790. }
  791. if (ritterRadius < naiveRadius) {
  792. Matrix2.Cartesian3.clone(ritterCenter, result.center);
  793. result.radius = ritterRadius;
  794. } else {
  795. Matrix2.Cartesian3.clone(naiveCenter, result.center);
  796. result.radius = naiveRadius;
  797. }
  798. return result;
  799. };
  800. /**
  801. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  802. * tightly and fully encompasses the box.
  803. *
  804. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  805. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  806. * @param {BoundingSphere} [result] The object onto which to store the result.
  807. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  808. *
  809. * @example
  810. * // Create a bounding sphere around the unit cube
  811. * const sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  812. */
  813. BoundingSphere.fromCornerPoints = function (corner, oppositeCorner, result) {
  814. //>>includeStart('debug', pragmas.debug);
  815. RuntimeError.Check.typeOf.object("corner", corner);
  816. RuntimeError.Check.typeOf.object("oppositeCorner", oppositeCorner);
  817. //>>includeEnd('debug');
  818. if (!defaultValue.defined(result)) {
  819. result = new BoundingSphere();
  820. }
  821. const center = Matrix2.Cartesian3.midpoint(corner, oppositeCorner, result.center);
  822. result.radius = Matrix2.Cartesian3.distance(center, oppositeCorner);
  823. return result;
  824. };
  825. /**
  826. * Creates a bounding sphere encompassing an ellipsoid.
  827. *
  828. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  829. * @param {BoundingSphere} [result] The object onto which to store the result.
  830. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  831. *
  832. * @example
  833. * const boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  834. */
  835. BoundingSphere.fromEllipsoid = function (ellipsoid, result) {
  836. //>>includeStart('debug', pragmas.debug);
  837. RuntimeError.Check.typeOf.object("ellipsoid", ellipsoid);
  838. //>>includeEnd('debug');
  839. if (!defaultValue.defined(result)) {
  840. result = new BoundingSphere();
  841. }
  842. Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  843. result.radius = ellipsoid.maximumRadius;
  844. return result;
  845. };
  846. const fromBoundingSpheresScratch = new Matrix2.Cartesian3();
  847. /**
  848. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  849. *
  850. * @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
  851. * @param {BoundingSphere} [result] The object onto which to store the result.
  852. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  853. */
  854. BoundingSphere.fromBoundingSpheres = function (boundingSpheres, result) {
  855. if (!defaultValue.defined(result)) {
  856. result = new BoundingSphere();
  857. }
  858. if (!defaultValue.defined(boundingSpheres) || boundingSpheres.length === 0) {
  859. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  860. result.radius = 0.0;
  861. return result;
  862. }
  863. const length = boundingSpheres.length;
  864. if (length === 1) {
  865. return BoundingSphere.clone(boundingSpheres[0], result);
  866. }
  867. if (length === 2) {
  868. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  869. }
  870. const positions = [];
  871. let i;
  872. for (i = 0; i < length; i++) {
  873. positions.push(boundingSpheres[i].center);
  874. }
  875. result = BoundingSphere.fromPoints(positions, result);
  876. const center = result.center;
  877. let radius = result.radius;
  878. for (i = 0; i < length; i++) {
  879. const tmp = boundingSpheres[i];
  880. radius = Math.max(
  881. radius,
  882. Matrix2.Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) +
  883. tmp.radius
  884. );
  885. }
  886. result.radius = radius;
  887. return result;
  888. };
  889. const fromOrientedBoundingBoxScratchU = new Matrix2.Cartesian3();
  890. const fromOrientedBoundingBoxScratchV = new Matrix2.Cartesian3();
  891. const fromOrientedBoundingBoxScratchW = new Matrix2.Cartesian3();
  892. /**
  893. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  894. *
  895. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  896. * @param {BoundingSphere} [result] The object onto which to store the result.
  897. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  898. */
  899. BoundingSphere.fromOrientedBoundingBox = function (
  900. orientedBoundingBox,
  901. result
  902. ) {
  903. //>>includeStart('debug', pragmas.debug);
  904. RuntimeError.Check.defined("orientedBoundingBox", orientedBoundingBox);
  905. //>>includeEnd('debug');
  906. if (!defaultValue.defined(result)) {
  907. result = new BoundingSphere();
  908. }
  909. const halfAxes = orientedBoundingBox.halfAxes;
  910. const u = Matrix2.Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  911. const v = Matrix2.Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  912. const w = Matrix2.Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  913. Matrix2.Cartesian3.add(u, v, u);
  914. Matrix2.Cartesian3.add(u, w, u);
  915. result.center = Matrix2.Cartesian3.clone(orientedBoundingBox.center, result.center);
  916. result.radius = Matrix2.Cartesian3.magnitude(u);
  917. return result;
  918. };
  919. const scratchFromTransformationCenter = new Matrix2.Cartesian3();
  920. const scratchFromTransformationScale = new Matrix2.Cartesian3();
  921. /**
  922. * Computes a tight-fitting bounding sphere enclosing the provided affine transformation.
  923. *
  924. * @param {Matrix4} transformation The affine transformation.
  925. * @param {BoundingSphere} [result] The object onto which to store the result.
  926. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  927. */
  928. BoundingSphere.fromTransformation = function (transformation, result) {
  929. //>>includeStart('debug', pragmas.debug);
  930. RuntimeError.Check.typeOf.object("transformation", transformation);
  931. //>>includeEnd('debug');
  932. if (!defaultValue.defined(result)) {
  933. result = new BoundingSphere();
  934. }
  935. const center = Matrix2.Matrix4.getTranslation(
  936. transformation,
  937. scratchFromTransformationCenter
  938. );
  939. const scale = Matrix2.Matrix4.getScale(
  940. transformation,
  941. scratchFromTransformationScale
  942. );
  943. const radius = 0.5 * Matrix2.Cartesian3.magnitude(scale);
  944. result.center = Matrix2.Cartesian3.clone(center, result.center);
  945. result.radius = radius;
  946. return result;
  947. };
  948. /**
  949. * Duplicates a BoundingSphere instance.
  950. *
  951. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  952. * @param {BoundingSphere} [result] The object onto which to store the result.
  953. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  954. */
  955. BoundingSphere.clone = function (sphere, result) {
  956. if (!defaultValue.defined(sphere)) {
  957. return undefined;
  958. }
  959. if (!defaultValue.defined(result)) {
  960. return new BoundingSphere(sphere.center, sphere.radius);
  961. }
  962. result.center = Matrix2.Cartesian3.clone(sphere.center, result.center);
  963. result.radius = sphere.radius;
  964. return result;
  965. };
  966. /**
  967. * The number of elements used to pack the object into an array.
  968. * @type {Number}
  969. */
  970. BoundingSphere.packedLength = 4;
  971. /**
  972. * Stores the provided instance into the provided array.
  973. *
  974. * @param {BoundingSphere} value The value to pack.
  975. * @param {Number[]} array The array to pack into.
  976. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  977. *
  978. * @returns {Number[]} The array that was packed into
  979. */
  980. BoundingSphere.pack = function (value, array, startingIndex) {
  981. //>>includeStart('debug', pragmas.debug);
  982. RuntimeError.Check.typeOf.object("value", value);
  983. RuntimeError.Check.defined("array", array);
  984. //>>includeEnd('debug');
  985. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  986. const center = value.center;
  987. array[startingIndex++] = center.x;
  988. array[startingIndex++] = center.y;
  989. array[startingIndex++] = center.z;
  990. array[startingIndex] = value.radius;
  991. return array;
  992. };
  993. /**
  994. * Retrieves an instance from a packed array.
  995. *
  996. * @param {Number[]} array The packed array.
  997. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  998. * @param {BoundingSphere} [result] The object into which to store the result.
  999. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  1000. */
  1001. BoundingSphere.unpack = function (array, startingIndex, result) {
  1002. //>>includeStart('debug', pragmas.debug);
  1003. RuntimeError.Check.defined("array", array);
  1004. //>>includeEnd('debug');
  1005. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  1006. if (!defaultValue.defined(result)) {
  1007. result = new BoundingSphere();
  1008. }
  1009. const center = result.center;
  1010. center.x = array[startingIndex++];
  1011. center.y = array[startingIndex++];
  1012. center.z = array[startingIndex++];
  1013. result.radius = array[startingIndex];
  1014. return result;
  1015. };
  1016. const unionScratch = new Matrix2.Cartesian3();
  1017. const unionScratchCenter = new Matrix2.Cartesian3();
  1018. /**
  1019. * Computes a bounding sphere that contains both the left and right bounding spheres.
  1020. *
  1021. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  1022. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  1023. * @param {BoundingSphere} [result] The object onto which to store the result.
  1024. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1025. */
  1026. BoundingSphere.union = function (left, right, result) {
  1027. //>>includeStart('debug', pragmas.debug);
  1028. RuntimeError.Check.typeOf.object("left", left);
  1029. RuntimeError.Check.typeOf.object("right", right);
  1030. //>>includeEnd('debug');
  1031. if (!defaultValue.defined(result)) {
  1032. result = new BoundingSphere();
  1033. }
  1034. const leftCenter = left.center;
  1035. const leftRadius = left.radius;
  1036. const rightCenter = right.center;
  1037. const rightRadius = right.radius;
  1038. const toRightCenter = Matrix2.Cartesian3.subtract(
  1039. rightCenter,
  1040. leftCenter,
  1041. unionScratch
  1042. );
  1043. const centerSeparation = Matrix2.Cartesian3.magnitude(toRightCenter);
  1044. if (leftRadius >= centerSeparation + rightRadius) {
  1045. // Left sphere wins.
  1046. left.clone(result);
  1047. return result;
  1048. }
  1049. if (rightRadius >= centerSeparation + leftRadius) {
  1050. // Right sphere wins.
  1051. right.clone(result);
  1052. return result;
  1053. }
  1054. // There are two tangent points, one on far side of each sphere.
  1055. const halfDistanceBetweenTangentPoints =
  1056. (leftRadius + centerSeparation + rightRadius) * 0.5;
  1057. // Compute the center point halfway between the two tangent points.
  1058. const center = Matrix2.Cartesian3.multiplyByScalar(
  1059. toRightCenter,
  1060. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
  1061. unionScratchCenter
  1062. );
  1063. Matrix2.Cartesian3.add(center, leftCenter, center);
  1064. Matrix2.Cartesian3.clone(center, result.center);
  1065. result.radius = halfDistanceBetweenTangentPoints;
  1066. return result;
  1067. };
  1068. const expandScratch = new Matrix2.Cartesian3();
  1069. /**
  1070. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  1071. *
  1072. * @param {BoundingSphere} sphere A sphere to expand.
  1073. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  1074. * @param {BoundingSphere} [result] The object onto which to store the result.
  1075. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1076. */
  1077. BoundingSphere.expand = function (sphere, point, result) {
  1078. //>>includeStart('debug', pragmas.debug);
  1079. RuntimeError.Check.typeOf.object("sphere", sphere);
  1080. RuntimeError.Check.typeOf.object("point", point);
  1081. //>>includeEnd('debug');
  1082. result = BoundingSphere.clone(sphere, result);
  1083. const radius = Matrix2.Cartesian3.magnitude(
  1084. Matrix2.Cartesian3.subtract(point, result.center, expandScratch)
  1085. );
  1086. if (radius > result.radius) {
  1087. result.radius = radius;
  1088. }
  1089. return result;
  1090. };
  1091. /**
  1092. * Determines which side of a plane a sphere is located.
  1093. *
  1094. * @param {BoundingSphere} sphere The bounding sphere to test.
  1095. * @param {Plane} plane The plane to test against.
  1096. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  1097. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  1098. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  1099. * intersects the plane.
  1100. */
  1101. BoundingSphere.intersectPlane = function (sphere, plane) {
  1102. //>>includeStart('debug', pragmas.debug);
  1103. RuntimeError.Check.typeOf.object("sphere", sphere);
  1104. RuntimeError.Check.typeOf.object("plane", plane);
  1105. //>>includeEnd('debug');
  1106. const center = sphere.center;
  1107. const radius = sphere.radius;
  1108. const normal = plane.normal;
  1109. const distanceToPlane = Matrix2.Cartesian3.dot(normal, center) + plane.distance;
  1110. if (distanceToPlane < -radius) {
  1111. // The center point is negative side of the plane normal
  1112. return Intersect$1.OUTSIDE;
  1113. } else if (distanceToPlane < radius) {
  1114. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  1115. return Intersect$1.INTERSECTING;
  1116. }
  1117. return Intersect$1.INSIDE;
  1118. };
  1119. /**
  1120. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  1121. *
  1122. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  1123. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  1124. * @param {BoundingSphere} [result] The object onto which to store the result.
  1125. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1126. */
  1127. BoundingSphere.transform = function (sphere, transform, result) {
  1128. //>>includeStart('debug', pragmas.debug);
  1129. RuntimeError.Check.typeOf.object("sphere", sphere);
  1130. RuntimeError.Check.typeOf.object("transform", transform);
  1131. //>>includeEnd('debug');
  1132. if (!defaultValue.defined(result)) {
  1133. result = new BoundingSphere();
  1134. }
  1135. result.center = Matrix2.Matrix4.multiplyByPoint(
  1136. transform,
  1137. sphere.center,
  1138. result.center
  1139. );
  1140. result.radius = Matrix2.Matrix4.getMaximumScale(transform) * sphere.radius;
  1141. return result;
  1142. };
  1143. const distanceSquaredToScratch = new Matrix2.Cartesian3();
  1144. /**
  1145. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  1146. *
  1147. * @param {BoundingSphere} sphere The sphere.
  1148. * @param {Cartesian3} cartesian The point
  1149. * @returns {Number} The distance squared from the bounding sphere to the point. Returns 0 if the point is inside the sphere.
  1150. *
  1151. * @example
  1152. * // Sort bounding spheres from back to front
  1153. * spheres.sort(function(a, b) {
  1154. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  1155. * });
  1156. */
  1157. BoundingSphere.distanceSquaredTo = function (sphere, cartesian) {
  1158. //>>includeStart('debug', pragmas.debug);
  1159. RuntimeError.Check.typeOf.object("sphere", sphere);
  1160. RuntimeError.Check.typeOf.object("cartesian", cartesian);
  1161. //>>includeEnd('debug');
  1162. const diff = Matrix2.Cartesian3.subtract(
  1163. sphere.center,
  1164. cartesian,
  1165. distanceSquaredToScratch
  1166. );
  1167. const distance = Matrix2.Cartesian3.magnitude(diff) - sphere.radius;
  1168. if (distance <= 0.0) {
  1169. return 0.0;
  1170. }
  1171. return distance * distance;
  1172. };
  1173. /**
  1174. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  1175. * The transformation matrix is not verified to have a uniform scale of 1.
  1176. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  1177. *
  1178. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  1179. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  1180. * @param {BoundingSphere} [result] The object onto which to store the result.
  1181. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1182. *
  1183. * @example
  1184. * const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  1185. * const boundingSphere = new Cesium.BoundingSphere();
  1186. * const newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  1187. */
  1188. BoundingSphere.transformWithoutScale = function (sphere, transform, result) {
  1189. //>>includeStart('debug', pragmas.debug);
  1190. RuntimeError.Check.typeOf.object("sphere", sphere);
  1191. RuntimeError.Check.typeOf.object("transform", transform);
  1192. //>>includeEnd('debug');
  1193. if (!defaultValue.defined(result)) {
  1194. result = new BoundingSphere();
  1195. }
  1196. result.center = Matrix2.Matrix4.multiplyByPoint(
  1197. transform,
  1198. sphere.center,
  1199. result.center
  1200. );
  1201. result.radius = sphere.radius;
  1202. return result;
  1203. };
  1204. const scratchCartesian3 = new Matrix2.Cartesian3();
  1205. /**
  1206. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  1207. * plus/minus the radius of the bounding sphere.
  1208. * <br>
  1209. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  1210. * closest and farthest planes from position that intersect the bounding sphere.
  1211. *
  1212. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  1213. * @param {Cartesian3} position The position to calculate the distance from.
  1214. * @param {Cartesian3} direction The direction from position.
  1215. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  1216. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  1217. */
  1218. BoundingSphere.computePlaneDistances = function (
  1219. sphere,
  1220. position,
  1221. direction,
  1222. result
  1223. ) {
  1224. //>>includeStart('debug', pragmas.debug);
  1225. RuntimeError.Check.typeOf.object("sphere", sphere);
  1226. RuntimeError.Check.typeOf.object("position", position);
  1227. RuntimeError.Check.typeOf.object("direction", direction);
  1228. //>>includeEnd('debug');
  1229. if (!defaultValue.defined(result)) {
  1230. result = new Interval();
  1231. }
  1232. const toCenter = Matrix2.Cartesian3.subtract(
  1233. sphere.center,
  1234. position,
  1235. scratchCartesian3
  1236. );
  1237. const mag = Matrix2.Cartesian3.dot(direction, toCenter);
  1238. result.start = mag - sphere.radius;
  1239. result.stop = mag + sphere.radius;
  1240. return result;
  1241. };
  1242. const projectTo2DNormalScratch = new Matrix2.Cartesian3();
  1243. const projectTo2DEastScratch = new Matrix2.Cartesian3();
  1244. const projectTo2DNorthScratch = new Matrix2.Cartesian3();
  1245. const projectTo2DWestScratch = new Matrix2.Cartesian3();
  1246. const projectTo2DSouthScratch = new Matrix2.Cartesian3();
  1247. const projectTo2DCartographicScratch = new Matrix2.Cartographic();
  1248. const projectTo2DPositionsScratch = new Array(8);
  1249. for (let n = 0; n < 8; ++n) {
  1250. projectTo2DPositionsScratch[n] = new Matrix2.Cartesian3();
  1251. }
  1252. const projectTo2DProjection = new GeographicProjection();
  1253. /**
  1254. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  1255. *
  1256. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  1257. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  1258. * @param {BoundingSphere} [result] The object onto which to store the result.
  1259. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1260. */
  1261. BoundingSphere.projectTo2D = function (sphere, projection, result) {
  1262. //>>includeStart('debug', pragmas.debug);
  1263. RuntimeError.Check.typeOf.object("sphere", sphere);
  1264. //>>includeEnd('debug');
  1265. projection = defaultValue.defaultValue(projection, projectTo2DProjection);
  1266. const ellipsoid = projection.ellipsoid;
  1267. let center = sphere.center;
  1268. const radius = sphere.radius;
  1269. let normal;
  1270. if (Matrix2.Cartesian3.equals(center, Matrix2.Cartesian3.ZERO)) {
  1271. // Bounding sphere is at the center. The geodetic surface normal is not
  1272. // defined here so pick the x-axis as a fallback.
  1273. normal = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, projectTo2DNormalScratch);
  1274. } else {
  1275. normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  1276. }
  1277. const east = Matrix2.Cartesian3.cross(
  1278. Matrix2.Cartesian3.UNIT_Z,
  1279. normal,
  1280. projectTo2DEastScratch
  1281. );
  1282. Matrix2.Cartesian3.normalize(east, east);
  1283. const north = Matrix2.Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  1284. Matrix2.Cartesian3.normalize(north, north);
  1285. Matrix2.Cartesian3.multiplyByScalar(normal, radius, normal);
  1286. Matrix2.Cartesian3.multiplyByScalar(north, radius, north);
  1287. Matrix2.Cartesian3.multiplyByScalar(east, radius, east);
  1288. const south = Matrix2.Cartesian3.negate(north, projectTo2DSouthScratch);
  1289. const west = Matrix2.Cartesian3.negate(east, projectTo2DWestScratch);
  1290. const positions = projectTo2DPositionsScratch;
  1291. // top NE corner
  1292. let corner = positions[0];
  1293. Matrix2.Cartesian3.add(normal, north, corner);
  1294. Matrix2.Cartesian3.add(corner, east, corner);
  1295. // top NW corner
  1296. corner = positions[1];
  1297. Matrix2.Cartesian3.add(normal, north, corner);
  1298. Matrix2.Cartesian3.add(corner, west, corner);
  1299. // top SW corner
  1300. corner = positions[2];
  1301. Matrix2.Cartesian3.add(normal, south, corner);
  1302. Matrix2.Cartesian3.add(corner, west, corner);
  1303. // top SE corner
  1304. corner = positions[3];
  1305. Matrix2.Cartesian3.add(normal, south, corner);
  1306. Matrix2.Cartesian3.add(corner, east, corner);
  1307. Matrix2.Cartesian3.negate(normal, normal);
  1308. // bottom NE corner
  1309. corner = positions[4];
  1310. Matrix2.Cartesian3.add(normal, north, corner);
  1311. Matrix2.Cartesian3.add(corner, east, corner);
  1312. // bottom NW corner
  1313. corner = positions[5];
  1314. Matrix2.Cartesian3.add(normal, north, corner);
  1315. Matrix2.Cartesian3.add(corner, west, corner);
  1316. // bottom SW corner
  1317. corner = positions[6];
  1318. Matrix2.Cartesian3.add(normal, south, corner);
  1319. Matrix2.Cartesian3.add(corner, west, corner);
  1320. // bottom SE corner
  1321. corner = positions[7];
  1322. Matrix2.Cartesian3.add(normal, south, corner);
  1323. Matrix2.Cartesian3.add(corner, east, corner);
  1324. const length = positions.length;
  1325. for (let i = 0; i < length; ++i) {
  1326. const position = positions[i];
  1327. Matrix2.Cartesian3.add(center, position, position);
  1328. const cartographic = ellipsoid.cartesianToCartographic(
  1329. position,
  1330. projectTo2DCartographicScratch
  1331. );
  1332. projection.project(cartographic, position);
  1333. }
  1334. result = BoundingSphere.fromPoints(positions, result);
  1335. // swizzle center components
  1336. center = result.center;
  1337. const x = center.x;
  1338. const y = center.y;
  1339. const z = center.z;
  1340. center.x = z;
  1341. center.y = x;
  1342. center.z = y;
  1343. return result;
  1344. };
  1345. /**
  1346. * Determines whether or not a sphere is hidden from view by the occluder.
  1347. *
  1348. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  1349. * @param {Occluder} occluder The occluder.
  1350. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  1351. */
  1352. BoundingSphere.isOccluded = function (sphere, occluder) {
  1353. //>>includeStart('debug', pragmas.debug);
  1354. RuntimeError.Check.typeOf.object("sphere", sphere);
  1355. RuntimeError.Check.typeOf.object("occluder", occluder);
  1356. //>>includeEnd('debug');
  1357. return !occluder.isBoundingSphereVisible(sphere);
  1358. };
  1359. /**
  1360. * Compares the provided BoundingSphere componentwise and returns
  1361. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1362. *
  1363. * @param {BoundingSphere} [left] The first BoundingSphere.
  1364. * @param {BoundingSphere} [right] The second BoundingSphere.
  1365. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1366. */
  1367. BoundingSphere.equals = function (left, right) {
  1368. return (
  1369. left === right ||
  1370. (defaultValue.defined(left) &&
  1371. defaultValue.defined(right) &&
  1372. Matrix2.Cartesian3.equals(left.center, right.center) &&
  1373. left.radius === right.radius)
  1374. );
  1375. };
  1376. /**
  1377. * Determines which side of a plane the sphere is located.
  1378. *
  1379. * @param {Plane} plane The plane to test against.
  1380. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  1381. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  1382. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  1383. * intersects the plane.
  1384. */
  1385. BoundingSphere.prototype.intersectPlane = function (plane) {
  1386. return BoundingSphere.intersectPlane(this, plane);
  1387. };
  1388. /**
  1389. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  1390. *
  1391. * @param {Cartesian3} cartesian The point
  1392. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  1393. *
  1394. * @example
  1395. * // Sort bounding spheres from back to front
  1396. * spheres.sort(function(a, b) {
  1397. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  1398. * });
  1399. */
  1400. BoundingSphere.prototype.distanceSquaredTo = function (cartesian) {
  1401. return BoundingSphere.distanceSquaredTo(this, cartesian);
  1402. };
  1403. /**
  1404. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  1405. * plus/minus the radius of the bounding sphere.
  1406. * <br>
  1407. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  1408. * closest and farthest planes from position that intersect the bounding sphere.
  1409. *
  1410. * @param {Cartesian3} position The position to calculate the distance from.
  1411. * @param {Cartesian3} direction The direction from position.
  1412. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  1413. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  1414. */
  1415. BoundingSphere.prototype.computePlaneDistances = function (
  1416. position,
  1417. direction,
  1418. result
  1419. ) {
  1420. return BoundingSphere.computePlaneDistances(
  1421. this,
  1422. position,
  1423. direction,
  1424. result
  1425. );
  1426. };
  1427. /**
  1428. * Determines whether or not a sphere is hidden from view by the occluder.
  1429. *
  1430. * @param {Occluder} occluder The occluder.
  1431. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  1432. */
  1433. BoundingSphere.prototype.isOccluded = function (occluder) {
  1434. return BoundingSphere.isOccluded(this, occluder);
  1435. };
  1436. /**
  1437. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  1438. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1439. *
  1440. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  1441. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  1442. */
  1443. BoundingSphere.prototype.equals = function (right) {
  1444. return BoundingSphere.equals(this, right);
  1445. };
  1446. /**
  1447. * Duplicates this BoundingSphere instance.
  1448. *
  1449. * @param {BoundingSphere} [result] The object onto which to store the result.
  1450. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1451. */
  1452. BoundingSphere.prototype.clone = function (result) {
  1453. return BoundingSphere.clone(this, result);
  1454. };
  1455. /**
  1456. * Computes the radius of the BoundingSphere.
  1457. * @returns {Number} The radius of the BoundingSphere.
  1458. */
  1459. BoundingSphere.prototype.volume = function () {
  1460. const radius = this.radius;
  1461. return volumeConstant * radius * radius * radius;
  1462. };
  1463. /**
  1464. * A function used to resolve a promise upon completion .
  1465. * @callback defer.resolve
  1466. *
  1467. * @param {*} value The resulting value.
  1468. */
  1469. /**
  1470. * A function used to reject a promise upon failure.
  1471. * @callback defer.reject
  1472. *
  1473. * @param {*} error The error.
  1474. */
  1475. /**
  1476. * An object which contains a promise object, and functions to resolve or reject the promise.
  1477. *
  1478. * @typedef {Object} defer.deferred
  1479. * @property {defer.resolve} resolve Resolves the promise when called.
  1480. * @property {defer.reject} reject Rejects the promise when called.
  1481. * @property {Promise} promise Promise object.
  1482. */
  1483. /**
  1484. * Creates a deferred object, containing a promise object, and functions to resolve or reject the promise.
  1485. * @returns {defer.deferred}
  1486. * @private
  1487. */
  1488. function defer() {
  1489. let resolve;
  1490. let reject;
  1491. const promise = new Promise(function (res, rej) {
  1492. resolve = res;
  1493. reject = rej;
  1494. });
  1495. return {
  1496. resolve: resolve,
  1497. reject: reject,
  1498. promise: promise,
  1499. };
  1500. }
  1501. let _supportsFullscreen;
  1502. const _names = {
  1503. requestFullscreen: undefined,
  1504. exitFullscreen: undefined,
  1505. fullscreenEnabled: undefined,
  1506. fullscreenElement: undefined,
  1507. fullscreenchange: undefined,
  1508. fullscreenerror: undefined,
  1509. };
  1510. /**
  1511. * Browser-independent functions for working with the standard fullscreen API.
  1512. *
  1513. * @namespace Fullscreen
  1514. *
  1515. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  1516. */
  1517. const Fullscreen = {};
  1518. Object.defineProperties(Fullscreen, {
  1519. /**
  1520. * The element that is currently fullscreen, if any. To simply check if the
  1521. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  1522. * @memberof Fullscreen
  1523. * @type {Object}
  1524. * @readonly
  1525. */
  1526. element: {
  1527. get: function () {
  1528. if (!Fullscreen.supportsFullscreen()) {
  1529. return undefined;
  1530. }
  1531. return document[_names.fullscreenElement];
  1532. },
  1533. },
  1534. /**
  1535. * The name of the event on the document that is fired when fullscreen is
  1536. * entered or exited. This event name is intended for use with addEventListener.
  1537. * In your event handler, to determine if the browser is in fullscreen mode or not,
  1538. * use {@link Fullscreen#fullscreen}.
  1539. * @memberof Fullscreen
  1540. * @type {String}
  1541. * @readonly
  1542. */
  1543. changeEventName: {
  1544. get: function () {
  1545. if (!Fullscreen.supportsFullscreen()) {
  1546. return undefined;
  1547. }
  1548. return _names.fullscreenchange;
  1549. },
  1550. },
  1551. /**
  1552. * The name of the event that is fired when a fullscreen error
  1553. * occurs. This event name is intended for use with addEventListener.
  1554. * @memberof Fullscreen
  1555. * @type {String}
  1556. * @readonly
  1557. */
  1558. errorEventName: {
  1559. get: function () {
  1560. if (!Fullscreen.supportsFullscreen()) {
  1561. return undefined;
  1562. }
  1563. return _names.fullscreenerror;
  1564. },
  1565. },
  1566. /**
  1567. * Determine whether the browser will allow an element to be made fullscreen, or not.
  1568. * For example, by default, iframes cannot go fullscreen unless the containing page
  1569. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  1570. * @memberof Fullscreen
  1571. * @type {Boolean}
  1572. * @readonly
  1573. */
  1574. enabled: {
  1575. get: function () {
  1576. if (!Fullscreen.supportsFullscreen()) {
  1577. return undefined;
  1578. }
  1579. return document[_names.fullscreenEnabled];
  1580. },
  1581. },
  1582. /**
  1583. * Determines if the browser is currently in fullscreen mode.
  1584. * @memberof Fullscreen
  1585. * @type {Boolean}
  1586. * @readonly
  1587. */
  1588. fullscreen: {
  1589. get: function () {
  1590. if (!Fullscreen.supportsFullscreen()) {
  1591. return undefined;
  1592. }
  1593. return Fullscreen.element !== null;
  1594. },
  1595. },
  1596. });
  1597. /**
  1598. * Detects whether the browser supports the standard fullscreen API.
  1599. *
  1600. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  1601. * <code>false</code> otherwise.
  1602. */
  1603. Fullscreen.supportsFullscreen = function () {
  1604. if (defaultValue.defined(_supportsFullscreen)) {
  1605. return _supportsFullscreen;
  1606. }
  1607. _supportsFullscreen = false;
  1608. const body = document.body;
  1609. if (typeof body.requestFullscreen === "function") {
  1610. // go with the unprefixed, standard set of names
  1611. _names.requestFullscreen = "requestFullscreen";
  1612. _names.exitFullscreen = "exitFullscreen";
  1613. _names.fullscreenEnabled = "fullscreenEnabled";
  1614. _names.fullscreenElement = "fullscreenElement";
  1615. _names.fullscreenchange = "fullscreenchange";
  1616. _names.fullscreenerror = "fullscreenerror";
  1617. _supportsFullscreen = true;
  1618. return _supportsFullscreen;
  1619. }
  1620. //check for the correct combination of prefix plus the various names that browsers use
  1621. const prefixes = ["webkit", "moz", "o", "ms", "khtml"];
  1622. let name;
  1623. for (let i = 0, len = prefixes.length; i < len; ++i) {
  1624. const prefix = prefixes[i];
  1625. // casing of Fullscreen differs across browsers
  1626. name = `${prefix}RequestFullscreen`;
  1627. if (typeof body[name] === "function") {
  1628. _names.requestFullscreen = name;
  1629. _supportsFullscreen = true;
  1630. } else {
  1631. name = `${prefix}RequestFullScreen`;
  1632. if (typeof body[name] === "function") {
  1633. _names.requestFullscreen = name;
  1634. _supportsFullscreen = true;
  1635. }
  1636. }
  1637. // disagreement about whether it's "exit" as per spec, or "cancel"
  1638. name = `${prefix}ExitFullscreen`;
  1639. if (typeof document[name] === "function") {
  1640. _names.exitFullscreen = name;
  1641. } else {
  1642. name = `${prefix}CancelFullScreen`;
  1643. if (typeof document[name] === "function") {
  1644. _names.exitFullscreen = name;
  1645. }
  1646. }
  1647. // casing of Fullscreen differs across browsers
  1648. name = `${prefix}FullscreenEnabled`;
  1649. if (document[name] !== undefined) {
  1650. _names.fullscreenEnabled = name;
  1651. } else {
  1652. name = `${prefix}FullScreenEnabled`;
  1653. if (document[name] !== undefined) {
  1654. _names.fullscreenEnabled = name;
  1655. }
  1656. }
  1657. // casing of Fullscreen differs across browsers
  1658. name = `${prefix}FullscreenElement`;
  1659. if (document[name] !== undefined) {
  1660. _names.fullscreenElement = name;
  1661. } else {
  1662. name = `${prefix}FullScreenElement`;
  1663. if (document[name] !== undefined) {
  1664. _names.fullscreenElement = name;
  1665. }
  1666. }
  1667. // thankfully, event names are all lowercase per spec
  1668. name = `${prefix}fullscreenchange`;
  1669. // event names do not have 'on' in the front, but the property on the document does
  1670. if (document[`on${name}`] !== undefined) {
  1671. //except on IE
  1672. if (prefix === "ms") {
  1673. name = "MSFullscreenChange";
  1674. }
  1675. _names.fullscreenchange = name;
  1676. }
  1677. name = `${prefix}fullscreenerror`;
  1678. if (document[`on${name}`] !== undefined) {
  1679. //except on IE
  1680. if (prefix === "ms") {
  1681. name = "MSFullscreenError";
  1682. }
  1683. _names.fullscreenerror = name;
  1684. }
  1685. }
  1686. return _supportsFullscreen;
  1687. };
  1688. /**
  1689. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  1690. * If fullscreen mode is not supported by the browser, does nothing.
  1691. *
  1692. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  1693. * @param {Object} [vrDevice] The HMDVRDevice device.
  1694. *
  1695. * @example
  1696. * // Put the entire page into fullscreen.
  1697. * Cesium.Fullscreen.requestFullscreen(document.body)
  1698. *
  1699. * // Place only the Cesium canvas into fullscreen.
  1700. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  1701. */
  1702. Fullscreen.requestFullscreen = function (element, vrDevice) {
  1703. if (!Fullscreen.supportsFullscreen()) {
  1704. return;
  1705. }
  1706. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  1707. };
  1708. /**
  1709. * Asynchronously exits fullscreen mode. If the browser is not currently
  1710. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  1711. */
  1712. Fullscreen.exitFullscreen = function () {
  1713. if (!Fullscreen.supportsFullscreen()) {
  1714. return;
  1715. }
  1716. document[_names.exitFullscreen]();
  1717. };
  1718. //For unit tests
  1719. Fullscreen._names = _names;
  1720. let theNavigator;
  1721. if (typeof navigator !== "undefined") {
  1722. theNavigator = navigator;
  1723. } else {
  1724. theNavigator = {};
  1725. }
  1726. function extractVersion(versionString) {
  1727. const parts = versionString.split(".");
  1728. for (let i = 0, len = parts.length; i < len; ++i) {
  1729. parts[i] = parseInt(parts[i], 10);
  1730. }
  1731. return parts;
  1732. }
  1733. let isChromeResult;
  1734. let chromeVersionResult;
  1735. function isChrome() {
  1736. if (!defaultValue.defined(isChromeResult)) {
  1737. isChromeResult = false;
  1738. // Edge contains Chrome in the user agent too
  1739. if (!isEdge()) {
  1740. const fields = / Chrome\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1741. if (fields !== null) {
  1742. isChromeResult = true;
  1743. chromeVersionResult = extractVersion(fields[1]);
  1744. }
  1745. }
  1746. }
  1747. return isChromeResult;
  1748. }
  1749. function chromeVersion() {
  1750. return isChrome() && chromeVersionResult;
  1751. }
  1752. let isSafariResult;
  1753. let safariVersionResult;
  1754. function isSafari() {
  1755. if (!defaultValue.defined(isSafariResult)) {
  1756. isSafariResult = false;
  1757. // Chrome and Edge contain Safari in the user agent too
  1758. if (
  1759. !isChrome() &&
  1760. !isEdge() &&
  1761. / Safari\/[\.0-9]+/.test(theNavigator.userAgent)
  1762. ) {
  1763. const fields = / Version\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1764. if (fields !== null) {
  1765. isSafariResult = true;
  1766. safariVersionResult = extractVersion(fields[1]);
  1767. }
  1768. }
  1769. }
  1770. return isSafariResult;
  1771. }
  1772. function safariVersion() {
  1773. return isSafari() && safariVersionResult;
  1774. }
  1775. let isWebkitResult;
  1776. let webkitVersionResult;
  1777. function isWebkit() {
  1778. if (!defaultValue.defined(isWebkitResult)) {
  1779. isWebkitResult = false;
  1780. const fields = / AppleWebKit\/([\.0-9]+)(\+?)/.exec(theNavigator.userAgent);
  1781. if (fields !== null) {
  1782. isWebkitResult = true;
  1783. webkitVersionResult = extractVersion(fields[1]);
  1784. webkitVersionResult.isNightly = !!fields[2];
  1785. }
  1786. }
  1787. return isWebkitResult;
  1788. }
  1789. function webkitVersion() {
  1790. return isWebkit() && webkitVersionResult;
  1791. }
  1792. let isInternetExplorerResult;
  1793. let internetExplorerVersionResult;
  1794. function isInternetExplorer() {
  1795. if (!defaultValue.defined(isInternetExplorerResult)) {
  1796. isInternetExplorerResult = false;
  1797. let fields;
  1798. if (theNavigator.appName === "Microsoft Internet Explorer") {
  1799. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  1800. if (fields !== null) {
  1801. isInternetExplorerResult = true;
  1802. internetExplorerVersionResult = extractVersion(fields[1]);
  1803. }
  1804. } else if (theNavigator.appName === "Netscape") {
  1805. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(
  1806. theNavigator.userAgent
  1807. );
  1808. if (fields !== null) {
  1809. isInternetExplorerResult = true;
  1810. internetExplorerVersionResult = extractVersion(fields[1]);
  1811. }
  1812. }
  1813. }
  1814. return isInternetExplorerResult;
  1815. }
  1816. function internetExplorerVersion() {
  1817. return isInternetExplorer() && internetExplorerVersionResult;
  1818. }
  1819. let isEdgeResult;
  1820. let edgeVersionResult;
  1821. function isEdge() {
  1822. if (!defaultValue.defined(isEdgeResult)) {
  1823. isEdgeResult = false;
  1824. const fields = / Edg\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1825. if (fields !== null) {
  1826. isEdgeResult = true;
  1827. edgeVersionResult = extractVersion(fields[1]);
  1828. }
  1829. }
  1830. return isEdgeResult;
  1831. }
  1832. function edgeVersion() {
  1833. return isEdge() && edgeVersionResult;
  1834. }
  1835. let isFirefoxResult;
  1836. let firefoxVersionResult;
  1837. function isFirefox() {
  1838. if (!defaultValue.defined(isFirefoxResult)) {
  1839. isFirefoxResult = false;
  1840. const fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1841. if (fields !== null) {
  1842. isFirefoxResult = true;
  1843. firefoxVersionResult = extractVersion(fields[1]);
  1844. }
  1845. }
  1846. return isFirefoxResult;
  1847. }
  1848. let isWindowsResult;
  1849. function isWindows() {
  1850. if (!defaultValue.defined(isWindowsResult)) {
  1851. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  1852. }
  1853. return isWindowsResult;
  1854. }
  1855. let isIPadOrIOSResult;
  1856. function isIPadOrIOS() {
  1857. if (!defaultValue.defined(isIPadOrIOSResult)) {
  1858. isIPadOrIOSResult =
  1859. navigator.platform === "iPhone" ||
  1860. navigator.platform === "iPod" ||
  1861. navigator.platform === "iPad";
  1862. }
  1863. return isIPadOrIOSResult;
  1864. }
  1865. function firefoxVersion() {
  1866. return isFirefox() && firefoxVersionResult;
  1867. }
  1868. let hasPointerEvents;
  1869. function supportsPointerEvents() {
  1870. if (!defaultValue.defined(hasPointerEvents)) {
  1871. //While navigator.pointerEnabled is deprecated in the W3C specification
  1872. //we still need to use it if it exists in order to support browsers
  1873. //that rely on it, such as the Windows WebBrowser control which defines
  1874. //PointerEvent but sets navigator.pointerEnabled to false.
  1875. //Firefox disabled because of https://github.com/CesiumGS/cesium/issues/6372
  1876. hasPointerEvents =
  1877. !isFirefox() &&
  1878. typeof PointerEvent !== "undefined" &&
  1879. (!defaultValue.defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  1880. }
  1881. return hasPointerEvents;
  1882. }
  1883. let imageRenderingValueResult;
  1884. let supportsImageRenderingPixelatedResult;
  1885. function supportsImageRenderingPixelated() {
  1886. if (!defaultValue.defined(supportsImageRenderingPixelatedResult)) {
  1887. const canvas = document.createElement("canvas");
  1888. canvas.setAttribute(
  1889. "style",
  1890. "image-rendering: -moz-crisp-edges;" + "image-rendering: pixelated;"
  1891. );
  1892. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  1893. const tmp = canvas.style.imageRendering;
  1894. supportsImageRenderingPixelatedResult = defaultValue.defined(tmp) && tmp !== "";
  1895. if (supportsImageRenderingPixelatedResult) {
  1896. imageRenderingValueResult = tmp;
  1897. }
  1898. }
  1899. return supportsImageRenderingPixelatedResult;
  1900. }
  1901. function imageRenderingValue() {
  1902. return supportsImageRenderingPixelated()
  1903. ? imageRenderingValueResult
  1904. : undefined;
  1905. }
  1906. function supportsWebP() {
  1907. //>>includeStart('debug', pragmas.debug);
  1908. if (!supportsWebP.initialized) {
  1909. throw new RuntimeError.DeveloperError(
  1910. "You must call FeatureDetection.supportsWebP.initialize and wait for the promise to resolve before calling FeatureDetection.supportsWebP"
  1911. );
  1912. }
  1913. //>>includeEnd('debug');
  1914. return supportsWebP._result;
  1915. }
  1916. supportsWebP._promise = undefined;
  1917. supportsWebP._result = undefined;
  1918. supportsWebP.initialize = function () {
  1919. // From https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp
  1920. if (defaultValue.defined(supportsWebP._promise)) {
  1921. return supportsWebP._promise;
  1922. }
  1923. const supportsWebPDeferred = defer();
  1924. supportsWebP._promise = supportsWebPDeferred.promise;
  1925. if (isEdge()) {
  1926. // Edge's WebP support with WebGL is incomplete.
  1927. // See bug report: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/19221241/
  1928. supportsWebP._result = false;
  1929. supportsWebPDeferred.resolve(supportsWebP._result);
  1930. return supportsWebPDeferred.promise;
  1931. }
  1932. const image = new Image();
  1933. image.onload = function () {
  1934. supportsWebP._result = image.width > 0 && image.height > 0;
  1935. supportsWebPDeferred.resolve(supportsWebP._result);
  1936. };
  1937. image.onerror = function () {
  1938. supportsWebP._result = false;
  1939. supportsWebPDeferred.resolve(supportsWebP._result);
  1940. };
  1941. image.src =
  1942. "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
  1943. return supportsWebPDeferred.promise;
  1944. };
  1945. Object.defineProperties(supportsWebP, {
  1946. initialized: {
  1947. get: function () {
  1948. return defaultValue.defined(supportsWebP._result);
  1949. },
  1950. },
  1951. });
  1952. const typedArrayTypes = [];
  1953. if (typeof ArrayBuffer !== "undefined") {
  1954. typedArrayTypes.push(
  1955. Int8Array,
  1956. Uint8Array,
  1957. Int16Array,
  1958. Uint16Array,
  1959. Int32Array,
  1960. Uint32Array,
  1961. Float32Array,
  1962. Float64Array
  1963. );
  1964. if (typeof Uint8ClampedArray !== "undefined") {
  1965. typedArrayTypes.push(Uint8ClampedArray);
  1966. }
  1967. if (typeof Uint8ClampedArray !== "undefined") {
  1968. typedArrayTypes.push(Uint8ClampedArray);
  1969. }
  1970. if (typeof BigInt64Array !== "undefined") {
  1971. // eslint-disable-next-line no-undef
  1972. typedArrayTypes.push(BigInt64Array);
  1973. }
  1974. if (typeof BigUint64Array !== "undefined") {
  1975. // eslint-disable-next-line no-undef
  1976. typedArrayTypes.push(BigUint64Array);
  1977. }
  1978. }
  1979. /**
  1980. * A set of functions to detect whether the current browser supports
  1981. * various features.
  1982. *
  1983. * @namespace FeatureDetection
  1984. */
  1985. const FeatureDetection = {
  1986. isChrome: isChrome,
  1987. chromeVersion: chromeVersion,
  1988. isSafari: isSafari,
  1989. safariVersion: safariVersion,
  1990. isWebkit: isWebkit,
  1991. webkitVersion: webkitVersion,
  1992. isInternetExplorer: isInternetExplorer,
  1993. internetExplorerVersion: internetExplorerVersion,
  1994. isEdge: isEdge,
  1995. edgeVersion: edgeVersion,
  1996. isFirefox: isFirefox,
  1997. firefoxVersion: firefoxVersion,
  1998. isWindows: isWindows,
  1999. isIPadOrIOS: isIPadOrIOS,
  2000. hardwareConcurrency: defaultValue.defaultValue(theNavigator.hardwareConcurrency, 3),
  2001. supportsPointerEvents: supportsPointerEvents,
  2002. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  2003. supportsWebP: supportsWebP,
  2004. imageRenderingValue: imageRenderingValue,
  2005. typedArrayTypes: typedArrayTypes,
  2006. };
  2007. /**
  2008. * Detects whether the current browser supports Basis Universal textures and the web assembly modules needed to transcode them.
  2009. *
  2010. * @param {Scene} scene
  2011. * @returns {Boolean} true if the browser supports web assembly modules and the scene supports Basis Universal textures, false if not.
  2012. */
  2013. FeatureDetection.supportsBasis = function (scene) {
  2014. return FeatureDetection.supportsWebAssembly() && scene.context.supportsBasis;
  2015. };
  2016. /**
  2017. * Detects whether the current browser supports the full screen standard.
  2018. *
  2019. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  2020. *
  2021. * @see Fullscreen
  2022. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  2023. */
  2024. FeatureDetection.supportsFullscreen = function () {
  2025. return Fullscreen.supportsFullscreen();
  2026. };
  2027. /**
  2028. * Detects whether the current browser supports typed arrays.
  2029. *
  2030. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  2031. *
  2032. * @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
  2033. */
  2034. FeatureDetection.supportsTypedArrays = function () {
  2035. return typeof ArrayBuffer !== "undefined";
  2036. };
  2037. /**
  2038. * Detects whether the current browser supports BigInt64Array typed arrays.
  2039. *
  2040. * @returns {Boolean} true if the browser supports BigInt64Array typed arrays, false if not.
  2041. *
  2042. * @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
  2043. */
  2044. FeatureDetection.supportsBigInt64Array = function () {
  2045. return typeof BigInt64Array !== "undefined";
  2046. };
  2047. /**
  2048. * Detects whether the current browser supports BigUint64Array typed arrays.
  2049. *
  2050. * @returns {Boolean} true if the browser supports BigUint64Array typed arrays, false if not.
  2051. *
  2052. * @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
  2053. */
  2054. FeatureDetection.supportsBigUint64Array = function () {
  2055. return typeof BigUint64Array !== "undefined";
  2056. };
  2057. /**
  2058. * Detects whether the current browser supports BigInt.
  2059. *
  2060. * @returns {Boolean} true if the browser supports BigInt, false if not.
  2061. *
  2062. * @see {@link https://tc39.es/ecma262/#sec-bigint-objects|BigInt Specification}
  2063. */
  2064. FeatureDetection.supportsBigInt = function () {
  2065. return typeof BigInt !== "undefined";
  2066. };
  2067. /**
  2068. * Detects whether the current browser supports Web Workers.
  2069. *
  2070. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  2071. *
  2072. * @see {@link http://www.w3.org/TR/workers/}
  2073. */
  2074. FeatureDetection.supportsWebWorkers = function () {
  2075. return typeof Worker !== "undefined";
  2076. };
  2077. /**
  2078. * Detects whether the current browser supports Web Assembly.
  2079. *
  2080. * @returns {Boolean} true if the browsers supports Web Assembly, false if not.
  2081. *
  2082. * @see {@link https://developer.mozilla.org/en-US/docs/WebAssembly}
  2083. */
  2084. FeatureDetection.supportsWebAssembly = function () {
  2085. return typeof WebAssembly !== "undefined";
  2086. };
  2087. /**
  2088. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  2089. * @alias Quaternion
  2090. * @constructor
  2091. *
  2092. * @param {Number} [x=0.0] The X component.
  2093. * @param {Number} [y=0.0] The Y component.
  2094. * @param {Number} [z=0.0] The Z component.
  2095. * @param {Number} [w=0.0] The W component.
  2096. *
  2097. * @see PackableForInterpolation
  2098. */
  2099. function Quaternion(x, y, z, w) {
  2100. /**
  2101. * The X component.
  2102. * @type {Number}
  2103. * @default 0.0
  2104. */
  2105. this.x = defaultValue.defaultValue(x, 0.0);
  2106. /**
  2107. * The Y component.
  2108. * @type {Number}
  2109. * @default 0.0
  2110. */
  2111. this.y = defaultValue.defaultValue(y, 0.0);
  2112. /**
  2113. * The Z component.
  2114. * @type {Number}
  2115. * @default 0.0
  2116. */
  2117. this.z = defaultValue.defaultValue(z, 0.0);
  2118. /**
  2119. * The W component.
  2120. * @type {Number}
  2121. * @default 0.0
  2122. */
  2123. this.w = defaultValue.defaultValue(w, 0.0);
  2124. }
  2125. let fromAxisAngleScratch = new Matrix2.Cartesian3();
  2126. /**
  2127. * Computes a quaternion representing a rotation around an axis.
  2128. *
  2129. * @param {Cartesian3} axis The axis of rotation.
  2130. * @param {Number} angle The angle in radians to rotate around the axis.
  2131. * @param {Quaternion} [result] The object onto which to store the result.
  2132. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2133. */
  2134. Quaternion.fromAxisAngle = function (axis, angle, result) {
  2135. //>>includeStart('debug', pragmas.debug);
  2136. RuntimeError.Check.typeOf.object("axis", axis);
  2137. RuntimeError.Check.typeOf.number("angle", angle);
  2138. //>>includeEnd('debug');
  2139. const halfAngle = angle / 2.0;
  2140. const s = Math.sin(halfAngle);
  2141. fromAxisAngleScratch = Matrix2.Cartesian3.normalize(axis, fromAxisAngleScratch);
  2142. const x = fromAxisAngleScratch.x * s;
  2143. const y = fromAxisAngleScratch.y * s;
  2144. const z = fromAxisAngleScratch.z * s;
  2145. const w = Math.cos(halfAngle);
  2146. if (!defaultValue.defined(result)) {
  2147. return new Quaternion(x, y, z, w);
  2148. }
  2149. result.x = x;
  2150. result.y = y;
  2151. result.z = z;
  2152. result.w = w;
  2153. return result;
  2154. };
  2155. const fromRotationMatrixNext = [1, 2, 0];
  2156. const fromRotationMatrixQuat = new Array(3);
  2157. /**
  2158. * Computes a Quaternion from the provided Matrix3 instance.
  2159. *
  2160. * @param {Matrix3} matrix The rotation matrix.
  2161. * @param {Quaternion} [result] The object onto which to store the result.
  2162. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2163. *
  2164. * @see Matrix3.fromQuaternion
  2165. */
  2166. Quaternion.fromRotationMatrix = function (matrix, result) {
  2167. //>>includeStart('debug', pragmas.debug);
  2168. RuntimeError.Check.typeOf.object("matrix", matrix);
  2169. //>>includeEnd('debug');
  2170. let root;
  2171. let x;
  2172. let y;
  2173. let z;
  2174. let w;
  2175. const m00 = matrix[Matrix2.Matrix3.COLUMN0ROW0];
  2176. const m11 = matrix[Matrix2.Matrix3.COLUMN1ROW1];
  2177. const m22 = matrix[Matrix2.Matrix3.COLUMN2ROW2];
  2178. const trace = m00 + m11 + m22;
  2179. if (trace > 0.0) {
  2180. // |w| > 1/2, may as well choose w > 1/2
  2181. root = Math.sqrt(trace + 1.0); // 2w
  2182. w = 0.5 * root;
  2183. root = 0.5 / root; // 1/(4w)
  2184. x = (matrix[Matrix2.Matrix3.COLUMN1ROW2] - matrix[Matrix2.Matrix3.COLUMN2ROW1]) * root;
  2185. y = (matrix[Matrix2.Matrix3.COLUMN2ROW0] - matrix[Matrix2.Matrix3.COLUMN0ROW2]) * root;
  2186. z = (matrix[Matrix2.Matrix3.COLUMN0ROW1] - matrix[Matrix2.Matrix3.COLUMN1ROW0]) * root;
  2187. } else {
  2188. // |w| <= 1/2
  2189. const next = fromRotationMatrixNext;
  2190. let i = 0;
  2191. if (m11 > m00) {
  2192. i = 1;
  2193. }
  2194. if (m22 > m00 && m22 > m11) {
  2195. i = 2;
  2196. }
  2197. const j = next[i];
  2198. const k = next[j];
  2199. root = Math.sqrt(
  2200. matrix[Matrix2.Matrix3.getElementIndex(i, i)] -
  2201. matrix[Matrix2.Matrix3.getElementIndex(j, j)] -
  2202. matrix[Matrix2.Matrix3.getElementIndex(k, k)] +
  2203. 1.0
  2204. );
  2205. const quat = fromRotationMatrixQuat;
  2206. quat[i] = 0.5 * root;
  2207. root = 0.5 / root;
  2208. w =
  2209. (matrix[Matrix2.Matrix3.getElementIndex(k, j)] -
  2210. matrix[Matrix2.Matrix3.getElementIndex(j, k)]) *
  2211. root;
  2212. quat[j] =
  2213. (matrix[Matrix2.Matrix3.getElementIndex(j, i)] +
  2214. matrix[Matrix2.Matrix3.getElementIndex(i, j)]) *
  2215. root;
  2216. quat[k] =
  2217. (matrix[Matrix2.Matrix3.getElementIndex(k, i)] +
  2218. matrix[Matrix2.Matrix3.getElementIndex(i, k)]) *
  2219. root;
  2220. x = -quat[0];
  2221. y = -quat[1];
  2222. z = -quat[2];
  2223. }
  2224. if (!defaultValue.defined(result)) {
  2225. return new Quaternion(x, y, z, w);
  2226. }
  2227. result.x = x;
  2228. result.y = y;
  2229. result.z = z;
  2230. result.w = w;
  2231. return result;
  2232. };
  2233. const scratchHPRQuaternion$1 = new Quaternion();
  2234. let scratchHeadingQuaternion = new Quaternion();
  2235. let scratchPitchQuaternion = new Quaternion();
  2236. let scratchRollQuaternion = new Quaternion();
  2237. /**
  2238. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  2239. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  2240. * the positive x axis.
  2241. *
  2242. * @param {HeadingPitchRoll} headingPitchRoll The rotation expressed as a heading, pitch and roll.
  2243. * @param {Quaternion} [result] The object onto which to store the result.
  2244. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  2245. */
  2246. Quaternion.fromHeadingPitchRoll = function (headingPitchRoll, result) {
  2247. //>>includeStart('debug', pragmas.debug);
  2248. RuntimeError.Check.typeOf.object("headingPitchRoll", headingPitchRoll);
  2249. //>>includeEnd('debug');
  2250. scratchRollQuaternion = Quaternion.fromAxisAngle(
  2251. Matrix2.Cartesian3.UNIT_X,
  2252. headingPitchRoll.roll,
  2253. scratchHPRQuaternion$1
  2254. );
  2255. scratchPitchQuaternion = Quaternion.fromAxisAngle(
  2256. Matrix2.Cartesian3.UNIT_Y,
  2257. -headingPitchRoll.pitch,
  2258. result
  2259. );
  2260. result = Quaternion.multiply(
  2261. scratchPitchQuaternion,
  2262. scratchRollQuaternion,
  2263. scratchPitchQuaternion
  2264. );
  2265. scratchHeadingQuaternion = Quaternion.fromAxisAngle(
  2266. Matrix2.Cartesian3.UNIT_Z,
  2267. -headingPitchRoll.heading,
  2268. scratchHPRQuaternion$1
  2269. );
  2270. return Quaternion.multiply(scratchHeadingQuaternion, result, result);
  2271. };
  2272. const sampledQuaternionAxis = new Matrix2.Cartesian3();
  2273. const sampledQuaternionRotation = new Matrix2.Cartesian3();
  2274. const sampledQuaternionTempQuaternion = new Quaternion();
  2275. const sampledQuaternionQuaternion0 = new Quaternion();
  2276. const sampledQuaternionQuaternion0Conjugate = new Quaternion();
  2277. /**
  2278. * The number of elements used to pack the object into an array.
  2279. * @type {Number}
  2280. */
  2281. Quaternion.packedLength = 4;
  2282. /**
  2283. * Stores the provided instance into the provided array.
  2284. *
  2285. * @param {Quaternion} value The value to pack.
  2286. * @param {Number[]} array The array to pack into.
  2287. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2288. *
  2289. * @returns {Number[]} The array that was packed into
  2290. */
  2291. Quaternion.pack = function (value, array, startingIndex) {
  2292. //>>includeStart('debug', pragmas.debug);
  2293. RuntimeError.Check.typeOf.object("value", value);
  2294. RuntimeError.Check.defined("array", array);
  2295. //>>includeEnd('debug');
  2296. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  2297. array[startingIndex++] = value.x;
  2298. array[startingIndex++] = value.y;
  2299. array[startingIndex++] = value.z;
  2300. array[startingIndex] = value.w;
  2301. return array;
  2302. };
  2303. /**
  2304. * Retrieves an instance from a packed array.
  2305. *
  2306. * @param {Number[]} array The packed array.
  2307. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2308. * @param {Quaternion} [result] The object into which to store the result.
  2309. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2310. */
  2311. Quaternion.unpack = function (array, startingIndex, result) {
  2312. //>>includeStart('debug', pragmas.debug);
  2313. RuntimeError.Check.defined("array", array);
  2314. //>>includeEnd('debug');
  2315. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  2316. if (!defaultValue.defined(result)) {
  2317. result = new Quaternion();
  2318. }
  2319. result.x = array[startingIndex];
  2320. result.y = array[startingIndex + 1];
  2321. result.z = array[startingIndex + 2];
  2322. result.w = array[startingIndex + 3];
  2323. return result;
  2324. };
  2325. /**
  2326. * The number of elements used to store the object into an array in its interpolatable form.
  2327. * @type {Number}
  2328. */
  2329. Quaternion.packedInterpolationLength = 3;
  2330. /**
  2331. * Converts a packed array into a form suitable for interpolation.
  2332. *
  2333. * @param {Number[]} packedArray The packed array.
  2334. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  2335. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  2336. * @param {Number[]} [result] The object into which to store the result.
  2337. */
  2338. Quaternion.convertPackedArrayForInterpolation = function (
  2339. packedArray,
  2340. startingIndex,
  2341. lastIndex,
  2342. result
  2343. ) {
  2344. Quaternion.unpack(
  2345. packedArray,
  2346. lastIndex * 4,
  2347. sampledQuaternionQuaternion0Conjugate
  2348. );
  2349. Quaternion.conjugate(
  2350. sampledQuaternionQuaternion0Conjugate,
  2351. sampledQuaternionQuaternion0Conjugate
  2352. );
  2353. for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  2354. const offset = i * 3;
  2355. Quaternion.unpack(
  2356. packedArray,
  2357. (startingIndex + i) * 4,
  2358. sampledQuaternionTempQuaternion
  2359. );
  2360. Quaternion.multiply(
  2361. sampledQuaternionTempQuaternion,
  2362. sampledQuaternionQuaternion0Conjugate,
  2363. sampledQuaternionTempQuaternion
  2364. );
  2365. if (sampledQuaternionTempQuaternion.w < 0) {
  2366. Quaternion.negate(
  2367. sampledQuaternionTempQuaternion,
  2368. sampledQuaternionTempQuaternion
  2369. );
  2370. }
  2371. Quaternion.computeAxis(
  2372. sampledQuaternionTempQuaternion,
  2373. sampledQuaternionAxis
  2374. );
  2375. const angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  2376. if (!defaultValue.defined(result)) {
  2377. result = [];
  2378. }
  2379. result[offset] = sampledQuaternionAxis.x * angle;
  2380. result[offset + 1] = sampledQuaternionAxis.y * angle;
  2381. result[offset + 2] = sampledQuaternionAxis.z * angle;
  2382. }
  2383. };
  2384. /**
  2385. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  2386. *
  2387. * @param {Number[]} array The array previously packed for interpolation.
  2388. * @param {Number[]} sourceArray The original packed array.
  2389. * @param {Number} [firstIndex=0] The firstIndex used to convert the array.
  2390. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  2391. * @param {Quaternion} [result] The object into which to store the result.
  2392. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2393. */
  2394. Quaternion.unpackInterpolationResult = function (
  2395. array,
  2396. sourceArray,
  2397. firstIndex,
  2398. lastIndex,
  2399. result
  2400. ) {
  2401. if (!defaultValue.defined(result)) {
  2402. result = new Quaternion();
  2403. }
  2404. Matrix2.Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  2405. const magnitude = Matrix2.Cartesian3.magnitude(sampledQuaternionRotation);
  2406. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  2407. if (magnitude === 0) {
  2408. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  2409. } else {
  2410. Quaternion.fromAxisAngle(
  2411. sampledQuaternionRotation,
  2412. magnitude,
  2413. sampledQuaternionTempQuaternion
  2414. );
  2415. }
  2416. return Quaternion.multiply(
  2417. sampledQuaternionTempQuaternion,
  2418. sampledQuaternionQuaternion0,
  2419. result
  2420. );
  2421. };
  2422. /**
  2423. * Duplicates a Quaternion instance.
  2424. *
  2425. * @param {Quaternion} quaternion The quaternion to duplicate.
  2426. * @param {Quaternion} [result] The object onto which to store the result.
  2427. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  2428. */
  2429. Quaternion.clone = function (quaternion, result) {
  2430. if (!defaultValue.defined(quaternion)) {
  2431. return undefined;
  2432. }
  2433. if (!defaultValue.defined(result)) {
  2434. return new Quaternion(
  2435. quaternion.x,
  2436. quaternion.y,
  2437. quaternion.z,
  2438. quaternion.w
  2439. );
  2440. }
  2441. result.x = quaternion.x;
  2442. result.y = quaternion.y;
  2443. result.z = quaternion.z;
  2444. result.w = quaternion.w;
  2445. return result;
  2446. };
  2447. /**
  2448. * Computes the conjugate of the provided quaternion.
  2449. *
  2450. * @param {Quaternion} quaternion The quaternion to conjugate.
  2451. * @param {Quaternion} result The object onto which to store the result.
  2452. * @returns {Quaternion} The modified result parameter.
  2453. */
  2454. Quaternion.conjugate = function (quaternion, result) {
  2455. //>>includeStart('debug', pragmas.debug);
  2456. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2457. RuntimeError.Check.typeOf.object("result", result);
  2458. //>>includeEnd('debug');
  2459. result.x = -quaternion.x;
  2460. result.y = -quaternion.y;
  2461. result.z = -quaternion.z;
  2462. result.w = quaternion.w;
  2463. return result;
  2464. };
  2465. /**
  2466. * Computes magnitude squared for the provided quaternion.
  2467. *
  2468. * @param {Quaternion} quaternion The quaternion to conjugate.
  2469. * @returns {Number} The magnitude squared.
  2470. */
  2471. Quaternion.magnitudeSquared = function (quaternion) {
  2472. //>>includeStart('debug', pragmas.debug);
  2473. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2474. //>>includeEnd('debug');
  2475. return (
  2476. quaternion.x * quaternion.x +
  2477. quaternion.y * quaternion.y +
  2478. quaternion.z * quaternion.z +
  2479. quaternion.w * quaternion.w
  2480. );
  2481. };
  2482. /**
  2483. * Computes magnitude for the provided quaternion.
  2484. *
  2485. * @param {Quaternion} quaternion The quaternion to conjugate.
  2486. * @returns {Number} The magnitude.
  2487. */
  2488. Quaternion.magnitude = function (quaternion) {
  2489. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  2490. };
  2491. /**
  2492. * Computes the normalized form of the provided quaternion.
  2493. *
  2494. * @param {Quaternion} quaternion The quaternion to normalize.
  2495. * @param {Quaternion} result The object onto which to store the result.
  2496. * @returns {Quaternion} The modified result parameter.
  2497. */
  2498. Quaternion.normalize = function (quaternion, result) {
  2499. //>>includeStart('debug', pragmas.debug);
  2500. RuntimeError.Check.typeOf.object("result", result);
  2501. //>>includeEnd('debug');
  2502. const inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  2503. const x = quaternion.x * inverseMagnitude;
  2504. const y = quaternion.y * inverseMagnitude;
  2505. const z = quaternion.z * inverseMagnitude;
  2506. const w = quaternion.w * inverseMagnitude;
  2507. result.x = x;
  2508. result.y = y;
  2509. result.z = z;
  2510. result.w = w;
  2511. return result;
  2512. };
  2513. /**
  2514. * Computes the inverse of the provided quaternion.
  2515. *
  2516. * @param {Quaternion} quaternion The quaternion to normalize.
  2517. * @param {Quaternion} result The object onto which to store the result.
  2518. * @returns {Quaternion} The modified result parameter.
  2519. */
  2520. Quaternion.inverse = function (quaternion, result) {
  2521. //>>includeStart('debug', pragmas.debug);
  2522. RuntimeError.Check.typeOf.object("result", result);
  2523. //>>includeEnd('debug');
  2524. const magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  2525. result = Quaternion.conjugate(quaternion, result);
  2526. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  2527. };
  2528. /**
  2529. * Computes the componentwise sum of two quaternions.
  2530. *
  2531. * @param {Quaternion} left The first quaternion.
  2532. * @param {Quaternion} right The second quaternion.
  2533. * @param {Quaternion} result The object onto which to store the result.
  2534. * @returns {Quaternion} The modified result parameter.
  2535. */
  2536. Quaternion.add = function (left, right, result) {
  2537. //>>includeStart('debug', pragmas.debug);
  2538. RuntimeError.Check.typeOf.object("left", left);
  2539. RuntimeError.Check.typeOf.object("right", right);
  2540. RuntimeError.Check.typeOf.object("result", result);
  2541. //>>includeEnd('debug');
  2542. result.x = left.x + right.x;
  2543. result.y = left.y + right.y;
  2544. result.z = left.z + right.z;
  2545. result.w = left.w + right.w;
  2546. return result;
  2547. };
  2548. /**
  2549. * Computes the componentwise difference of two quaternions.
  2550. *
  2551. * @param {Quaternion} left The first quaternion.
  2552. * @param {Quaternion} right The second quaternion.
  2553. * @param {Quaternion} result The object onto which to store the result.
  2554. * @returns {Quaternion} The modified result parameter.
  2555. */
  2556. Quaternion.subtract = function (left, right, result) {
  2557. //>>includeStart('debug', pragmas.debug);
  2558. RuntimeError.Check.typeOf.object("left", left);
  2559. RuntimeError.Check.typeOf.object("right", right);
  2560. RuntimeError.Check.typeOf.object("result", result);
  2561. //>>includeEnd('debug');
  2562. result.x = left.x - right.x;
  2563. result.y = left.y - right.y;
  2564. result.z = left.z - right.z;
  2565. result.w = left.w - right.w;
  2566. return result;
  2567. };
  2568. /**
  2569. * Negates the provided quaternion.
  2570. *
  2571. * @param {Quaternion} quaternion The quaternion to be negated.
  2572. * @param {Quaternion} result The object onto which to store the result.
  2573. * @returns {Quaternion} The modified result parameter.
  2574. */
  2575. Quaternion.negate = function (quaternion, result) {
  2576. //>>includeStart('debug', pragmas.debug);
  2577. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2578. RuntimeError.Check.typeOf.object("result", result);
  2579. //>>includeEnd('debug');
  2580. result.x = -quaternion.x;
  2581. result.y = -quaternion.y;
  2582. result.z = -quaternion.z;
  2583. result.w = -quaternion.w;
  2584. return result;
  2585. };
  2586. /**
  2587. * Computes the dot (scalar) product of two quaternions.
  2588. *
  2589. * @param {Quaternion} left The first quaternion.
  2590. * @param {Quaternion} right The second quaternion.
  2591. * @returns {Number} The dot product.
  2592. */
  2593. Quaternion.dot = function (left, right) {
  2594. //>>includeStart('debug', pragmas.debug);
  2595. RuntimeError.Check.typeOf.object("left", left);
  2596. RuntimeError.Check.typeOf.object("right", right);
  2597. //>>includeEnd('debug');
  2598. return (
  2599. left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
  2600. );
  2601. };
  2602. /**
  2603. * Computes the product of two quaternions.
  2604. *
  2605. * @param {Quaternion} left The first quaternion.
  2606. * @param {Quaternion} right The second quaternion.
  2607. * @param {Quaternion} result The object onto which to store the result.
  2608. * @returns {Quaternion} The modified result parameter.
  2609. */
  2610. Quaternion.multiply = function (left, right, result) {
  2611. //>>includeStart('debug', pragmas.debug);
  2612. RuntimeError.Check.typeOf.object("left", left);
  2613. RuntimeError.Check.typeOf.object("right", right);
  2614. RuntimeError.Check.typeOf.object("result", result);
  2615. //>>includeEnd('debug');
  2616. const leftX = left.x;
  2617. const leftY = left.y;
  2618. const leftZ = left.z;
  2619. const leftW = left.w;
  2620. const rightX = right.x;
  2621. const rightY = right.y;
  2622. const rightZ = right.z;
  2623. const rightW = right.w;
  2624. const x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  2625. const y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  2626. const z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  2627. const w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  2628. result.x = x;
  2629. result.y = y;
  2630. result.z = z;
  2631. result.w = w;
  2632. return result;
  2633. };
  2634. /**
  2635. * Multiplies the provided quaternion componentwise by the provided scalar.
  2636. *
  2637. * @param {Quaternion} quaternion The quaternion to be scaled.
  2638. * @param {Number} scalar The scalar to multiply with.
  2639. * @param {Quaternion} result The object onto which to store the result.
  2640. * @returns {Quaternion} The modified result parameter.
  2641. */
  2642. Quaternion.multiplyByScalar = function (quaternion, scalar, result) {
  2643. //>>includeStart('debug', pragmas.debug);
  2644. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2645. RuntimeError.Check.typeOf.number("scalar", scalar);
  2646. RuntimeError.Check.typeOf.object("result", result);
  2647. //>>includeEnd('debug');
  2648. result.x = quaternion.x * scalar;
  2649. result.y = quaternion.y * scalar;
  2650. result.z = quaternion.z * scalar;
  2651. result.w = quaternion.w * scalar;
  2652. return result;
  2653. };
  2654. /**
  2655. * Divides the provided quaternion componentwise by the provided scalar.
  2656. *
  2657. * @param {Quaternion} quaternion The quaternion to be divided.
  2658. * @param {Number} scalar The scalar to divide by.
  2659. * @param {Quaternion} result The object onto which to store the result.
  2660. * @returns {Quaternion} The modified result parameter.
  2661. */
  2662. Quaternion.divideByScalar = function (quaternion, scalar, result) {
  2663. //>>includeStart('debug', pragmas.debug);
  2664. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2665. RuntimeError.Check.typeOf.number("scalar", scalar);
  2666. RuntimeError.Check.typeOf.object("result", result);
  2667. //>>includeEnd('debug');
  2668. result.x = quaternion.x / scalar;
  2669. result.y = quaternion.y / scalar;
  2670. result.z = quaternion.z / scalar;
  2671. result.w = quaternion.w / scalar;
  2672. return result;
  2673. };
  2674. /**
  2675. * Computes the axis of rotation of the provided quaternion.
  2676. *
  2677. * @param {Quaternion} quaternion The quaternion to use.
  2678. * @param {Cartesian3} result The object onto which to store the result.
  2679. * @returns {Cartesian3} The modified result parameter.
  2680. */
  2681. Quaternion.computeAxis = function (quaternion, result) {
  2682. //>>includeStart('debug', pragmas.debug);
  2683. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2684. RuntimeError.Check.typeOf.object("result", result);
  2685. //>>includeEnd('debug');
  2686. const w = quaternion.w;
  2687. if (Math.abs(w - 1.0) < ComponentDatatype.CesiumMath.EPSILON6) {
  2688. result.x = result.y = result.z = 0;
  2689. return result;
  2690. }
  2691. const scalar = 1.0 / Math.sqrt(1.0 - w * w);
  2692. result.x = quaternion.x * scalar;
  2693. result.y = quaternion.y * scalar;
  2694. result.z = quaternion.z * scalar;
  2695. return result;
  2696. };
  2697. /**
  2698. * Computes the angle of rotation of the provided quaternion.
  2699. *
  2700. * @param {Quaternion} quaternion The quaternion to use.
  2701. * @returns {Number} The angle of rotation.
  2702. */
  2703. Quaternion.computeAngle = function (quaternion) {
  2704. //>>includeStart('debug', pragmas.debug);
  2705. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2706. //>>includeEnd('debug');
  2707. if (Math.abs(quaternion.w - 1.0) < ComponentDatatype.CesiumMath.EPSILON6) {
  2708. return 0.0;
  2709. }
  2710. return 2.0 * Math.acos(quaternion.w);
  2711. };
  2712. let lerpScratch = new Quaternion();
  2713. /**
  2714. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  2715. *
  2716. * @param {Quaternion} start The value corresponding to t at 0.0.
  2717. * @param {Quaternion} end The value corresponding to t at 1.0.
  2718. * @param {Number} t The point along t at which to interpolate.
  2719. * @param {Quaternion} result The object onto which to store the result.
  2720. * @returns {Quaternion} The modified result parameter.
  2721. */
  2722. Quaternion.lerp = function (start, end, t, result) {
  2723. //>>includeStart('debug', pragmas.debug);
  2724. RuntimeError.Check.typeOf.object("start", start);
  2725. RuntimeError.Check.typeOf.object("end", end);
  2726. RuntimeError.Check.typeOf.number("t", t);
  2727. RuntimeError.Check.typeOf.object("result", result);
  2728. //>>includeEnd('debug');
  2729. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  2730. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  2731. return Quaternion.add(lerpScratch, result, result);
  2732. };
  2733. let slerpEndNegated = new Quaternion();
  2734. let slerpScaledP = new Quaternion();
  2735. let slerpScaledR = new Quaternion();
  2736. /**
  2737. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  2738. *
  2739. * @param {Quaternion} start The value corresponding to t at 0.0.
  2740. * @param {Quaternion} end The value corresponding to t at 1.0.
  2741. * @param {Number} t The point along t at which to interpolate.
  2742. * @param {Quaternion} result The object onto which to store the result.
  2743. * @returns {Quaternion} The modified result parameter.
  2744. *
  2745. * @see Quaternion#fastSlerp
  2746. */
  2747. Quaternion.slerp = function (start, end, t, result) {
  2748. //>>includeStart('debug', pragmas.debug);
  2749. RuntimeError.Check.typeOf.object("start", start);
  2750. RuntimeError.Check.typeOf.object("end", end);
  2751. RuntimeError.Check.typeOf.number("t", t);
  2752. RuntimeError.Check.typeOf.object("result", result);
  2753. //>>includeEnd('debug');
  2754. let dot = Quaternion.dot(start, end);
  2755. // The angle between start must be acute. Since q and -q represent
  2756. // the same rotation, negate q to get the acute angle.
  2757. let r = end;
  2758. if (dot < 0.0) {
  2759. dot = -dot;
  2760. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  2761. }
  2762. // dot > 0, as the dot product approaches 1, the angle between the
  2763. // quaternions vanishes. use linear interpolation.
  2764. if (1.0 - dot < ComponentDatatype.CesiumMath.EPSILON6) {
  2765. return Quaternion.lerp(start, r, t, result);
  2766. }
  2767. const theta = Math.acos(dot);
  2768. slerpScaledP = Quaternion.multiplyByScalar(
  2769. start,
  2770. Math.sin((1 - t) * theta),
  2771. slerpScaledP
  2772. );
  2773. slerpScaledR = Quaternion.multiplyByScalar(
  2774. r,
  2775. Math.sin(t * theta),
  2776. slerpScaledR
  2777. );
  2778. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  2779. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  2780. };
  2781. /**
  2782. * The logarithmic quaternion function.
  2783. *
  2784. * @param {Quaternion} quaternion The unit quaternion.
  2785. * @param {Cartesian3} result The object onto which to store the result.
  2786. * @returns {Cartesian3} The modified result parameter.
  2787. */
  2788. Quaternion.log = function (quaternion, result) {
  2789. //>>includeStart('debug', pragmas.debug);
  2790. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2791. RuntimeError.Check.typeOf.object("result", result);
  2792. //>>includeEnd('debug');
  2793. const theta = ComponentDatatype.CesiumMath.acosClamped(quaternion.w);
  2794. let thetaOverSinTheta = 0.0;
  2795. if (theta !== 0.0) {
  2796. thetaOverSinTheta = theta / Math.sin(theta);
  2797. }
  2798. return Matrix2.Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  2799. };
  2800. /**
  2801. * The exponential quaternion function.
  2802. *
  2803. * @param {Cartesian3} cartesian The cartesian.
  2804. * @param {Quaternion} result The object onto which to store the result.
  2805. * @returns {Quaternion} The modified result parameter.
  2806. */
  2807. Quaternion.exp = function (cartesian, result) {
  2808. //>>includeStart('debug', pragmas.debug);
  2809. RuntimeError.Check.typeOf.object("cartesian", cartesian);
  2810. RuntimeError.Check.typeOf.object("result", result);
  2811. //>>includeEnd('debug');
  2812. const theta = Matrix2.Cartesian3.magnitude(cartesian);
  2813. let sinThetaOverTheta = 0.0;
  2814. if (theta !== 0.0) {
  2815. sinThetaOverTheta = Math.sin(theta) / theta;
  2816. }
  2817. result.x = cartesian.x * sinThetaOverTheta;
  2818. result.y = cartesian.y * sinThetaOverTheta;
  2819. result.z = cartesian.z * sinThetaOverTheta;
  2820. result.w = Math.cos(theta);
  2821. return result;
  2822. };
  2823. const squadScratchCartesian0 = new Matrix2.Cartesian3();
  2824. const squadScratchCartesian1 = new Matrix2.Cartesian3();
  2825. const squadScratchQuaternion0 = new Quaternion();
  2826. const squadScratchQuaternion1 = new Quaternion();
  2827. /**
  2828. * Computes an inner quadrangle point.
  2829. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  2830. *
  2831. * @param {Quaternion} q0 The first quaternion.
  2832. * @param {Quaternion} q1 The second quaternion.
  2833. * @param {Quaternion} q2 The third quaternion.
  2834. * @param {Quaternion} result The object onto which to store the result.
  2835. * @returns {Quaternion} The modified result parameter.
  2836. *
  2837. * @see Quaternion#squad
  2838. */
  2839. Quaternion.computeInnerQuadrangle = function (q0, q1, q2, result) {
  2840. //>>includeStart('debug', pragmas.debug);
  2841. RuntimeError.Check.typeOf.object("q0", q0);
  2842. RuntimeError.Check.typeOf.object("q1", q1);
  2843. RuntimeError.Check.typeOf.object("q2", q2);
  2844. RuntimeError.Check.typeOf.object("result", result);
  2845. //>>includeEnd('debug');
  2846. const qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  2847. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  2848. const cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  2849. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  2850. const cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  2851. Matrix2.Cartesian3.add(cart0, cart1, cart0);
  2852. Matrix2.Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  2853. Matrix2.Cartesian3.negate(cart0, cart0);
  2854. Quaternion.exp(cart0, squadScratchQuaternion0);
  2855. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  2856. };
  2857. /**
  2858. * Computes the spherical quadrangle interpolation between quaternions.
  2859. *
  2860. * @param {Quaternion} q0 The first quaternion.
  2861. * @param {Quaternion} q1 The second quaternion.
  2862. * @param {Quaternion} s0 The first inner quadrangle.
  2863. * @param {Quaternion} s1 The second inner quadrangle.
  2864. * @param {Number} t The time in [0,1] used to interpolate.
  2865. * @param {Quaternion} result The object onto which to store the result.
  2866. * @returns {Quaternion} The modified result parameter.
  2867. *
  2868. *
  2869. * @example
  2870. * // 1. compute the squad interpolation between two quaternions on a curve
  2871. * const s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  2872. * const s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  2873. * const q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  2874. *
  2875. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  2876. * const s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  2877. * const q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  2878. *
  2879. * @see Quaternion#computeInnerQuadrangle
  2880. */
  2881. Quaternion.squad = function (q0, q1, s0, s1, t, result) {
  2882. //>>includeStart('debug', pragmas.debug);
  2883. RuntimeError.Check.typeOf.object("q0", q0);
  2884. RuntimeError.Check.typeOf.object("q1", q1);
  2885. RuntimeError.Check.typeOf.object("s0", s0);
  2886. RuntimeError.Check.typeOf.object("s1", s1);
  2887. RuntimeError.Check.typeOf.number("t", t);
  2888. RuntimeError.Check.typeOf.object("result", result);
  2889. //>>includeEnd('debug');
  2890. const slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  2891. const slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  2892. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  2893. };
  2894. const fastSlerpScratchQuaternion = new Quaternion();
  2895. const opmu = 1.90110745351730037;
  2896. const u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2897. const v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2898. const bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2899. const bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2900. for (let i = 0; i < 7; ++i) {
  2901. const s = i + 1.0;
  2902. const t = 2.0 * s + 1.0;
  2903. u[i] = 1.0 / (s * t);
  2904. v[i] = s / t;
  2905. }
  2906. u[7] = opmu / (8.0 * 17.0);
  2907. v[7] = (opmu * 8.0) / 17.0;
  2908. /**
  2909. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  2910. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  2911. *
  2912. * @param {Quaternion} start The value corresponding to t at 0.0.
  2913. * @param {Quaternion} end The value corresponding to t at 1.0.
  2914. * @param {Number} t The point along t at which to interpolate.
  2915. * @param {Quaternion} result The object onto which to store the result.
  2916. * @returns {Quaternion} The modified result parameter.
  2917. *
  2918. * @see Quaternion#slerp
  2919. */
  2920. Quaternion.fastSlerp = function (start, end, t, result) {
  2921. //>>includeStart('debug', pragmas.debug);
  2922. RuntimeError.Check.typeOf.object("start", start);
  2923. RuntimeError.Check.typeOf.object("end", end);
  2924. RuntimeError.Check.typeOf.number("t", t);
  2925. RuntimeError.Check.typeOf.object("result", result);
  2926. //>>includeEnd('debug');
  2927. let x = Quaternion.dot(start, end);
  2928. let sign;
  2929. if (x >= 0) {
  2930. sign = 1.0;
  2931. } else {
  2932. sign = -1.0;
  2933. x = -x;
  2934. }
  2935. const xm1 = x - 1.0;
  2936. const d = 1.0 - t;
  2937. const sqrT = t * t;
  2938. const sqrD = d * d;
  2939. for (let i = 7; i >= 0; --i) {
  2940. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  2941. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  2942. }
  2943. const cT =
  2944. sign *
  2945. t *
  2946. (1.0 +
  2947. bT[0] *
  2948. (1.0 +
  2949. bT[1] *
  2950. (1.0 +
  2951. bT[2] *
  2952. (1.0 +
  2953. bT[3] *
  2954. (1.0 +
  2955. bT[4] *
  2956. (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  2957. const cD =
  2958. d *
  2959. (1.0 +
  2960. bD[0] *
  2961. (1.0 +
  2962. bD[1] *
  2963. (1.0 +
  2964. bD[2] *
  2965. (1.0 +
  2966. bD[3] *
  2967. (1.0 +
  2968. bD[4] *
  2969. (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  2970. const temp = Quaternion.multiplyByScalar(
  2971. start,
  2972. cD,
  2973. fastSlerpScratchQuaternion
  2974. );
  2975. Quaternion.multiplyByScalar(end, cT, result);
  2976. return Quaternion.add(temp, result, result);
  2977. };
  2978. /**
  2979. * Computes the spherical quadrangle interpolation between quaternions.
  2980. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  2981. *
  2982. * @param {Quaternion} q0 The first quaternion.
  2983. * @param {Quaternion} q1 The second quaternion.
  2984. * @param {Quaternion} s0 The first inner quadrangle.
  2985. * @param {Quaternion} s1 The second inner quadrangle.
  2986. * @param {Number} t The time in [0,1] used to interpolate.
  2987. * @param {Quaternion} result The object onto which to store the result.
  2988. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  2989. *
  2990. * @see Quaternion#squad
  2991. */
  2992. Quaternion.fastSquad = function (q0, q1, s0, s1, t, result) {
  2993. //>>includeStart('debug', pragmas.debug);
  2994. RuntimeError.Check.typeOf.object("q0", q0);
  2995. RuntimeError.Check.typeOf.object("q1", q1);
  2996. RuntimeError.Check.typeOf.object("s0", s0);
  2997. RuntimeError.Check.typeOf.object("s1", s1);
  2998. RuntimeError.Check.typeOf.number("t", t);
  2999. RuntimeError.Check.typeOf.object("result", result);
  3000. //>>includeEnd('debug');
  3001. const slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  3002. const slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  3003. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  3004. };
  3005. /**
  3006. * Compares the provided quaternions componentwise and returns
  3007. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3008. *
  3009. * @param {Quaternion} [left] The first quaternion.
  3010. * @param {Quaternion} [right] The second quaternion.
  3011. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3012. */
  3013. Quaternion.equals = function (left, right) {
  3014. return (
  3015. left === right ||
  3016. (defaultValue.defined(left) &&
  3017. defaultValue.defined(right) &&
  3018. left.x === right.x &&
  3019. left.y === right.y &&
  3020. left.z === right.z &&
  3021. left.w === right.w)
  3022. );
  3023. };
  3024. /**
  3025. * Compares the provided quaternions componentwise and returns
  3026. * <code>true</code> if they are within the provided epsilon,
  3027. * <code>false</code> otherwise.
  3028. *
  3029. * @param {Quaternion} [left] The first quaternion.
  3030. * @param {Quaternion} [right] The second quaternion.
  3031. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  3032. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3033. */
  3034. Quaternion.equalsEpsilon = function (left, right, epsilon) {
  3035. epsilon = defaultValue.defaultValue(epsilon, 0);
  3036. return (
  3037. left === right ||
  3038. (defaultValue.defined(left) &&
  3039. defaultValue.defined(right) &&
  3040. Math.abs(left.x - right.x) <= epsilon &&
  3041. Math.abs(left.y - right.y) <= epsilon &&
  3042. Math.abs(left.z - right.z) <= epsilon &&
  3043. Math.abs(left.w - right.w) <= epsilon)
  3044. );
  3045. };
  3046. /**
  3047. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  3048. *
  3049. * @type {Quaternion}
  3050. * @constant
  3051. */
  3052. Quaternion.ZERO = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 0.0));
  3053. /**
  3054. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  3055. *
  3056. * @type {Quaternion}
  3057. * @constant
  3058. */
  3059. Quaternion.IDENTITY = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 1.0));
  3060. /**
  3061. * Duplicates this Quaternion instance.
  3062. *
  3063. * @param {Quaternion} [result] The object onto which to store the result.
  3064. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  3065. */
  3066. Quaternion.prototype.clone = function (result) {
  3067. return Quaternion.clone(this, result);
  3068. };
  3069. /**
  3070. * Compares this and the provided quaternion componentwise and returns
  3071. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3072. *
  3073. * @param {Quaternion} [right] The right hand side quaternion.
  3074. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3075. */
  3076. Quaternion.prototype.equals = function (right) {
  3077. return Quaternion.equals(this, right);
  3078. };
  3079. /**
  3080. * Compares this and the provided quaternion componentwise and returns
  3081. * <code>true</code> if they are within the provided epsilon,
  3082. * <code>false</code> otherwise.
  3083. *
  3084. * @param {Quaternion} [right] The right hand side quaternion.
  3085. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  3086. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3087. */
  3088. Quaternion.prototype.equalsEpsilon = function (right, epsilon) {
  3089. return Quaternion.equalsEpsilon(this, right, epsilon);
  3090. };
  3091. /**
  3092. * Returns a string representing this quaternion in the format (x, y, z, w).
  3093. *
  3094. * @returns {String} A string representing this Quaternion.
  3095. */
  3096. Quaternion.prototype.toString = function () {
  3097. return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`;
  3098. };
  3099. /**
  3100. * Finds an item in a sorted array.
  3101. *
  3102. * @function
  3103. * @param {Array} array The sorted array to search.
  3104. * @param {*} itemToFind The item to find in the array.
  3105. * @param {binarySearchComparator} comparator The function to use to compare the item to
  3106. * elements in the array.
  3107. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  3108. * does not exist, the return value is a negative number which is the bitwise complement (~)
  3109. * of the index before which the itemToFind should be inserted in order to maintain the
  3110. * sorted order of the array.
  3111. *
  3112. * @example
  3113. * // Create a comparator function to search through an array of numbers.
  3114. * function comparator(a, b) {
  3115. * return a - b;
  3116. * };
  3117. * const numbers = [0, 2, 4, 6, 8];
  3118. * const index = Cesium.binarySearch(numbers, 6, comparator); // 3
  3119. */
  3120. function binarySearch(array, itemToFind, comparator) {
  3121. //>>includeStart('debug', pragmas.debug);
  3122. RuntimeError.Check.defined("array", array);
  3123. RuntimeError.Check.defined("itemToFind", itemToFind);
  3124. RuntimeError.Check.defined("comparator", comparator);
  3125. //>>includeEnd('debug');
  3126. let low = 0;
  3127. let high = array.length - 1;
  3128. let i;
  3129. let comparison;
  3130. while (low <= high) {
  3131. i = ~~((low + high) / 2);
  3132. comparison = comparator(array[i], itemToFind);
  3133. if (comparison < 0) {
  3134. low = i + 1;
  3135. continue;
  3136. }
  3137. if (comparison > 0) {
  3138. high = i - 1;
  3139. continue;
  3140. }
  3141. return i;
  3142. }
  3143. return ~(high + 1);
  3144. }
  3145. /**
  3146. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  3147. *
  3148. * @alias EarthOrientationParametersSample
  3149. * @constructor
  3150. *
  3151. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  3152. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  3153. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  3154. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  3155. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  3156. *
  3157. * @private
  3158. */
  3159. function EarthOrientationParametersSample(
  3160. xPoleWander,
  3161. yPoleWander,
  3162. xPoleOffset,
  3163. yPoleOffset,
  3164. ut1MinusUtc
  3165. ) {
  3166. /**
  3167. * The pole wander about the X axis, in radians.
  3168. * @type {Number}
  3169. */
  3170. this.xPoleWander = xPoleWander;
  3171. /**
  3172. * The pole wander about the Y axis, in radians.
  3173. * @type {Number}
  3174. */
  3175. this.yPoleWander = yPoleWander;
  3176. /**
  3177. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  3178. * @type {Number}
  3179. */
  3180. this.xPoleOffset = xPoleOffset;
  3181. /**
  3182. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  3183. * @type {Number}
  3184. */
  3185. this.yPoleOffset = yPoleOffset;
  3186. /**
  3187. * The difference in time standards, UT1 - UTC, in seconds.
  3188. * @type {Number}
  3189. */
  3190. this.ut1MinusUtc = ut1MinusUtc;
  3191. }
  3192. /**
  3193. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  3194. * In addition to submillisecond precision, this object can also represent leap seconds.
  3195. * @alias GregorianDate
  3196. * @constructor
  3197. *
  3198. * @param {Number} [year] The year as a whole number.
  3199. * @param {Number} [month] The month as a whole number with range [1, 12].
  3200. * @param {Number} [day] The day of the month as a whole number starting at 1.
  3201. * @param {Number} [hour] The hour as a whole number with range [0, 23].
  3202. * @param {Number} [minute] The minute of the hour as a whole number with range [0, 59].
  3203. * @param {Number} [second] The second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  3204. * @param {Number} [millisecond] The millisecond of the second as a floating point number with range [0.0, 1000.0).
  3205. * @param {Boolean} [isLeapSecond] Whether this time is during a leap second.
  3206. *
  3207. * @see JulianDate#toGregorianDate
  3208. */
  3209. function GregorianDate(
  3210. year,
  3211. month,
  3212. day,
  3213. hour,
  3214. minute,
  3215. second,
  3216. millisecond,
  3217. isLeapSecond
  3218. ) {
  3219. /**
  3220. * Gets or sets the year as a whole number.
  3221. * @type {Number}
  3222. */
  3223. this.year = year;
  3224. /**
  3225. * Gets or sets the month as a whole number with range [1, 12].
  3226. * @type {Number}
  3227. */
  3228. this.month = month;
  3229. /**
  3230. * Gets or sets the day of the month as a whole number starting at 1.
  3231. * @type {Number}
  3232. */
  3233. this.day = day;
  3234. /**
  3235. * Gets or sets the hour as a whole number with range [0, 23].
  3236. * @type {Number}
  3237. */
  3238. this.hour = hour;
  3239. /**
  3240. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  3241. * @type {Number}
  3242. */
  3243. this.minute = minute;
  3244. /**
  3245. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  3246. * @type {Number}
  3247. */
  3248. this.second = second;
  3249. /**
  3250. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  3251. * @type {Number}
  3252. */
  3253. this.millisecond = millisecond;
  3254. /**
  3255. * Gets or sets whether this time is during a leap second.
  3256. * @type {Boolean}
  3257. */
  3258. this.isLeapSecond = isLeapSecond;
  3259. }
  3260. /**
  3261. * Determines if a given date is a leap year.
  3262. *
  3263. * @function isLeapYear
  3264. *
  3265. * @param {Number} year The year to be tested.
  3266. * @returns {Boolean} True if <code>year</code> is a leap year.
  3267. *
  3268. * @example
  3269. * const leapYear = Cesium.isLeapYear(2000); // true
  3270. */
  3271. function isLeapYear(year) {
  3272. //>>includeStart('debug', pragmas.debug);
  3273. if (year === null || isNaN(year)) {
  3274. throw new RuntimeError.DeveloperError("year is required and must be a number.");
  3275. }
  3276. //>>includeEnd('debug');
  3277. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  3278. }
  3279. /**
  3280. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  3281. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  3282. * @alias LeapSecond
  3283. * @constructor
  3284. *
  3285. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  3286. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  3287. */
  3288. function LeapSecond(date, offset) {
  3289. /**
  3290. * Gets or sets the date at which this leap second occurs.
  3291. * @type {JulianDate}
  3292. */
  3293. this.julianDate = date;
  3294. /**
  3295. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  3296. * of this leap second.
  3297. * @type {Number}
  3298. */
  3299. this.offset = offset;
  3300. }
  3301. /**
  3302. * Constants for time conversions like those done by {@link JulianDate}.
  3303. *
  3304. * @namespace TimeConstants
  3305. *
  3306. * @see JulianDate
  3307. *
  3308. * @private
  3309. */
  3310. const TimeConstants = {
  3311. /**
  3312. * The number of seconds in one millisecond: <code>0.001</code>
  3313. * @type {Number}
  3314. * @constant
  3315. */
  3316. SECONDS_PER_MILLISECOND: 0.001,
  3317. /**
  3318. * The number of seconds in one minute: <code>60</code>.
  3319. * @type {Number}
  3320. * @constant
  3321. */
  3322. SECONDS_PER_MINUTE: 60.0,
  3323. /**
  3324. * The number of minutes in one hour: <code>60</code>.
  3325. * @type {Number}
  3326. * @constant
  3327. */
  3328. MINUTES_PER_HOUR: 60.0,
  3329. /**
  3330. * The number of hours in one day: <code>24</code>.
  3331. * @type {Number}
  3332. * @constant
  3333. */
  3334. HOURS_PER_DAY: 24.0,
  3335. /**
  3336. * The number of seconds in one hour: <code>3600</code>.
  3337. * @type {Number}
  3338. * @constant
  3339. */
  3340. SECONDS_PER_HOUR: 3600.0,
  3341. /**
  3342. * The number of minutes in one day: <code>1440</code>.
  3343. * @type {Number}
  3344. * @constant
  3345. */
  3346. MINUTES_PER_DAY: 1440.0,
  3347. /**
  3348. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  3349. * @type {Number}
  3350. * @constant
  3351. */
  3352. SECONDS_PER_DAY: 86400.0,
  3353. /**
  3354. * The number of days in one Julian century: <code>36525</code>.
  3355. * @type {Number}
  3356. * @constant
  3357. */
  3358. DAYS_PER_JULIAN_CENTURY: 36525.0,
  3359. /**
  3360. * One trillionth of a second.
  3361. * @type {Number}
  3362. * @constant
  3363. */
  3364. PICOSECOND: 0.000000001,
  3365. /**
  3366. * The number of days to subtract from a Julian date to determine the
  3367. * modified Julian date, which gives the number of days since midnight
  3368. * on November 17, 1858.
  3369. * @type {Number}
  3370. * @constant
  3371. */
  3372. MODIFIED_JULIAN_DATE_DIFFERENCE: 2400000.5,
  3373. };
  3374. var TimeConstants$1 = Object.freeze(TimeConstants);
  3375. /**
  3376. * Provides the type of time standards which JulianDate can take as input.
  3377. *
  3378. * @enum {Number}
  3379. *
  3380. * @see JulianDate
  3381. */
  3382. const TimeStandard = {
  3383. /**
  3384. * Represents the coordinated Universal Time (UTC) time standard.
  3385. *
  3386. * UTC is related to TAI according to the relationship
  3387. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  3388. * seconds which have been introduced as of the time in TAI.
  3389. *
  3390. * @type {Number}
  3391. * @constant
  3392. */
  3393. UTC: 0,
  3394. /**
  3395. * Represents the International Atomic Time (TAI) time standard.
  3396. * TAI is the principal time standard to which the other time standards are related.
  3397. *
  3398. * @type {Number}
  3399. * @constant
  3400. */
  3401. TAI: 1,
  3402. };
  3403. var TimeStandard$1 = Object.freeze(TimeStandard);
  3404. const gregorianDateScratch = new GregorianDate();
  3405. const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  3406. const daysInLeapFeburary = 29;
  3407. function compareLeapSecondDates$1(leapSecond, dateToFind) {
  3408. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  3409. }
  3410. // we don't really need a leap second instance, anything with a julianDate property will do
  3411. const binarySearchScratchLeapSecond = new LeapSecond();
  3412. function convertUtcToTai(julianDate) {
  3413. //Even though julianDate is in UTC, we'll treat it as TAI and
  3414. //search the leap second table for it.
  3415. binarySearchScratchLeapSecond.julianDate = julianDate;
  3416. const leapSeconds = JulianDate.leapSeconds;
  3417. let index = binarySearch(
  3418. leapSeconds,
  3419. binarySearchScratchLeapSecond,
  3420. compareLeapSecondDates$1
  3421. );
  3422. if (index < 0) {
  3423. index = ~index;
  3424. }
  3425. if (index >= leapSeconds.length) {
  3426. index = leapSeconds.length - 1;
  3427. }
  3428. let offset = leapSeconds[index].offset;
  3429. if (index > 0) {
  3430. //Now we have the index of the closest leap second that comes on or after our UTC time.
  3431. //However, if the difference between the UTC date being converted and the TAI
  3432. //defined leap second is greater than the offset, we are off by one and need to use
  3433. //the previous leap second.
  3434. const difference = JulianDate.secondsDifference(
  3435. leapSeconds[index].julianDate,
  3436. julianDate
  3437. );
  3438. if (difference > offset) {
  3439. index--;
  3440. offset = leapSeconds[index].offset;
  3441. }
  3442. }
  3443. JulianDate.addSeconds(julianDate, offset, julianDate);
  3444. }
  3445. function convertTaiToUtc(julianDate, result) {
  3446. binarySearchScratchLeapSecond.julianDate = julianDate;
  3447. const leapSeconds = JulianDate.leapSeconds;
  3448. let index = binarySearch(
  3449. leapSeconds,
  3450. binarySearchScratchLeapSecond,
  3451. compareLeapSecondDates$1
  3452. );
  3453. if (index < 0) {
  3454. index = ~index;
  3455. }
  3456. //All times before our first leap second get the first offset.
  3457. if (index === 0) {
  3458. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  3459. }
  3460. //All times after our leap second get the last offset.
  3461. if (index >= leapSeconds.length) {
  3462. return JulianDate.addSeconds(
  3463. julianDate,
  3464. -leapSeconds[index - 1].offset,
  3465. result
  3466. );
  3467. }
  3468. //Compute the difference between the found leap second and the time we are converting.
  3469. const difference = JulianDate.secondsDifference(
  3470. leapSeconds[index].julianDate,
  3471. julianDate
  3472. );
  3473. if (difference === 0) {
  3474. //The date is in our leap second table.
  3475. return JulianDate.addSeconds(
  3476. julianDate,
  3477. -leapSeconds[index].offset,
  3478. result
  3479. );
  3480. }
  3481. if (difference <= 1.0) {
  3482. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  3483. return undefined;
  3484. }
  3485. //The time is in between two leap seconds, index is the leap second after the date
  3486. //we're converting, so we subtract one to get the correct LeapSecond instance.
  3487. return JulianDate.addSeconds(
  3488. julianDate,
  3489. -leapSeconds[--index].offset,
  3490. result
  3491. );
  3492. }
  3493. function setComponents(wholeDays, secondsOfDay, julianDate) {
  3494. const extraDays = (secondsOfDay / TimeConstants$1.SECONDS_PER_DAY) | 0;
  3495. wholeDays += extraDays;
  3496. secondsOfDay -= TimeConstants$1.SECONDS_PER_DAY * extraDays;
  3497. if (secondsOfDay < 0) {
  3498. wholeDays--;
  3499. secondsOfDay += TimeConstants$1.SECONDS_PER_DAY;
  3500. }
  3501. julianDate.dayNumber = wholeDays;
  3502. julianDate.secondsOfDay = secondsOfDay;
  3503. return julianDate;
  3504. }
  3505. function computeJulianDateComponents(
  3506. year,
  3507. month,
  3508. day,
  3509. hour,
  3510. minute,
  3511. second,
  3512. millisecond
  3513. ) {
  3514. // Algorithm from page 604 of the Explanatory Supplement to the
  3515. // Astronomical Almanac (Seidelmann 1992).
  3516. const a = ((month - 14) / 12) | 0;
  3517. const b = year + 4800 + a;
  3518. let dayNumber =
  3519. (((1461 * b) / 4) | 0) +
  3520. (((367 * (month - 2 - 12 * a)) / 12) | 0) -
  3521. (((3 * (((b + 100) / 100) | 0)) / 4) | 0) +
  3522. day -
  3523. 32075;
  3524. // JulianDates are noon-based
  3525. hour = hour - 12;
  3526. if (hour < 0) {
  3527. hour += 24;
  3528. }
  3529. const secondsOfDay =
  3530. second +
  3531. (hour * TimeConstants$1.SECONDS_PER_HOUR +
  3532. minute * TimeConstants$1.SECONDS_PER_MINUTE +
  3533. millisecond * TimeConstants$1.SECONDS_PER_MILLISECOND);
  3534. if (secondsOfDay >= 43200.0) {
  3535. dayNumber -= 1;
  3536. }
  3537. return [dayNumber, secondsOfDay];
  3538. }
  3539. //Regular expressions used for ISO8601 date parsing.
  3540. //YYYY
  3541. const matchCalendarYear = /^(\d{4})$/;
  3542. //YYYY-MM (YYYYMM is invalid)
  3543. const matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  3544. //YYYY-DDD or YYYYDDD
  3545. const matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  3546. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  3547. const matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  3548. //YYYY-MM-DD or YYYYMMDD
  3549. const matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  3550. // Match utc offset
  3551. const utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  3552. // Match hours HH or HH.xxxxx
  3553. const matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  3554. // Match hours/minutes HH:MM HHMM.xxxxx
  3555. const matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  3556. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  3557. const matchHoursMinutesSeconds =
  3558. /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  3559. const iso8601ErrorMessage = "Invalid ISO 8601 date.";
  3560. /**
  3561. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  3562. * For increased precision, this class stores the whole number part of the date and the seconds
  3563. * part of the date in separate components. In order to be safe for arithmetic and represent
  3564. * leap seconds, the date is always stored in the International Atomic Time standard
  3565. * {@link TimeStandard.TAI}.
  3566. * @alias JulianDate
  3567. * @constructor
  3568. *
  3569. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  3570. * @param {Number} [secondsOfDay=0.0] The number of seconds into the current Julian Day Number. Fractional seconds, negative seconds and seconds greater than a day will be handled correctly.
  3571. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  3572. */
  3573. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  3574. /**
  3575. * Gets or sets the number of whole days.
  3576. * @type {Number}
  3577. */
  3578. this.dayNumber = undefined;
  3579. /**
  3580. * Gets or sets the number of seconds into the current day.
  3581. * @type {Number}
  3582. */
  3583. this.secondsOfDay = undefined;
  3584. julianDayNumber = defaultValue.defaultValue(julianDayNumber, 0.0);
  3585. secondsOfDay = defaultValue.defaultValue(secondsOfDay, 0.0);
  3586. timeStandard = defaultValue.defaultValue(timeStandard, TimeStandard$1.UTC);
  3587. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  3588. const wholeDays = julianDayNumber | 0;
  3589. secondsOfDay =
  3590. secondsOfDay +
  3591. (julianDayNumber - wholeDays) * TimeConstants$1.SECONDS_PER_DAY;
  3592. setComponents(wholeDays, secondsOfDay, this);
  3593. if (timeStandard === TimeStandard$1.UTC) {
  3594. convertUtcToTai(this);
  3595. }
  3596. }
  3597. /**
  3598. * Creates a new instance from a GregorianDate.
  3599. *
  3600. * @param {GregorianDate} date A GregorianDate.
  3601. * @param {JulianDate} [result] An existing instance to use for the result.
  3602. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3603. *
  3604. * @exception {DeveloperError} date must be a valid GregorianDate.
  3605. */
  3606. JulianDate.fromGregorianDate = function (date, result) {
  3607. //>>includeStart('debug', pragmas.debug);
  3608. if (!(date instanceof GregorianDate)) {
  3609. throw new RuntimeError.DeveloperError("date must be a valid GregorianDate.");
  3610. }
  3611. //>>includeEnd('debug');
  3612. const components = computeJulianDateComponents(
  3613. date.year,
  3614. date.month,
  3615. date.day,
  3616. date.hour,
  3617. date.minute,
  3618. date.second,
  3619. date.millisecond
  3620. );
  3621. if (!defaultValue.defined(result)) {
  3622. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  3623. }
  3624. setComponents(components[0], components[1], result);
  3625. convertUtcToTai(result);
  3626. return result;
  3627. };
  3628. /**
  3629. * Creates a new instance from a JavaScript Date.
  3630. *
  3631. * @param {Date} date A JavaScript Date.
  3632. * @param {JulianDate} [result] An existing instance to use for the result.
  3633. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3634. *
  3635. * @exception {DeveloperError} date must be a valid JavaScript Date.
  3636. */
  3637. JulianDate.fromDate = function (date, result) {
  3638. //>>includeStart('debug', pragmas.debug);
  3639. if (!(date instanceof Date) || isNaN(date.getTime())) {
  3640. throw new RuntimeError.DeveloperError("date must be a valid JavaScript Date.");
  3641. }
  3642. //>>includeEnd('debug');
  3643. const components = computeJulianDateComponents(
  3644. date.getUTCFullYear(),
  3645. date.getUTCMonth() + 1,
  3646. date.getUTCDate(),
  3647. date.getUTCHours(),
  3648. date.getUTCMinutes(),
  3649. date.getUTCSeconds(),
  3650. date.getUTCMilliseconds()
  3651. );
  3652. if (!defaultValue.defined(result)) {
  3653. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  3654. }
  3655. setComponents(components[0], components[1], result);
  3656. convertUtcToTai(result);
  3657. return result;
  3658. };
  3659. /**
  3660. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  3661. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  3662. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  3663. *
  3664. * @param {String} iso8601String An ISO 8601 date.
  3665. * @param {JulianDate} [result] An existing instance to use for the result.
  3666. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3667. *
  3668. * @exception {DeveloperError} Invalid ISO 8601 date.
  3669. */
  3670. JulianDate.fromIso8601 = function (iso8601String, result) {
  3671. //>>includeStart('debug', pragmas.debug);
  3672. if (typeof iso8601String !== "string") {
  3673. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3674. }
  3675. //>>includeEnd('debug');
  3676. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  3677. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  3678. iso8601String = iso8601String.replace(",", ".");
  3679. //Split the string into its date and time components, denoted by a mandatory T
  3680. let tokens = iso8601String.split("T");
  3681. let year;
  3682. let month = 1;
  3683. let day = 1;
  3684. let hour = 0;
  3685. let minute = 0;
  3686. let second = 0;
  3687. let millisecond = 0;
  3688. //Lacking a time is okay, but a missing date is illegal.
  3689. const date = tokens[0];
  3690. const time = tokens[1];
  3691. let tmp;
  3692. let inLeapYear;
  3693. //>>includeStart('debug', pragmas.debug);
  3694. if (!defaultValue.defined(date)) {
  3695. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3696. }
  3697. let dashCount;
  3698. //>>includeEnd('debug');
  3699. //First match the date against possible regular expressions.
  3700. tokens = date.match(matchCalendarDate);
  3701. if (tokens !== null) {
  3702. //>>includeStart('debug', pragmas.debug);
  3703. dashCount = date.split("-").length - 1;
  3704. if (dashCount > 0 && dashCount !== 2) {
  3705. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3706. }
  3707. //>>includeEnd('debug');
  3708. year = +tokens[1];
  3709. month = +tokens[2];
  3710. day = +tokens[3];
  3711. } else {
  3712. tokens = date.match(matchCalendarMonth);
  3713. if (tokens !== null) {
  3714. year = +tokens[1];
  3715. month = +tokens[2];
  3716. } else {
  3717. tokens = date.match(matchCalendarYear);
  3718. if (tokens !== null) {
  3719. year = +tokens[1];
  3720. } else {
  3721. //Not a year/month/day so it must be an ordinal date.
  3722. let dayOfYear;
  3723. tokens = date.match(matchOrdinalDate);
  3724. if (tokens !== null) {
  3725. year = +tokens[1];
  3726. dayOfYear = +tokens[2];
  3727. inLeapYear = isLeapYear(year);
  3728. //This validation is only applicable for this format.
  3729. //>>includeStart('debug', pragmas.debug);
  3730. if (
  3731. dayOfYear < 1 ||
  3732. (inLeapYear && dayOfYear > 366) ||
  3733. (!inLeapYear && dayOfYear > 365)
  3734. ) {
  3735. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3736. }
  3737. //>>includeEnd('debug')
  3738. } else {
  3739. tokens = date.match(matchWeekDate);
  3740. if (tokens !== null) {
  3741. //ISO week date to ordinal date from
  3742. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  3743. year = +tokens[1];
  3744. const weekNumber = +tokens[2];
  3745. const dayOfWeek = +tokens[3] || 0;
  3746. //>>includeStart('debug', pragmas.debug);
  3747. dashCount = date.split("-").length - 1;
  3748. if (
  3749. dashCount > 0 &&
  3750. ((!defaultValue.defined(tokens[3]) && dashCount !== 1) ||
  3751. (defaultValue.defined(tokens[3]) && dashCount !== 2))
  3752. ) {
  3753. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3754. }
  3755. //>>includeEnd('debug')
  3756. const january4 = new Date(Date.UTC(year, 0, 4));
  3757. dayOfYear = weekNumber * 7 + dayOfWeek - january4.getUTCDay() - 3;
  3758. } else {
  3759. //None of our regular expressions succeeded in parsing the date properly.
  3760. //>>includeStart('debug', pragmas.debug);
  3761. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3762. //>>includeEnd('debug')
  3763. }
  3764. }
  3765. //Split an ordinal date into month/day.
  3766. tmp = new Date(Date.UTC(year, 0, 1));
  3767. tmp.setUTCDate(dayOfYear);
  3768. month = tmp.getUTCMonth() + 1;
  3769. day = tmp.getUTCDate();
  3770. }
  3771. }
  3772. }
  3773. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  3774. inLeapYear = isLeapYear(year);
  3775. //>>includeStart('debug', pragmas.debug);
  3776. if (
  3777. month < 1 ||
  3778. month > 12 ||
  3779. day < 1 ||
  3780. ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) ||
  3781. (inLeapYear && month === 2 && day > daysInLeapFeburary)
  3782. ) {
  3783. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3784. }
  3785. //>>includeEnd('debug')
  3786. //Now move onto the time string, which is much simpler.
  3787. //If no time is specified, it is considered the beginning of the day, UTC to match Javascript's implementation.
  3788. let offsetIndex;
  3789. if (defaultValue.defined(time)) {
  3790. tokens = time.match(matchHoursMinutesSeconds);
  3791. if (tokens !== null) {
  3792. //>>includeStart('debug', pragmas.debug);
  3793. dashCount = time.split(":").length - 1;
  3794. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  3795. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3796. }
  3797. //>>includeEnd('debug')
  3798. hour = +tokens[1];
  3799. minute = +tokens[2];
  3800. second = +tokens[3];
  3801. millisecond = +(tokens[4] || 0) * 1000.0;
  3802. offsetIndex = 5;
  3803. } else {
  3804. tokens = time.match(matchHoursMinutes);
  3805. if (tokens !== null) {
  3806. //>>includeStart('debug', pragmas.debug);
  3807. dashCount = time.split(":").length - 1;
  3808. if (dashCount > 2) {
  3809. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3810. }
  3811. //>>includeEnd('debug')
  3812. hour = +tokens[1];
  3813. minute = +tokens[2];
  3814. second = +(tokens[3] || 0) * 60.0;
  3815. offsetIndex = 4;
  3816. } else {
  3817. tokens = time.match(matchHours);
  3818. if (tokens !== null) {
  3819. hour = +tokens[1];
  3820. minute = +(tokens[2] || 0) * 60.0;
  3821. offsetIndex = 3;
  3822. } else {
  3823. //>>includeStart('debug', pragmas.debug);
  3824. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3825. //>>includeEnd('debug')
  3826. }
  3827. }
  3828. }
  3829. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  3830. //>>includeStart('debug', pragmas.debug);
  3831. if (
  3832. minute >= 60 ||
  3833. second >= 61 ||
  3834. hour > 24 ||
  3835. (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))
  3836. ) {
  3837. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3838. }
  3839. //>>includeEnd('debug');
  3840. //Check the UTC offset value, if no value exists, use local time
  3841. //a Z indicates UTC, + or - are offsets.
  3842. const offset = tokens[offsetIndex];
  3843. const offsetHours = +tokens[offsetIndex + 1];
  3844. const offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  3845. switch (offset) {
  3846. case "+":
  3847. hour = hour - offsetHours;
  3848. minute = minute - offsetMinutes;
  3849. break;
  3850. case "-":
  3851. hour = hour + offsetHours;
  3852. minute = minute + offsetMinutes;
  3853. break;
  3854. case "Z":
  3855. break;
  3856. default:
  3857. minute =
  3858. minute +
  3859. new Date(
  3860. Date.UTC(year, month - 1, day, hour, minute)
  3861. ).getTimezoneOffset();
  3862. break;
  3863. }
  3864. }
  3865. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  3866. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  3867. //Then we add it back in after converting to TAI.
  3868. const isLeapSecond = second === 60;
  3869. if (isLeapSecond) {
  3870. second--;
  3871. }
  3872. //Even if we successfully parsed the string into its components, after applying UTC offset or
  3873. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  3874. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  3875. while (minute >= 60) {
  3876. minute -= 60;
  3877. hour++;
  3878. }
  3879. while (hour >= 24) {
  3880. hour -= 24;
  3881. day++;
  3882. }
  3883. tmp = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  3884. while (day > tmp) {
  3885. day -= tmp;
  3886. month++;
  3887. if (month > 12) {
  3888. month -= 12;
  3889. year++;
  3890. }
  3891. tmp =
  3892. inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  3893. }
  3894. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  3895. while (minute < 0) {
  3896. minute += 60;
  3897. hour--;
  3898. }
  3899. while (hour < 0) {
  3900. hour += 24;
  3901. day--;
  3902. }
  3903. while (day < 1) {
  3904. month--;
  3905. if (month < 1) {
  3906. month += 12;
  3907. year--;
  3908. }
  3909. tmp =
  3910. inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  3911. day += tmp;
  3912. }
  3913. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  3914. const components = computeJulianDateComponents(
  3915. year,
  3916. month,
  3917. day,
  3918. hour,
  3919. minute,
  3920. second,
  3921. millisecond
  3922. );
  3923. if (!defaultValue.defined(result)) {
  3924. result = new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  3925. } else {
  3926. setComponents(components[0], components[1], result);
  3927. convertUtcToTai(result);
  3928. }
  3929. //If we were on a leap second, add it back.
  3930. if (isLeapSecond) {
  3931. JulianDate.addSeconds(result, 1, result);
  3932. }
  3933. return result;
  3934. };
  3935. /**
  3936. * Creates a new instance that represents the current system time.
  3937. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  3938. *
  3939. * @param {JulianDate} [result] An existing instance to use for the result.
  3940. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3941. */
  3942. JulianDate.now = function (result) {
  3943. return JulianDate.fromDate(new Date(), result);
  3944. };
  3945. const toGregorianDateScratch = new JulianDate(0, 0, TimeStandard$1.TAI);
  3946. /**
  3947. * Creates a {@link GregorianDate} from the provided instance.
  3948. *
  3949. * @param {JulianDate} julianDate The date to be converted.
  3950. * @param {GregorianDate} [result] An existing instance to use for the result.
  3951. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  3952. */
  3953. JulianDate.toGregorianDate = function (julianDate, result) {
  3954. //>>includeStart('debug', pragmas.debug);
  3955. if (!defaultValue.defined(julianDate)) {
  3956. throw new RuntimeError.DeveloperError("julianDate is required.");
  3957. }
  3958. //>>includeEnd('debug');
  3959. let isLeapSecond = false;
  3960. let thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  3961. if (!defaultValue.defined(thisUtc)) {
  3962. //Conversion to UTC will fail if we are during a leap second.
  3963. //If that's the case, subtract a second and convert again.
  3964. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  3965. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  3966. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  3967. isLeapSecond = true;
  3968. }
  3969. let julianDayNumber = thisUtc.dayNumber;
  3970. const secondsOfDay = thisUtc.secondsOfDay;
  3971. if (secondsOfDay >= 43200.0) {
  3972. julianDayNumber += 1;
  3973. }
  3974. // Algorithm from page 604 of the Explanatory Supplement to the
  3975. // Astronomical Almanac (Seidelmann 1992).
  3976. let L = (julianDayNumber + 68569) | 0;
  3977. const N = ((4 * L) / 146097) | 0;
  3978. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  3979. const I = ((4000 * (L + 1)) / 1461001) | 0;
  3980. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  3981. const J = ((80 * L) / 2447) | 0;
  3982. const day = (L - (((2447 * J) / 80) | 0)) | 0;
  3983. L = (J / 11) | 0;
  3984. const month = (J + 2 - 12 * L) | 0;
  3985. const year = (100 * (N - 49) + I + L) | 0;
  3986. let hour = (secondsOfDay / TimeConstants$1.SECONDS_PER_HOUR) | 0;
  3987. let remainingSeconds = secondsOfDay - hour * TimeConstants$1.SECONDS_PER_HOUR;
  3988. const minute = (remainingSeconds / TimeConstants$1.SECONDS_PER_MINUTE) | 0;
  3989. remainingSeconds =
  3990. remainingSeconds - minute * TimeConstants$1.SECONDS_PER_MINUTE;
  3991. let second = remainingSeconds | 0;
  3992. const millisecond =
  3993. (remainingSeconds - second) / TimeConstants$1.SECONDS_PER_MILLISECOND;
  3994. // JulianDates are noon-based
  3995. hour += 12;
  3996. if (hour > 23) {
  3997. hour -= 24;
  3998. }
  3999. //If we were on a leap second, add it back.
  4000. if (isLeapSecond) {
  4001. second += 1;
  4002. }
  4003. if (!defaultValue.defined(result)) {
  4004. return new GregorianDate(
  4005. year,
  4006. month,
  4007. day,
  4008. hour,
  4009. minute,
  4010. second,
  4011. millisecond,
  4012. isLeapSecond
  4013. );
  4014. }
  4015. result.year = year;
  4016. result.month = month;
  4017. result.day = day;
  4018. result.hour = hour;
  4019. result.minute = minute;
  4020. result.second = second;
  4021. result.millisecond = millisecond;
  4022. result.isLeapSecond = isLeapSecond;
  4023. return result;
  4024. };
  4025. /**
  4026. * Creates a JavaScript Date from the provided instance.
  4027. * Since JavaScript dates are only accurate to the nearest millisecond and
  4028. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  4029. * If the provided JulianDate is during a leap second, the previous second is used.
  4030. *
  4031. * @param {JulianDate} julianDate The date to be converted.
  4032. * @returns {Date} A new instance representing the provided date.
  4033. */
  4034. JulianDate.toDate = function (julianDate) {
  4035. //>>includeStart('debug', pragmas.debug);
  4036. if (!defaultValue.defined(julianDate)) {
  4037. throw new RuntimeError.DeveloperError("julianDate is required.");
  4038. }
  4039. //>>includeEnd('debug');
  4040. const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  4041. let second = gDate.second;
  4042. if (gDate.isLeapSecond) {
  4043. second -= 1;
  4044. }
  4045. return new Date(
  4046. Date.UTC(
  4047. gDate.year,
  4048. gDate.month - 1,
  4049. gDate.day,
  4050. gDate.hour,
  4051. gDate.minute,
  4052. second,
  4053. gDate.millisecond
  4054. )
  4055. );
  4056. };
  4057. /**
  4058. * Creates an ISO8601 representation of the provided date.
  4059. *
  4060. * @param {JulianDate} julianDate The date to be converted.
  4061. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  4062. * @returns {String} The ISO8601 representation of the provided date.
  4063. */
  4064. JulianDate.toIso8601 = function (julianDate, precision) {
  4065. //>>includeStart('debug', pragmas.debug);
  4066. if (!defaultValue.defined(julianDate)) {
  4067. throw new RuntimeError.DeveloperError("julianDate is required.");
  4068. }
  4069. //>>includeEnd('debug');
  4070. const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  4071. let year = gDate.year;
  4072. let month = gDate.month;
  4073. let day = gDate.day;
  4074. let hour = gDate.hour;
  4075. const minute = gDate.minute;
  4076. const second = gDate.second;
  4077. const millisecond = gDate.millisecond;
  4078. // special case - Iso8601.MAXIMUM_VALUE produces a string which we can't parse unless we adjust.
  4079. // 10000-01-01T00:00:00 is the same instant as 9999-12-31T24:00:00
  4080. if (
  4081. year === 10000 &&
  4082. month === 1 &&
  4083. day === 1 &&
  4084. hour === 0 &&
  4085. minute === 0 &&
  4086. second === 0 &&
  4087. millisecond === 0
  4088. ) {
  4089. year = 9999;
  4090. month = 12;
  4091. day = 31;
  4092. hour = 24;
  4093. }
  4094. let millisecondStr;
  4095. if (!defaultValue.defined(precision) && millisecond !== 0) {
  4096. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  4097. millisecondStr = (millisecond * 0.01).toString().replace(".", "");
  4098. return `${year.toString().padStart(4, "0")}-${month
  4099. .toString()
  4100. .padStart(2, "0")}-${day
  4101. .toString()
  4102. .padStart(2, "0")}T${hour
  4103. .toString()
  4104. .padStart(2, "0")}:${minute
  4105. .toString()
  4106. .padStart(2, "0")}:${second
  4107. .toString()
  4108. .padStart(2, "0")}.${millisecondStr}Z`;
  4109. }
  4110. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  4111. if (!defaultValue.defined(precision) || precision === 0) {
  4112. return `${year.toString().padStart(4, "0")}-${month
  4113. .toString()
  4114. .padStart(2, "0")}-${day
  4115. .toString()
  4116. .padStart(2, "0")}T${hour
  4117. .toString()
  4118. .padStart(2, "0")}:${minute
  4119. .toString()
  4120. .padStart(2, "0")}:${second.toString().padStart(2, "0")}Z`;
  4121. }
  4122. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  4123. millisecondStr = (millisecond * 0.01)
  4124. .toFixed(precision)
  4125. .replace(".", "")
  4126. .slice(0, precision);
  4127. return `${year.toString().padStart(4, "0")}-${month
  4128. .toString()
  4129. .padStart(2, "0")}-${day
  4130. .toString()
  4131. .padStart(2, "0")}T${hour
  4132. .toString()
  4133. .padStart(2, "0")}:${minute
  4134. .toString()
  4135. .padStart(2, "0")}:${second
  4136. .toString()
  4137. .padStart(2, "0")}.${millisecondStr}Z`;
  4138. };
  4139. /**
  4140. * Duplicates a JulianDate instance.
  4141. *
  4142. * @param {JulianDate} julianDate The date to duplicate.
  4143. * @param {JulianDate} [result] An existing instance to use for the result.
  4144. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  4145. */
  4146. JulianDate.clone = function (julianDate, result) {
  4147. if (!defaultValue.defined(julianDate)) {
  4148. return undefined;
  4149. }
  4150. if (!defaultValue.defined(result)) {
  4151. return new JulianDate(
  4152. julianDate.dayNumber,
  4153. julianDate.secondsOfDay,
  4154. TimeStandard$1.TAI
  4155. );
  4156. }
  4157. result.dayNumber = julianDate.dayNumber;
  4158. result.secondsOfDay = julianDate.secondsOfDay;
  4159. return result;
  4160. };
  4161. /**
  4162. * Compares two instances.
  4163. *
  4164. * @param {JulianDate} left The first instance.
  4165. * @param {JulianDate} right The second instance.
  4166. * @returns {Number} A negative value if left is less than right, a positive value if left is greater than right, or zero if left and right are equal.
  4167. */
  4168. JulianDate.compare = function (left, right) {
  4169. //>>includeStart('debug', pragmas.debug);
  4170. if (!defaultValue.defined(left)) {
  4171. throw new RuntimeError.DeveloperError("left is required.");
  4172. }
  4173. if (!defaultValue.defined(right)) {
  4174. throw new RuntimeError.DeveloperError("right is required.");
  4175. }
  4176. //>>includeEnd('debug');
  4177. const julianDayNumberDifference = left.dayNumber - right.dayNumber;
  4178. if (julianDayNumberDifference !== 0) {
  4179. return julianDayNumberDifference;
  4180. }
  4181. return left.secondsOfDay - right.secondsOfDay;
  4182. };
  4183. /**
  4184. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  4185. *
  4186. * @param {JulianDate} [left] The first instance.
  4187. * @param {JulianDate} [right] The second instance.
  4188. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  4189. */
  4190. JulianDate.equals = function (left, right) {
  4191. return (
  4192. left === right ||
  4193. (defaultValue.defined(left) &&
  4194. defaultValue.defined(right) &&
  4195. left.dayNumber === right.dayNumber &&
  4196. left.secondsOfDay === right.secondsOfDay)
  4197. );
  4198. };
  4199. /**
  4200. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  4201. * each other. That is, in order for the dates to be considered equal (and for
  4202. * this function to return <code>true</code>), the absolute value of the difference between them, in
  4203. * seconds, must be less than <code>epsilon</code>.
  4204. *
  4205. * @param {JulianDate} [left] The first instance.
  4206. * @param {JulianDate} [right] The second instance.
  4207. * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
  4208. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  4209. */
  4210. JulianDate.equalsEpsilon = function (left, right, epsilon) {
  4211. epsilon = defaultValue.defaultValue(epsilon, 0);
  4212. return (
  4213. left === right ||
  4214. (defaultValue.defined(left) &&
  4215. defaultValue.defined(right) &&
  4216. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon)
  4217. );
  4218. };
  4219. /**
  4220. * Computes the total number of whole and fractional days represented by the provided instance.
  4221. *
  4222. * @param {JulianDate} julianDate The date.
  4223. * @returns {Number} The Julian date as single floating point number.
  4224. */
  4225. JulianDate.totalDays = function (julianDate) {
  4226. //>>includeStart('debug', pragmas.debug);
  4227. if (!defaultValue.defined(julianDate)) {
  4228. throw new RuntimeError.DeveloperError("julianDate is required.");
  4229. }
  4230. //>>includeEnd('debug');
  4231. return (
  4232. julianDate.dayNumber +
  4233. julianDate.secondsOfDay / TimeConstants$1.SECONDS_PER_DAY
  4234. );
  4235. };
  4236. /**
  4237. * Computes the difference in seconds between the provided instance.
  4238. *
  4239. * @param {JulianDate} left The first instance.
  4240. * @param {JulianDate} right The second instance.
  4241. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  4242. */
  4243. JulianDate.secondsDifference = function (left, right) {
  4244. //>>includeStart('debug', pragmas.debug);
  4245. if (!defaultValue.defined(left)) {
  4246. throw new RuntimeError.DeveloperError("left is required.");
  4247. }
  4248. if (!defaultValue.defined(right)) {
  4249. throw new RuntimeError.DeveloperError("right is required.");
  4250. }
  4251. //>>includeEnd('debug');
  4252. const dayDifference =
  4253. (left.dayNumber - right.dayNumber) * TimeConstants$1.SECONDS_PER_DAY;
  4254. return dayDifference + (left.secondsOfDay - right.secondsOfDay);
  4255. };
  4256. /**
  4257. * Computes the difference in days between the provided instance.
  4258. *
  4259. * @param {JulianDate} left The first instance.
  4260. * @param {JulianDate} right The second instance.
  4261. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  4262. */
  4263. JulianDate.daysDifference = function (left, right) {
  4264. //>>includeStart('debug', pragmas.debug);
  4265. if (!defaultValue.defined(left)) {
  4266. throw new RuntimeError.DeveloperError("left is required.");
  4267. }
  4268. if (!defaultValue.defined(right)) {
  4269. throw new RuntimeError.DeveloperError("right is required.");
  4270. }
  4271. //>>includeEnd('debug');
  4272. const dayDifference = left.dayNumber - right.dayNumber;
  4273. const secondDifference =
  4274. (left.secondsOfDay - right.secondsOfDay) / TimeConstants$1.SECONDS_PER_DAY;
  4275. return dayDifference + secondDifference;
  4276. };
  4277. /**
  4278. * Computes the number of seconds the provided instance is ahead of UTC.
  4279. *
  4280. * @param {JulianDate} julianDate The date.
  4281. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  4282. */
  4283. JulianDate.computeTaiMinusUtc = function (julianDate) {
  4284. binarySearchScratchLeapSecond.julianDate = julianDate;
  4285. const leapSeconds = JulianDate.leapSeconds;
  4286. let index = binarySearch(
  4287. leapSeconds,
  4288. binarySearchScratchLeapSecond,
  4289. compareLeapSecondDates$1
  4290. );
  4291. if (index < 0) {
  4292. index = ~index;
  4293. --index;
  4294. if (index < 0) {
  4295. index = 0;
  4296. }
  4297. }
  4298. return leapSeconds[index].offset;
  4299. };
  4300. /**
  4301. * Adds the provided number of seconds to the provided date instance.
  4302. *
  4303. * @param {JulianDate} julianDate The date.
  4304. * @param {Number} seconds The number of seconds to add or subtract.
  4305. * @param {JulianDate} result An existing instance to use for the result.
  4306. * @returns {JulianDate} The modified result parameter.
  4307. */
  4308. JulianDate.addSeconds = function (julianDate, seconds, result) {
  4309. //>>includeStart('debug', pragmas.debug);
  4310. if (!defaultValue.defined(julianDate)) {
  4311. throw new RuntimeError.DeveloperError("julianDate is required.");
  4312. }
  4313. if (!defaultValue.defined(seconds)) {
  4314. throw new RuntimeError.DeveloperError("seconds is required.");
  4315. }
  4316. if (!defaultValue.defined(result)) {
  4317. throw new RuntimeError.DeveloperError("result is required.");
  4318. }
  4319. //>>includeEnd('debug');
  4320. return setComponents(
  4321. julianDate.dayNumber,
  4322. julianDate.secondsOfDay + seconds,
  4323. result
  4324. );
  4325. };
  4326. /**
  4327. * Adds the provided number of minutes to the provided date instance.
  4328. *
  4329. * @param {JulianDate} julianDate The date.
  4330. * @param {Number} minutes The number of minutes to add or subtract.
  4331. * @param {JulianDate} result An existing instance to use for the result.
  4332. * @returns {JulianDate} The modified result parameter.
  4333. */
  4334. JulianDate.addMinutes = function (julianDate, minutes, result) {
  4335. //>>includeStart('debug', pragmas.debug);
  4336. if (!defaultValue.defined(julianDate)) {
  4337. throw new RuntimeError.DeveloperError("julianDate is required.");
  4338. }
  4339. if (!defaultValue.defined(minutes)) {
  4340. throw new RuntimeError.DeveloperError("minutes is required.");
  4341. }
  4342. if (!defaultValue.defined(result)) {
  4343. throw new RuntimeError.DeveloperError("result is required.");
  4344. }
  4345. //>>includeEnd('debug');
  4346. const newSecondsOfDay =
  4347. julianDate.secondsOfDay + minutes * TimeConstants$1.SECONDS_PER_MINUTE;
  4348. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  4349. };
  4350. /**
  4351. * Adds the provided number of hours to the provided date instance.
  4352. *
  4353. * @param {JulianDate} julianDate The date.
  4354. * @param {Number} hours The number of hours to add or subtract.
  4355. * @param {JulianDate} result An existing instance to use for the result.
  4356. * @returns {JulianDate} The modified result parameter.
  4357. */
  4358. JulianDate.addHours = function (julianDate, hours, result) {
  4359. //>>includeStart('debug', pragmas.debug);
  4360. if (!defaultValue.defined(julianDate)) {
  4361. throw new RuntimeError.DeveloperError("julianDate is required.");
  4362. }
  4363. if (!defaultValue.defined(hours)) {
  4364. throw new RuntimeError.DeveloperError("hours is required.");
  4365. }
  4366. if (!defaultValue.defined(result)) {
  4367. throw new RuntimeError.DeveloperError("result is required.");
  4368. }
  4369. //>>includeEnd('debug');
  4370. const newSecondsOfDay =
  4371. julianDate.secondsOfDay + hours * TimeConstants$1.SECONDS_PER_HOUR;
  4372. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  4373. };
  4374. /**
  4375. * Adds the provided number of days to the provided date instance.
  4376. *
  4377. * @param {JulianDate} julianDate The date.
  4378. * @param {Number} days The number of days to add or subtract.
  4379. * @param {JulianDate} result An existing instance to use for the result.
  4380. * @returns {JulianDate} The modified result parameter.
  4381. */
  4382. JulianDate.addDays = function (julianDate, days, result) {
  4383. //>>includeStart('debug', pragmas.debug);
  4384. if (!defaultValue.defined(julianDate)) {
  4385. throw new RuntimeError.DeveloperError("julianDate is required.");
  4386. }
  4387. if (!defaultValue.defined(days)) {
  4388. throw new RuntimeError.DeveloperError("days is required.");
  4389. }
  4390. if (!defaultValue.defined(result)) {
  4391. throw new RuntimeError.DeveloperError("result is required.");
  4392. }
  4393. //>>includeEnd('debug');
  4394. const newJulianDayNumber = julianDate.dayNumber + days;
  4395. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  4396. };
  4397. /**
  4398. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  4399. *
  4400. * @param {JulianDate} left The first instance.
  4401. * @param {JulianDate} right The second instance.
  4402. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  4403. */
  4404. JulianDate.lessThan = function (left, right) {
  4405. return JulianDate.compare(left, right) < 0;
  4406. };
  4407. /**
  4408. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  4409. *
  4410. * @param {JulianDate} left The first instance.
  4411. * @param {JulianDate} right The second instance.
  4412. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  4413. */
  4414. JulianDate.lessThanOrEquals = function (left, right) {
  4415. return JulianDate.compare(left, right) <= 0;
  4416. };
  4417. /**
  4418. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  4419. *
  4420. * @param {JulianDate} left The first instance.
  4421. * @param {JulianDate} right The second instance.
  4422. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  4423. */
  4424. JulianDate.greaterThan = function (left, right) {
  4425. return JulianDate.compare(left, right) > 0;
  4426. };
  4427. /**
  4428. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  4429. *
  4430. * @param {JulianDate} left The first instance.
  4431. * @param {JulianDate} right The second instance.
  4432. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  4433. */
  4434. JulianDate.greaterThanOrEquals = function (left, right) {
  4435. return JulianDate.compare(left, right) >= 0;
  4436. };
  4437. /**
  4438. * Duplicates this instance.
  4439. *
  4440. * @param {JulianDate} [result] An existing instance to use for the result.
  4441. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  4442. */
  4443. JulianDate.prototype.clone = function (result) {
  4444. return JulianDate.clone(this, result);
  4445. };
  4446. /**
  4447. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  4448. *
  4449. * @param {JulianDate} [right] The second instance.
  4450. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  4451. */
  4452. JulianDate.prototype.equals = function (right) {
  4453. return JulianDate.equals(this, right);
  4454. };
  4455. /**
  4456. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  4457. * each other. That is, in order for the dates to be considered equal (and for
  4458. * this function to return <code>true</code>), the absolute value of the difference between them, in
  4459. * seconds, must be less than <code>epsilon</code>.
  4460. *
  4461. * @param {JulianDate} [right] The second instance.
  4462. * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
  4463. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  4464. */
  4465. JulianDate.prototype.equalsEpsilon = function (right, epsilon) {
  4466. return JulianDate.equalsEpsilon(this, right, epsilon);
  4467. };
  4468. /**
  4469. * Creates a string representing this date in ISO8601 format.
  4470. *
  4471. * @returns {String} A string representing this date in ISO8601 format.
  4472. */
  4473. JulianDate.prototype.toString = function () {
  4474. return JulianDate.toIso8601(this);
  4475. };
  4476. /**
  4477. * Gets or sets the list of leap seconds used throughout Cesium.
  4478. * @memberof JulianDate
  4479. * @type {LeapSecond[]}
  4480. */
  4481. JulianDate.leapSeconds = [
  4482. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard$1.TAI), 10), // January 1, 1972 00:00:00 UTC
  4483. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard$1.TAI), 11), // July 1, 1972 00:00:00 UTC
  4484. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard$1.TAI), 12), // January 1, 1973 00:00:00 UTC
  4485. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard$1.TAI), 13), // January 1, 1974 00:00:00 UTC
  4486. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard$1.TAI), 14), // January 1, 1975 00:00:00 UTC
  4487. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard$1.TAI), 15), // January 1, 1976 00:00:00 UTC
  4488. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard$1.TAI), 16), // January 1, 1977 00:00:00 UTC
  4489. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard$1.TAI), 17), // January 1, 1978 00:00:00 UTC
  4490. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard$1.TAI), 18), // January 1, 1979 00:00:00 UTC
  4491. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard$1.TAI), 19), // January 1, 1980 00:00:00 UTC
  4492. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard$1.TAI), 20), // July 1, 1981 00:00:00 UTC
  4493. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard$1.TAI), 21), // July 1, 1982 00:00:00 UTC
  4494. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard$1.TAI), 22), // July 1, 1983 00:00:00 UTC
  4495. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard$1.TAI), 23), // July 1, 1985 00:00:00 UTC
  4496. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard$1.TAI), 24), // January 1, 1988 00:00:00 UTC
  4497. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard$1.TAI), 25), // January 1, 1990 00:00:00 UTC
  4498. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard$1.TAI), 26), // January 1, 1991 00:00:00 UTC
  4499. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard$1.TAI), 27), // July 1, 1992 00:00:00 UTC
  4500. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard$1.TAI), 28), // July 1, 1993 00:00:00 UTC
  4501. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard$1.TAI), 29), // July 1, 1994 00:00:00 UTC
  4502. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard$1.TAI), 30), // January 1, 1996 00:00:00 UTC
  4503. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard$1.TAI), 31), // July 1, 1997 00:00:00 UTC
  4504. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard$1.TAI), 32), // January 1, 1999 00:00:00 UTC
  4505. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard$1.TAI), 33), // January 1, 2006 00:00:00 UTC
  4506. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard$1.TAI), 34), // January 1, 2009 00:00:00 UTC
  4507. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard$1.TAI), 35), // July 1, 2012 00:00:00 UTC
  4508. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard$1.TAI), 36), // July 1, 2015 00:00:00 UTC
  4509. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard$1.TAI), 37), // January 1, 2017 00:00:00 UTC
  4510. ];
  4511. /* This file is automatically rebuilt by the Cesium build process. */
  4512. var punycode = _commonjsHelpers3aae1032.createCommonjsModule(function (module, exports) {
  4513. (function(root) {
  4514. /** Detect free variables */
  4515. var freeExports = exports &&
  4516. !exports.nodeType && exports;
  4517. var freeModule = module &&
  4518. !module.nodeType && module;
  4519. var freeGlobal = typeof _commonjsHelpers3aae1032.commonjsGlobal == 'object' && _commonjsHelpers3aae1032.commonjsGlobal;
  4520. if (
  4521. freeGlobal.global === freeGlobal ||
  4522. freeGlobal.window === freeGlobal ||
  4523. freeGlobal.self === freeGlobal
  4524. ) {
  4525. root = freeGlobal;
  4526. }
  4527. /**
  4528. * The `punycode` object.
  4529. * @name punycode
  4530. * @type Object
  4531. */
  4532. var punycode,
  4533. /** Highest positive signed 32-bit float value */
  4534. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  4535. /** Bootstring parameters */
  4536. base = 36,
  4537. tMin = 1,
  4538. tMax = 26,
  4539. skew = 38,
  4540. damp = 700,
  4541. initialBias = 72,
  4542. initialN = 128, // 0x80
  4543. delimiter = '-', // '\x2D'
  4544. /** Regular expressions */
  4545. regexPunycode = /^xn--/,
  4546. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  4547. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  4548. /** Error messages */
  4549. errors = {
  4550. 'overflow': 'Overflow: input needs wider integers to process',
  4551. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  4552. 'invalid-input': 'Invalid input'
  4553. },
  4554. /** Convenience shortcuts */
  4555. baseMinusTMin = base - tMin,
  4556. floor = Math.floor,
  4557. stringFromCharCode = String.fromCharCode,
  4558. /** Temporary variable */
  4559. key;
  4560. /*--------------------------------------------------------------------------*/
  4561. /**
  4562. * A generic error utility function.
  4563. * @private
  4564. * @param {String} type The error type.
  4565. * @returns {Error} Throws a `RangeError` with the applicable error message.
  4566. */
  4567. function error(type) {
  4568. throw new RangeError(errors[type]);
  4569. }
  4570. /**
  4571. * A generic `Array#map` utility function.
  4572. * @private
  4573. * @param {Array} array The array to iterate over.
  4574. * @param {Function} callback The function that gets called for every array
  4575. * item.
  4576. * @returns {Array} A new array of values returned by the callback function.
  4577. */
  4578. function map(array, fn) {
  4579. var length = array.length;
  4580. var result = [];
  4581. while (length--) {
  4582. result[length] = fn(array[length]);
  4583. }
  4584. return result;
  4585. }
  4586. /**
  4587. * A simple `Array#map`-like wrapper to work with domain name strings or email
  4588. * addresses.
  4589. * @private
  4590. * @param {String} domain The domain name or email address.
  4591. * @param {Function} callback The function that gets called for every
  4592. * character.
  4593. * @returns {Array} A new string of characters returned by the callback
  4594. * function.
  4595. */
  4596. function mapDomain(string, fn) {
  4597. var parts = string.split('@');
  4598. var result = '';
  4599. if (parts.length > 1) {
  4600. // In email addresses, only the domain name should be punycoded. Leave
  4601. // the local part (i.e. everything up to `@`) intact.
  4602. result = parts[0] + '@';
  4603. string = parts[1];
  4604. }
  4605. // Avoid `split(regex)` for IE8 compatibility. See #17.
  4606. string = string.replace(regexSeparators, '\x2E');
  4607. var labels = string.split('.');
  4608. var encoded = map(labels, fn).join('.');
  4609. return result + encoded;
  4610. }
  4611. /**
  4612. * Creates an array containing the numeric code points of each Unicode
  4613. * character in the string. While JavaScript uses UCS-2 internally,
  4614. * this function will convert a pair of surrogate halves (each of which
  4615. * UCS-2 exposes as separate characters) into a single code point,
  4616. * matching UTF-16.
  4617. * @see `punycode.ucs2.encode`
  4618. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  4619. * @memberOf punycode.ucs2
  4620. * @name decode
  4621. * @param {String} string The Unicode input string (UCS-2).
  4622. * @returns {Array} The new array of code points.
  4623. */
  4624. function ucs2decode(string) {
  4625. var output = [],
  4626. counter = 0,
  4627. length = string.length,
  4628. value,
  4629. extra;
  4630. while (counter < length) {
  4631. value = string.charCodeAt(counter++);
  4632. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  4633. // high surrogate, and there is a next character
  4634. extra = string.charCodeAt(counter++);
  4635. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  4636. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  4637. } else {
  4638. // unmatched surrogate; only append this code unit, in case the next
  4639. // code unit is the high surrogate of a surrogate pair
  4640. output.push(value);
  4641. counter--;
  4642. }
  4643. } else {
  4644. output.push(value);
  4645. }
  4646. }
  4647. return output;
  4648. }
  4649. /**
  4650. * Creates a string based on an array of numeric code points.
  4651. * @see `punycode.ucs2.decode`
  4652. * @memberOf punycode.ucs2
  4653. * @name encode
  4654. * @param {Array} codePoints The array of numeric code points.
  4655. * @returns {String} The new Unicode string (UCS-2).
  4656. */
  4657. function ucs2encode(array) {
  4658. return map(array, function(value) {
  4659. var output = '';
  4660. if (value > 0xFFFF) {
  4661. value -= 0x10000;
  4662. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  4663. value = 0xDC00 | value & 0x3FF;
  4664. }
  4665. output += stringFromCharCode(value);
  4666. return output;
  4667. }).join('');
  4668. }
  4669. /**
  4670. * Converts a basic code point into a digit/integer.
  4671. * @see `digitToBasic()`
  4672. * @private
  4673. * @param {Number} codePoint The basic numeric code point value.
  4674. * @returns {Number} The numeric value of a basic code point (for use in
  4675. * representing integers) in the range `0` to `base - 1`, or `base` if
  4676. * the code point does not represent a value.
  4677. */
  4678. function basicToDigit(codePoint) {
  4679. if (codePoint - 48 < 10) {
  4680. return codePoint - 22;
  4681. }
  4682. if (codePoint - 65 < 26) {
  4683. return codePoint - 65;
  4684. }
  4685. if (codePoint - 97 < 26) {
  4686. return codePoint - 97;
  4687. }
  4688. return base;
  4689. }
  4690. /**
  4691. * Converts a digit/integer into a basic code point.
  4692. * @see `basicToDigit()`
  4693. * @private
  4694. * @param {Number} digit The numeric value of a basic code point.
  4695. * @returns {Number} The basic code point whose value (when used for
  4696. * representing integers) is `digit`, which needs to be in the range
  4697. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  4698. * used; else, the lowercase form is used. The behavior is undefined
  4699. * if `flag` is non-zero and `digit` has no uppercase form.
  4700. */
  4701. function digitToBasic(digit, flag) {
  4702. // 0..25 map to ASCII a..z or A..Z
  4703. // 26..35 map to ASCII 0..9
  4704. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  4705. }
  4706. /**
  4707. * Bias adaptation function as per section 3.4 of RFC 3492.
  4708. * https://tools.ietf.org/html/rfc3492#section-3.4
  4709. * @private
  4710. */
  4711. function adapt(delta, numPoints, firstTime) {
  4712. var k = 0;
  4713. delta = firstTime ? floor(delta / damp) : delta >> 1;
  4714. delta += floor(delta / numPoints);
  4715. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  4716. delta = floor(delta / baseMinusTMin);
  4717. }
  4718. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  4719. }
  4720. /**
  4721. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  4722. * symbols.
  4723. * @memberOf punycode
  4724. * @param {String} input The Punycode string of ASCII-only symbols.
  4725. * @returns {String} The resulting string of Unicode symbols.
  4726. */
  4727. function decode(input) {
  4728. // Don't use UCS-2
  4729. var output = [],
  4730. inputLength = input.length,
  4731. out,
  4732. i = 0,
  4733. n = initialN,
  4734. bias = initialBias,
  4735. basic,
  4736. j,
  4737. index,
  4738. oldi,
  4739. w,
  4740. k,
  4741. digit,
  4742. t,
  4743. /** Cached calculation results */
  4744. baseMinusT;
  4745. // Handle the basic code points: let `basic` be the number of input code
  4746. // points before the last delimiter, or `0` if there is none, then copy
  4747. // the first basic code points to the output.
  4748. basic = input.lastIndexOf(delimiter);
  4749. if (basic < 0) {
  4750. basic = 0;
  4751. }
  4752. for (j = 0; j < basic; ++j) {
  4753. // if it's not a basic code point
  4754. if (input.charCodeAt(j) >= 0x80) {
  4755. error('not-basic');
  4756. }
  4757. output.push(input.charCodeAt(j));
  4758. }
  4759. // Main decoding loop: start just after the last delimiter if any basic code
  4760. // points were copied; start at the beginning otherwise.
  4761. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  4762. // `index` is the index of the next character to be consumed.
  4763. // Decode a generalized variable-length integer into `delta`,
  4764. // which gets added to `i`. The overflow checking is easier
  4765. // if we increase `i` as we go, then subtract off its starting
  4766. // value at the end to obtain `delta`.
  4767. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  4768. if (index >= inputLength) {
  4769. error('invalid-input');
  4770. }
  4771. digit = basicToDigit(input.charCodeAt(index++));
  4772. if (digit >= base || digit > floor((maxInt - i) / w)) {
  4773. error('overflow');
  4774. }
  4775. i += digit * w;
  4776. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  4777. if (digit < t) {
  4778. break;
  4779. }
  4780. baseMinusT = base - t;
  4781. if (w > floor(maxInt / baseMinusT)) {
  4782. error('overflow');
  4783. }
  4784. w *= baseMinusT;
  4785. }
  4786. out = output.length + 1;
  4787. bias = adapt(i - oldi, out, oldi == 0);
  4788. // `i` was supposed to wrap around from `out` to `0`,
  4789. // incrementing `n` each time, so we'll fix that now:
  4790. if (floor(i / out) > maxInt - n) {
  4791. error('overflow');
  4792. }
  4793. n += floor(i / out);
  4794. i %= out;
  4795. // Insert `n` at position `i` of the output
  4796. output.splice(i++, 0, n);
  4797. }
  4798. return ucs2encode(output);
  4799. }
  4800. /**
  4801. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  4802. * Punycode string of ASCII-only symbols.
  4803. * @memberOf punycode
  4804. * @param {String} input The string of Unicode symbols.
  4805. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  4806. */
  4807. function encode(input) {
  4808. var n,
  4809. delta,
  4810. handledCPCount,
  4811. basicLength,
  4812. bias,
  4813. j,
  4814. m,
  4815. q,
  4816. k,
  4817. t,
  4818. currentValue,
  4819. output = [],
  4820. /** `inputLength` will hold the number of code points in `input`. */
  4821. inputLength,
  4822. /** Cached calculation results */
  4823. handledCPCountPlusOne,
  4824. baseMinusT,
  4825. qMinusT;
  4826. // Convert the input in UCS-2 to Unicode
  4827. input = ucs2decode(input);
  4828. // Cache the length
  4829. inputLength = input.length;
  4830. // Initialize the state
  4831. n = initialN;
  4832. delta = 0;
  4833. bias = initialBias;
  4834. // Handle the basic code points
  4835. for (j = 0; j < inputLength; ++j) {
  4836. currentValue = input[j];
  4837. if (currentValue < 0x80) {
  4838. output.push(stringFromCharCode(currentValue));
  4839. }
  4840. }
  4841. handledCPCount = basicLength = output.length;
  4842. // `handledCPCount` is the number of code points that have been handled;
  4843. // `basicLength` is the number of basic code points.
  4844. // Finish the basic string - if it is not empty - with a delimiter
  4845. if (basicLength) {
  4846. output.push(delimiter);
  4847. }
  4848. // Main encoding loop:
  4849. while (handledCPCount < inputLength) {
  4850. // All non-basic code points < n have been handled already. Find the next
  4851. // larger one:
  4852. for (m = maxInt, j = 0; j < inputLength; ++j) {
  4853. currentValue = input[j];
  4854. if (currentValue >= n && currentValue < m) {
  4855. m = currentValue;
  4856. }
  4857. }
  4858. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  4859. // but guard against overflow
  4860. handledCPCountPlusOne = handledCPCount + 1;
  4861. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  4862. error('overflow');
  4863. }
  4864. delta += (m - n) * handledCPCountPlusOne;
  4865. n = m;
  4866. for (j = 0; j < inputLength; ++j) {
  4867. currentValue = input[j];
  4868. if (currentValue < n && ++delta > maxInt) {
  4869. error('overflow');
  4870. }
  4871. if (currentValue == n) {
  4872. // Represent delta as a generalized variable-length integer
  4873. for (q = delta, k = base; /* no condition */; k += base) {
  4874. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  4875. if (q < t) {
  4876. break;
  4877. }
  4878. qMinusT = q - t;
  4879. baseMinusT = base - t;
  4880. output.push(
  4881. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  4882. );
  4883. q = floor(qMinusT / baseMinusT);
  4884. }
  4885. output.push(stringFromCharCode(digitToBasic(q, 0)));
  4886. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  4887. delta = 0;
  4888. ++handledCPCount;
  4889. }
  4890. }
  4891. ++delta;
  4892. ++n;
  4893. }
  4894. return output.join('');
  4895. }
  4896. /**
  4897. * Converts a Punycode string representing a domain name or an email address
  4898. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  4899. * it doesn't matter if you call it on a string that has already been
  4900. * converted to Unicode.
  4901. * @memberOf punycode
  4902. * @param {String} input The Punycoded domain name or email address to
  4903. * convert to Unicode.
  4904. * @returns {String} The Unicode representation of the given Punycode
  4905. * string.
  4906. */
  4907. function toUnicode(input) {
  4908. return mapDomain(input, function(string) {
  4909. return regexPunycode.test(string)
  4910. ? decode(string.slice(4).toLowerCase())
  4911. : string;
  4912. });
  4913. }
  4914. /**
  4915. * Converts a Unicode string representing a domain name or an email address to
  4916. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  4917. * i.e. it doesn't matter if you call it with a domain that's already in
  4918. * ASCII.
  4919. * @memberOf punycode
  4920. * @param {String} input The domain name or email address to convert, as a
  4921. * Unicode string.
  4922. * @returns {String} The Punycode representation of the given domain name or
  4923. * email address.
  4924. */
  4925. function toASCII(input) {
  4926. return mapDomain(input, function(string) {
  4927. return regexNonASCII.test(string)
  4928. ? 'xn--' + encode(string)
  4929. : string;
  4930. });
  4931. }
  4932. /*--------------------------------------------------------------------------*/
  4933. /** Define the public API */
  4934. punycode = {
  4935. /**
  4936. * A string representing the current Punycode.js version number.
  4937. * @memberOf punycode
  4938. * @type String
  4939. */
  4940. 'version': '1.3.2',
  4941. /**
  4942. * An object of methods to convert from JavaScript's internal character
  4943. * representation (UCS-2) to Unicode code points, and back.
  4944. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  4945. * @memberOf punycode
  4946. * @type Object
  4947. */
  4948. 'ucs2': {
  4949. 'decode': ucs2decode,
  4950. 'encode': ucs2encode
  4951. },
  4952. 'decode': decode,
  4953. 'encode': encode,
  4954. 'toASCII': toASCII,
  4955. 'toUnicode': toUnicode
  4956. };
  4957. /** Expose `punycode` */
  4958. // Some AMD build optimizers, like r.js, check for specific condition patterns
  4959. // like the following:
  4960. if (freeExports && freeModule) {
  4961. if (module.exports == freeExports) {
  4962. // in Node.js, io.js, or RingoJS v0.8.0+
  4963. freeModule.exports = punycode;
  4964. } else {
  4965. // in Narwhal or RingoJS v0.7.0-
  4966. for (key in punycode) {
  4967. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  4968. }
  4969. }
  4970. } else {
  4971. // in Rhino or a web browser
  4972. root.punycode = punycode;
  4973. }
  4974. }(_commonjsHelpers3aae1032.commonjsGlobal));
  4975. });
  4976. var IPv6 = _commonjsHelpers3aae1032.createCommonjsModule(function (module) {
  4977. /*!
  4978. * URI.js - Mutating URLs
  4979. * IPv6 Support
  4980. *
  4981. * Version: 1.19.11
  4982. *
  4983. * Author: Rodney Rehm
  4984. * Web: http://medialize.github.io/URI.js/
  4985. *
  4986. * Licensed under
  4987. * MIT License http://www.opensource.org/licenses/mit-license
  4988. *
  4989. */
  4990. (function (root, factory) {
  4991. // https://github.com/umdjs/umd/blob/master/returnExports.js
  4992. if (module.exports) {
  4993. // Node
  4994. module.exports = factory();
  4995. } else {
  4996. // Browser globals (root is window)
  4997. root.IPv6 = factory(root);
  4998. }
  4999. }(_commonjsHelpers3aae1032.commonjsGlobal, function (root) {
  5000. /*
  5001. var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
  5002. var _out = IPv6.best(_in);
  5003. var _expected = "fe80::204:61ff:fe9d:f156";
  5004. console.log(_in, _out, _expected, _out === _expected);
  5005. */
  5006. // save current IPv6 variable, if any
  5007. var _IPv6 = root && root.IPv6;
  5008. function bestPresentation(address) {
  5009. // based on:
  5010. // Javascript to test an IPv6 address for proper format, and to
  5011. // present the "best text representation" according to IETF Draft RFC at
  5012. // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
  5013. // 8 Feb 2010 Rich Brown, Dartware, LLC
  5014. // Please feel free to use this code as long as you provide a link to
  5015. // http://www.intermapper.com
  5016. // http://intermapper.com/support/tools/IPV6-Validator.aspx
  5017. // http://download.dartware.com/thirdparty/ipv6validator.js
  5018. var _address = address.toLowerCase();
  5019. var segments = _address.split(':');
  5020. var length = segments.length;
  5021. var total = 8;
  5022. // trim colons (:: or ::a:b:c… or …a:b:c::)
  5023. if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
  5024. // must have been ::
  5025. // remove first two items
  5026. segments.shift();
  5027. segments.shift();
  5028. } else if (segments[0] === '' && segments[1] === '') {
  5029. // must have been ::xxxx
  5030. // remove the first item
  5031. segments.shift();
  5032. } else if (segments[length - 1] === '' && segments[length - 2] === '') {
  5033. // must have been xxxx::
  5034. segments.pop();
  5035. }
  5036. length = segments.length;
  5037. // adjust total segments for IPv4 trailer
  5038. if (segments[length - 1].indexOf('.') !== -1) {
  5039. // found a "." which means IPv4
  5040. total = 7;
  5041. }
  5042. // fill empty segments them with "0000"
  5043. var pos;
  5044. for (pos = 0; pos < length; pos++) {
  5045. if (segments[pos] === '') {
  5046. break;
  5047. }
  5048. }
  5049. if (pos < total) {
  5050. segments.splice(pos, 1, '0000');
  5051. while (segments.length < total) {
  5052. segments.splice(pos, 0, '0000');
  5053. }
  5054. }
  5055. // strip leading zeros
  5056. var _segments;
  5057. for (var i = 0; i < total; i++) {
  5058. _segments = segments[i].split('');
  5059. for (var j = 0; j < 3 ; j++) {
  5060. if (_segments[0] === '0' && _segments.length > 1) {
  5061. _segments.splice(0,1);
  5062. } else {
  5063. break;
  5064. }
  5065. }
  5066. segments[i] = _segments.join('');
  5067. }
  5068. // find longest sequence of zeroes and coalesce them into one segment
  5069. var best = -1;
  5070. var _best = 0;
  5071. var _current = 0;
  5072. var current = -1;
  5073. var inzeroes = false;
  5074. // i; already declared
  5075. for (i = 0; i < total; i++) {
  5076. if (inzeroes) {
  5077. if (segments[i] === '0') {
  5078. _current += 1;
  5079. } else {
  5080. inzeroes = false;
  5081. if (_current > _best) {
  5082. best = current;
  5083. _best = _current;
  5084. }
  5085. }
  5086. } else {
  5087. if (segments[i] === '0') {
  5088. inzeroes = true;
  5089. current = i;
  5090. _current = 1;
  5091. }
  5092. }
  5093. }
  5094. if (_current > _best) {
  5095. best = current;
  5096. _best = _current;
  5097. }
  5098. if (_best > 1) {
  5099. segments.splice(best, _best, '');
  5100. }
  5101. length = segments.length;
  5102. // assemble remaining segments
  5103. var result = '';
  5104. if (segments[0] === '') {
  5105. result = ':';
  5106. }
  5107. for (i = 0; i < length; i++) {
  5108. result += segments[i];
  5109. if (i === length - 1) {
  5110. break;
  5111. }
  5112. result += ':';
  5113. }
  5114. if (segments[length - 1] === '') {
  5115. result += ':';
  5116. }
  5117. return result;
  5118. }
  5119. function noConflict() {
  5120. /*jshint validthis: true */
  5121. if (root.IPv6 === this) {
  5122. root.IPv6 = _IPv6;
  5123. }
  5124. return this;
  5125. }
  5126. return {
  5127. best: bestPresentation,
  5128. noConflict: noConflict
  5129. };
  5130. }));
  5131. });
  5132. var SecondLevelDomains = _commonjsHelpers3aae1032.createCommonjsModule(function (module) {
  5133. /*!
  5134. * URI.js - Mutating URLs
  5135. * Second Level Domain (SLD) Support
  5136. *
  5137. * Version: 1.19.11
  5138. *
  5139. * Author: Rodney Rehm
  5140. * Web: http://medialize.github.io/URI.js/
  5141. *
  5142. * Licensed under
  5143. * MIT License http://www.opensource.org/licenses/mit-license
  5144. *
  5145. */
  5146. (function (root, factory) {
  5147. // https://github.com/umdjs/umd/blob/master/returnExports.js
  5148. if (module.exports) {
  5149. // Node
  5150. module.exports = factory();
  5151. } else {
  5152. // Browser globals (root is window)
  5153. root.SecondLevelDomains = factory(root);
  5154. }
  5155. }(_commonjsHelpers3aae1032.commonjsGlobal, function (root) {
  5156. // save current SecondLevelDomains variable, if any
  5157. var _SecondLevelDomains = root && root.SecondLevelDomains;
  5158. var SLD = {
  5159. // list of known Second Level Domains
  5160. // converted list of SLDs from https://github.com/gavingmiller/second-level-domains
  5161. // ----
  5162. // publicsuffix.org is more current and actually used by a couple of browsers internally.
  5163. // downside is it also contains domains like "dyndns.org" - which is fine for the security
  5164. // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
  5165. // ----
  5166. list: {
  5167. 'ac':' com gov mil net org ',
  5168. 'ae':' ac co gov mil name net org pro sch ',
  5169. 'af':' com edu gov net org ',
  5170. 'al':' com edu gov mil net org ',
  5171. 'ao':' co ed gv it og pb ',
  5172. 'ar':' com edu gob gov int mil net org tur ',
  5173. 'at':' ac co gv or ',
  5174. 'au':' asn com csiro edu gov id net org ',
  5175. 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
  5176. 'bb':' biz co com edu gov info net org store tv ',
  5177. 'bh':' biz cc com edu gov info net org ',
  5178. 'bn':' com edu gov net org ',
  5179. 'bo':' com edu gob gov int mil net org tv ',
  5180. 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
  5181. 'bs':' com edu gov net org ',
  5182. 'bz':' du et om ov rg ',
  5183. 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
  5184. 'ck':' biz co edu gen gov info net org ',
  5185. 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
  5186. 'co':' com edu gov mil net nom org ',
  5187. 'cr':' ac c co ed fi go or sa ',
  5188. 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
  5189. 'do':' art com edu gob gov mil net org sld web ',
  5190. 'dz':' art asso com edu gov net org pol ',
  5191. 'ec':' com edu fin gov info med mil net org pro ',
  5192. 'eg':' com edu eun gov mil name net org sci ',
  5193. 'er':' com edu gov ind mil net org rochest w ',
  5194. 'es':' com edu gob nom org ',
  5195. 'et':' biz com edu gov info name net org ',
  5196. 'fj':' ac biz com info mil name net org pro ',
  5197. 'fk':' ac co gov net nom org ',
  5198. 'fr':' asso com f gouv nom prd presse tm ',
  5199. 'gg':' co net org ',
  5200. 'gh':' com edu gov mil org ',
  5201. 'gn':' ac com gov net org ',
  5202. 'gr':' com edu gov mil net org ',
  5203. 'gt':' com edu gob ind mil net org ',
  5204. 'gu':' com edu gov net org ',
  5205. 'hk':' com edu gov idv net org ',
  5206. 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
  5207. 'id':' ac co go mil net or sch web ',
  5208. 'il':' ac co gov idf k12 muni net org ',
  5209. 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
  5210. 'iq':' com edu gov i mil net org ',
  5211. 'ir':' ac co dnssec gov i id net org sch ',
  5212. 'it':' edu gov ',
  5213. 'je':' co net org ',
  5214. 'jo':' com edu gov mil name net org sch ',
  5215. 'jp':' ac ad co ed go gr lg ne or ',
  5216. 'ke':' ac co go info me mobi ne or sc ',
  5217. 'kh':' com edu gov mil net org per ',
  5218. 'ki':' biz com de edu gov info mob net org tel ',
  5219. 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
  5220. 'kn':' edu gov net org ',
  5221. 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
  5222. 'kw':' com edu gov net org ',
  5223. 'ky':' com edu gov net org ',
  5224. 'kz':' com edu gov mil net org ',
  5225. 'lb':' com edu gov net org ',
  5226. 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
  5227. 'lr':' com edu gov net org ',
  5228. 'lv':' asn com conf edu gov id mil net org ',
  5229. 'ly':' com edu gov id med net org plc sch ',
  5230. 'ma':' ac co gov m net org press ',
  5231. 'mc':' asso tm ',
  5232. 'me':' ac co edu gov its net org priv ',
  5233. 'mg':' com edu gov mil nom org prd tm ',
  5234. 'mk':' com edu gov inf name net org pro ',
  5235. 'ml':' com edu gov net org presse ',
  5236. 'mn':' edu gov org ',
  5237. 'mo':' com edu gov net org ',
  5238. 'mt':' com edu gov net org ',
  5239. 'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
  5240. 'mw':' ac co com coop edu gov int museum net org ',
  5241. 'mx':' com edu gob net org ',
  5242. 'my':' com edu gov mil name net org sch ',
  5243. 'nf':' arts com firm info net other per rec store web ',
  5244. 'ng':' biz com edu gov mil mobi name net org sch ',
  5245. 'ni':' ac co com edu gob mil net nom org ',
  5246. 'np':' com edu gov mil net org ',
  5247. 'nr':' biz com edu gov info net org ',
  5248. 'om':' ac biz co com edu gov med mil museum net org pro sch ',
  5249. 'pe':' com edu gob mil net nom org sld ',
  5250. 'ph':' com edu gov i mil net ngo org ',
  5251. 'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
  5252. 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
  5253. 'pr':' ac biz com edu est gov info isla name net org pro prof ',
  5254. 'ps':' com edu gov net org plo sec ',
  5255. 'pw':' belau co ed go ne or ',
  5256. 'ro':' arts com firm info nom nt org rec store tm www ',
  5257. 'rs':' ac co edu gov in org ',
  5258. 'sb':' com edu gov net org ',
  5259. 'sc':' com edu gov net org ',
  5260. 'sh':' co com edu gov net nom org ',
  5261. 'sl':' com edu gov net org ',
  5262. 'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
  5263. 'sv':' com edu gob org red ',
  5264. 'sz':' ac co org ',
  5265. 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
  5266. 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
  5267. 'tw':' club com ebiz edu game gov idv mil net org ',
  5268. 'mu':' ac co com gov net or org ',
  5269. 'mz':' ac co edu gov org ',
  5270. 'na':' co com ',
  5271. 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
  5272. 'pa':' abo ac com edu gob ing med net nom org sld ',
  5273. 'pt':' com edu gov int net nome org publ ',
  5274. 'py':' com edu gov mil net org ',
  5275. 'qa':' com edu gov mil net org ',
  5276. 're':' asso com nom ',
  5277. 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
  5278. 'rw':' ac co com edu gouv gov int mil net ',
  5279. 'sa':' com edu gov med net org pub sch ',
  5280. 'sd':' com edu gov info med net org tv ',
  5281. 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
  5282. 'sg':' com edu gov idn net org per ',
  5283. 'sn':' art com edu gouv org perso univ ',
  5284. 'sy':' com edu gov mil net news org ',
  5285. 'th':' ac co go in mi net or ',
  5286. 'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
  5287. 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
  5288. 'tz':' ac co go ne or ',
  5289. 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
  5290. 'ug':' ac co go ne or org sc ',
  5291. 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
  5292. 'us':' dni fed isa kids nsn ',
  5293. 'uy':' com edu gub mil net org ',
  5294. 've':' co com edu gob info mil net org web ',
  5295. 'vi':' co com k12 net org ',
  5296. 'vn':' ac biz com edu gov health info int name net org pro ',
  5297. 'ye':' co com gov ltd me net org plc ',
  5298. 'yu':' ac co edu gov org ',
  5299. 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
  5300. 'zm':' ac co com edu gov net org sch ',
  5301. // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
  5302. 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
  5303. 'net': 'gb jp se uk ',
  5304. 'org': 'ae',
  5305. 'de': 'com '
  5306. },
  5307. // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
  5308. // in both performance and memory footprint. No initialization required.
  5309. // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
  5310. // Following methods use lastIndexOf() rather than array.split() in order
  5311. // to avoid any memory allocations.
  5312. has: function(domain) {
  5313. var tldOffset = domain.lastIndexOf('.');
  5314. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  5315. return false;
  5316. }
  5317. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  5318. if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
  5319. return false;
  5320. }
  5321. var sldList = SLD.list[domain.slice(tldOffset+1)];
  5322. if (!sldList) {
  5323. return false;
  5324. }
  5325. return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
  5326. },
  5327. is: function(domain) {
  5328. var tldOffset = domain.lastIndexOf('.');
  5329. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  5330. return false;
  5331. }
  5332. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  5333. if (sldOffset >= 0) {
  5334. return false;
  5335. }
  5336. var sldList = SLD.list[domain.slice(tldOffset+1)];
  5337. if (!sldList) {
  5338. return false;
  5339. }
  5340. return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
  5341. },
  5342. get: function(domain) {
  5343. var tldOffset = domain.lastIndexOf('.');
  5344. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  5345. return null;
  5346. }
  5347. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  5348. if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
  5349. return null;
  5350. }
  5351. var sldList = SLD.list[domain.slice(tldOffset+1)];
  5352. if (!sldList) {
  5353. return null;
  5354. }
  5355. if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
  5356. return null;
  5357. }
  5358. return domain.slice(sldOffset+1);
  5359. },
  5360. noConflict: function(){
  5361. if (root.SecondLevelDomains === this) {
  5362. root.SecondLevelDomains = _SecondLevelDomains;
  5363. }
  5364. return this;
  5365. }
  5366. };
  5367. return SLD;
  5368. }));
  5369. });
  5370. var URI = _commonjsHelpers3aae1032.createCommonjsModule(function (module) {
  5371. /*!
  5372. * URI.js - Mutating URLs
  5373. *
  5374. * Version: 1.19.11
  5375. *
  5376. * Author: Rodney Rehm
  5377. * Web: http://medialize.github.io/URI.js/
  5378. *
  5379. * Licensed under
  5380. * MIT License http://www.opensource.org/licenses/mit-license
  5381. *
  5382. */
  5383. (function (root, factory) {
  5384. // https://github.com/umdjs/umd/blob/master/returnExports.js
  5385. if (module.exports) {
  5386. // Node
  5387. module.exports = factory(punycode, IPv6, SecondLevelDomains);
  5388. } else {
  5389. // Browser globals (root is window)
  5390. root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);
  5391. }
  5392. }(_commonjsHelpers3aae1032.commonjsGlobal, function (punycode, IPv6, SLD, root) {
  5393. /*global location, escape, unescape */
  5394. // FIXME: v2.0.0 renamce non-camelCase properties to uppercase
  5395. /*jshint camelcase: false */
  5396. // save current URI variable, if any
  5397. var _URI = root && root.URI;
  5398. function URI(url, base) {
  5399. var _urlSupplied = arguments.length >= 1;
  5400. var _baseSupplied = arguments.length >= 2;
  5401. // Allow instantiation without the 'new' keyword
  5402. if (!(this instanceof URI)) {
  5403. if (_urlSupplied) {
  5404. if (_baseSupplied) {
  5405. return new URI(url, base);
  5406. }
  5407. return new URI(url);
  5408. }
  5409. return new URI();
  5410. }
  5411. if (url === undefined) {
  5412. if (_urlSupplied) {
  5413. throw new TypeError('undefined is not a valid argument for URI');
  5414. }
  5415. if (typeof location !== 'undefined') {
  5416. url = location.href + '';
  5417. } else {
  5418. url = '';
  5419. }
  5420. }
  5421. if (url === null) {
  5422. if (_urlSupplied) {
  5423. throw new TypeError('null is not a valid argument for URI');
  5424. }
  5425. }
  5426. this.href(url);
  5427. // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
  5428. if (base !== undefined) {
  5429. return this.absoluteTo(base);
  5430. }
  5431. return this;
  5432. }
  5433. function isInteger(value) {
  5434. return /^[0-9]+$/.test(value);
  5435. }
  5436. URI.version = '1.19.11';
  5437. var p = URI.prototype;
  5438. var hasOwn = Object.prototype.hasOwnProperty;
  5439. function escapeRegEx(string) {
  5440. // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
  5441. return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  5442. }
  5443. function getType(value) {
  5444. // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
  5445. if (value === undefined) {
  5446. return 'Undefined';
  5447. }
  5448. return String(Object.prototype.toString.call(value)).slice(8, -1);
  5449. }
  5450. function isArray(obj) {
  5451. return getType(obj) === 'Array';
  5452. }
  5453. function filterArrayValues(data, value) {
  5454. var lookup = {};
  5455. var i, length;
  5456. if (getType(value) === 'RegExp') {
  5457. lookup = null;
  5458. } else if (isArray(value)) {
  5459. for (i = 0, length = value.length; i < length; i++) {
  5460. lookup[value[i]] = true;
  5461. }
  5462. } else {
  5463. lookup[value] = true;
  5464. }
  5465. for (i = 0, length = data.length; i < length; i++) {
  5466. /*jshint laxbreak: true */
  5467. var _match = lookup && lookup[data[i]] !== undefined
  5468. || !lookup && value.test(data[i]);
  5469. /*jshint laxbreak: false */
  5470. if (_match) {
  5471. data.splice(i, 1);
  5472. length--;
  5473. i--;
  5474. }
  5475. }
  5476. return data;
  5477. }
  5478. function arrayContains(list, value) {
  5479. var i, length;
  5480. // value may be string, number, array, regexp
  5481. if (isArray(value)) {
  5482. // Note: this can be optimized to O(n) (instead of current O(m * n))
  5483. for (i = 0, length = value.length; i < length; i++) {
  5484. if (!arrayContains(list, value[i])) {
  5485. return false;
  5486. }
  5487. }
  5488. return true;
  5489. }
  5490. var _type = getType(value);
  5491. for (i = 0, length = list.length; i < length; i++) {
  5492. if (_type === 'RegExp') {
  5493. if (typeof list[i] === 'string' && list[i].match(value)) {
  5494. return true;
  5495. }
  5496. } else if (list[i] === value) {
  5497. return true;
  5498. }
  5499. }
  5500. return false;
  5501. }
  5502. function arraysEqual(one, two) {
  5503. if (!isArray(one) || !isArray(two)) {
  5504. return false;
  5505. }
  5506. // arrays can't be equal if they have different amount of content
  5507. if (one.length !== two.length) {
  5508. return false;
  5509. }
  5510. one.sort();
  5511. two.sort();
  5512. for (var i = 0, l = one.length; i < l; i++) {
  5513. if (one[i] !== two[i]) {
  5514. return false;
  5515. }
  5516. }
  5517. return true;
  5518. }
  5519. function trimSlashes(text) {
  5520. var trim_expression = /^\/+|\/+$/g;
  5521. return text.replace(trim_expression, '');
  5522. }
  5523. URI._parts = function() {
  5524. return {
  5525. protocol: null,
  5526. username: null,
  5527. password: null,
  5528. hostname: null,
  5529. urn: null,
  5530. port: null,
  5531. path: null,
  5532. query: null,
  5533. fragment: null,
  5534. // state
  5535. preventInvalidHostname: URI.preventInvalidHostname,
  5536. duplicateQueryParameters: URI.duplicateQueryParameters,
  5537. escapeQuerySpace: URI.escapeQuerySpace
  5538. };
  5539. };
  5540. // state: throw on invalid hostname
  5541. // see https://github.com/medialize/URI.js/pull/345
  5542. // and https://github.com/medialize/URI.js/issues/354
  5543. URI.preventInvalidHostname = false;
  5544. // state: allow duplicate query parameters (a=1&a=1)
  5545. URI.duplicateQueryParameters = false;
  5546. // state: replaces + with %20 (space in query strings)
  5547. URI.escapeQuerySpace = true;
  5548. // static properties
  5549. URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
  5550. URI.idn_expression = /[^a-z0-9\._-]/i;
  5551. URI.punycode_expression = /(xn--)/i;
  5552. // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
  5553. URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  5554. // credits to Rich Brown
  5555. // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
  5556. // specification: http://www.ietf.org/rfc/rfc4291.txt
  5557. URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
  5558. // expression used is "gruber revised" (@gruber v2) determined to be the
  5559. // best solution in a regex-golf we did a couple of ages ago at
  5560. // * http://mathiasbynens.be/demo/url-regex
  5561. // * http://rodneyrehm.de/t/url-regex.html
  5562. URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
  5563. URI.findUri = {
  5564. // valid "scheme://" or "www."
  5565. start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
  5566. // everything up to the next whitespace
  5567. end: /[\s\r\n]|$/,
  5568. // trim trailing punctuation captured by end RegExp
  5569. trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
  5570. // balanced parens inclusion (), [], {}, <>
  5571. parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
  5572. };
  5573. URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
  5574. // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  5575. URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g;
  5576. // http://www.iana.org/assignments/uri-schemes.html
  5577. // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
  5578. URI.defaultPorts = {
  5579. http: '80',
  5580. https: '443',
  5581. ftp: '21',
  5582. gopher: '70',
  5583. ws: '80',
  5584. wss: '443'
  5585. };
  5586. // list of protocols which always require a hostname
  5587. URI.hostProtocols = [
  5588. 'http',
  5589. 'https'
  5590. ];
  5591. // allowed hostname characters according to RFC 3986
  5592. // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
  5593. // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
  5594. URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
  5595. // map DOM Elements to their URI attribute
  5596. URI.domAttributes = {
  5597. 'a': 'href',
  5598. 'blockquote': 'cite',
  5599. 'link': 'href',
  5600. 'base': 'href',
  5601. 'script': 'src',
  5602. 'form': 'action',
  5603. 'img': 'src',
  5604. 'area': 'href',
  5605. 'iframe': 'src',
  5606. 'embed': 'src',
  5607. 'source': 'src',
  5608. 'track': 'src',
  5609. 'input': 'src', // but only if type="image"
  5610. 'audio': 'src',
  5611. 'video': 'src'
  5612. };
  5613. URI.getDomAttribute = function(node) {
  5614. if (!node || !node.nodeName) {
  5615. return undefined;
  5616. }
  5617. var nodeName = node.nodeName.toLowerCase();
  5618. // <input> should only expose src for type="image"
  5619. if (nodeName === 'input' && node.type !== 'image') {
  5620. return undefined;
  5621. }
  5622. return URI.domAttributes[nodeName];
  5623. };
  5624. function escapeForDumbFirefox36(value) {
  5625. // https://github.com/medialize/URI.js/issues/91
  5626. return escape(value);
  5627. }
  5628. // encoding / decoding according to RFC3986
  5629. function strictEncodeURIComponent(string) {
  5630. // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
  5631. return encodeURIComponent(string)
  5632. .replace(/[!'()*]/g, escapeForDumbFirefox36)
  5633. .replace(/\*/g, '%2A');
  5634. }
  5635. URI.encode = strictEncodeURIComponent;
  5636. URI.decode = decodeURIComponent;
  5637. URI.iso8859 = function() {
  5638. URI.encode = escape;
  5639. URI.decode = unescape;
  5640. };
  5641. URI.unicode = function() {
  5642. URI.encode = strictEncodeURIComponent;
  5643. URI.decode = decodeURIComponent;
  5644. };
  5645. URI.characters = {
  5646. pathname: {
  5647. encode: {
  5648. // RFC3986 2.1: For consistency, URI producers and normalizers should
  5649. // use uppercase hexadecimal digits for all percent-encodings.
  5650. expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
  5651. map: {
  5652. // -._~!'()*
  5653. '%24': '$',
  5654. '%26': '&',
  5655. '%2B': '+',
  5656. '%2C': ',',
  5657. '%3B': ';',
  5658. '%3D': '=',
  5659. '%3A': ':',
  5660. '%40': '@'
  5661. }
  5662. },
  5663. decode: {
  5664. expression: /[\/\?#]/g,
  5665. map: {
  5666. '/': '%2F',
  5667. '?': '%3F',
  5668. '#': '%23'
  5669. }
  5670. }
  5671. },
  5672. reserved: {
  5673. encode: {
  5674. // RFC3986 2.1: For consistency, URI producers and normalizers should
  5675. // use uppercase hexadecimal digits for all percent-encodings.
  5676. expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
  5677. map: {
  5678. // gen-delims
  5679. '%3A': ':',
  5680. '%2F': '/',
  5681. '%3F': '?',
  5682. '%23': '#',
  5683. '%5B': '[',
  5684. '%5D': ']',
  5685. '%40': '@',
  5686. // sub-delims
  5687. '%21': '!',
  5688. '%24': '$',
  5689. '%26': '&',
  5690. '%27': '\'',
  5691. '%28': '(',
  5692. '%29': ')',
  5693. '%2A': '*',
  5694. '%2B': '+',
  5695. '%2C': ',',
  5696. '%3B': ';',
  5697. '%3D': '='
  5698. }
  5699. }
  5700. },
  5701. urnpath: {
  5702. // The characters under `encode` are the characters called out by RFC 2141 as being acceptable
  5703. // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
  5704. // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
  5705. // note that the colon character is not featured in the encoding map; this is because URI.js
  5706. // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
  5707. // should not appear unencoded in a segment itself.
  5708. // See also the note above about RFC3986 and capitalalized hex digits.
  5709. encode: {
  5710. expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
  5711. map: {
  5712. '%21': '!',
  5713. '%24': '$',
  5714. '%27': '\'',
  5715. '%28': '(',
  5716. '%29': ')',
  5717. '%2A': '*',
  5718. '%2B': '+',
  5719. '%2C': ',',
  5720. '%3B': ';',
  5721. '%3D': '=',
  5722. '%40': '@'
  5723. }
  5724. },
  5725. // These characters are the characters called out by RFC2141 as "reserved" characters that
  5726. // should never appear in a URN, plus the colon character (see note above).
  5727. decode: {
  5728. expression: /[\/\?#:]/g,
  5729. map: {
  5730. '/': '%2F',
  5731. '?': '%3F',
  5732. '#': '%23',
  5733. ':': '%3A'
  5734. }
  5735. }
  5736. }
  5737. };
  5738. URI.encodeQuery = function(string, escapeQuerySpace) {
  5739. var escaped = URI.encode(string + '');
  5740. if (escapeQuerySpace === undefined) {
  5741. escapeQuerySpace = URI.escapeQuerySpace;
  5742. }
  5743. return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
  5744. };
  5745. URI.decodeQuery = function(string, escapeQuerySpace) {
  5746. string += '';
  5747. if (escapeQuerySpace === undefined) {
  5748. escapeQuerySpace = URI.escapeQuerySpace;
  5749. }
  5750. try {
  5751. return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
  5752. } catch(e) {
  5753. // we're not going to mess with weird encodings,
  5754. // give up and return the undecoded original string
  5755. // see https://github.com/medialize/URI.js/issues/87
  5756. // see https://github.com/medialize/URI.js/issues/92
  5757. return string;
  5758. }
  5759. };
  5760. // generate encode/decode path functions
  5761. var _parts = {'encode':'encode', 'decode':'decode'};
  5762. var _part;
  5763. var generateAccessor = function(_group, _part) {
  5764. return function(string) {
  5765. try {
  5766. return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
  5767. return URI.characters[_group][_part].map[c];
  5768. });
  5769. } catch (e) {
  5770. // we're not going to mess with weird encodings,
  5771. // give up and return the undecoded original string
  5772. // see https://github.com/medialize/URI.js/issues/87
  5773. // see https://github.com/medialize/URI.js/issues/92
  5774. return string;
  5775. }
  5776. };
  5777. };
  5778. for (_part in _parts) {
  5779. URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
  5780. URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
  5781. }
  5782. var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
  5783. return function(string) {
  5784. // Why pass in names of functions, rather than the function objects themselves? The
  5785. // definitions of some functions (but in particular, URI.decode) will occasionally change due
  5786. // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
  5787. // that the functions we use here are "fresh".
  5788. var actualCodingFunc;
  5789. if (!_innerCodingFuncName) {
  5790. actualCodingFunc = URI[_codingFuncName];
  5791. } else {
  5792. actualCodingFunc = function(string) {
  5793. return URI[_codingFuncName](URI[_innerCodingFuncName](string));
  5794. };
  5795. }
  5796. var segments = (string + '').split(_sep);
  5797. for (var i = 0, length = segments.length; i < length; i++) {
  5798. segments[i] = actualCodingFunc(segments[i]);
  5799. }
  5800. return segments.join(_sep);
  5801. };
  5802. };
  5803. // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
  5804. URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
  5805. URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
  5806. URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
  5807. URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
  5808. URI.encodeReserved = generateAccessor('reserved', 'encode');
  5809. URI.parse = function(string, parts) {
  5810. var pos;
  5811. if (!parts) {
  5812. parts = {
  5813. preventInvalidHostname: URI.preventInvalidHostname
  5814. };
  5815. }
  5816. string = string.replace(URI.leading_whitespace_expression, '');
  5817. // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  5818. string = string.replace(URI.ascii_tab_whitespace, '');
  5819. // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
  5820. // extract fragment
  5821. pos = string.indexOf('#');
  5822. if (pos > -1) {
  5823. // escaping?
  5824. parts.fragment = string.substring(pos + 1) || null;
  5825. string = string.substring(0, pos);
  5826. }
  5827. // extract query
  5828. pos = string.indexOf('?');
  5829. if (pos > -1) {
  5830. // escaping?
  5831. parts.query = string.substring(pos + 1) || null;
  5832. string = string.substring(0, pos);
  5833. }
  5834. // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
  5835. string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
  5836. // slashes and backslashes have lost all meaning for scheme relative URLs
  5837. string = string.replace(/^[/\\]{2,}/i, '//');
  5838. // extract protocol
  5839. if (string.substring(0, 2) === '//') {
  5840. // relative-scheme
  5841. parts.protocol = null;
  5842. string = string.substring(2);
  5843. // extract "user:pass@host:port"
  5844. string = URI.parseAuthority(string, parts);
  5845. } else {
  5846. pos = string.indexOf(':');
  5847. if (pos > -1) {
  5848. parts.protocol = string.substring(0, pos) || null;
  5849. if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
  5850. // : may be within the path
  5851. parts.protocol = undefined;
  5852. } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
  5853. string = string.substring(pos + 3);
  5854. // extract "user:pass@host:port"
  5855. string = URI.parseAuthority(string, parts);
  5856. } else {
  5857. string = string.substring(pos + 1);
  5858. parts.urn = true;
  5859. }
  5860. }
  5861. }
  5862. // what's left must be the path
  5863. parts.path = string;
  5864. // and we're done
  5865. return parts;
  5866. };
  5867. URI.parseHost = function(string, parts) {
  5868. if (!string) {
  5869. string = '';
  5870. }
  5871. // Copy chrome, IE, opera backslash-handling behavior.
  5872. // Back slashes before the query string get converted to forward slashes
  5873. // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
  5874. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  5875. // https://github.com/medialize/URI.js/pull/233
  5876. string = string.replace(/\\/g, '/');
  5877. // extract host:port
  5878. var pos = string.indexOf('/');
  5879. var bracketPos;
  5880. var t;
  5881. if (pos === -1) {
  5882. pos = string.length;
  5883. }
  5884. if (string.charAt(0) === '[') {
  5885. // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
  5886. // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
  5887. // IPv6+port in the format [2001:db8::1]:80 (for the time being)
  5888. bracketPos = string.indexOf(']');
  5889. parts.hostname = string.substring(1, bracketPos) || null;
  5890. parts.port = string.substring(bracketPos + 2, pos) || null;
  5891. if (parts.port === '/') {
  5892. parts.port = null;
  5893. }
  5894. } else {
  5895. var firstColon = string.indexOf(':');
  5896. var firstSlash = string.indexOf('/');
  5897. var nextColon = string.indexOf(':', firstColon + 1);
  5898. if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
  5899. // IPv6 host contains multiple colons - but no port
  5900. // this notation is actually not allowed by RFC 3986, but we're a liberal parser
  5901. parts.hostname = string.substring(0, pos) || null;
  5902. parts.port = null;
  5903. } else {
  5904. t = string.substring(0, pos).split(':');
  5905. parts.hostname = t[0] || null;
  5906. parts.port = t[1] || null;
  5907. }
  5908. }
  5909. if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
  5910. pos++;
  5911. string = '/' + string;
  5912. }
  5913. if (parts.preventInvalidHostname) {
  5914. URI.ensureValidHostname(parts.hostname, parts.protocol);
  5915. }
  5916. if (parts.port) {
  5917. URI.ensureValidPort(parts.port);
  5918. }
  5919. return string.substring(pos) || '/';
  5920. };
  5921. URI.parseAuthority = function(string, parts) {
  5922. string = URI.parseUserinfo(string, parts);
  5923. return URI.parseHost(string, parts);
  5924. };
  5925. URI.parseUserinfo = function(string, parts) {
  5926. // extract username:password
  5927. var _string = string;
  5928. var firstBackSlash = string.indexOf('\\');
  5929. if (firstBackSlash !== -1) {
  5930. string = string.replace(/\\/g, '/');
  5931. }
  5932. var firstSlash = string.indexOf('/');
  5933. var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
  5934. var t;
  5935. // authority@ must come before /path or \path
  5936. if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
  5937. t = string.substring(0, pos).split(':');
  5938. parts.username = t[0] ? URI.decode(t[0]) : null;
  5939. t.shift();
  5940. parts.password = t[0] ? URI.decode(t.join(':')) : null;
  5941. string = _string.substring(pos + 1);
  5942. } else {
  5943. parts.username = null;
  5944. parts.password = null;
  5945. }
  5946. return string;
  5947. };
  5948. URI.parseQuery = function(string, escapeQuerySpace) {
  5949. if (!string) {
  5950. return {};
  5951. }
  5952. // throw out the funky business - "?"[name"="value"&"]+
  5953. string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
  5954. if (!string) {
  5955. return {};
  5956. }
  5957. var items = {};
  5958. var splits = string.split('&');
  5959. var length = splits.length;
  5960. var v, name, value;
  5961. for (var i = 0; i < length; i++) {
  5962. v = splits[i].split('=');
  5963. name = URI.decodeQuery(v.shift(), escapeQuerySpace);
  5964. // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
  5965. value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
  5966. if (name === '__proto__') {
  5967. // ignore attempt at exploiting JavaScript internals
  5968. continue;
  5969. } else if (hasOwn.call(items, name)) {
  5970. if (typeof items[name] === 'string' || items[name] === null) {
  5971. items[name] = [items[name]];
  5972. }
  5973. items[name].push(value);
  5974. } else {
  5975. items[name] = value;
  5976. }
  5977. }
  5978. return items;
  5979. };
  5980. URI.build = function(parts) {
  5981. var t = '';
  5982. var requireAbsolutePath = false;
  5983. if (parts.protocol) {
  5984. t += parts.protocol + ':';
  5985. }
  5986. if (!parts.urn && (t || parts.hostname)) {
  5987. t += '//';
  5988. requireAbsolutePath = true;
  5989. }
  5990. t += (URI.buildAuthority(parts) || '');
  5991. if (typeof parts.path === 'string') {
  5992. if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
  5993. t += '/';
  5994. }
  5995. t += parts.path;
  5996. }
  5997. if (typeof parts.query === 'string' && parts.query) {
  5998. t += '?' + parts.query;
  5999. }
  6000. if (typeof parts.fragment === 'string' && parts.fragment) {
  6001. t += '#' + parts.fragment;
  6002. }
  6003. return t;
  6004. };
  6005. URI.buildHost = function(parts) {
  6006. var t = '';
  6007. if (!parts.hostname) {
  6008. return '';
  6009. } else if (URI.ip6_expression.test(parts.hostname)) {
  6010. t += '[' + parts.hostname + ']';
  6011. } else {
  6012. t += parts.hostname;
  6013. }
  6014. if (parts.port) {
  6015. t += ':' + parts.port;
  6016. }
  6017. return t;
  6018. };
  6019. URI.buildAuthority = function(parts) {
  6020. return URI.buildUserinfo(parts) + URI.buildHost(parts);
  6021. };
  6022. URI.buildUserinfo = function(parts) {
  6023. var t = '';
  6024. if (parts.username) {
  6025. t += URI.encode(parts.username);
  6026. }
  6027. if (parts.password) {
  6028. t += ':' + URI.encode(parts.password);
  6029. }
  6030. if (t) {
  6031. t += '@';
  6032. }
  6033. return t;
  6034. };
  6035. URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
  6036. // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
  6037. // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
  6038. // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
  6039. // URI.js treats the query string as being application/x-www-form-urlencoded
  6040. // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
  6041. var t = '';
  6042. var unique, key, i, length;
  6043. for (key in data) {
  6044. if (key === '__proto__') {
  6045. // ignore attempt at exploiting JavaScript internals
  6046. continue;
  6047. } else if (hasOwn.call(data, key)) {
  6048. if (isArray(data[key])) {
  6049. unique = {};
  6050. for (i = 0, length = data[key].length; i < length; i++) {
  6051. if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
  6052. t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
  6053. if (duplicateQueryParameters !== true) {
  6054. unique[data[key][i] + ''] = true;
  6055. }
  6056. }
  6057. }
  6058. } else if (data[key] !== undefined) {
  6059. t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
  6060. }
  6061. }
  6062. }
  6063. return t.substring(1);
  6064. };
  6065. URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
  6066. // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
  6067. // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
  6068. return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
  6069. };
  6070. URI.addQuery = function(data, name, value) {
  6071. if (typeof name === 'object') {
  6072. for (var key in name) {
  6073. if (hasOwn.call(name, key)) {
  6074. URI.addQuery(data, key, name[key]);
  6075. }
  6076. }
  6077. } else if (typeof name === 'string') {
  6078. if (data[name] === undefined) {
  6079. data[name] = value;
  6080. return;
  6081. } else if (typeof data[name] === 'string') {
  6082. data[name] = [data[name]];
  6083. }
  6084. if (!isArray(value)) {
  6085. value = [value];
  6086. }
  6087. data[name] = (data[name] || []).concat(value);
  6088. } else {
  6089. throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
  6090. }
  6091. };
  6092. URI.setQuery = function(data, name, value) {
  6093. if (typeof name === 'object') {
  6094. for (var key in name) {
  6095. if (hasOwn.call(name, key)) {
  6096. URI.setQuery(data, key, name[key]);
  6097. }
  6098. }
  6099. } else if (typeof name === 'string') {
  6100. data[name] = value === undefined ? null : value;
  6101. } else {
  6102. throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
  6103. }
  6104. };
  6105. URI.removeQuery = function(data, name, value) {
  6106. var i, length, key;
  6107. if (isArray(name)) {
  6108. for (i = 0, length = name.length; i < length; i++) {
  6109. data[name[i]] = undefined;
  6110. }
  6111. } else if (getType(name) === 'RegExp') {
  6112. for (key in data) {
  6113. if (name.test(key)) {
  6114. data[key] = undefined;
  6115. }
  6116. }
  6117. } else if (typeof name === 'object') {
  6118. for (key in name) {
  6119. if (hasOwn.call(name, key)) {
  6120. URI.removeQuery(data, key, name[key]);
  6121. }
  6122. }
  6123. } else if (typeof name === 'string') {
  6124. if (value !== undefined) {
  6125. if (getType(value) === 'RegExp') {
  6126. if (!isArray(data[name]) && value.test(data[name])) {
  6127. data[name] = undefined;
  6128. } else {
  6129. data[name] = filterArrayValues(data[name], value);
  6130. }
  6131. } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
  6132. data[name] = undefined;
  6133. } else if (isArray(data[name])) {
  6134. data[name] = filterArrayValues(data[name], value);
  6135. }
  6136. } else {
  6137. data[name] = undefined;
  6138. }
  6139. } else {
  6140. throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
  6141. }
  6142. };
  6143. URI.hasQuery = function(data, name, value, withinArray) {
  6144. switch (getType(name)) {
  6145. case 'String':
  6146. // Nothing to do here
  6147. break;
  6148. case 'RegExp':
  6149. for (var key in data) {
  6150. if (hasOwn.call(data, key)) {
  6151. if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
  6152. return true;
  6153. }
  6154. }
  6155. }
  6156. return false;
  6157. case 'Object':
  6158. for (var _key in name) {
  6159. if (hasOwn.call(name, _key)) {
  6160. if (!URI.hasQuery(data, _key, name[_key])) {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. return true;
  6166. default:
  6167. throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
  6168. }
  6169. switch (getType(value)) {
  6170. case 'Undefined':
  6171. // true if exists (but may be empty)
  6172. return name in data; // data[name] !== undefined;
  6173. case 'Boolean':
  6174. // true if exists and non-empty
  6175. var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
  6176. return value === _booly;
  6177. case 'Function':
  6178. // allow complex comparison
  6179. return !!value(data[name], name, data);
  6180. case 'Array':
  6181. if (!isArray(data[name])) {
  6182. return false;
  6183. }
  6184. var op = withinArray ? arrayContains : arraysEqual;
  6185. return op(data[name], value);
  6186. case 'RegExp':
  6187. if (!isArray(data[name])) {
  6188. return Boolean(data[name] && data[name].match(value));
  6189. }
  6190. if (!withinArray) {
  6191. return false;
  6192. }
  6193. return arrayContains(data[name], value);
  6194. case 'Number':
  6195. value = String(value);
  6196. /* falls through */
  6197. case 'String':
  6198. if (!isArray(data[name])) {
  6199. return data[name] === value;
  6200. }
  6201. if (!withinArray) {
  6202. return false;
  6203. }
  6204. return arrayContains(data[name], value);
  6205. default:
  6206. throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
  6207. }
  6208. };
  6209. URI.joinPaths = function() {
  6210. var input = [];
  6211. var segments = [];
  6212. var nonEmptySegments = 0;
  6213. for (var i = 0; i < arguments.length; i++) {
  6214. var url = new URI(arguments[i]);
  6215. input.push(url);
  6216. var _segments = url.segment();
  6217. for (var s = 0; s < _segments.length; s++) {
  6218. if (typeof _segments[s] === 'string') {
  6219. segments.push(_segments[s]);
  6220. }
  6221. if (_segments[s]) {
  6222. nonEmptySegments++;
  6223. }
  6224. }
  6225. }
  6226. if (!segments.length || !nonEmptySegments) {
  6227. return new URI('');
  6228. }
  6229. var uri = new URI('').segment(segments);
  6230. if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
  6231. uri.path('/' + uri.path());
  6232. }
  6233. return uri.normalize();
  6234. };
  6235. URI.commonPath = function(one, two) {
  6236. var length = Math.min(one.length, two.length);
  6237. var pos;
  6238. // find first non-matching character
  6239. for (pos = 0; pos < length; pos++) {
  6240. if (one.charAt(pos) !== two.charAt(pos)) {
  6241. pos--;
  6242. break;
  6243. }
  6244. }
  6245. if (pos < 1) {
  6246. return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
  6247. }
  6248. // revert to last /
  6249. if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
  6250. pos = one.substring(0, pos).lastIndexOf('/');
  6251. }
  6252. return one.substring(0, pos + 1);
  6253. };
  6254. URI.withinString = function(string, callback, options) {
  6255. options || (options = {});
  6256. var _start = options.start || URI.findUri.start;
  6257. var _end = options.end || URI.findUri.end;
  6258. var _trim = options.trim || URI.findUri.trim;
  6259. var _parens = options.parens || URI.findUri.parens;
  6260. var _attributeOpen = /[a-z0-9-]=["']?$/i;
  6261. _start.lastIndex = 0;
  6262. while (true) {
  6263. var match = _start.exec(string);
  6264. if (!match) {
  6265. break;
  6266. }
  6267. var start = match.index;
  6268. if (options.ignoreHtml) {
  6269. // attribut(e=["']?$)
  6270. var attributeOpen = string.slice(Math.max(start - 3, 0), start);
  6271. if (attributeOpen && _attributeOpen.test(attributeOpen)) {
  6272. continue;
  6273. }
  6274. }
  6275. var end = start + string.slice(start).search(_end);
  6276. var slice = string.slice(start, end);
  6277. // make sure we include well balanced parens
  6278. var parensEnd = -1;
  6279. while (true) {
  6280. var parensMatch = _parens.exec(slice);
  6281. if (!parensMatch) {
  6282. break;
  6283. }
  6284. var parensMatchEnd = parensMatch.index + parensMatch[0].length;
  6285. parensEnd = Math.max(parensEnd, parensMatchEnd);
  6286. }
  6287. if (parensEnd > -1) {
  6288. slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
  6289. } else {
  6290. slice = slice.replace(_trim, '');
  6291. }
  6292. if (slice.length <= match[0].length) {
  6293. // the extract only contains the starting marker of a URI,
  6294. // e.g. "www" or "http://"
  6295. continue;
  6296. }
  6297. if (options.ignore && options.ignore.test(slice)) {
  6298. continue;
  6299. }
  6300. end = start + slice.length;
  6301. var result = callback(slice, start, end, string);
  6302. if (result === undefined) {
  6303. _start.lastIndex = end;
  6304. continue;
  6305. }
  6306. result = String(result);
  6307. string = string.slice(0, start) + result + string.slice(end);
  6308. _start.lastIndex = start + result.length;
  6309. }
  6310. _start.lastIndex = 0;
  6311. return string;
  6312. };
  6313. URI.ensureValidHostname = function(v, protocol) {
  6314. // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
  6315. // they are not part of DNS and therefore ignored by URI.js
  6316. var hasHostname = !!v; // not null and not an empty string
  6317. var hasProtocol = !!protocol;
  6318. var rejectEmptyHostname = false;
  6319. if (hasProtocol) {
  6320. rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
  6321. }
  6322. if (rejectEmptyHostname && !hasHostname) {
  6323. throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
  6324. } else if (v && v.match(URI.invalid_hostname_characters)) {
  6325. // test punycode
  6326. if (!punycode) {
  6327. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
  6328. }
  6329. if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
  6330. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
  6331. }
  6332. }
  6333. };
  6334. URI.ensureValidPort = function (v) {
  6335. if (!v) {
  6336. return;
  6337. }
  6338. var port = Number(v);
  6339. if (isInteger(port) && (port > 0) && (port < 65536)) {
  6340. return;
  6341. }
  6342. throw new TypeError('Port "' + v + '" is not a valid port');
  6343. };
  6344. // noConflict
  6345. URI.noConflict = function(removeAll) {
  6346. if (removeAll) {
  6347. var unconflicted = {
  6348. URI: this.noConflict()
  6349. };
  6350. if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
  6351. unconflicted.URITemplate = root.URITemplate.noConflict();
  6352. }
  6353. if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
  6354. unconflicted.IPv6 = root.IPv6.noConflict();
  6355. }
  6356. if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
  6357. unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
  6358. }
  6359. return unconflicted;
  6360. } else if (root.URI === this) {
  6361. root.URI = _URI;
  6362. }
  6363. return this;
  6364. };
  6365. p.build = function(deferBuild) {
  6366. if (deferBuild === true) {
  6367. this._deferred_build = true;
  6368. } else if (deferBuild === undefined || this._deferred_build) {
  6369. this._string = URI.build(this._parts);
  6370. this._deferred_build = false;
  6371. }
  6372. return this;
  6373. };
  6374. p.clone = function() {
  6375. return new URI(this);
  6376. };
  6377. p.valueOf = p.toString = function() {
  6378. return this.build(false)._string;
  6379. };
  6380. function generateSimpleAccessor(_part){
  6381. return function(v, build) {
  6382. if (v === undefined) {
  6383. return this._parts[_part] || '';
  6384. } else {
  6385. this._parts[_part] = v || null;
  6386. this.build(!build);
  6387. return this;
  6388. }
  6389. };
  6390. }
  6391. function generatePrefixAccessor(_part, _key){
  6392. return function(v, build) {
  6393. if (v === undefined) {
  6394. return this._parts[_part] || '';
  6395. } else {
  6396. if (v !== null) {
  6397. v = v + '';
  6398. if (v.charAt(0) === _key) {
  6399. v = v.substring(1);
  6400. }
  6401. }
  6402. this._parts[_part] = v;
  6403. this.build(!build);
  6404. return this;
  6405. }
  6406. };
  6407. }
  6408. p.protocol = generateSimpleAccessor('protocol');
  6409. p.username = generateSimpleAccessor('username');
  6410. p.password = generateSimpleAccessor('password');
  6411. p.hostname = generateSimpleAccessor('hostname');
  6412. p.port = generateSimpleAccessor('port');
  6413. p.query = generatePrefixAccessor('query', '?');
  6414. p.fragment = generatePrefixAccessor('fragment', '#');
  6415. p.search = function(v, build) {
  6416. var t = this.query(v, build);
  6417. return typeof t === 'string' && t.length ? ('?' + t) : t;
  6418. };
  6419. p.hash = function(v, build) {
  6420. var t = this.fragment(v, build);
  6421. return typeof t === 'string' && t.length ? ('#' + t) : t;
  6422. };
  6423. p.pathname = function(v, build) {
  6424. if (v === undefined || v === true) {
  6425. var res = this._parts.path || (this._parts.hostname ? '/' : '');
  6426. return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
  6427. } else {
  6428. if (this._parts.urn) {
  6429. this._parts.path = v ? URI.recodeUrnPath(v) : '';
  6430. } else {
  6431. this._parts.path = v ? URI.recodePath(v) : '/';
  6432. }
  6433. this.build(!build);
  6434. return this;
  6435. }
  6436. };
  6437. p.path = p.pathname;
  6438. p.href = function(href, build) {
  6439. var key;
  6440. if (href === undefined) {
  6441. return this.toString();
  6442. }
  6443. this._string = '';
  6444. this._parts = URI._parts();
  6445. var _URI = href instanceof URI;
  6446. var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
  6447. if (href.nodeName) {
  6448. var attribute = URI.getDomAttribute(href);
  6449. href = href[attribute] || '';
  6450. _object = false;
  6451. }
  6452. // window.location is reported to be an object, but it's not the sort
  6453. // of object we're looking for:
  6454. // * location.protocol ends with a colon
  6455. // * location.query != object.search
  6456. // * location.hash != object.fragment
  6457. // simply serializing the unknown object should do the trick
  6458. // (for location, not for everything...)
  6459. if (!_URI && _object && href.pathname !== undefined) {
  6460. href = href.toString();
  6461. }
  6462. if (typeof href === 'string' || href instanceof String) {
  6463. this._parts = URI.parse(String(href), this._parts);
  6464. } else if (_URI || _object) {
  6465. var src = _URI ? href._parts : href;
  6466. for (key in src) {
  6467. if (key === 'query') { continue; }
  6468. if (hasOwn.call(this._parts, key)) {
  6469. this._parts[key] = src[key];
  6470. }
  6471. }
  6472. if (src.query) {
  6473. this.query(src.query, false);
  6474. }
  6475. } else {
  6476. throw new TypeError('invalid input');
  6477. }
  6478. this.build(!build);
  6479. return this;
  6480. };
  6481. // identification accessors
  6482. p.is = function(what) {
  6483. var ip = false;
  6484. var ip4 = false;
  6485. var ip6 = false;
  6486. var name = false;
  6487. var sld = false;
  6488. var idn = false;
  6489. var punycode = false;
  6490. var relative = !this._parts.urn;
  6491. if (this._parts.hostname) {
  6492. relative = false;
  6493. ip4 = URI.ip4_expression.test(this._parts.hostname);
  6494. ip6 = URI.ip6_expression.test(this._parts.hostname);
  6495. ip = ip4 || ip6;
  6496. name = !ip;
  6497. sld = name && SLD && SLD.has(this._parts.hostname);
  6498. idn = name && URI.idn_expression.test(this._parts.hostname);
  6499. punycode = name && URI.punycode_expression.test(this._parts.hostname);
  6500. }
  6501. switch (what.toLowerCase()) {
  6502. case 'relative':
  6503. return relative;
  6504. case 'absolute':
  6505. return !relative;
  6506. // hostname identification
  6507. case 'domain':
  6508. case 'name':
  6509. return name;
  6510. case 'sld':
  6511. return sld;
  6512. case 'ip':
  6513. return ip;
  6514. case 'ip4':
  6515. case 'ipv4':
  6516. case 'inet4':
  6517. return ip4;
  6518. case 'ip6':
  6519. case 'ipv6':
  6520. case 'inet6':
  6521. return ip6;
  6522. case 'idn':
  6523. return idn;
  6524. case 'url':
  6525. return !this._parts.urn;
  6526. case 'urn':
  6527. return !!this._parts.urn;
  6528. case 'punycode':
  6529. return punycode;
  6530. }
  6531. return null;
  6532. };
  6533. // component specific input validation
  6534. var _protocol = p.protocol;
  6535. var _port = p.port;
  6536. var _hostname = p.hostname;
  6537. p.protocol = function(v, build) {
  6538. if (v) {
  6539. // accept trailing ://
  6540. v = v.replace(/:(\/\/)?$/, '');
  6541. if (!v.match(URI.protocol_expression)) {
  6542. throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
  6543. }
  6544. }
  6545. return _protocol.call(this, v, build);
  6546. };
  6547. p.scheme = p.protocol;
  6548. p.port = function(v, build) {
  6549. if (this._parts.urn) {
  6550. return v === undefined ? '' : this;
  6551. }
  6552. if (v !== undefined) {
  6553. if (v === 0) {
  6554. v = null;
  6555. }
  6556. if (v) {
  6557. v += '';
  6558. if (v.charAt(0) === ':') {
  6559. v = v.substring(1);
  6560. }
  6561. URI.ensureValidPort(v);
  6562. }
  6563. }
  6564. return _port.call(this, v, build);
  6565. };
  6566. p.hostname = function(v, build) {
  6567. if (this._parts.urn) {
  6568. return v === undefined ? '' : this;
  6569. }
  6570. if (v !== undefined) {
  6571. var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
  6572. var res = URI.parseHost(v, x);
  6573. if (res !== '/') {
  6574. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  6575. }
  6576. v = x.hostname;
  6577. if (this._parts.preventInvalidHostname) {
  6578. URI.ensureValidHostname(v, this._parts.protocol);
  6579. }
  6580. }
  6581. return _hostname.call(this, v, build);
  6582. };
  6583. // compound accessors
  6584. p.origin = function(v, build) {
  6585. if (this._parts.urn) {
  6586. return v === undefined ? '' : this;
  6587. }
  6588. if (v === undefined) {
  6589. var protocol = this.protocol();
  6590. var authority = this.authority();
  6591. if (!authority) {
  6592. return '';
  6593. }
  6594. return (protocol ? protocol + '://' : '') + this.authority();
  6595. } else {
  6596. var origin = URI(v);
  6597. this
  6598. .protocol(origin.protocol())
  6599. .authority(origin.authority())
  6600. .build(!build);
  6601. return this;
  6602. }
  6603. };
  6604. p.host = function(v, build) {
  6605. if (this._parts.urn) {
  6606. return v === undefined ? '' : this;
  6607. }
  6608. if (v === undefined) {
  6609. return this._parts.hostname ? URI.buildHost(this._parts) : '';
  6610. } else {
  6611. var res = URI.parseHost(v, this._parts);
  6612. if (res !== '/') {
  6613. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  6614. }
  6615. this.build(!build);
  6616. return this;
  6617. }
  6618. };
  6619. p.authority = function(v, build) {
  6620. if (this._parts.urn) {
  6621. return v === undefined ? '' : this;
  6622. }
  6623. if (v === undefined) {
  6624. return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
  6625. } else {
  6626. var res = URI.parseAuthority(v, this._parts);
  6627. if (res !== '/') {
  6628. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  6629. }
  6630. this.build(!build);
  6631. return this;
  6632. }
  6633. };
  6634. p.userinfo = function(v, build) {
  6635. if (this._parts.urn) {
  6636. return v === undefined ? '' : this;
  6637. }
  6638. if (v === undefined) {
  6639. var t = URI.buildUserinfo(this._parts);
  6640. return t ? t.substring(0, t.length -1) : t;
  6641. } else {
  6642. if (v[v.length-1] !== '@') {
  6643. v += '@';
  6644. }
  6645. URI.parseUserinfo(v, this._parts);
  6646. this.build(!build);
  6647. return this;
  6648. }
  6649. };
  6650. p.resource = function(v, build) {
  6651. var parts;
  6652. if (v === undefined) {
  6653. return this.path() + this.search() + this.hash();
  6654. }
  6655. parts = URI.parse(v);
  6656. this._parts.path = parts.path;
  6657. this._parts.query = parts.query;
  6658. this._parts.fragment = parts.fragment;
  6659. this.build(!build);
  6660. return this;
  6661. };
  6662. // fraction accessors
  6663. p.subdomain = function(v, build) {
  6664. if (this._parts.urn) {
  6665. return v === undefined ? '' : this;
  6666. }
  6667. // convenience, return "www" from "www.example.org"
  6668. if (v === undefined) {
  6669. if (!this._parts.hostname || this.is('IP')) {
  6670. return '';
  6671. }
  6672. // grab domain and add another segment
  6673. var end = this._parts.hostname.length - this.domain().length - 1;
  6674. return this._parts.hostname.substring(0, end) || '';
  6675. } else {
  6676. var e = this._parts.hostname.length - this.domain().length;
  6677. var sub = this._parts.hostname.substring(0, e);
  6678. var replace = new RegExp('^' + escapeRegEx(sub));
  6679. if (v && v.charAt(v.length - 1) !== '.') {
  6680. v += '.';
  6681. }
  6682. if (v.indexOf(':') !== -1) {
  6683. throw new TypeError('Domains cannot contain colons');
  6684. }
  6685. if (v) {
  6686. URI.ensureValidHostname(v, this._parts.protocol);
  6687. }
  6688. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6689. this.build(!build);
  6690. return this;
  6691. }
  6692. };
  6693. p.domain = function(v, build) {
  6694. if (this._parts.urn) {
  6695. return v === undefined ? '' : this;
  6696. }
  6697. if (typeof v === 'boolean') {
  6698. build = v;
  6699. v = undefined;
  6700. }
  6701. // convenience, return "example.org" from "www.example.org"
  6702. if (v === undefined) {
  6703. if (!this._parts.hostname || this.is('IP')) {
  6704. return '';
  6705. }
  6706. // if hostname consists of 1 or 2 segments, it must be the domain
  6707. var t = this._parts.hostname.match(/\./g);
  6708. if (t && t.length < 2) {
  6709. return this._parts.hostname;
  6710. }
  6711. // grab tld and add another segment
  6712. var end = this._parts.hostname.length - this.tld(build).length - 1;
  6713. end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
  6714. return this._parts.hostname.substring(end) || '';
  6715. } else {
  6716. if (!v) {
  6717. throw new TypeError('cannot set domain empty');
  6718. }
  6719. if (v.indexOf(':') !== -1) {
  6720. throw new TypeError('Domains cannot contain colons');
  6721. }
  6722. URI.ensureValidHostname(v, this._parts.protocol);
  6723. if (!this._parts.hostname || this.is('IP')) {
  6724. this._parts.hostname = v;
  6725. } else {
  6726. var replace = new RegExp(escapeRegEx(this.domain()) + '$');
  6727. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6728. }
  6729. this.build(!build);
  6730. return this;
  6731. }
  6732. };
  6733. p.tld = function(v, build) {
  6734. if (this._parts.urn) {
  6735. return v === undefined ? '' : this;
  6736. }
  6737. if (typeof v === 'boolean') {
  6738. build = v;
  6739. v = undefined;
  6740. }
  6741. // return "org" from "www.example.org"
  6742. if (v === undefined) {
  6743. if (!this._parts.hostname || this.is('IP')) {
  6744. return '';
  6745. }
  6746. var pos = this._parts.hostname.lastIndexOf('.');
  6747. var tld = this._parts.hostname.substring(pos + 1);
  6748. if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
  6749. return SLD.get(this._parts.hostname) || tld;
  6750. }
  6751. return tld;
  6752. } else {
  6753. var replace;
  6754. if (!v) {
  6755. throw new TypeError('cannot set TLD empty');
  6756. } else if (v.match(/[^a-zA-Z0-9-]/)) {
  6757. if (SLD && SLD.is(v)) {
  6758. replace = new RegExp(escapeRegEx(this.tld()) + '$');
  6759. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6760. } else {
  6761. throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
  6762. }
  6763. } else if (!this._parts.hostname || this.is('IP')) {
  6764. throw new ReferenceError('cannot set TLD on non-domain host');
  6765. } else {
  6766. replace = new RegExp(escapeRegEx(this.tld()) + '$');
  6767. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6768. }
  6769. this.build(!build);
  6770. return this;
  6771. }
  6772. };
  6773. p.directory = function(v, build) {
  6774. if (this._parts.urn) {
  6775. return v === undefined ? '' : this;
  6776. }
  6777. if (v === undefined || v === true) {
  6778. if (!this._parts.path && !this._parts.hostname) {
  6779. return '';
  6780. }
  6781. if (this._parts.path === '/') {
  6782. return '/';
  6783. }
  6784. var end = this._parts.path.length - this.filename().length - 1;
  6785. var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
  6786. return v ? URI.decodePath(res) : res;
  6787. } else {
  6788. var e = this._parts.path.length - this.filename().length;
  6789. var directory = this._parts.path.substring(0, e);
  6790. var replace = new RegExp('^' + escapeRegEx(directory));
  6791. // fully qualifier directories begin with a slash
  6792. if (!this.is('relative')) {
  6793. if (!v) {
  6794. v = '/';
  6795. }
  6796. if (v.charAt(0) !== '/') {
  6797. v = '/' + v;
  6798. }
  6799. }
  6800. // directories always end with a slash
  6801. if (v && v.charAt(v.length - 1) !== '/') {
  6802. v += '/';
  6803. }
  6804. v = URI.recodePath(v);
  6805. this._parts.path = this._parts.path.replace(replace, v);
  6806. this.build(!build);
  6807. return this;
  6808. }
  6809. };
  6810. p.filename = function(v, build) {
  6811. if (this._parts.urn) {
  6812. return v === undefined ? '' : this;
  6813. }
  6814. if (typeof v !== 'string') {
  6815. if (!this._parts.path || this._parts.path === '/') {
  6816. return '';
  6817. }
  6818. var pos = this._parts.path.lastIndexOf('/');
  6819. var res = this._parts.path.substring(pos+1);
  6820. return v ? URI.decodePathSegment(res) : res;
  6821. } else {
  6822. var mutatedDirectory = false;
  6823. if (v.charAt(0) === '/') {
  6824. v = v.substring(1);
  6825. }
  6826. if (v.match(/\.?\//)) {
  6827. mutatedDirectory = true;
  6828. }
  6829. var replace = new RegExp(escapeRegEx(this.filename()) + '$');
  6830. v = URI.recodePath(v);
  6831. this._parts.path = this._parts.path.replace(replace, v);
  6832. if (mutatedDirectory) {
  6833. this.normalizePath(build);
  6834. } else {
  6835. this.build(!build);
  6836. }
  6837. return this;
  6838. }
  6839. };
  6840. p.suffix = function(v, build) {
  6841. if (this._parts.urn) {
  6842. return v === undefined ? '' : this;
  6843. }
  6844. if (v === undefined || v === true) {
  6845. if (!this._parts.path || this._parts.path === '/') {
  6846. return '';
  6847. }
  6848. var filename = this.filename();
  6849. var pos = filename.lastIndexOf('.');
  6850. var s, res;
  6851. if (pos === -1) {
  6852. return '';
  6853. }
  6854. // suffix may only contain alnum characters (yup, I made this up.)
  6855. s = filename.substring(pos+1);
  6856. res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
  6857. return v ? URI.decodePathSegment(res) : res;
  6858. } else {
  6859. if (v.charAt(0) === '.') {
  6860. v = v.substring(1);
  6861. }
  6862. var suffix = this.suffix();
  6863. var replace;
  6864. if (!suffix) {
  6865. if (!v) {
  6866. return this;
  6867. }
  6868. this._parts.path += '.' + URI.recodePath(v);
  6869. } else if (!v) {
  6870. replace = new RegExp(escapeRegEx('.' + suffix) + '$');
  6871. } else {
  6872. replace = new RegExp(escapeRegEx(suffix) + '$');
  6873. }
  6874. if (replace) {
  6875. v = URI.recodePath(v);
  6876. this._parts.path = this._parts.path.replace(replace, v);
  6877. }
  6878. this.build(!build);
  6879. return this;
  6880. }
  6881. };
  6882. p.segment = function(segment, v, build) {
  6883. var separator = this._parts.urn ? ':' : '/';
  6884. var path = this.path();
  6885. var absolute = path.substring(0, 1) === '/';
  6886. var segments = path.split(separator);
  6887. if (segment !== undefined && typeof segment !== 'number') {
  6888. build = v;
  6889. v = segment;
  6890. segment = undefined;
  6891. }
  6892. if (segment !== undefined && typeof segment !== 'number') {
  6893. throw new Error('Bad segment "' + segment + '", must be 0-based integer');
  6894. }
  6895. if (absolute) {
  6896. segments.shift();
  6897. }
  6898. if (segment < 0) {
  6899. // allow negative indexes to address from the end
  6900. segment = Math.max(segments.length + segment, 0);
  6901. }
  6902. if (v === undefined) {
  6903. /*jshint laxbreak: true */
  6904. return segment === undefined
  6905. ? segments
  6906. : segments[segment];
  6907. /*jshint laxbreak: false */
  6908. } else if (segment === null || segments[segment] === undefined) {
  6909. if (isArray(v)) {
  6910. segments = [];
  6911. // collapse empty elements within array
  6912. for (var i=0, l=v.length; i < l; i++) {
  6913. if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
  6914. continue;
  6915. }
  6916. if (segments.length && !segments[segments.length -1].length) {
  6917. segments.pop();
  6918. }
  6919. segments.push(trimSlashes(v[i]));
  6920. }
  6921. } else if (v || typeof v === 'string') {
  6922. v = trimSlashes(v);
  6923. if (segments[segments.length -1] === '') {
  6924. // empty trailing elements have to be overwritten
  6925. // to prevent results such as /foo//bar
  6926. segments[segments.length -1] = v;
  6927. } else {
  6928. segments.push(v);
  6929. }
  6930. }
  6931. } else {
  6932. if (v) {
  6933. segments[segment] = trimSlashes(v);
  6934. } else {
  6935. segments.splice(segment, 1);
  6936. }
  6937. }
  6938. if (absolute) {
  6939. segments.unshift('');
  6940. }
  6941. return this.path(segments.join(separator), build);
  6942. };
  6943. p.segmentCoded = function(segment, v, build) {
  6944. var segments, i, l;
  6945. if (typeof segment !== 'number') {
  6946. build = v;
  6947. v = segment;
  6948. segment = undefined;
  6949. }
  6950. if (v === undefined) {
  6951. segments = this.segment(segment, v, build);
  6952. if (!isArray(segments)) {
  6953. segments = segments !== undefined ? URI.decode(segments) : undefined;
  6954. } else {
  6955. for (i = 0, l = segments.length; i < l; i++) {
  6956. segments[i] = URI.decode(segments[i]);
  6957. }
  6958. }
  6959. return segments;
  6960. }
  6961. if (!isArray(v)) {
  6962. v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
  6963. } else {
  6964. for (i = 0, l = v.length; i < l; i++) {
  6965. v[i] = URI.encode(v[i]);
  6966. }
  6967. }
  6968. return this.segment(segment, v, build);
  6969. };
  6970. // mutating query string
  6971. var q = p.query;
  6972. p.query = function(v, build) {
  6973. if (v === true) {
  6974. return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6975. } else if (typeof v === 'function') {
  6976. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6977. var result = v.call(this, data);
  6978. this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  6979. this.build(!build);
  6980. return this;
  6981. } else if (v !== undefined && typeof v !== 'string') {
  6982. this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  6983. this.build(!build);
  6984. return this;
  6985. } else {
  6986. return q.call(this, v, build);
  6987. }
  6988. };
  6989. p.setQuery = function(name, value, build) {
  6990. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6991. if (typeof name === 'string' || name instanceof String) {
  6992. data[name] = value !== undefined ? value : null;
  6993. } else if (typeof name === 'object') {
  6994. for (var key in name) {
  6995. if (hasOwn.call(name, key)) {
  6996. data[key] = name[key];
  6997. }
  6998. }
  6999. } else {
  7000. throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
  7001. }
  7002. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  7003. if (typeof name !== 'string') {
  7004. build = value;
  7005. }
  7006. this.build(!build);
  7007. return this;
  7008. };
  7009. p.addQuery = function(name, value, build) {
  7010. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  7011. URI.addQuery(data, name, value === undefined ? null : value);
  7012. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  7013. if (typeof name !== 'string') {
  7014. build = value;
  7015. }
  7016. this.build(!build);
  7017. return this;
  7018. };
  7019. p.removeQuery = function(name, value, build) {
  7020. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  7021. URI.removeQuery(data, name, value);
  7022. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  7023. if (typeof name !== 'string') {
  7024. build = value;
  7025. }
  7026. this.build(!build);
  7027. return this;
  7028. };
  7029. p.hasQuery = function(name, value, withinArray) {
  7030. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  7031. return URI.hasQuery(data, name, value, withinArray);
  7032. };
  7033. p.setSearch = p.setQuery;
  7034. p.addSearch = p.addQuery;
  7035. p.removeSearch = p.removeQuery;
  7036. p.hasSearch = p.hasQuery;
  7037. // sanitizing URLs
  7038. p.normalize = function() {
  7039. if (this._parts.urn) {
  7040. return this
  7041. .normalizeProtocol(false)
  7042. .normalizePath(false)
  7043. .normalizeQuery(false)
  7044. .normalizeFragment(false)
  7045. .build();
  7046. }
  7047. return this
  7048. .normalizeProtocol(false)
  7049. .normalizeHostname(false)
  7050. .normalizePort(false)
  7051. .normalizePath(false)
  7052. .normalizeQuery(false)
  7053. .normalizeFragment(false)
  7054. .build();
  7055. };
  7056. p.normalizeProtocol = function(build) {
  7057. if (typeof this._parts.protocol === 'string') {
  7058. this._parts.protocol = this._parts.protocol.toLowerCase();
  7059. this.build(!build);
  7060. }
  7061. return this;
  7062. };
  7063. p.normalizeHostname = function(build) {
  7064. if (this._parts.hostname) {
  7065. if (this.is('IDN') && punycode) {
  7066. this._parts.hostname = punycode.toASCII(this._parts.hostname);
  7067. } else if (this.is('IPv6') && IPv6) {
  7068. this._parts.hostname = IPv6.best(this._parts.hostname);
  7069. }
  7070. this._parts.hostname = this._parts.hostname.toLowerCase();
  7071. this.build(!build);
  7072. }
  7073. return this;
  7074. };
  7075. p.normalizePort = function(build) {
  7076. // remove port of it's the protocol's default
  7077. if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
  7078. this._parts.port = null;
  7079. this.build(!build);
  7080. }
  7081. return this;
  7082. };
  7083. p.normalizePath = function(build) {
  7084. var _path = this._parts.path;
  7085. if (!_path) {
  7086. return this;
  7087. }
  7088. if (this._parts.urn) {
  7089. this._parts.path = URI.recodeUrnPath(this._parts.path);
  7090. this.build(!build);
  7091. return this;
  7092. }
  7093. if (this._parts.path === '/') {
  7094. return this;
  7095. }
  7096. _path = URI.recodePath(_path);
  7097. var _was_relative;
  7098. var _leadingParents = '';
  7099. var _parent, _pos;
  7100. // handle relative paths
  7101. if (_path.charAt(0) !== '/') {
  7102. _was_relative = true;
  7103. _path = '/' + _path;
  7104. }
  7105. // handle relative files (as opposed to directories)
  7106. if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
  7107. _path += '/';
  7108. }
  7109. // resolve simples
  7110. _path = _path
  7111. .replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
  7112. .replace(/\/{2,}/g, '/');
  7113. // remember leading parents
  7114. if (_was_relative) {
  7115. _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
  7116. if (_leadingParents) {
  7117. _leadingParents = _leadingParents[0];
  7118. }
  7119. }
  7120. // resolve parents
  7121. while (true) {
  7122. _parent = _path.search(/\/\.\.(\/|$)/);
  7123. if (_parent === -1) {
  7124. // no more ../ to resolve
  7125. break;
  7126. } else if (_parent === 0) {
  7127. // top level cannot be relative, skip it
  7128. _path = _path.substring(3);
  7129. continue;
  7130. }
  7131. _pos = _path.substring(0, _parent).lastIndexOf('/');
  7132. if (_pos === -1) {
  7133. _pos = _parent;
  7134. }
  7135. _path = _path.substring(0, _pos) + _path.substring(_parent + 3);
  7136. }
  7137. // revert to relative
  7138. if (_was_relative && this.is('relative')) {
  7139. _path = _leadingParents + _path.substring(1);
  7140. }
  7141. this._parts.path = _path;
  7142. this.build(!build);
  7143. return this;
  7144. };
  7145. p.normalizePathname = p.normalizePath;
  7146. p.normalizeQuery = function(build) {
  7147. if (typeof this._parts.query === 'string') {
  7148. if (!this._parts.query.length) {
  7149. this._parts.query = null;
  7150. } else {
  7151. this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
  7152. }
  7153. this.build(!build);
  7154. }
  7155. return this;
  7156. };
  7157. p.normalizeFragment = function(build) {
  7158. if (!this._parts.fragment) {
  7159. this._parts.fragment = null;
  7160. this.build(!build);
  7161. }
  7162. return this;
  7163. };
  7164. p.normalizeSearch = p.normalizeQuery;
  7165. p.normalizeHash = p.normalizeFragment;
  7166. p.iso8859 = function() {
  7167. // expect unicode input, iso8859 output
  7168. var e = URI.encode;
  7169. var d = URI.decode;
  7170. URI.encode = escape;
  7171. URI.decode = decodeURIComponent;
  7172. try {
  7173. this.normalize();
  7174. } finally {
  7175. URI.encode = e;
  7176. URI.decode = d;
  7177. }
  7178. return this;
  7179. };
  7180. p.unicode = function() {
  7181. // expect iso8859 input, unicode output
  7182. var e = URI.encode;
  7183. var d = URI.decode;
  7184. URI.encode = strictEncodeURIComponent;
  7185. URI.decode = unescape;
  7186. try {
  7187. this.normalize();
  7188. } finally {
  7189. URI.encode = e;
  7190. URI.decode = d;
  7191. }
  7192. return this;
  7193. };
  7194. p.readable = function() {
  7195. var uri = this.clone();
  7196. // removing username, password, because they shouldn't be displayed according to RFC 3986
  7197. uri.username('').password('').normalize();
  7198. var t = '';
  7199. if (uri._parts.protocol) {
  7200. t += uri._parts.protocol + '://';
  7201. }
  7202. if (uri._parts.hostname) {
  7203. if (uri.is('punycode') && punycode) {
  7204. t += punycode.toUnicode(uri._parts.hostname);
  7205. if (uri._parts.port) {
  7206. t += ':' + uri._parts.port;
  7207. }
  7208. } else {
  7209. t += uri.host();
  7210. }
  7211. }
  7212. if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
  7213. t += '/';
  7214. }
  7215. t += uri.path(true);
  7216. if (uri._parts.query) {
  7217. var q = '';
  7218. for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
  7219. var kv = (qp[i] || '').split('=');
  7220. q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
  7221. .replace(/&/g, '%26');
  7222. if (kv[1] !== undefined) {
  7223. q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
  7224. .replace(/&/g, '%26');
  7225. }
  7226. }
  7227. t += '?' + q.substring(1);
  7228. }
  7229. t += URI.decodeQuery(uri.hash(), true);
  7230. return t;
  7231. };
  7232. // resolving relative and absolute URLs
  7233. p.absoluteTo = function(base) {
  7234. var resolved = this.clone();
  7235. var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
  7236. var basedir, i, p;
  7237. if (this._parts.urn) {
  7238. throw new Error('URNs do not have any generally defined hierarchical components');
  7239. }
  7240. if (!(base instanceof URI)) {
  7241. base = new URI(base);
  7242. }
  7243. if (resolved._parts.protocol) {
  7244. // Directly returns even if this._parts.hostname is empty.
  7245. return resolved;
  7246. } else {
  7247. resolved._parts.protocol = base._parts.protocol;
  7248. }
  7249. if (this._parts.hostname) {
  7250. return resolved;
  7251. }
  7252. for (i = 0; (p = properties[i]); i++) {
  7253. resolved._parts[p] = base._parts[p];
  7254. }
  7255. if (!resolved._parts.path) {
  7256. resolved._parts.path = base._parts.path;
  7257. if (!resolved._parts.query) {
  7258. resolved._parts.query = base._parts.query;
  7259. }
  7260. } else {
  7261. if (resolved._parts.path.substring(-2) === '..') {
  7262. resolved._parts.path += '/';
  7263. }
  7264. if (resolved.path().charAt(0) !== '/') {
  7265. basedir = base.directory();
  7266. basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
  7267. resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
  7268. resolved.normalizePath();
  7269. }
  7270. }
  7271. resolved.build();
  7272. return resolved;
  7273. };
  7274. p.relativeTo = function(base) {
  7275. var relative = this.clone().normalize();
  7276. var relativeParts, baseParts, common, relativePath, basePath;
  7277. if (relative._parts.urn) {
  7278. throw new Error('URNs do not have any generally defined hierarchical components');
  7279. }
  7280. base = new URI(base).normalize();
  7281. relativeParts = relative._parts;
  7282. baseParts = base._parts;
  7283. relativePath = relative.path();
  7284. basePath = base.path();
  7285. if (relativePath.charAt(0) !== '/') {
  7286. throw new Error('URI is already relative');
  7287. }
  7288. if (basePath.charAt(0) !== '/') {
  7289. throw new Error('Cannot calculate a URI relative to another relative URI');
  7290. }
  7291. if (relativeParts.protocol === baseParts.protocol) {
  7292. relativeParts.protocol = null;
  7293. }
  7294. if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
  7295. return relative.build();
  7296. }
  7297. if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
  7298. return relative.build();
  7299. }
  7300. if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
  7301. relativeParts.hostname = null;
  7302. relativeParts.port = null;
  7303. } else {
  7304. return relative.build();
  7305. }
  7306. if (relativePath === basePath) {
  7307. relativeParts.path = '';
  7308. return relative.build();
  7309. }
  7310. // determine common sub path
  7311. common = URI.commonPath(relativePath, basePath);
  7312. // If the paths have nothing in common, return a relative URL with the absolute path.
  7313. if (!common) {
  7314. return relative.build();
  7315. }
  7316. var parents = baseParts.path
  7317. .substring(common.length)
  7318. .replace(/[^\/]*$/, '')
  7319. .replace(/.*?\//g, '../');
  7320. relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
  7321. return relative.build();
  7322. };
  7323. // comparing URIs
  7324. p.equals = function(uri) {
  7325. var one = this.clone();
  7326. var two = new URI(uri);
  7327. var one_map = {};
  7328. var two_map = {};
  7329. var checked = {};
  7330. var one_query, two_query, key;
  7331. one.normalize();
  7332. two.normalize();
  7333. // exact match
  7334. if (one.toString() === two.toString()) {
  7335. return true;
  7336. }
  7337. // extract query string
  7338. one_query = one.query();
  7339. two_query = two.query();
  7340. one.query('');
  7341. two.query('');
  7342. // definitely not equal if not even non-query parts match
  7343. if (one.toString() !== two.toString()) {
  7344. return false;
  7345. }
  7346. // query parameters have the same length, even if they're permuted
  7347. if (one_query.length !== two_query.length) {
  7348. return false;
  7349. }
  7350. one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
  7351. two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
  7352. for (key in one_map) {
  7353. if (hasOwn.call(one_map, key)) {
  7354. if (!isArray(one_map[key])) {
  7355. if (one_map[key] !== two_map[key]) {
  7356. return false;
  7357. }
  7358. } else if (!arraysEqual(one_map[key], two_map[key])) {
  7359. return false;
  7360. }
  7361. checked[key] = true;
  7362. }
  7363. }
  7364. for (key in two_map) {
  7365. if (hasOwn.call(two_map, key)) {
  7366. if (!checked[key]) {
  7367. // two contains a parameter not present in one
  7368. return false;
  7369. }
  7370. }
  7371. }
  7372. return true;
  7373. };
  7374. // state
  7375. p.preventInvalidHostname = function(v) {
  7376. this._parts.preventInvalidHostname = !!v;
  7377. return this;
  7378. };
  7379. p.duplicateQueryParameters = function(v) {
  7380. this._parts.duplicateQueryParameters = !!v;
  7381. return this;
  7382. };
  7383. p.escapeQuerySpace = function(v) {
  7384. this._parts.escapeQuerySpace = !!v;
  7385. return this;
  7386. };
  7387. return URI;
  7388. }));
  7389. });
  7390. /**
  7391. * @private
  7392. */
  7393. function appendForwardSlash(url) {
  7394. if (url.length === 0 || url[url.length - 1] !== "/") {
  7395. url = `${url}/`;
  7396. }
  7397. return url;
  7398. }
  7399. /**
  7400. * Clones an object, returning a new object containing the same properties.
  7401. *
  7402. * @function
  7403. *
  7404. * @param {Object} object The object to clone.
  7405. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  7406. * @returns {Object} The cloned object.
  7407. */
  7408. function clone(object, deep) {
  7409. if (object === null || typeof object !== "object") {
  7410. return object;
  7411. }
  7412. deep = defaultValue.defaultValue(deep, false);
  7413. const result = new object.constructor();
  7414. for (const propertyName in object) {
  7415. if (object.hasOwnProperty(propertyName)) {
  7416. let value = object[propertyName];
  7417. if (deep) {
  7418. value = clone(value, deep);
  7419. }
  7420. result[propertyName] = value;
  7421. }
  7422. }
  7423. return result;
  7424. }
  7425. /**
  7426. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  7427. * @function
  7428. *
  7429. * @param {String} relative The relative Uri.
  7430. * @param {String} [base] The base Uri.
  7431. * @returns {String} The absolute Uri of the given relative Uri.
  7432. *
  7433. * @example
  7434. * //absolute Uri will be "https://test.com/awesome.png";
  7435. * const absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  7436. */
  7437. function getAbsoluteUri(relative, base) {
  7438. let documentObject;
  7439. if (typeof document !== "undefined") {
  7440. documentObject = document;
  7441. }
  7442. return getAbsoluteUri._implementation(relative, base, documentObject);
  7443. }
  7444. getAbsoluteUri._implementation = function (relative, base, documentObject) {
  7445. //>>includeStart('debug', pragmas.debug);
  7446. if (!defaultValue.defined(relative)) {
  7447. throw new RuntimeError.DeveloperError("relative uri is required.");
  7448. }
  7449. //>>includeEnd('debug');
  7450. if (!defaultValue.defined(base)) {
  7451. if (typeof documentObject === "undefined") {
  7452. return relative;
  7453. }
  7454. base = defaultValue.defaultValue(documentObject.baseURI, documentObject.location.href);
  7455. }
  7456. const relativeUri = new URI(relative);
  7457. if (relativeUri.scheme() !== "") {
  7458. return relativeUri.toString();
  7459. }
  7460. return relativeUri.absoluteTo(base).toString();
  7461. };
  7462. /**
  7463. * Given a URI, returns the base path of the URI.
  7464. * @function
  7465. *
  7466. * @param {String} uri The Uri.
  7467. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  7468. * @returns {String} The base path of the Uri.
  7469. *
  7470. * @example
  7471. * // basePath will be "/Gallery/";
  7472. * const basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
  7473. *
  7474. * // basePath will be "/Gallery/?value=true&example=false";
  7475. * const basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
  7476. */
  7477. function getBaseUri(uri, includeQuery) {
  7478. //>>includeStart('debug', pragmas.debug);
  7479. if (!defaultValue.defined(uri)) {
  7480. throw new RuntimeError.DeveloperError("uri is required.");
  7481. }
  7482. //>>includeEnd('debug');
  7483. let basePath = "";
  7484. const i = uri.lastIndexOf("/");
  7485. if (i !== -1) {
  7486. basePath = uri.substring(0, i + 1);
  7487. }
  7488. if (!includeQuery) {
  7489. return basePath;
  7490. }
  7491. uri = new URI(uri);
  7492. if (uri.query().length !== 0) {
  7493. basePath += `?${uri.query()}`;
  7494. }
  7495. if (uri.fragment().length !== 0) {
  7496. basePath += `#${uri.fragment()}`;
  7497. }
  7498. return basePath;
  7499. }
  7500. /**
  7501. * Given a URI, returns the extension of the URI.
  7502. * @function getExtensionFromUri
  7503. *
  7504. * @param {String} uri The Uri.
  7505. * @returns {String} The extension of the Uri.
  7506. *
  7507. * @example
  7508. * //extension will be "czml";
  7509. * const extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
  7510. */
  7511. function getExtensionFromUri(uri) {
  7512. //>>includeStart('debug', pragmas.debug);
  7513. if (!defaultValue.defined(uri)) {
  7514. throw new RuntimeError.DeveloperError("uri is required.");
  7515. }
  7516. //>>includeEnd('debug');
  7517. const uriObject = new URI(uri);
  7518. uriObject.normalize();
  7519. let path = uriObject.path();
  7520. let index = path.lastIndexOf("/");
  7521. if (index !== -1) {
  7522. path = path.substr(index + 1);
  7523. }
  7524. index = path.lastIndexOf(".");
  7525. if (index === -1) {
  7526. path = "";
  7527. } else {
  7528. path = path.substr(index + 1);
  7529. }
  7530. return path;
  7531. }
  7532. const context2DsByWidthAndHeight = {};
  7533. /**
  7534. * Extract a pixel array from a loaded image. Draws the image
  7535. * into a canvas so it can read the pixels back.
  7536. *
  7537. * @function getImagePixels
  7538. *
  7539. * @param {HTMLImageElement|ImageBitmap} image The image to extract pixels from.
  7540. * @param {Number} width The width of the image. If not defined, then image.width is assigned.
  7541. * @param {Number} height The height of the image. If not defined, then image.height is assigned.
  7542. * @returns {ImageData} The pixels of the image.
  7543. */
  7544. function getImagePixels(image, width, height) {
  7545. if (!defaultValue.defined(width)) {
  7546. width = image.width;
  7547. }
  7548. if (!defaultValue.defined(height)) {
  7549. height = image.height;
  7550. }
  7551. let context2DsByHeight = context2DsByWidthAndHeight[width];
  7552. if (!defaultValue.defined(context2DsByHeight)) {
  7553. context2DsByHeight = {};
  7554. context2DsByWidthAndHeight[width] = context2DsByHeight;
  7555. }
  7556. let context2d = context2DsByHeight[height];
  7557. if (!defaultValue.defined(context2d)) {
  7558. const canvas = document.createElement("canvas");
  7559. canvas.width = width;
  7560. canvas.height = height;
  7561. context2d = canvas.getContext("2d");
  7562. context2d.globalCompositeOperation = "copy";
  7563. context2DsByHeight[height] = context2d;
  7564. }
  7565. context2d.drawImage(image, 0, 0, width, height);
  7566. return context2d.getImageData(0, 0, width, height).data;
  7567. }
  7568. const blobUriRegex = /^blob:/i;
  7569. /**
  7570. * Determines if the specified uri is a blob uri.
  7571. *
  7572. * @function isBlobUri
  7573. *
  7574. * @param {String} uri The uri to test.
  7575. * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
  7576. *
  7577. * @private
  7578. */
  7579. function isBlobUri(uri) {
  7580. //>>includeStart('debug', pragmas.debug);
  7581. RuntimeError.Check.typeOf.string("uri", uri);
  7582. //>>includeEnd('debug');
  7583. return blobUriRegex.test(uri);
  7584. }
  7585. let a$1;
  7586. /**
  7587. * Given a URL, determine whether that URL is considered cross-origin to the current page.
  7588. *
  7589. * @private
  7590. */
  7591. function isCrossOriginUrl(url) {
  7592. if (!defaultValue.defined(a$1)) {
  7593. a$1 = document.createElement("a");
  7594. }
  7595. // copy window location into the anchor to get consistent results
  7596. // when the port is default for the protocol (e.g. 80 for HTTP)
  7597. a$1.href = window.location.href;
  7598. // host includes both hostname and port if the port is not standard
  7599. const host = a$1.host;
  7600. const protocol = a$1.protocol;
  7601. a$1.href = url;
  7602. // IE only absolutizes href on get, not set
  7603. // eslint-disable-next-line no-self-assign
  7604. a$1.href = a$1.href;
  7605. return protocol !== a$1.protocol || host !== a$1.host;
  7606. }
  7607. const dataUriRegex$1 = /^data:/i;
  7608. /**
  7609. * Determines if the specified uri is a data uri.
  7610. *
  7611. * @function isDataUri
  7612. *
  7613. * @param {String} uri The uri to test.
  7614. * @returns {Boolean} true when the uri is a data uri; otherwise, false.
  7615. *
  7616. * @private
  7617. */
  7618. function isDataUri(uri) {
  7619. //>>includeStart('debug', pragmas.debug);
  7620. RuntimeError.Check.typeOf.string("uri", uri);
  7621. //>>includeEnd('debug');
  7622. return dataUriRegex$1.test(uri);
  7623. }
  7624. /**
  7625. * @private
  7626. */
  7627. function loadAndExecuteScript(url) {
  7628. const deferred = defer();
  7629. const script = document.createElement("script");
  7630. script.async = true;
  7631. script.src = url;
  7632. const head = document.getElementsByTagName("head")[0];
  7633. script.onload = function () {
  7634. script.onload = undefined;
  7635. head.removeChild(script);
  7636. deferred.resolve();
  7637. };
  7638. script.onerror = function (e) {
  7639. deferred.reject(e);
  7640. };
  7641. head.appendChild(script);
  7642. return deferred.promise;
  7643. }
  7644. /**
  7645. * Converts an object representing a set of name/value pairs into a query string,
  7646. * with names and values encoded properly for use in a URL. Values that are arrays
  7647. * will produce multiple values with the same name.
  7648. * @function objectToQuery
  7649. *
  7650. * @param {Object} obj The object containing data to encode.
  7651. * @returns {String} An encoded query string.
  7652. *
  7653. *
  7654. * @example
  7655. * const str = Cesium.objectToQuery({
  7656. * key1 : 'some value',
  7657. * key2 : 'a/b',
  7658. * key3 : ['x', 'y']
  7659. * });
  7660. *
  7661. * @see queryToObject
  7662. * // str will be:
  7663. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  7664. */
  7665. function objectToQuery(obj) {
  7666. //>>includeStart('debug', pragmas.debug);
  7667. if (!defaultValue.defined(obj)) {
  7668. throw new RuntimeError.DeveloperError("obj is required.");
  7669. }
  7670. //>>includeEnd('debug');
  7671. let result = "";
  7672. for (const propName in obj) {
  7673. if (obj.hasOwnProperty(propName)) {
  7674. const value = obj[propName];
  7675. const part = `${encodeURIComponent(propName)}=`;
  7676. if (Array.isArray(value)) {
  7677. for (let i = 0, len = value.length; i < len; ++i) {
  7678. result += `${part + encodeURIComponent(value[i])}&`;
  7679. }
  7680. } else {
  7681. result += `${part + encodeURIComponent(value)}&`;
  7682. }
  7683. }
  7684. }
  7685. // trim last &
  7686. result = result.slice(0, -1);
  7687. // This function used to replace %20 with + which is more compact and readable.
  7688. // However, some servers didn't properly handle + as a space.
  7689. // https://github.com/CesiumGS/cesium/issues/2192
  7690. return result;
  7691. }
  7692. /**
  7693. * Parses a query string into an object, where the keys and values of the object are the
  7694. * name/value pairs from the query string, decoded. If a name appears multiple times,
  7695. * the value in the object will be an array of values.
  7696. * @function queryToObject
  7697. *
  7698. * @param {String} queryString The query string.
  7699. * @returns {Object} An object containing the parameters parsed from the query string.
  7700. *
  7701. *
  7702. * @example
  7703. * const obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
  7704. * // obj will be:
  7705. * // {
  7706. * // key1 : 'some value',
  7707. * // key2 : 'a/b',
  7708. * // key3 : ['x', 'y']
  7709. * // }
  7710. *
  7711. * @see objectToQuery
  7712. */
  7713. function queryToObject(queryString) {
  7714. //>>includeStart('debug', pragmas.debug);
  7715. if (!defaultValue.defined(queryString)) {
  7716. throw new RuntimeError.DeveloperError("queryString is required.");
  7717. }
  7718. //>>includeEnd('debug');
  7719. const result = {};
  7720. if (queryString === "") {
  7721. return result;
  7722. }
  7723. const parts = queryString.replace(/\+/g, "%20").split(/[&;]/);
  7724. for (let i = 0, len = parts.length; i < len; ++i) {
  7725. const subparts = parts[i].split("=");
  7726. const name = decodeURIComponent(subparts[0]);
  7727. let value = subparts[1];
  7728. if (defaultValue.defined(value)) {
  7729. value = decodeURIComponent(value);
  7730. } else {
  7731. value = "";
  7732. }
  7733. const resultValue = result[name];
  7734. if (typeof resultValue === "string") {
  7735. // expand the single value to an array
  7736. result[name] = [resultValue, value];
  7737. } else if (Array.isArray(resultValue)) {
  7738. resultValue.push(value);
  7739. } else {
  7740. result[name] = value;
  7741. }
  7742. }
  7743. return result;
  7744. }
  7745. /**
  7746. * State of the request.
  7747. *
  7748. * @enum {Number}
  7749. */
  7750. const RequestState = {
  7751. /**
  7752. * Initial unissued state.
  7753. *
  7754. * @type Number
  7755. * @constant
  7756. */
  7757. UNISSUED: 0,
  7758. /**
  7759. * Issued but not yet active. Will become active when open slots are available.
  7760. *
  7761. * @type Number
  7762. * @constant
  7763. */
  7764. ISSUED: 1,
  7765. /**
  7766. * Actual http request has been sent.
  7767. *
  7768. * @type Number
  7769. * @constant
  7770. */
  7771. ACTIVE: 2,
  7772. /**
  7773. * Request completed successfully.
  7774. *
  7775. * @type Number
  7776. * @constant
  7777. */
  7778. RECEIVED: 3,
  7779. /**
  7780. * Request was cancelled, either explicitly or automatically because of low priority.
  7781. *
  7782. * @type Number
  7783. * @constant
  7784. */
  7785. CANCELLED: 4,
  7786. /**
  7787. * Request failed.
  7788. *
  7789. * @type Number
  7790. * @constant
  7791. */
  7792. FAILED: 5,
  7793. };
  7794. var RequestState$1 = Object.freeze(RequestState);
  7795. /**
  7796. * An enum identifying the type of request. Used for finer grained logging and priority sorting.
  7797. *
  7798. * @enum {Number}
  7799. */
  7800. const RequestType = {
  7801. /**
  7802. * Terrain request.
  7803. *
  7804. * @type Number
  7805. * @constant
  7806. */
  7807. TERRAIN: 0,
  7808. /**
  7809. * Imagery request.
  7810. *
  7811. * @type Number
  7812. * @constant
  7813. */
  7814. IMAGERY: 1,
  7815. /**
  7816. * 3D Tiles request.
  7817. *
  7818. * @type Number
  7819. * @constant
  7820. */
  7821. TILES3D: 2,
  7822. /**
  7823. * Other request.
  7824. *
  7825. * @type Number
  7826. * @constant
  7827. */
  7828. OTHER: 3,
  7829. };
  7830. var RequestType$1 = Object.freeze(RequestType);
  7831. /**
  7832. * Stores information for making a request. In general this does not need to be constructed directly.
  7833. *
  7834. * @alias Request
  7835. * @constructor
  7836. * @param {Object} [options] An object with the following properties:
  7837. * @param {String} [options.url] The url to request.
  7838. * @param {Request.RequestCallback} [options.requestFunction] The function that makes the actual data request.
  7839. * @param {Request.CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
  7840. * @param {Request.PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
  7841. * @param {Number} [options.priority=0.0] The initial priority of the request.
  7842. * @param {Boolean} [options.throttle=false] Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the request will be throttled and sent based on priority.
  7843. * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
  7844. * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
  7845. */
  7846. function Request(options) {
  7847. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  7848. const throttleByServer = defaultValue.defaultValue(options.throttleByServer, false);
  7849. const throttle = defaultValue.defaultValue(options.throttle, false);
  7850. /**
  7851. * The URL to request.
  7852. *
  7853. * @type {String}
  7854. */
  7855. this.url = options.url;
  7856. /**
  7857. * The function that makes the actual data request.
  7858. *
  7859. * @type {Request.RequestCallback}
  7860. */
  7861. this.requestFunction = options.requestFunction;
  7862. /**
  7863. * The function that is called when the request is cancelled.
  7864. *
  7865. * @type {Request.CancelCallback}
  7866. */
  7867. this.cancelFunction = options.cancelFunction;
  7868. /**
  7869. * The function that is called to update the request's priority, which occurs once per frame.
  7870. *
  7871. * @type {Request.PriorityCallback}
  7872. */
  7873. this.priorityFunction = options.priorityFunction;
  7874. /**
  7875. * Priority is a unit-less value where lower values represent higher priority.
  7876. * For world-based objects, this is usually the distance from the camera.
  7877. * A request that does not have a priority function defaults to a priority of 0.
  7878. *
  7879. * If priorityFunction is defined, this value is updated every frame with the result of that call.
  7880. *
  7881. * @type {Number}
  7882. * @default 0.0
  7883. */
  7884. this.priority = defaultValue.defaultValue(options.priority, 0.0);
  7885. /**
  7886. * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
  7887. * request will be throttled and sent based on priority.
  7888. *
  7889. * @type {Boolean}
  7890. * @readonly
  7891. *
  7892. * @default false
  7893. */
  7894. this.throttle = throttle;
  7895. /**
  7896. * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
  7897. * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
  7898. * to <code>true</code> is preferable for requests going through HTTP/1 servers.
  7899. *
  7900. * @type {Boolean}
  7901. * @readonly
  7902. *
  7903. * @default false
  7904. */
  7905. this.throttleByServer = throttleByServer;
  7906. /**
  7907. * Type of request.
  7908. *
  7909. * @type {RequestType}
  7910. * @readonly
  7911. *
  7912. * @default RequestType.OTHER
  7913. */
  7914. this.type = defaultValue.defaultValue(options.type, RequestType$1.OTHER);
  7915. /**
  7916. * A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
  7917. *
  7918. * @type {String}
  7919. *
  7920. * @private
  7921. */
  7922. this.serverKey = undefined;
  7923. /**
  7924. * The current state of the request.
  7925. *
  7926. * @type {RequestState}
  7927. * @readonly
  7928. */
  7929. this.state = RequestState$1.UNISSUED;
  7930. /**
  7931. * The requests's deferred promise.
  7932. *
  7933. * @type {Object}
  7934. *
  7935. * @private
  7936. */
  7937. this.deferred = undefined;
  7938. /**
  7939. * Whether the request was explicitly cancelled.
  7940. *
  7941. * @type {Boolean}
  7942. *
  7943. * @private
  7944. */
  7945. this.cancelled = false;
  7946. }
  7947. /**
  7948. * Mark the request as cancelled.
  7949. *
  7950. * @private
  7951. */
  7952. Request.prototype.cancel = function () {
  7953. this.cancelled = true;
  7954. };
  7955. /**
  7956. * Duplicates a Request instance.
  7957. *
  7958. * @param {Request} [result] The object onto which to store the result.
  7959. *
  7960. * @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
  7961. */
  7962. Request.prototype.clone = function (result) {
  7963. if (!defaultValue.defined(result)) {
  7964. return new Request(this);
  7965. }
  7966. result.url = this.url;
  7967. result.requestFunction = this.requestFunction;
  7968. result.cancelFunction = this.cancelFunction;
  7969. result.priorityFunction = this.priorityFunction;
  7970. result.priority = this.priority;
  7971. result.throttle = this.throttle;
  7972. result.throttleByServer = this.throttleByServer;
  7973. result.type = this.type;
  7974. result.serverKey = this.serverKey;
  7975. // These get defaulted because the cloned request hasn't been issued
  7976. result.state = this.RequestState.UNISSUED;
  7977. result.deferred = undefined;
  7978. result.cancelled = false;
  7979. return result;
  7980. };
  7981. /**
  7982. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  7983. * a dictionary.
  7984. *
  7985. * @function parseResponseHeaders
  7986. *
  7987. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  7988. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  7989. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  7990. * is that header's value.
  7991. *
  7992. * @private
  7993. */
  7994. function parseResponseHeaders(headerString) {
  7995. const headers = {};
  7996. if (!headerString) {
  7997. return headers;
  7998. }
  7999. const headerPairs = headerString.split("\u000d\u000a");
  8000. for (let i = 0; i < headerPairs.length; ++i) {
  8001. const headerPair = headerPairs[i];
  8002. // Can't use split() here because it does the wrong thing
  8003. // if the header value has the string ": " in it.
  8004. const index = headerPair.indexOf("\u003a\u0020");
  8005. if (index > 0) {
  8006. const key = headerPair.substring(0, index);
  8007. const val = headerPair.substring(index + 2);
  8008. headers[key] = val;
  8009. }
  8010. }
  8011. return headers;
  8012. }
  8013. /**
  8014. * An event that is raised when a request encounters an error.
  8015. *
  8016. * @constructor
  8017. * @alias RequestErrorEvent
  8018. *
  8019. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  8020. * @param {Object} [response] The response included along with the error.
  8021. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  8022. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  8023. */
  8024. function RequestErrorEvent(statusCode, response, responseHeaders) {
  8025. /**
  8026. * The HTTP error status code, such as 404. If the error does not have a particular
  8027. * HTTP code, this property will be undefined.
  8028. *
  8029. * @type {Number}
  8030. */
  8031. this.statusCode = statusCode;
  8032. /**
  8033. * The response included along with the error. If the error does not include a response,
  8034. * this property will be undefined.
  8035. *
  8036. * @type {Object}
  8037. */
  8038. this.response = response;
  8039. /**
  8040. * The headers included in the response, represented as an object literal of key/value pairs.
  8041. * If the error does not include any headers, this property will be undefined.
  8042. *
  8043. * @type {Object}
  8044. */
  8045. this.responseHeaders = responseHeaders;
  8046. if (typeof this.responseHeaders === "string") {
  8047. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  8048. }
  8049. }
  8050. /**
  8051. * Creates a string representing this RequestErrorEvent.
  8052. * @memberof RequestErrorEvent
  8053. *
  8054. * @returns {String} A string representing the provided RequestErrorEvent.
  8055. */
  8056. RequestErrorEvent.prototype.toString = function () {
  8057. let str = "Request has failed.";
  8058. if (defaultValue.defined(this.statusCode)) {
  8059. str += ` Status Code: ${this.statusCode}`;
  8060. }
  8061. return str;
  8062. };
  8063. /**
  8064. * A generic utility class for managing subscribers for a particular event.
  8065. * This class is usually instantiated inside of a container class and
  8066. * exposed as a property for others to subscribe to.
  8067. *
  8068. * @alias Event
  8069. * @template Listener extends (...args: any[]) => void = (...args: any[]) => void
  8070. * @constructor
  8071. * @example
  8072. * MyObject.prototype.myListener = function(arg1, arg2) {
  8073. * this.myArg1Copy = arg1;
  8074. * this.myArg2Copy = arg2;
  8075. * }
  8076. *
  8077. * const myObjectInstance = new MyObject();
  8078. * const evt = new Cesium.Event();
  8079. * evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
  8080. * evt.raiseEvent('1', '2');
  8081. * evt.removeEventListener(MyObject.prototype.myListener);
  8082. */
  8083. function Event() {
  8084. this._listeners = [];
  8085. this._scopes = [];
  8086. this._toRemove = [];
  8087. this._insideRaiseEvent = false;
  8088. }
  8089. Object.defineProperties(Event.prototype, {
  8090. /**
  8091. * The number of listeners currently subscribed to the event.
  8092. * @memberof Event.prototype
  8093. * @type {Number}
  8094. * @readonly
  8095. */
  8096. numberOfListeners: {
  8097. get: function () {
  8098. return this._listeners.length - this._toRemove.length;
  8099. },
  8100. },
  8101. });
  8102. /**
  8103. * Registers a callback function to be executed whenever the event is raised.
  8104. * An optional scope can be provided to serve as the <code>this</code> pointer
  8105. * in which the function will execute.
  8106. *
  8107. * @param {Listener} listener The function to be executed when the event is raised.
  8108. * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
  8109. * pointer in which the listener function will execute.
  8110. * @returns {Event.RemoveCallback} A function that will remove this event listener when invoked.
  8111. *
  8112. * @see Event#raiseEvent
  8113. * @see Event#removeEventListener
  8114. */
  8115. Event.prototype.addEventListener = function (listener, scope) {
  8116. //>>includeStart('debug', pragmas.debug);
  8117. RuntimeError.Check.typeOf.func("listener", listener);
  8118. //>>includeEnd('debug');
  8119. this._listeners.push(listener);
  8120. this._scopes.push(scope);
  8121. const event = this;
  8122. return function () {
  8123. event.removeEventListener(listener, scope);
  8124. };
  8125. };
  8126. /**
  8127. * Unregisters a previously registered callback.
  8128. *
  8129. * @param {Listener} listener The function to be unregistered.
  8130. * @param {Object} [scope] The scope that was originally passed to addEventListener.
  8131. * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> if the listener and scope are not registered with the event.
  8132. *
  8133. * @see Event#addEventListener
  8134. * @see Event#raiseEvent
  8135. */
  8136. Event.prototype.removeEventListener = function (listener, scope) {
  8137. //>>includeStart('debug', pragmas.debug);
  8138. RuntimeError.Check.typeOf.func("listener", listener);
  8139. //>>includeEnd('debug');
  8140. const listeners = this._listeners;
  8141. const scopes = this._scopes;
  8142. let index = -1;
  8143. for (let i = 0; i < listeners.length; i++) {
  8144. if (listeners[i] === listener && scopes[i] === scope) {
  8145. index = i;
  8146. break;
  8147. }
  8148. }
  8149. if (index !== -1) {
  8150. if (this._insideRaiseEvent) {
  8151. //In order to allow removing an event subscription from within
  8152. //a callback, we don't actually remove the items here. Instead
  8153. //remember the index they are at and undefined their value.
  8154. this._toRemove.push(index);
  8155. listeners[index] = undefined;
  8156. scopes[index] = undefined;
  8157. } else {
  8158. listeners.splice(index, 1);
  8159. scopes.splice(index, 1);
  8160. }
  8161. return true;
  8162. }
  8163. return false;
  8164. };
  8165. function compareNumber(a, b) {
  8166. return b - a;
  8167. }
  8168. /**
  8169. * Raises the event by calling each registered listener with all supplied arguments.
  8170. *
  8171. * @param {...Parameters<Listener>} arguments This method takes any number of parameters and passes them through to the listener functions.
  8172. *
  8173. * @see Event#addEventListener
  8174. * @see Event#removeEventListener
  8175. */
  8176. Event.prototype.raiseEvent = function () {
  8177. this._insideRaiseEvent = true;
  8178. let i;
  8179. const listeners = this._listeners;
  8180. const scopes = this._scopes;
  8181. let length = listeners.length;
  8182. for (i = 0; i < length; i++) {
  8183. const listener = listeners[i];
  8184. if (defaultValue.defined(listener)) {
  8185. listeners[i].apply(scopes[i], arguments);
  8186. }
  8187. }
  8188. //Actually remove items removed in removeEventListener.
  8189. const toRemove = this._toRemove;
  8190. length = toRemove.length;
  8191. if (length > 0) {
  8192. toRemove.sort(compareNumber);
  8193. for (i = 0; i < length; i++) {
  8194. const index = toRemove[i];
  8195. listeners.splice(index, 1);
  8196. scopes.splice(index, 1);
  8197. }
  8198. toRemove.length = 0;
  8199. }
  8200. this._insideRaiseEvent = false;
  8201. };
  8202. /**
  8203. * Array implementation of a heap.
  8204. *
  8205. * @alias Heap
  8206. * @constructor
  8207. * @private
  8208. *
  8209. * @param {Object} options Object with the following properties:
  8210. * @param {Heap.ComparatorCallback} options.comparator The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
  8211. */
  8212. function Heap(options) {
  8213. //>>includeStart('debug', pragmas.debug);
  8214. RuntimeError.Check.typeOf.object("options", options);
  8215. RuntimeError.Check.defined("options.comparator", options.comparator);
  8216. //>>includeEnd('debug');
  8217. this._comparator = options.comparator;
  8218. this._array = [];
  8219. this._length = 0;
  8220. this._maximumLength = undefined;
  8221. }
  8222. Object.defineProperties(Heap.prototype, {
  8223. /**
  8224. * Gets the length of the heap.
  8225. *
  8226. * @memberof Heap.prototype
  8227. *
  8228. * @type {Number}
  8229. * @readonly
  8230. */
  8231. length: {
  8232. get: function () {
  8233. return this._length;
  8234. },
  8235. },
  8236. /**
  8237. * Gets the internal array.
  8238. *
  8239. * @memberof Heap.prototype
  8240. *
  8241. * @type {Array}
  8242. * @readonly
  8243. */
  8244. internalArray: {
  8245. get: function () {
  8246. return this._array;
  8247. },
  8248. },
  8249. /**
  8250. * Gets and sets the maximum length of the heap.
  8251. *
  8252. * @memberof Heap.prototype
  8253. *
  8254. * @type {Number}
  8255. */
  8256. maximumLength: {
  8257. get: function () {
  8258. return this._maximumLength;
  8259. },
  8260. set: function (value) {
  8261. //>>includeStart('debug', pragmas.debug);
  8262. RuntimeError.Check.typeOf.number.greaterThanOrEquals("maximumLength", value, 0);
  8263. //>>includeEnd('debug');
  8264. const originalLength = this._length;
  8265. if (value < originalLength) {
  8266. const array = this._array;
  8267. // Remove trailing references
  8268. for (let i = value; i < originalLength; ++i) {
  8269. array[i] = undefined;
  8270. }
  8271. this._length = value;
  8272. array.length = value;
  8273. }
  8274. this._maximumLength = value;
  8275. },
  8276. },
  8277. /**
  8278. * The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
  8279. *
  8280. * @memberof Heap.prototype
  8281. *
  8282. * @type {Heap.ComparatorCallback}
  8283. */
  8284. comparator: {
  8285. get: function () {
  8286. return this._comparator;
  8287. },
  8288. },
  8289. });
  8290. function swap(array, a, b) {
  8291. const temp = array[a];
  8292. array[a] = array[b];
  8293. array[b] = temp;
  8294. }
  8295. /**
  8296. * Resizes the internal array of the heap.
  8297. *
  8298. * @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
  8299. */
  8300. Heap.prototype.reserve = function (length) {
  8301. length = defaultValue.defaultValue(length, this._length);
  8302. this._array.length = length;
  8303. };
  8304. /**
  8305. * Update the heap so that index and all descendants satisfy the heap property.
  8306. *
  8307. * @param {Number} [index=0] The starting index to heapify from.
  8308. */
  8309. Heap.prototype.heapify = function (index) {
  8310. index = defaultValue.defaultValue(index, 0);
  8311. const length = this._length;
  8312. const comparator = this._comparator;
  8313. const array = this._array;
  8314. let candidate = -1;
  8315. let inserting = true;
  8316. while (inserting) {
  8317. const right = 2 * (index + 1);
  8318. const left = right - 1;
  8319. if (left < length && comparator(array[left], array[index]) < 0) {
  8320. candidate = left;
  8321. } else {
  8322. candidate = index;
  8323. }
  8324. if (right < length && comparator(array[right], array[candidate]) < 0) {
  8325. candidate = right;
  8326. }
  8327. if (candidate !== index) {
  8328. swap(array, candidate, index);
  8329. index = candidate;
  8330. } else {
  8331. inserting = false;
  8332. }
  8333. }
  8334. };
  8335. /**
  8336. * Resort the heap.
  8337. */
  8338. Heap.prototype.resort = function () {
  8339. const length = this._length;
  8340. for (let i = Math.ceil(length / 2); i >= 0; --i) {
  8341. this.heapify(i);
  8342. }
  8343. };
  8344. /**
  8345. * Insert an element into the heap. If the length would grow greater than maximumLength
  8346. * of the heap, extra elements are removed.
  8347. *
  8348. * @param {*} element The element to insert
  8349. *
  8350. * @return {*} The element that was removed from the heap if the heap is at full capacity.
  8351. */
  8352. Heap.prototype.insert = function (element) {
  8353. //>>includeStart('debug', pragmas.debug);
  8354. RuntimeError.Check.defined("element", element);
  8355. //>>includeEnd('debug');
  8356. const array = this._array;
  8357. const comparator = this._comparator;
  8358. const maximumLength = this._maximumLength;
  8359. let index = this._length++;
  8360. if (index < array.length) {
  8361. array[index] = element;
  8362. } else {
  8363. array.push(element);
  8364. }
  8365. while (index !== 0) {
  8366. const parent = Math.floor((index - 1) / 2);
  8367. if (comparator(array[index], array[parent]) < 0) {
  8368. swap(array, index, parent);
  8369. index = parent;
  8370. } else {
  8371. break;
  8372. }
  8373. }
  8374. let removedElement;
  8375. if (defaultValue.defined(maximumLength) && this._length > maximumLength) {
  8376. removedElement = array[maximumLength];
  8377. this._length = maximumLength;
  8378. }
  8379. return removedElement;
  8380. };
  8381. /**
  8382. * Remove the element specified by index from the heap and return it.
  8383. *
  8384. * @param {Number} [index=0] The index to remove.
  8385. * @returns {*} The specified element of the heap.
  8386. */
  8387. Heap.prototype.pop = function (index) {
  8388. index = defaultValue.defaultValue(index, 0);
  8389. if (this._length === 0) {
  8390. return undefined;
  8391. }
  8392. //>>includeStart('debug', pragmas.debug);
  8393. RuntimeError.Check.typeOf.number.lessThan("index", index, this._length);
  8394. //>>includeEnd('debug');
  8395. const array = this._array;
  8396. const root = array[index];
  8397. swap(array, index, --this._length);
  8398. this.heapify(index);
  8399. array[this._length] = undefined; // Remove trailing reference
  8400. return root;
  8401. };
  8402. function sortRequests(a, b) {
  8403. return a.priority - b.priority;
  8404. }
  8405. const statistics = {
  8406. numberOfAttemptedRequests: 0,
  8407. numberOfActiveRequests: 0,
  8408. numberOfCancelledRequests: 0,
  8409. numberOfCancelledActiveRequests: 0,
  8410. numberOfFailedRequests: 0,
  8411. numberOfActiveRequestsEver: 0,
  8412. lastNumberOfActiveRequests: 0,
  8413. };
  8414. let priorityHeapLength = 20;
  8415. const requestHeap = new Heap({
  8416. comparator: sortRequests,
  8417. });
  8418. requestHeap.maximumLength = priorityHeapLength;
  8419. requestHeap.reserve(priorityHeapLength);
  8420. const activeRequests = [];
  8421. let numberOfActiveRequestsByServer = {};
  8422. const pageUri =
  8423. typeof document !== "undefined" ? new URI(document.location.href) : new URI();
  8424. const requestCompletedEvent = new Event();
  8425. /**
  8426. * The request scheduler is used to track and constrain the number of active requests in order to prioritize incoming requests. The ability
  8427. * to retain control over the number of requests in CesiumJS is important because due to events such as changes in the camera position,
  8428. * a lot of new requests may be generated and a lot of in-flight requests may become redundant. The request scheduler manually constrains the
  8429. * number of requests so that newer requests wait in a shorter queue and don't have to compete for bandwidth with requests that have expired.
  8430. *
  8431. * @namespace RequestScheduler
  8432. *
  8433. */
  8434. function RequestScheduler() {}
  8435. /**
  8436. * The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
  8437. * @type {Number}
  8438. * @default 50
  8439. */
  8440. RequestScheduler.maximumRequests = 50;
  8441. /**
  8442. * The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
  8443. * listed in {@link requestsByServer} do not observe this limit.
  8444. * @type {Number}
  8445. * @default 6
  8446. */
  8447. RequestScheduler.maximumRequestsPerServer = 6;
  8448. /**
  8449. * A per server key list of overrides to use for throttling instead of <code>maximumRequestsPerServer</code>
  8450. * @type {Object}
  8451. *
  8452. * @example
  8453. * RequestScheduler.requestsByServer = {
  8454. * 'api.cesium.com:443': 18,
  8455. * 'assets.cesium.com:443': 18
  8456. * };
  8457. */
  8458. RequestScheduler.requestsByServer = {
  8459. "api.cesium.com:443": 18,
  8460. "assets.cesium.com:443": 18,
  8461. };
  8462. /**
  8463. * Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
  8464. * @type {Boolean}
  8465. * @default true
  8466. */
  8467. RequestScheduler.throttleRequests = true;
  8468. /**
  8469. * When true, log statistics to the console every frame
  8470. * @type {Boolean}
  8471. * @default false
  8472. * @private
  8473. */
  8474. RequestScheduler.debugShowStatistics = false;
  8475. /**
  8476. * An event that's raised when a request is completed. Event handlers are passed
  8477. * the error object if the request fails.
  8478. *
  8479. * @type {Event}
  8480. * @default Event()
  8481. * @private
  8482. */
  8483. RequestScheduler.requestCompletedEvent = requestCompletedEvent;
  8484. Object.defineProperties(RequestScheduler, {
  8485. /**
  8486. * Returns the statistics used by the request scheduler.
  8487. *
  8488. * @memberof RequestScheduler
  8489. *
  8490. * @type Object
  8491. * @readonly
  8492. * @private
  8493. */
  8494. statistics: {
  8495. get: function () {
  8496. return statistics;
  8497. },
  8498. },
  8499. /**
  8500. * The maximum size of the priority heap. This limits the number of requests that are sorted by priority. Only applies to requests that are not yet active.
  8501. *
  8502. * @memberof RequestScheduler
  8503. *
  8504. * @type {Number}
  8505. * @default 20
  8506. * @private
  8507. */
  8508. priorityHeapLength: {
  8509. get: function () {
  8510. return priorityHeapLength;
  8511. },
  8512. set: function (value) {
  8513. // If the new length shrinks the heap, need to cancel some of the requests.
  8514. // Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
  8515. if (value < priorityHeapLength) {
  8516. while (requestHeap.length > value) {
  8517. const request = requestHeap.pop();
  8518. cancelRequest(request);
  8519. }
  8520. }
  8521. priorityHeapLength = value;
  8522. requestHeap.maximumLength = value;
  8523. requestHeap.reserve(value);
  8524. },
  8525. },
  8526. });
  8527. function updatePriority(request) {
  8528. if (defaultValue.defined(request.priorityFunction)) {
  8529. request.priority = request.priorityFunction();
  8530. }
  8531. }
  8532. /**
  8533. * Check if there are open slots for a particular server key. If desiredRequests is greater than 1, this checks if the queue has room for scheduling multiple requests.
  8534. * @param {String} serverKey The server key returned by {@link RequestScheduler.getServerKey}.
  8535. * @param {Number} [desiredRequests=1] How many requests the caller plans to request
  8536. * @return {Boolean} True if there are enough open slots for <code>desiredRequests</code> more requests.
  8537. * @private
  8538. */
  8539. RequestScheduler.serverHasOpenSlots = function (serverKey, desiredRequests) {
  8540. desiredRequests = defaultValue.defaultValue(desiredRequests, 1);
  8541. const maxRequests = defaultValue.defaultValue(
  8542. RequestScheduler.requestsByServer[serverKey],
  8543. RequestScheduler.maximumRequestsPerServer
  8544. );
  8545. const hasOpenSlotsServer =
  8546. numberOfActiveRequestsByServer[serverKey] + desiredRequests <= maxRequests;
  8547. return hasOpenSlotsServer;
  8548. };
  8549. /**
  8550. * Check if the priority heap has open slots, regardless of which server they
  8551. * are from. This is used in {@link Multiple3DTileContent} for determining when
  8552. * all requests can be scheduled
  8553. * @param {Number} desiredRequests The number of requests the caller intends to make
  8554. * @return {Boolean} <code>true</code> if the heap has enough available slots to meet the desiredRequests. <code>false</code> otherwise.
  8555. *
  8556. * @private
  8557. */
  8558. RequestScheduler.heapHasOpenSlots = function (desiredRequests) {
  8559. const hasOpenSlotsHeap =
  8560. requestHeap.length + desiredRequests <= priorityHeapLength;
  8561. return hasOpenSlotsHeap;
  8562. };
  8563. function issueRequest(request) {
  8564. if (request.state === RequestState$1.UNISSUED) {
  8565. request.state = RequestState$1.ISSUED;
  8566. request.deferred = defer();
  8567. }
  8568. return request.deferred.promise;
  8569. }
  8570. function getRequestReceivedFunction(request) {
  8571. return function (results) {
  8572. if (request.state === RequestState$1.CANCELLED) {
  8573. // If the data request comes back but the request is cancelled, ignore it.
  8574. return;
  8575. }
  8576. // explicitly set to undefined to ensure GC of request response data. See #8843
  8577. const deferred = request.deferred;
  8578. --statistics.numberOfActiveRequests;
  8579. --numberOfActiveRequestsByServer[request.serverKey];
  8580. requestCompletedEvent.raiseEvent();
  8581. request.state = RequestState$1.RECEIVED;
  8582. request.deferred = undefined;
  8583. deferred.resolve(results);
  8584. };
  8585. }
  8586. function getRequestFailedFunction(request) {
  8587. return function (error) {
  8588. if (request.state === RequestState$1.CANCELLED) {
  8589. // If the data request comes back but the request is cancelled, ignore it.
  8590. return;
  8591. }
  8592. ++statistics.numberOfFailedRequests;
  8593. --statistics.numberOfActiveRequests;
  8594. --numberOfActiveRequestsByServer[request.serverKey];
  8595. requestCompletedEvent.raiseEvent(error);
  8596. request.state = RequestState$1.FAILED;
  8597. request.deferred.reject(error);
  8598. };
  8599. }
  8600. function startRequest(request) {
  8601. const promise = issueRequest(request);
  8602. request.state = RequestState$1.ACTIVE;
  8603. activeRequests.push(request);
  8604. ++statistics.numberOfActiveRequests;
  8605. ++statistics.numberOfActiveRequestsEver;
  8606. ++numberOfActiveRequestsByServer[request.serverKey];
  8607. request
  8608. .requestFunction()
  8609. .then(getRequestReceivedFunction(request))
  8610. .catch(getRequestFailedFunction(request));
  8611. return promise;
  8612. }
  8613. function cancelRequest(request) {
  8614. const active = request.state === RequestState$1.ACTIVE;
  8615. request.state = RequestState$1.CANCELLED;
  8616. ++statistics.numberOfCancelledRequests;
  8617. // check that deferred has not been cleared since cancelRequest can be called
  8618. // on a finished request, e.g. by clearForSpecs during tests
  8619. if (defaultValue.defined(request.deferred)) {
  8620. const deferred = request.deferred;
  8621. request.deferred = undefined;
  8622. deferred.reject();
  8623. }
  8624. if (active) {
  8625. --statistics.numberOfActiveRequests;
  8626. --numberOfActiveRequestsByServer[request.serverKey];
  8627. ++statistics.numberOfCancelledActiveRequests;
  8628. }
  8629. if (defaultValue.defined(request.cancelFunction)) {
  8630. request.cancelFunction();
  8631. }
  8632. }
  8633. /**
  8634. * Sort requests by priority and start requests.
  8635. * @private
  8636. */
  8637. RequestScheduler.update = function () {
  8638. let i;
  8639. let request;
  8640. // Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
  8641. let removeCount = 0;
  8642. const activeLength = activeRequests.length;
  8643. for (i = 0; i < activeLength; ++i) {
  8644. request = activeRequests[i];
  8645. if (request.cancelled) {
  8646. // Request was explicitly cancelled
  8647. cancelRequest(request);
  8648. }
  8649. if (request.state !== RequestState$1.ACTIVE) {
  8650. // Request is no longer active, remove from array
  8651. ++removeCount;
  8652. continue;
  8653. }
  8654. if (removeCount > 0) {
  8655. // Shift back to fill in vacated slots from completed requests
  8656. activeRequests[i - removeCount] = request;
  8657. }
  8658. }
  8659. activeRequests.length -= removeCount;
  8660. // Update priority of issued requests and resort the heap
  8661. const issuedRequests = requestHeap.internalArray;
  8662. const issuedLength = requestHeap.length;
  8663. for (i = 0; i < issuedLength; ++i) {
  8664. updatePriority(issuedRequests[i]);
  8665. }
  8666. requestHeap.resort();
  8667. // Get the number of open slots and fill with the highest priority requests.
  8668. // Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
  8669. const openSlots = Math.max(
  8670. RequestScheduler.maximumRequests - activeRequests.length,
  8671. 0
  8672. );
  8673. let filledSlots = 0;
  8674. while (filledSlots < openSlots && requestHeap.length > 0) {
  8675. // Loop until all open slots are filled or the heap becomes empty
  8676. request = requestHeap.pop();
  8677. if (request.cancelled) {
  8678. // Request was explicitly cancelled
  8679. cancelRequest(request);
  8680. continue;
  8681. }
  8682. if (
  8683. request.throttleByServer &&
  8684. !RequestScheduler.serverHasOpenSlots(request.serverKey)
  8685. ) {
  8686. // Open slots are available, but the request is throttled by its server. Cancel and try again later.
  8687. cancelRequest(request);
  8688. continue;
  8689. }
  8690. startRequest(request);
  8691. ++filledSlots;
  8692. }
  8693. updateStatistics();
  8694. };
  8695. /**
  8696. * Get the server key from a given url.
  8697. *
  8698. * @param {String} url The url.
  8699. * @returns {String} The server key.
  8700. * @private
  8701. */
  8702. RequestScheduler.getServerKey = function (url) {
  8703. //>>includeStart('debug', pragmas.debug);
  8704. RuntimeError.Check.typeOf.string("url", url);
  8705. //>>includeEnd('debug');
  8706. let uri = new URI(url);
  8707. if (uri.scheme() === "") {
  8708. uri = new URI(url).absoluteTo(pageUri);
  8709. uri.normalize();
  8710. }
  8711. let serverKey = uri.authority();
  8712. if (!/:/.test(serverKey)) {
  8713. // If the authority does not contain a port number, add port 443 for https or port 80 for http
  8714. serverKey = `${serverKey}:${uri.scheme() === "https" ? "443" : "80"}`;
  8715. }
  8716. const length = numberOfActiveRequestsByServer[serverKey];
  8717. if (!defaultValue.defined(length)) {
  8718. numberOfActiveRequestsByServer[serverKey] = 0;
  8719. }
  8720. return serverKey;
  8721. };
  8722. /**
  8723. * Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
  8724. * queued and sorted by priority before being sent.
  8725. *
  8726. * @param {Request} request The request object.
  8727. *
  8728. * @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
  8729. *
  8730. * @private
  8731. */
  8732. RequestScheduler.request = function (request) {
  8733. //>>includeStart('debug', pragmas.debug);
  8734. RuntimeError.Check.typeOf.object("request", request);
  8735. RuntimeError.Check.typeOf.string("request.url", request.url);
  8736. RuntimeError.Check.typeOf.func("request.requestFunction", request.requestFunction);
  8737. //>>includeEnd('debug');
  8738. if (isDataUri(request.url) || isBlobUri(request.url)) {
  8739. requestCompletedEvent.raiseEvent();
  8740. request.state = RequestState$1.RECEIVED;
  8741. return request.requestFunction();
  8742. }
  8743. ++statistics.numberOfAttemptedRequests;
  8744. if (!defaultValue.defined(request.serverKey)) {
  8745. request.serverKey = RequestScheduler.getServerKey(request.url);
  8746. }
  8747. if (
  8748. RequestScheduler.throttleRequests &&
  8749. request.throttleByServer &&
  8750. !RequestScheduler.serverHasOpenSlots(request.serverKey)
  8751. ) {
  8752. // Server is saturated. Try again later.
  8753. return undefined;
  8754. }
  8755. if (!RequestScheduler.throttleRequests || !request.throttle) {
  8756. return startRequest(request);
  8757. }
  8758. if (activeRequests.length >= RequestScheduler.maximumRequests) {
  8759. // Active requests are saturated. Try again later.
  8760. return undefined;
  8761. }
  8762. // Insert into the priority heap and see if a request was bumped off. If this request is the lowest
  8763. // priority it will be returned.
  8764. updatePriority(request);
  8765. const removedRequest = requestHeap.insert(request);
  8766. if (defaultValue.defined(removedRequest)) {
  8767. if (removedRequest === request) {
  8768. // Request does not have high enough priority to be issued
  8769. return undefined;
  8770. }
  8771. // A previously issued request has been bumped off the priority heap, so cancel it
  8772. cancelRequest(removedRequest);
  8773. }
  8774. return issueRequest(request);
  8775. };
  8776. function updateStatistics() {
  8777. if (!RequestScheduler.debugShowStatistics) {
  8778. return;
  8779. }
  8780. if (
  8781. statistics.numberOfActiveRequests === 0 &&
  8782. statistics.lastNumberOfActiveRequests > 0
  8783. ) {
  8784. if (statistics.numberOfAttemptedRequests > 0) {
  8785. console.log(
  8786. `Number of attempted requests: ${statistics.numberOfAttemptedRequests}`
  8787. );
  8788. statistics.numberOfAttemptedRequests = 0;
  8789. }
  8790. if (statistics.numberOfCancelledRequests > 0) {
  8791. console.log(
  8792. `Number of cancelled requests: ${statistics.numberOfCancelledRequests}`
  8793. );
  8794. statistics.numberOfCancelledRequests = 0;
  8795. }
  8796. if (statistics.numberOfCancelledActiveRequests > 0) {
  8797. console.log(
  8798. `Number of cancelled active requests: ${statistics.numberOfCancelledActiveRequests}`
  8799. );
  8800. statistics.numberOfCancelledActiveRequests = 0;
  8801. }
  8802. if (statistics.numberOfFailedRequests > 0) {
  8803. console.log(
  8804. `Number of failed requests: ${statistics.numberOfFailedRequests}`
  8805. );
  8806. statistics.numberOfFailedRequests = 0;
  8807. }
  8808. }
  8809. statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
  8810. }
  8811. /**
  8812. * For testing only. Clears any requests that may not have completed from previous tests.
  8813. *
  8814. * @private
  8815. */
  8816. RequestScheduler.clearForSpecs = function () {
  8817. while (requestHeap.length > 0) {
  8818. const request = requestHeap.pop();
  8819. cancelRequest(request);
  8820. }
  8821. const length = activeRequests.length;
  8822. for (let i = 0; i < length; ++i) {
  8823. cancelRequest(activeRequests[i]);
  8824. }
  8825. activeRequests.length = 0;
  8826. numberOfActiveRequestsByServer = {};
  8827. // Clear stats
  8828. statistics.numberOfAttemptedRequests = 0;
  8829. statistics.numberOfActiveRequests = 0;
  8830. statistics.numberOfCancelledRequests = 0;
  8831. statistics.numberOfCancelledActiveRequests = 0;
  8832. statistics.numberOfFailedRequests = 0;
  8833. statistics.numberOfActiveRequestsEver = 0;
  8834. statistics.lastNumberOfActiveRequests = 0;
  8835. };
  8836. /**
  8837. * For testing only.
  8838. *
  8839. * @private
  8840. */
  8841. RequestScheduler.numberOfActiveRequestsByServer = function (serverKey) {
  8842. return numberOfActiveRequestsByServer[serverKey];
  8843. };
  8844. /**
  8845. * For testing only.
  8846. *
  8847. * @private
  8848. */
  8849. RequestScheduler.requestHeap = requestHeap;
  8850. /**
  8851. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  8852. * any requests to these servers.
  8853. *
  8854. * @namespace TrustedServers
  8855. *
  8856. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  8857. */
  8858. const TrustedServers = {};
  8859. let _servers = {};
  8860. /**
  8861. * Adds a trusted server to the registry
  8862. *
  8863. * @param {String} host The host to be added.
  8864. * @param {Number} port The port used to access the host.
  8865. *
  8866. * @example
  8867. * // Add a trusted server
  8868. * TrustedServers.add('my.server.com', 80);
  8869. */
  8870. TrustedServers.add = function (host, port) {
  8871. //>>includeStart('debug', pragmas.debug);
  8872. if (!defaultValue.defined(host)) {
  8873. throw new RuntimeError.DeveloperError("host is required.");
  8874. }
  8875. if (!defaultValue.defined(port) || port <= 0) {
  8876. throw new RuntimeError.DeveloperError("port is required to be greater than 0.");
  8877. }
  8878. //>>includeEnd('debug');
  8879. const authority = `${host.toLowerCase()}:${port}`;
  8880. if (!defaultValue.defined(_servers[authority])) {
  8881. _servers[authority] = true;
  8882. }
  8883. };
  8884. /**
  8885. * Removes a trusted server from the registry
  8886. *
  8887. * @param {String} host The host to be removed.
  8888. * @param {Number} port The port used to access the host.
  8889. *
  8890. * @example
  8891. * // Remove a trusted server
  8892. * TrustedServers.remove('my.server.com', 80);
  8893. */
  8894. TrustedServers.remove = function (host, port) {
  8895. //>>includeStart('debug', pragmas.debug);
  8896. if (!defaultValue.defined(host)) {
  8897. throw new RuntimeError.DeveloperError("host is required.");
  8898. }
  8899. if (!defaultValue.defined(port) || port <= 0) {
  8900. throw new RuntimeError.DeveloperError("port is required to be greater than 0.");
  8901. }
  8902. //>>includeEnd('debug');
  8903. const authority = `${host.toLowerCase()}:${port}`;
  8904. if (defaultValue.defined(_servers[authority])) {
  8905. delete _servers[authority];
  8906. }
  8907. };
  8908. function getAuthority(url) {
  8909. const uri = new URI(url);
  8910. uri.normalize();
  8911. // Removes username:password@ so we just have host[:port]
  8912. let authority = uri.authority();
  8913. if (authority.length === 0) {
  8914. return undefined; // Relative URL
  8915. }
  8916. uri.authority(authority);
  8917. if (authority.indexOf("@") !== -1) {
  8918. const parts = authority.split("@");
  8919. authority = parts[1];
  8920. }
  8921. // If the port is missing add one based on the scheme
  8922. if (authority.indexOf(":") === -1) {
  8923. let scheme = uri.scheme();
  8924. if (scheme.length === 0) {
  8925. scheme = window.location.protocol;
  8926. scheme = scheme.substring(0, scheme.length - 1);
  8927. }
  8928. if (scheme === "http") {
  8929. authority += ":80";
  8930. } else if (scheme === "https") {
  8931. authority += ":443";
  8932. } else {
  8933. return undefined;
  8934. }
  8935. }
  8936. return authority;
  8937. }
  8938. /**
  8939. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  8940. *
  8941. * @param {String} url The url to be tested against the trusted list
  8942. *
  8943. * @returns {boolean} Returns true if url is trusted, false otherwise.
  8944. *
  8945. * @example
  8946. * // Add server
  8947. * TrustedServers.add('my.server.com', 81);
  8948. *
  8949. * // Check if server is trusted
  8950. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  8951. * // my.server.com:81 is trusted
  8952. * }
  8953. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  8954. * // my.server.com isn't trusted
  8955. * }
  8956. */
  8957. TrustedServers.contains = function (url) {
  8958. //>>includeStart('debug', pragmas.debug);
  8959. if (!defaultValue.defined(url)) {
  8960. throw new RuntimeError.DeveloperError("url is required.");
  8961. }
  8962. //>>includeEnd('debug');
  8963. const authority = getAuthority(url);
  8964. if (defaultValue.defined(authority) && defaultValue.defined(_servers[authority])) {
  8965. return true;
  8966. }
  8967. return false;
  8968. };
  8969. /**
  8970. * Clears the registry
  8971. *
  8972. * @example
  8973. * // Remove a trusted server
  8974. * TrustedServers.clear();
  8975. */
  8976. TrustedServers.clear = function () {
  8977. _servers = {};
  8978. };
  8979. const xhrBlobSupported = (function () {
  8980. try {
  8981. const xhr = new XMLHttpRequest();
  8982. xhr.open("GET", "#", true);
  8983. xhr.responseType = "blob";
  8984. return xhr.responseType === "blob";
  8985. } catch (e) {
  8986. return false;
  8987. }
  8988. })();
  8989. /**
  8990. * Parses a query string and returns the object equivalent.
  8991. *
  8992. * @param {Uri} uri The Uri with a query object.
  8993. * @param {Resource} resource The Resource that will be assigned queryParameters.
  8994. * @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
  8995. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
  8996. *
  8997. * @private
  8998. */
  8999. function parseQuery(uri, resource, merge, preserveQueryParameters) {
  9000. const queryString = uri.query();
  9001. if (queryString.length === 0) {
  9002. return {};
  9003. }
  9004. let query;
  9005. // Special case we run into where the querystring is just a string, not key/value pairs
  9006. if (queryString.indexOf("=") === -1) {
  9007. const result = {};
  9008. result[queryString] = undefined;
  9009. query = result;
  9010. } else {
  9011. query = queryToObject(queryString);
  9012. }
  9013. if (merge) {
  9014. resource._queryParameters = combineQueryParameters(
  9015. query,
  9016. resource._queryParameters,
  9017. preserveQueryParameters
  9018. );
  9019. } else {
  9020. resource._queryParameters = query;
  9021. }
  9022. uri.search("");
  9023. }
  9024. /**
  9025. * Converts a query object into a string.
  9026. *
  9027. * @param {Uri} uri The Uri object that will have the query object set.
  9028. * @param {Resource} resource The resource that has queryParameters
  9029. *
  9030. * @private
  9031. */
  9032. function stringifyQuery(uri, resource) {
  9033. const queryObject = resource._queryParameters;
  9034. const keys = Object.keys(queryObject);
  9035. // We have 1 key with an undefined value, so this is just a string, not key/value pairs
  9036. if (keys.length === 1 && !defaultValue.defined(queryObject[keys[0]])) {
  9037. uri.search(keys[0]);
  9038. } else {
  9039. uri.search(objectToQuery(queryObject));
  9040. }
  9041. }
  9042. /**
  9043. * Clones a value if it is defined, otherwise returns the default value
  9044. *
  9045. * @param {*} [val] The value to clone.
  9046. * @param {*} [defaultVal] The default value.
  9047. *
  9048. * @returns {*} A clone of val or the defaultVal.
  9049. *
  9050. * @private
  9051. */
  9052. function defaultClone(val, defaultVal) {
  9053. if (!defaultValue.defined(val)) {
  9054. return defaultVal;
  9055. }
  9056. return defaultValue.defined(val.clone) ? val.clone() : clone(val);
  9057. }
  9058. /**
  9059. * Checks to make sure the Resource isn't already being requested.
  9060. *
  9061. * @param {Request} request The request to check.
  9062. *
  9063. * @private
  9064. */
  9065. function checkAndResetRequest(request) {
  9066. if (
  9067. request.state === RequestState$1.ISSUED ||
  9068. request.state === RequestState$1.ACTIVE
  9069. ) {
  9070. throw new RuntimeError.RuntimeError("The Resource is already being fetched.");
  9071. }
  9072. request.state = RequestState$1.UNISSUED;
  9073. request.deferred = undefined;
  9074. }
  9075. /**
  9076. * This combines a map of query parameters.
  9077. *
  9078. * @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
  9079. * @param {Object} q2 The second map of query parameters.
  9080. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
  9081. *
  9082. * @returns {Object} The combined map of query parameters.
  9083. *
  9084. * @example
  9085. * const q1 = {
  9086. * a: 1,
  9087. * b: 2
  9088. * };
  9089. * const q2 = {
  9090. * a: 3,
  9091. * c: 4
  9092. * };
  9093. * const q3 = {
  9094. * b: [5, 6],
  9095. * d: 7
  9096. * }
  9097. *
  9098. * // Returns
  9099. * // {
  9100. * // a: [1, 3],
  9101. * // b: 2,
  9102. * // c: 4
  9103. * // };
  9104. * combineQueryParameters(q1, q2, true);
  9105. *
  9106. * // Returns
  9107. * // {
  9108. * // a: 1,
  9109. * // b: 2,
  9110. * // c: 4
  9111. * // };
  9112. * combineQueryParameters(q1, q2, false);
  9113. *
  9114. * // Returns
  9115. * // {
  9116. * // a: 1,
  9117. * // b: [2, 5, 6],
  9118. * // d: 7
  9119. * // };
  9120. * combineQueryParameters(q1, q3, true);
  9121. *
  9122. * // Returns
  9123. * // {
  9124. * // a: 1,
  9125. * // b: 2,
  9126. * // d: 7
  9127. * // };
  9128. * combineQueryParameters(q1, q3, false);
  9129. *
  9130. * @private
  9131. */
  9132. function combineQueryParameters(q1, q2, preserveQueryParameters) {
  9133. if (!preserveQueryParameters) {
  9134. return combine.combine(q1, q2);
  9135. }
  9136. const result = clone(q1, true);
  9137. for (const param in q2) {
  9138. if (q2.hasOwnProperty(param)) {
  9139. let value = result[param];
  9140. const q2Value = q2[param];
  9141. if (defaultValue.defined(value)) {
  9142. if (!Array.isArray(value)) {
  9143. value = result[param] = [value];
  9144. }
  9145. result[param] = value.concat(q2Value);
  9146. } else {
  9147. result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
  9148. }
  9149. }
  9150. }
  9151. return result;
  9152. }
  9153. /**
  9154. * @typedef {Object} Resource.ConstructorOptions
  9155. *
  9156. * Initialization options for the Resource constructor
  9157. *
  9158. * @property {String} url The url of the resource.
  9159. * @property {Object} [queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9160. * @property {Object} [templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9161. * @property {Object} [headers={}] Additional HTTP headers that will be sent.
  9162. * @property {Proxy} [proxy] A proxy to be used when loading the resource.
  9163. * @property {Resource.RetryCallback} [retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  9164. * @property {Number} [retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9165. * @property {Request} [request] A Request object that will be used. Intended for internal use only.
  9166. */
  9167. /**
  9168. * A resource that includes the location and any other parameters we need to retrieve it or create derived resources. It also provides the ability to retry requests.
  9169. *
  9170. * @alias Resource
  9171. * @constructor
  9172. *
  9173. * @param {String|Resource.ConstructorOptions} options A url or an object describing initialization options
  9174. *
  9175. * @example
  9176. * function refreshTokenRetryCallback(resource, error) {
  9177. * if (error.statusCode === 403) {
  9178. * // 403 status code means a new token should be generated
  9179. * return getNewAccessToken()
  9180. * .then(function(token) {
  9181. * resource.queryParameters.access_token = token;
  9182. * return true;
  9183. * })
  9184. * .catch(function() {
  9185. * return false;
  9186. * });
  9187. * }
  9188. *
  9189. * return false;
  9190. * }
  9191. *
  9192. * const resource = new Resource({
  9193. * url: 'http://server.com/path/to/resource.json',
  9194. * proxy: new DefaultProxy('/proxy/'),
  9195. * headers: {
  9196. * 'X-My-Header': 'valueOfHeader'
  9197. * },
  9198. * queryParameters: {
  9199. * 'access_token': '123-435-456-000'
  9200. * },
  9201. * retryCallback: refreshTokenRetryCallback,
  9202. * retryAttempts: 1
  9203. * });
  9204. */
  9205. function Resource(options) {
  9206. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  9207. if (typeof options === "string") {
  9208. options = {
  9209. url: options,
  9210. };
  9211. }
  9212. //>>includeStart('debug', pragmas.debug);
  9213. RuntimeError.Check.typeOf.string("options.url", options.url);
  9214. //>>includeEnd('debug');
  9215. this._url = undefined;
  9216. this._templateValues = defaultClone(options.templateValues, {});
  9217. this._queryParameters = defaultClone(options.queryParameters, {});
  9218. /**
  9219. * Additional HTTP headers that will be sent with the request.
  9220. *
  9221. * @type {Object}
  9222. */
  9223. this.headers = defaultClone(options.headers, {});
  9224. /**
  9225. * A Request object that will be used. Intended for internal use only.
  9226. *
  9227. * @type {Request}
  9228. */
  9229. this.request = defaultValue.defaultValue(options.request, new Request());
  9230. /**
  9231. * A proxy to be used when loading the resource.
  9232. *
  9233. * @type {Proxy}
  9234. */
  9235. this.proxy = options.proxy;
  9236. /**
  9237. * Function to call when a request for this resource fails. If it returns true or a Promise that resolves to true, the request will be retried.
  9238. *
  9239. * @type {Function}
  9240. */
  9241. this.retryCallback = options.retryCallback;
  9242. /**
  9243. * The number of times the retryCallback should be called before giving up.
  9244. *
  9245. * @type {Number}
  9246. */
  9247. this.retryAttempts = defaultValue.defaultValue(options.retryAttempts, 0);
  9248. this._retryCount = 0;
  9249. const uri = new URI(options.url);
  9250. parseQuery(uri, this, true, true);
  9251. // Remove the fragment as it's not sent with a request
  9252. uri.fragment("");
  9253. this._url = uri.toString();
  9254. }
  9255. /**
  9256. * A helper function to create a resource depending on whether we have a String or a Resource
  9257. *
  9258. * @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
  9259. *
  9260. * @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
  9261. *
  9262. * @private
  9263. */
  9264. Resource.createIfNeeded = function (resource) {
  9265. if (resource instanceof Resource) {
  9266. // Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
  9267. // be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
  9268. // are managed outside of the providers, by the tile loading code, we want to keep the request property the same so if it is changed
  9269. // in the underlying tiling code the requests for this resource will use it.
  9270. return resource.getDerivedResource({
  9271. request: resource.request,
  9272. });
  9273. }
  9274. if (typeof resource !== "string") {
  9275. return resource;
  9276. }
  9277. return new Resource({
  9278. url: resource,
  9279. });
  9280. };
  9281. let supportsImageBitmapOptionsPromise;
  9282. /**
  9283. * A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
  9284. *
  9285. * @returns {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
  9286. *
  9287. * @private
  9288. */
  9289. Resource.supportsImageBitmapOptions = function () {
  9290. // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
  9291. // know if this browser supports passing options to the createImageBitmap function.
  9292. // https://github.com/whatwg/html/pull/4248
  9293. //
  9294. // We also need to check whether the colorSpaceConversion option is supported.
  9295. // We do this by loading a PNG with an embedded color profile, first with
  9296. // colorSpaceConversion: "none" and then with colorSpaceConversion: "default".
  9297. // If the pixel color is different then we know the option is working.
  9298. // As of Webkit 17612.3.6.1.6 the createImageBitmap promise resolves but the
  9299. // option is not actually supported.
  9300. if (defaultValue.defined(supportsImageBitmapOptionsPromise)) {
  9301. return supportsImageBitmapOptionsPromise;
  9302. }
  9303. if (typeof createImageBitmap !== "function") {
  9304. supportsImageBitmapOptionsPromise = Promise.resolve(false);
  9305. return supportsImageBitmapOptionsPromise;
  9306. }
  9307. const imageDataUri =
  9308. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGdBTUEAAE4g3rEiDgAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAADElEQVQI12Ng6GAAAAEUAIngE3ZiAAAAAElFTkSuQmCC";
  9309. supportsImageBitmapOptionsPromise = Resource.fetchBlob({
  9310. url: imageDataUri,
  9311. })
  9312. .then(function (blob) {
  9313. const imageBitmapOptions = {
  9314. imageOrientation: "flipY", // default is "none"
  9315. premultiplyAlpha: "none", // default is "default"
  9316. colorSpaceConversion: "none", // default is "default"
  9317. };
  9318. return Promise.all([
  9319. createImageBitmap(blob, imageBitmapOptions),
  9320. createImageBitmap(blob),
  9321. ]);
  9322. })
  9323. .then(function (imageBitmaps) {
  9324. // Check whether the colorSpaceConversion option had any effect on the green channel
  9325. const colorWithOptions = getImagePixels(imageBitmaps[0]);
  9326. const colorWithDefaults = getImagePixels(imageBitmaps[1]);
  9327. return colorWithOptions[1] !== colorWithDefaults[1];
  9328. })
  9329. .catch(function () {
  9330. return false;
  9331. });
  9332. return supportsImageBitmapOptionsPromise;
  9333. };
  9334. Object.defineProperties(Resource, {
  9335. /**
  9336. * Returns true if blobs are supported.
  9337. *
  9338. * @memberof Resource
  9339. * @type {Boolean}
  9340. *
  9341. * @readonly
  9342. */
  9343. isBlobSupported: {
  9344. get: function () {
  9345. return xhrBlobSupported;
  9346. },
  9347. },
  9348. });
  9349. Object.defineProperties(Resource.prototype, {
  9350. /**
  9351. * Query parameters appended to the url.
  9352. *
  9353. * @memberof Resource.prototype
  9354. * @type {Object}
  9355. *
  9356. * @readonly
  9357. */
  9358. queryParameters: {
  9359. get: function () {
  9360. return this._queryParameters;
  9361. },
  9362. },
  9363. /**
  9364. * The key/value pairs used to replace template parameters in the url.
  9365. *
  9366. * @memberof Resource.prototype
  9367. * @type {Object}
  9368. *
  9369. * @readonly
  9370. */
  9371. templateValues: {
  9372. get: function () {
  9373. return this._templateValues;
  9374. },
  9375. },
  9376. /**
  9377. * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
  9378. *
  9379. * @memberof Resource.prototype
  9380. * @type {String}
  9381. */
  9382. url: {
  9383. get: function () {
  9384. return this.getUrlComponent(true, true);
  9385. },
  9386. set: function (value) {
  9387. const uri = new URI(value);
  9388. parseQuery(uri, this, false);
  9389. // Remove the fragment as it's not sent with a request
  9390. uri.fragment("");
  9391. this._url = uri.toString();
  9392. },
  9393. },
  9394. /**
  9395. * The file extension of the resource.
  9396. *
  9397. * @memberof Resource.prototype
  9398. * @type {String}
  9399. *
  9400. * @readonly
  9401. */
  9402. extension: {
  9403. get: function () {
  9404. return getExtensionFromUri(this._url);
  9405. },
  9406. },
  9407. /**
  9408. * True if the Resource refers to a data URI.
  9409. *
  9410. * @memberof Resource.prototype
  9411. * @type {Boolean}
  9412. */
  9413. isDataUri: {
  9414. get: function () {
  9415. return isDataUri(this._url);
  9416. },
  9417. },
  9418. /**
  9419. * True if the Resource refers to a blob URI.
  9420. *
  9421. * @memberof Resource.prototype
  9422. * @type {Boolean}
  9423. */
  9424. isBlobUri: {
  9425. get: function () {
  9426. return isBlobUri(this._url);
  9427. },
  9428. },
  9429. /**
  9430. * True if the Resource refers to a cross origin URL.
  9431. *
  9432. * @memberof Resource.prototype
  9433. * @type {Boolean}
  9434. */
  9435. isCrossOriginUrl: {
  9436. get: function () {
  9437. return isCrossOriginUrl(this._url);
  9438. },
  9439. },
  9440. /**
  9441. * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
  9442. *
  9443. * @memberof Resource.prototype
  9444. * @type {Boolean}
  9445. */
  9446. hasHeaders: {
  9447. get: function () {
  9448. return Object.keys(this.headers).length > 0;
  9449. },
  9450. },
  9451. });
  9452. /**
  9453. * Override Object#toString so that implicit string conversion gives the
  9454. * complete URL represented by this Resource.
  9455. *
  9456. * @returns {String} The URL represented by this Resource
  9457. */
  9458. Resource.prototype.toString = function () {
  9459. return this.getUrlComponent(true, true);
  9460. };
  9461. /**
  9462. * Returns the url, optional with the query string and processed by a proxy.
  9463. *
  9464. * @param {Boolean} [query=false] If true, the query string is included.
  9465. * @param {Boolean} [proxy=false] If true, the url is processed by the proxy object, if defined.
  9466. *
  9467. * @returns {String} The url with all the requested components.
  9468. */
  9469. Resource.prototype.getUrlComponent = function (query, proxy) {
  9470. if (this.isDataUri) {
  9471. return this._url;
  9472. }
  9473. const uri = new URI(this._url);
  9474. if (query) {
  9475. stringifyQuery(uri, this);
  9476. }
  9477. // objectToQuery escapes the placeholders. Undo that.
  9478. let url = uri.toString().replace(/%7B/g, "{").replace(/%7D/g, "}");
  9479. const templateValues = this._templateValues;
  9480. url = url.replace(/{(.*?)}/g, function (match, key) {
  9481. const replacement = templateValues[key];
  9482. if (defaultValue.defined(replacement)) {
  9483. // use the replacement value from templateValues if there is one...
  9484. return encodeURIComponent(replacement);
  9485. }
  9486. // otherwise leave it unchanged
  9487. return match;
  9488. });
  9489. if (proxy && defaultValue.defined(this.proxy)) {
  9490. url = this.proxy.getURL(url);
  9491. }
  9492. return url;
  9493. };
  9494. /**
  9495. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  9496. * as opposed to adding them one at a time to the queryParameters property. If a value is already set, it will be replaced with the new value.
  9497. *
  9498. * @param {Object} params The query parameters
  9499. * @param {Boolean} [useAsDefault=false] If true the params will be used as the default values, so they will only be set if they are undefined.
  9500. */
  9501. Resource.prototype.setQueryParameters = function (params, useAsDefault) {
  9502. if (useAsDefault) {
  9503. this._queryParameters = combineQueryParameters(
  9504. this._queryParameters,
  9505. params,
  9506. false
  9507. );
  9508. } else {
  9509. this._queryParameters = combineQueryParameters(
  9510. params,
  9511. this._queryParameters,
  9512. false
  9513. );
  9514. }
  9515. };
  9516. /**
  9517. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  9518. * as opposed to adding them one at a time to the queryParameters property.
  9519. *
  9520. * @param {Object} params The query parameters
  9521. */
  9522. Resource.prototype.appendQueryParameters = function (params) {
  9523. this._queryParameters = combineQueryParameters(
  9524. params,
  9525. this._queryParameters,
  9526. true
  9527. );
  9528. };
  9529. /**
  9530. * Combines the specified object and the existing template values. This allows you to add many values at once,
  9531. * as opposed to adding them one at a time to the templateValues property. If a value is already set, it will become an array and the new value will be appended.
  9532. *
  9533. * @param {Object} template The template values
  9534. * @param {Boolean} [useAsDefault=false] If true the values will be used as the default values, so they will only be set if they are undefined.
  9535. */
  9536. Resource.prototype.setTemplateValues = function (template, useAsDefault) {
  9537. if (useAsDefault) {
  9538. this._templateValues = combine.combine(this._templateValues, template);
  9539. } else {
  9540. this._templateValues = combine.combine(template, this._templateValues);
  9541. }
  9542. };
  9543. /**
  9544. * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
  9545. *
  9546. * @param {Object} options An object with the following properties
  9547. * @param {String} [options.url] The url that will be resolved relative to the url of the current instance.
  9548. * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
  9549. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}). These will be combined with those of the current instance.
  9550. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9551. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9552. * @param {Resource.RetryCallback} [options.retryCallback] The function to call when loading the resource fails.
  9553. * @param {Number} [options.retryAttempts] The number of times the retryCallback should be called before giving up.
  9554. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9555. * @param {Boolean} [options.preserveQueryParameters=false] If true, this will keep all query parameters from the current resource and derived resource. If false, derived parameters will replace those of the current resource.
  9556. *
  9557. * @returns {Resource} The resource derived from the current one.
  9558. */
  9559. Resource.prototype.getDerivedResource = function (options) {
  9560. const resource = this.clone();
  9561. resource._retryCount = 0;
  9562. if (defaultValue.defined(options.url)) {
  9563. const uri = new URI(options.url);
  9564. const preserveQueryParameters = defaultValue.defaultValue(
  9565. options.preserveQueryParameters,
  9566. false
  9567. );
  9568. parseQuery(uri, resource, true, preserveQueryParameters);
  9569. // Remove the fragment as it's not sent with a request
  9570. uri.fragment("");
  9571. if (uri.scheme() !== "") {
  9572. resource._url = uri.toString();
  9573. } else {
  9574. resource._url = uri
  9575. .absoluteTo(new URI(getAbsoluteUri(this._url)))
  9576. .toString();
  9577. }
  9578. }
  9579. if (defaultValue.defined(options.queryParameters)) {
  9580. resource._queryParameters = combine.combine(
  9581. options.queryParameters,
  9582. resource._queryParameters
  9583. );
  9584. }
  9585. if (defaultValue.defined(options.templateValues)) {
  9586. resource._templateValues = combine.combine(
  9587. options.templateValues,
  9588. resource.templateValues
  9589. );
  9590. }
  9591. if (defaultValue.defined(options.headers)) {
  9592. resource.headers = combine.combine(options.headers, resource.headers);
  9593. }
  9594. if (defaultValue.defined(options.proxy)) {
  9595. resource.proxy = options.proxy;
  9596. }
  9597. if (defaultValue.defined(options.request)) {
  9598. resource.request = options.request;
  9599. }
  9600. if (defaultValue.defined(options.retryCallback)) {
  9601. resource.retryCallback = options.retryCallback;
  9602. }
  9603. if (defaultValue.defined(options.retryAttempts)) {
  9604. resource.retryAttempts = options.retryAttempts;
  9605. }
  9606. return resource;
  9607. };
  9608. /**
  9609. * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
  9610. *
  9611. * @param {Error} [error] The error that was encountered.
  9612. *
  9613. * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
  9614. *
  9615. * @private
  9616. */
  9617. Resource.prototype.retryOnError = function (error) {
  9618. const retryCallback = this.retryCallback;
  9619. if (
  9620. typeof retryCallback !== "function" ||
  9621. this._retryCount >= this.retryAttempts
  9622. ) {
  9623. return Promise.resolve(false);
  9624. }
  9625. const that = this;
  9626. return Promise.resolve(retryCallback(this, error)).then(function (result) {
  9627. ++that._retryCount;
  9628. return result;
  9629. });
  9630. };
  9631. /**
  9632. * Duplicates a Resource instance.
  9633. *
  9634. * @param {Resource} [result] The object onto which to store the result.
  9635. *
  9636. * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
  9637. */
  9638. Resource.prototype.clone = function (result) {
  9639. if (!defaultValue.defined(result)) {
  9640. result = new Resource({
  9641. url: this._url,
  9642. });
  9643. }
  9644. result._url = this._url;
  9645. result._queryParameters = clone(this._queryParameters);
  9646. result._templateValues = clone(this._templateValues);
  9647. result.headers = clone(this.headers);
  9648. result.proxy = this.proxy;
  9649. result.retryCallback = this.retryCallback;
  9650. result.retryAttempts = this.retryAttempts;
  9651. result._retryCount = 0;
  9652. result.request = this.request.clone();
  9653. return result;
  9654. };
  9655. /**
  9656. * Returns the base path of the Resource.
  9657. *
  9658. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  9659. *
  9660. * @returns {String} The base URI of the resource
  9661. */
  9662. Resource.prototype.getBaseUri = function (includeQuery) {
  9663. return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  9664. };
  9665. /**
  9666. * Appends a forward slash to the URL.
  9667. */
  9668. Resource.prototype.appendForwardSlash = function () {
  9669. this._url = appendForwardSlash(this._url);
  9670. };
  9671. /**
  9672. * Asynchronously loads the resource as raw binary data. Returns a promise that will resolve to
  9673. * an ArrayBuffer once loaded, or reject if the resource failed to load. The data is loaded
  9674. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9675. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  9676. *
  9677. * @returns {Promise.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9678. *
  9679. * @example
  9680. * // load a single URL asynchronously
  9681. * resource.fetchArrayBuffer().then(function(arrayBuffer) {
  9682. * // use the data
  9683. * }).catch(function(error) {
  9684. * // an error occurred
  9685. * });
  9686. *
  9687. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9688. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9689. */
  9690. Resource.prototype.fetchArrayBuffer = function () {
  9691. return this.fetch({
  9692. responseType: "arraybuffer",
  9693. });
  9694. };
  9695. /**
  9696. * Creates a Resource and calls fetchArrayBuffer() on it.
  9697. *
  9698. * @param {String|Object} options A url or an object with the following properties
  9699. * @param {String} options.url The url of the resource.
  9700. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9701. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9702. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9703. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9704. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  9705. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9706. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9707. * @returns {Promise.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9708. */
  9709. Resource.fetchArrayBuffer = function (options) {
  9710. const resource = new Resource(options);
  9711. return resource.fetchArrayBuffer();
  9712. };
  9713. /**
  9714. * Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
  9715. * a Blob once loaded, or reject if the resource failed to load. The data is loaded
  9716. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9717. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  9718. *
  9719. * @returns {Promise.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9720. *
  9721. * @example
  9722. * // load a single URL asynchronously
  9723. * resource.fetchBlob().then(function(blob) {
  9724. * // use the data
  9725. * }).catch(function(error) {
  9726. * // an error occurred
  9727. * });
  9728. *
  9729. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9730. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9731. */
  9732. Resource.prototype.fetchBlob = function () {
  9733. return this.fetch({
  9734. responseType: "blob",
  9735. });
  9736. };
  9737. /**
  9738. * Creates a Resource and calls fetchBlob() on it.
  9739. *
  9740. * @param {String|Object} options A url or an object with the following properties
  9741. * @param {String} options.url The url of the resource.
  9742. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9743. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9744. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9745. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9746. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  9747. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9748. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9749. * @returns {Promise.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9750. */
  9751. Resource.fetchBlob = function (options) {
  9752. const resource = new Resource(options);
  9753. return resource.fetchBlob();
  9754. };
  9755. /**
  9756. * Asynchronously loads the given image resource. Returns a promise that will resolve to
  9757. * an {@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap|ImageBitmap} if <code>preferImageBitmap</code> is true and the browser supports <code>createImageBitmap</code> or otherwise an
  9758. * {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
  9759. *
  9760. * @param {Object} [options] An object with the following properties.
  9761. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  9762. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  9763. * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  9764. * @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the image will be ignored. Only applies if the browser supports <code>createImageBitmap</code>.
  9765. * @returns {Promise.<ImageBitmap|HTMLImageElement>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9766. *
  9767. *
  9768. * @example
  9769. * // load a single image asynchronously
  9770. * resource.fetchImage().then(function(image) {
  9771. * // use the loaded image
  9772. * }).catch(function(error) {
  9773. * // an error occurred
  9774. * });
  9775. *
  9776. * // load several images in parallel
  9777. * Promise.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
  9778. * // images is an array containing all the loaded images
  9779. * });
  9780. *
  9781. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9782. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9783. */
  9784. Resource.prototype.fetchImage = function (options) {
  9785. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  9786. const preferImageBitmap = defaultValue.defaultValue(options.preferImageBitmap, false);
  9787. const preferBlob = defaultValue.defaultValue(options.preferBlob, false);
  9788. const flipY = defaultValue.defaultValue(options.flipY, false);
  9789. const skipColorSpaceConversion = defaultValue.defaultValue(
  9790. options.skipColorSpaceConversion,
  9791. false
  9792. );
  9793. checkAndResetRequest(this.request);
  9794. // We try to load the image normally if
  9795. // 1. Blobs aren't supported
  9796. // 2. It's a data URI
  9797. // 3. It's a blob URI
  9798. // 4. It doesn't have request headers and we preferBlob is false
  9799. if (
  9800. !xhrBlobSupported ||
  9801. this.isDataUri ||
  9802. this.isBlobUri ||
  9803. (!this.hasHeaders && !preferBlob)
  9804. ) {
  9805. return fetchImage({
  9806. resource: this,
  9807. flipY: flipY,
  9808. skipColorSpaceConversion: skipColorSpaceConversion,
  9809. preferImageBitmap: preferImageBitmap,
  9810. });
  9811. }
  9812. const blobPromise = this.fetchBlob();
  9813. if (!defaultValue.defined(blobPromise)) {
  9814. return;
  9815. }
  9816. let supportsImageBitmap;
  9817. let useImageBitmap;
  9818. let generatedBlobResource;
  9819. let generatedBlob;
  9820. return Resource.supportsImageBitmapOptions()
  9821. .then(function (result) {
  9822. supportsImageBitmap = result;
  9823. useImageBitmap = supportsImageBitmap && preferImageBitmap;
  9824. return blobPromise;
  9825. })
  9826. .then(function (blob) {
  9827. if (!defaultValue.defined(blob)) {
  9828. return;
  9829. }
  9830. generatedBlob = blob;
  9831. if (useImageBitmap) {
  9832. return Resource.createImageBitmapFromBlob(blob, {
  9833. flipY: flipY,
  9834. premultiplyAlpha: false,
  9835. skipColorSpaceConversion: skipColorSpaceConversion,
  9836. });
  9837. }
  9838. const blobUrl = window.URL.createObjectURL(blob);
  9839. generatedBlobResource = new Resource({
  9840. url: blobUrl,
  9841. });
  9842. return fetchImage({
  9843. resource: generatedBlobResource,
  9844. flipY: flipY,
  9845. skipColorSpaceConversion: skipColorSpaceConversion,
  9846. preferImageBitmap: false,
  9847. });
  9848. })
  9849. .then(function (image) {
  9850. if (!defaultValue.defined(image)) {
  9851. return;
  9852. }
  9853. // The blob object may be needed for use by a TileDiscardPolicy,
  9854. // so attach it to the image.
  9855. image.blob = generatedBlob;
  9856. if (useImageBitmap) {
  9857. return image;
  9858. }
  9859. window.URL.revokeObjectURL(generatedBlobResource.url);
  9860. return image;
  9861. })
  9862. .catch(function (error) {
  9863. if (defaultValue.defined(generatedBlobResource)) {
  9864. window.URL.revokeObjectURL(generatedBlobResource.url);
  9865. }
  9866. // If the blob load succeeded but the image decode failed, attach the blob
  9867. // to the error object for use by a TileDiscardPolicy.
  9868. // In particular, BingMapsImageryProvider uses this to detect the
  9869. // zero-length response that is returned when a tile is not available.
  9870. error.blob = generatedBlob;
  9871. return Promise.reject(error);
  9872. });
  9873. };
  9874. /**
  9875. * Fetches an image and returns a promise to it.
  9876. *
  9877. * @param {Object} [options] An object with the following properties.
  9878. * @param {Resource} [options.resource] Resource object that points to an image to fetch.
  9879. * @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  9880. * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  9881. * @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the image will be ignored. Only applies if the browser supports <code>createImageBitmap</code>.
  9882. * @private
  9883. */
  9884. function fetchImage(options) {
  9885. const resource = options.resource;
  9886. const flipY = options.flipY;
  9887. const skipColorSpaceConversion = options.skipColorSpaceConversion;
  9888. const preferImageBitmap = options.preferImageBitmap;
  9889. const request = resource.request;
  9890. request.url = resource.url;
  9891. request.requestFunction = function () {
  9892. let crossOrigin = false;
  9893. // data URIs can't have crossorigin set.
  9894. if (!resource.isDataUri && !resource.isBlobUri) {
  9895. crossOrigin = resource.isCrossOriginUrl;
  9896. }
  9897. const deferred = defer();
  9898. Resource._Implementations.createImage(
  9899. request,
  9900. crossOrigin,
  9901. deferred,
  9902. flipY,
  9903. skipColorSpaceConversion,
  9904. preferImageBitmap
  9905. );
  9906. return deferred.promise;
  9907. };
  9908. const promise = RequestScheduler.request(request);
  9909. if (!defaultValue.defined(promise)) {
  9910. return;
  9911. }
  9912. return promise.catch(function (e) {
  9913. // Don't retry cancelled or otherwise aborted requests
  9914. if (request.state !== RequestState$1.FAILED) {
  9915. return Promise.reject(e);
  9916. }
  9917. return resource.retryOnError(e).then(function (retry) {
  9918. if (retry) {
  9919. // Reset request so it can try again
  9920. request.state = RequestState$1.UNISSUED;
  9921. request.deferred = undefined;
  9922. return fetchImage({
  9923. resource: resource,
  9924. flipY: flipY,
  9925. skipColorSpaceConversion: skipColorSpaceConversion,
  9926. preferImageBitmap: preferImageBitmap,
  9927. });
  9928. }
  9929. return Promise.reject(e);
  9930. });
  9931. });
  9932. }
  9933. /**
  9934. * Creates a Resource and calls fetchImage() on it.
  9935. *
  9936. * @param {String|Object} options A url or an object with the following properties
  9937. * @param {String} options.url The url of the resource.
  9938. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9939. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9940. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9941. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9942. * @param {Boolean} [options.flipY=false] Whether to vertically flip the image during fetch and decode. Only applies when requesting an image and the browser supports <code>createImageBitmap</code>.
  9943. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  9944. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9945. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9946. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  9947. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  9948. * @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the image will be ignored. Only applies when requesting an image and the browser supports <code>createImageBitmap</code>.
  9949. * @returns {Promise.<ImageBitmap|HTMLImageElement>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9950. */
  9951. Resource.fetchImage = function (options) {
  9952. const resource = new Resource(options);
  9953. return resource.fetchImage({
  9954. flipY: options.flipY,
  9955. skipColorSpaceConversion: options.skipColorSpaceConversion,
  9956. preferBlob: options.preferBlob,
  9957. preferImageBitmap: options.preferImageBitmap,
  9958. });
  9959. };
  9960. /**
  9961. * Asynchronously loads the given resource as text. Returns a promise that will resolve to
  9962. * a String once loaded, or reject if the resource failed to load. The data is loaded
  9963. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9964. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  9965. *
  9966. * @returns {Promise.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  9967. *
  9968. * @example
  9969. * // load text from a URL, setting a custom header
  9970. * const resource = new Resource({
  9971. * url: 'http://someUrl.com/someJson.txt',
  9972. * headers: {
  9973. * 'X-Custom-Header' : 'some value'
  9974. * }
  9975. * });
  9976. * resource.fetchText().then(function(text) {
  9977. * // Do something with the text
  9978. * }).catch(function(error) {
  9979. * // an error occurred
  9980. * });
  9981. *
  9982. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  9983. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9984. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9985. */
  9986. Resource.prototype.fetchText = function () {
  9987. return this.fetch({
  9988. responseType: "text",
  9989. });
  9990. };
  9991. /**
  9992. * Creates a Resource and calls fetchText() on it.
  9993. *
  9994. * @param {String|Object} options A url or an object with the following properties
  9995. * @param {String} options.url The url of the resource.
  9996. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9997. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9998. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9999. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10000. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10001. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10002. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10003. * @returns {Promise.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10004. */
  10005. Resource.fetchText = function (options) {
  10006. const resource = new Resource(options);
  10007. return resource.fetchText();
  10008. };
  10009. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  10010. /**
  10011. * Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
  10012. * a JSON object once loaded, or reject if the resource failed to load. The data is loaded
  10013. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10014. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  10015. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  10016. * already specified.
  10017. *
  10018. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10019. *
  10020. *
  10021. * @example
  10022. * resource.fetchJson().then(function(jsonData) {
  10023. * // Do something with the JSON object
  10024. * }).catch(function(error) {
  10025. * // an error occurred
  10026. * });
  10027. *
  10028. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10029. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10030. */
  10031. Resource.prototype.fetchJson = function () {
  10032. const promise = this.fetch({
  10033. responseType: "text",
  10034. headers: {
  10035. Accept: "application/json,*/*;q=0.01",
  10036. },
  10037. });
  10038. if (!defaultValue.defined(promise)) {
  10039. return undefined;
  10040. }
  10041. return promise.then(function (value) {
  10042. if (!defaultValue.defined(value)) {
  10043. return;
  10044. }
  10045. return JSON.parse(value);
  10046. });
  10047. };
  10048. /**
  10049. * Creates a Resource and calls fetchJson() on it.
  10050. *
  10051. * @param {String|Object} options A url or an object with the following properties
  10052. * @param {String} options.url The url of the resource.
  10053. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10054. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10055. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10056. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10057. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10058. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10059. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10060. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10061. */
  10062. Resource.fetchJson = function (options) {
  10063. const resource = new Resource(options);
  10064. return resource.fetchJson();
  10065. };
  10066. /**
  10067. * Asynchronously loads the given resource as XML. Returns a promise that will resolve to
  10068. * an XML Document once loaded, or reject if the resource failed to load. The data is loaded
  10069. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10070. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10071. *
  10072. * @returns {Promise.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10073. *
  10074. *
  10075. * @example
  10076. * // load XML from a URL, setting a custom header
  10077. * Cesium.loadXML('http://someUrl.com/someXML.xml', {
  10078. * 'X-Custom-Header' : 'some value'
  10079. * }).then(function(document) {
  10080. * // Do something with the document
  10081. * }).catch(function(error) {
  10082. * // an error occurred
  10083. * });
  10084. *
  10085. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  10086. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10087. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10088. */
  10089. Resource.prototype.fetchXML = function () {
  10090. return this.fetch({
  10091. responseType: "document",
  10092. overrideMimeType: "text/xml",
  10093. });
  10094. };
  10095. /**
  10096. * Creates a Resource and calls fetchXML() on it.
  10097. *
  10098. * @param {String|Object} options A url or an object with the following properties
  10099. * @param {String} options.url The url of the resource.
  10100. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10101. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10102. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10103. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10104. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10105. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10106. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10107. * @returns {Promise.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10108. */
  10109. Resource.fetchXML = function (options) {
  10110. const resource = new Resource(options);
  10111. return resource.fetchXML();
  10112. };
  10113. /**
  10114. * Requests a resource using JSONP.
  10115. *
  10116. * @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
  10117. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10118. *
  10119. *
  10120. * @example
  10121. * // load a data asynchronously
  10122. * resource.fetchJsonp().then(function(data) {
  10123. * // use the loaded data
  10124. * }).catch(function(error) {
  10125. * // an error occurred
  10126. * });
  10127. *
  10128. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10129. */
  10130. Resource.prototype.fetchJsonp = function (callbackParameterName) {
  10131. callbackParameterName = defaultValue.defaultValue(callbackParameterName, "callback");
  10132. checkAndResetRequest(this.request);
  10133. //generate a unique function name
  10134. let functionName;
  10135. do {
  10136. functionName = `loadJsonp${ComponentDatatype.CesiumMath.nextRandomNumber()
  10137. .toString()
  10138. .substring(2, 8)}`;
  10139. } while (defaultValue.defined(window[functionName]));
  10140. return fetchJsonp(this, callbackParameterName, functionName);
  10141. };
  10142. function fetchJsonp(resource, callbackParameterName, functionName) {
  10143. const callbackQuery = {};
  10144. callbackQuery[callbackParameterName] = functionName;
  10145. resource.setQueryParameters(callbackQuery);
  10146. const request = resource.request;
  10147. request.url = resource.url;
  10148. request.requestFunction = function () {
  10149. const deferred = defer();
  10150. //assign a function with that name in the global scope
  10151. window[functionName] = function (data) {
  10152. deferred.resolve(data);
  10153. try {
  10154. delete window[functionName];
  10155. } catch (e) {
  10156. window[functionName] = undefined;
  10157. }
  10158. };
  10159. Resource._Implementations.loadAndExecuteScript(
  10160. resource.url,
  10161. functionName,
  10162. deferred
  10163. );
  10164. return deferred.promise;
  10165. };
  10166. const promise = RequestScheduler.request(request);
  10167. if (!defaultValue.defined(promise)) {
  10168. return;
  10169. }
  10170. return promise.catch(function (e) {
  10171. if (request.state !== RequestState$1.FAILED) {
  10172. return Promise.reject(e);
  10173. }
  10174. return resource.retryOnError(e).then(function (retry) {
  10175. if (retry) {
  10176. // Reset request so it can try again
  10177. request.state = RequestState$1.UNISSUED;
  10178. request.deferred = undefined;
  10179. return fetchJsonp(resource, callbackParameterName, functionName);
  10180. }
  10181. return Promise.reject(e);
  10182. });
  10183. });
  10184. }
  10185. /**
  10186. * Creates a Resource from a URL and calls fetchJsonp() on it.
  10187. *
  10188. * @param {String|Object} options A url or an object with the following properties
  10189. * @param {String} options.url The url of the resource.
  10190. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10191. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10192. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10193. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10194. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10195. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10196. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10197. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
  10198. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10199. */
  10200. Resource.fetchJsonp = function (options) {
  10201. const resource = new Resource(options);
  10202. return resource.fetchJsonp(options.callbackParameterName);
  10203. };
  10204. /**
  10205. * @private
  10206. */
  10207. Resource.prototype._makeRequest = function (options) {
  10208. const resource = this;
  10209. checkAndResetRequest(resource.request);
  10210. const request = resource.request;
  10211. request.url = resource.url;
  10212. request.requestFunction = function () {
  10213. const responseType = options.responseType;
  10214. const headers = combine.combine(options.headers, resource.headers);
  10215. const overrideMimeType = options.overrideMimeType;
  10216. const method = options.method;
  10217. const data = options.data;
  10218. const deferred = defer();
  10219. const xhr = Resource._Implementations.loadWithXhr(
  10220. resource.url,
  10221. responseType,
  10222. method,
  10223. data,
  10224. headers,
  10225. deferred,
  10226. overrideMimeType
  10227. );
  10228. if (defaultValue.defined(xhr) && defaultValue.defined(xhr.abort)) {
  10229. request.cancelFunction = function () {
  10230. xhr.abort();
  10231. };
  10232. }
  10233. return deferred.promise;
  10234. };
  10235. const promise = RequestScheduler.request(request);
  10236. if (!defaultValue.defined(promise)) {
  10237. return;
  10238. }
  10239. return promise
  10240. .then(function (data) {
  10241. // explicitly set to undefined to ensure GC of request response data. See #8843
  10242. request.cancelFunction = undefined;
  10243. return data;
  10244. })
  10245. .catch(function (e) {
  10246. request.cancelFunction = undefined;
  10247. if (request.state !== RequestState$1.FAILED) {
  10248. return Promise.reject(e);
  10249. }
  10250. return resource.retryOnError(e).then(function (retry) {
  10251. if (retry) {
  10252. // Reset request so it can try again
  10253. request.state = RequestState$1.UNISSUED;
  10254. request.deferred = undefined;
  10255. return resource.fetch(options);
  10256. }
  10257. return Promise.reject(e);
  10258. });
  10259. });
  10260. };
  10261. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  10262. function decodeDataUriText(isBase64, data) {
  10263. const result = decodeURIComponent(data);
  10264. if (isBase64) {
  10265. return atob(result);
  10266. }
  10267. return result;
  10268. }
  10269. function decodeDataUriArrayBuffer(isBase64, data) {
  10270. const byteString = decodeDataUriText(isBase64, data);
  10271. const buffer = new ArrayBuffer(byteString.length);
  10272. const view = new Uint8Array(buffer);
  10273. for (let i = 0; i < byteString.length; i++) {
  10274. view[i] = byteString.charCodeAt(i);
  10275. }
  10276. return buffer;
  10277. }
  10278. function decodeDataUri(dataUriRegexResult, responseType) {
  10279. responseType = defaultValue.defaultValue(responseType, "");
  10280. const mimeType = dataUriRegexResult[1];
  10281. const isBase64 = !!dataUriRegexResult[2];
  10282. const data = dataUriRegexResult[3];
  10283. let buffer;
  10284. let parser;
  10285. switch (responseType) {
  10286. case "":
  10287. case "text":
  10288. return decodeDataUriText(isBase64, data);
  10289. case "arraybuffer":
  10290. return decodeDataUriArrayBuffer(isBase64, data);
  10291. case "blob":
  10292. buffer = decodeDataUriArrayBuffer(isBase64, data);
  10293. return new Blob([buffer], {
  10294. type: mimeType,
  10295. });
  10296. case "document":
  10297. parser = new DOMParser();
  10298. return parser.parseFromString(
  10299. decodeDataUriText(isBase64, data),
  10300. mimeType
  10301. );
  10302. case "json":
  10303. return JSON.parse(decodeDataUriText(isBase64, data));
  10304. default:
  10305. //>>includeStart('debug', pragmas.debug);
  10306. throw new RuntimeError.DeveloperError(`Unhandled responseType: ${responseType}`);
  10307. //>>includeEnd('debug');
  10308. }
  10309. }
  10310. /**
  10311. * Asynchronously loads the given resource. Returns a promise that will resolve to
  10312. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10313. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10314. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
  10315. * the more specific functions eg. fetchJson, fetchBlob, etc.
  10316. *
  10317. * @param {Object} [options] Object with the following properties:
  10318. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10319. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10320. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10321. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10322. *
  10323. *
  10324. * @example
  10325. * resource.fetch()
  10326. * .then(function(body) {
  10327. * // use the data
  10328. * }).catch(function(error) {
  10329. * // an error occurred
  10330. * });
  10331. *
  10332. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10333. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10334. */
  10335. Resource.prototype.fetch = function (options) {
  10336. options = defaultClone(options, {});
  10337. options.method = "GET";
  10338. return this._makeRequest(options);
  10339. };
  10340. /**
  10341. * Creates a Resource from a URL and calls fetch() on it.
  10342. *
  10343. * @param {String|Object} options A url or an object with the following properties
  10344. * @param {String} options.url The url of the resource.
  10345. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10346. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10347. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10348. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10349. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10350. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10351. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10352. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10353. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10354. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10355. */
  10356. Resource.fetch = function (options) {
  10357. const resource = new Resource(options);
  10358. return resource.fetch({
  10359. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10360. responseType: options.responseType,
  10361. overrideMimeType: options.overrideMimeType,
  10362. });
  10363. };
  10364. /**
  10365. * Asynchronously deletes the given resource. Returns a promise that will resolve to
  10366. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10367. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10368. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10369. *
  10370. * @param {Object} [options] Object with the following properties:
  10371. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10372. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10373. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10374. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10375. *
  10376. *
  10377. * @example
  10378. * resource.delete()
  10379. * .then(function(body) {
  10380. * // use the data
  10381. * }).catch(function(error) {
  10382. * // an error occurred
  10383. * });
  10384. *
  10385. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10386. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10387. */
  10388. Resource.prototype.delete = function (options) {
  10389. options = defaultClone(options, {});
  10390. options.method = "DELETE";
  10391. return this._makeRequest(options);
  10392. };
  10393. /**
  10394. * Creates a Resource from a URL and calls delete() on it.
  10395. *
  10396. * @param {String|Object} options A url or an object with the following properties
  10397. * @param {String} options.url The url of the resource.
  10398. * @param {Object} [options.data] Data that is posted with the resource.
  10399. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10400. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10401. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10402. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10403. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10404. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10405. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10406. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10407. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10408. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10409. */
  10410. Resource.delete = function (options) {
  10411. const resource = new Resource(options);
  10412. return resource.delete({
  10413. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10414. responseType: options.responseType,
  10415. overrideMimeType: options.overrideMimeType,
  10416. data: options.data,
  10417. });
  10418. };
  10419. /**
  10420. * Asynchronously gets headers the given resource. Returns a promise that will resolve to
  10421. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10422. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10423. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10424. *
  10425. * @param {Object} [options] Object with the following properties:
  10426. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10427. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10428. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10429. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10430. *
  10431. *
  10432. * @example
  10433. * resource.head()
  10434. * .then(function(headers) {
  10435. * // use the data
  10436. * }).catch(function(error) {
  10437. * // an error occurred
  10438. * });
  10439. *
  10440. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10441. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10442. */
  10443. Resource.prototype.head = function (options) {
  10444. options = defaultClone(options, {});
  10445. options.method = "HEAD";
  10446. return this._makeRequest(options);
  10447. };
  10448. /**
  10449. * Creates a Resource from a URL and calls head() on it.
  10450. *
  10451. * @param {String|Object} options A url or an object with the following properties
  10452. * @param {String} options.url The url of the resource.
  10453. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10454. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10455. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10456. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10457. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10458. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10459. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10460. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10461. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10462. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10463. */
  10464. Resource.head = function (options) {
  10465. const resource = new Resource(options);
  10466. return resource.head({
  10467. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10468. responseType: options.responseType,
  10469. overrideMimeType: options.overrideMimeType,
  10470. });
  10471. };
  10472. /**
  10473. * Asynchronously gets options the given resource. Returns a promise that will resolve to
  10474. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10475. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10476. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10477. *
  10478. * @param {Object} [options] Object with the following properties:
  10479. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10480. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10481. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10482. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10483. *
  10484. *
  10485. * @example
  10486. * resource.options()
  10487. * .then(function(headers) {
  10488. * // use the data
  10489. * }).catch(function(error) {
  10490. * // an error occurred
  10491. * });
  10492. *
  10493. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10494. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10495. */
  10496. Resource.prototype.options = function (options) {
  10497. options = defaultClone(options, {});
  10498. options.method = "OPTIONS";
  10499. return this._makeRequest(options);
  10500. };
  10501. /**
  10502. * Creates a Resource from a URL and calls options() on it.
  10503. *
  10504. * @param {String|Object} options A url or an object with the following properties
  10505. * @param {String} options.url The url of the resource.
  10506. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10507. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10508. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10509. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10510. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10511. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10512. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10513. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10514. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10515. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10516. */
  10517. Resource.options = function (options) {
  10518. const resource = new Resource(options);
  10519. return resource.options({
  10520. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10521. responseType: options.responseType,
  10522. overrideMimeType: options.overrideMimeType,
  10523. });
  10524. };
  10525. /**
  10526. * Asynchronously posts data to the given resource. Returns a promise that will resolve to
  10527. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10528. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10529. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10530. *
  10531. * @param {Object} data Data that is posted with the resource.
  10532. * @param {Object} [options] Object with the following properties:
  10533. * @param {Object} [options.data] Data that is posted with the resource.
  10534. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10535. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10536. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10537. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10538. *
  10539. *
  10540. * @example
  10541. * resource.post(data)
  10542. * .then(function(result) {
  10543. * // use the result
  10544. * }).catch(function(error) {
  10545. * // an error occurred
  10546. * });
  10547. *
  10548. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10549. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10550. */
  10551. Resource.prototype.post = function (data, options) {
  10552. RuntimeError.Check.defined("data", data);
  10553. options = defaultClone(options, {});
  10554. options.method = "POST";
  10555. options.data = data;
  10556. return this._makeRequest(options);
  10557. };
  10558. /**
  10559. * Creates a Resource from a URL and calls post() on it.
  10560. *
  10561. * @param {Object} options A url or an object with the following properties
  10562. * @param {String} options.url The url of the resource.
  10563. * @param {Object} options.data Data that is posted with the resource.
  10564. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10565. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10566. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10567. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10568. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10569. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10570. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10571. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10572. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10573. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10574. */
  10575. Resource.post = function (options) {
  10576. const resource = new Resource(options);
  10577. return resource.post(options.data, {
  10578. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  10579. responseType: options.responseType,
  10580. overrideMimeType: options.overrideMimeType,
  10581. });
  10582. };
  10583. /**
  10584. * Asynchronously puts data to the given resource. Returns a promise that will resolve to
  10585. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10586. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10587. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10588. *
  10589. * @param {Object} data Data that is posted with the resource.
  10590. * @param {Object} [options] Object with the following properties:
  10591. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10592. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10593. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10594. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10595. *
  10596. *
  10597. * @example
  10598. * resource.put(data)
  10599. * .then(function(result) {
  10600. * // use the result
  10601. * }).catch(function(error) {
  10602. * // an error occurred
  10603. * });
  10604. *
  10605. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10606. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10607. */
  10608. Resource.prototype.put = function (data, options) {
  10609. RuntimeError.Check.defined("data", data);
  10610. options = defaultClone(options, {});
  10611. options.method = "PUT";
  10612. options.data = data;
  10613. return this._makeRequest(options);
  10614. };
  10615. /**
  10616. * Creates a Resource from a URL and calls put() on it.
  10617. *
  10618. * @param {Object} options A url or an object with the following properties
  10619. * @param {String} options.url The url of the resource.
  10620. * @param {Object} options.data Data that is posted with the resource.
  10621. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10622. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10623. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10624. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10625. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10626. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10627. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10628. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10629. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10630. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10631. */
  10632. Resource.put = function (options) {
  10633. const resource = new Resource(options);
  10634. return resource.put(options.data, {
  10635. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  10636. responseType: options.responseType,
  10637. overrideMimeType: options.overrideMimeType,
  10638. });
  10639. };
  10640. /**
  10641. * Asynchronously patches data to the given resource. Returns a promise that will resolve to
  10642. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10643. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10644. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10645. *
  10646. * @param {Object} data Data that is posted with the resource.
  10647. * @param {Object} [options] Object with the following properties:
  10648. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10649. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10650. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10651. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10652. *
  10653. *
  10654. * @example
  10655. * resource.patch(data)
  10656. * .then(function(result) {
  10657. * // use the result
  10658. * }).catch(function(error) {
  10659. * // an error occurred
  10660. * });
  10661. *
  10662. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10663. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10664. */
  10665. Resource.prototype.patch = function (data, options) {
  10666. RuntimeError.Check.defined("data", data);
  10667. options = defaultClone(options, {});
  10668. options.method = "PATCH";
  10669. options.data = data;
  10670. return this._makeRequest(options);
  10671. };
  10672. /**
  10673. * Creates a Resource from a URL and calls patch() on it.
  10674. *
  10675. * @param {Object} options A url or an object with the following properties
  10676. * @param {String} options.url The url of the resource.
  10677. * @param {Object} options.data Data that is posted with the resource.
  10678. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10679. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10680. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10681. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10682. * @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  10683. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10684. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10685. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10686. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10687. * @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  10688. */
  10689. Resource.patch = function (options) {
  10690. const resource = new Resource(options);
  10691. return resource.patch(options.data, {
  10692. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  10693. responseType: options.responseType,
  10694. overrideMimeType: options.overrideMimeType,
  10695. });
  10696. };
  10697. /**
  10698. * Contains implementations of functions that can be replaced for testing
  10699. *
  10700. * @private
  10701. */
  10702. Resource._Implementations = {};
  10703. Resource._Implementations.loadImageElement = function (
  10704. url,
  10705. crossOrigin,
  10706. deferred
  10707. ) {
  10708. const image = new Image();
  10709. image.onload = function () {
  10710. // work-around a known issue with Firefox and dimensionless SVG, see:
  10711. // - https://github.com/whatwg/html/issues/3510
  10712. // - https://bugzilla.mozilla.org/show_bug.cgi?id=700533
  10713. if (
  10714. image.naturalWidth === 0 &&
  10715. image.naturalHeight === 0 &&
  10716. image.width === 0 &&
  10717. image.height === 0
  10718. ) {
  10719. // these values affect rasterization and will likely mar the content
  10720. // until Firefox takes a stance on the issue, marred content is better than no content
  10721. // Chromium uses a more refined heuristic about its choice given nil viewBox, and a better stance and solution is
  10722. // proposed later in the original issue thread:
  10723. // - Chromium behavior: https://github.com/CesiumGS/cesium/issues/9188#issuecomment-704400825
  10724. // - Cesium's stance/solve: https://github.com/CesiumGS/cesium/issues/9188#issuecomment-720645777
  10725. image.width = 300;
  10726. image.height = 150;
  10727. }
  10728. deferred.resolve(image);
  10729. };
  10730. image.onerror = function (e) {
  10731. deferred.reject(e);
  10732. };
  10733. if (crossOrigin) {
  10734. if (TrustedServers.contains(url)) {
  10735. image.crossOrigin = "use-credentials";
  10736. } else {
  10737. image.crossOrigin = "";
  10738. }
  10739. }
  10740. image.src = url;
  10741. };
  10742. Resource._Implementations.createImage = function (
  10743. request,
  10744. crossOrigin,
  10745. deferred,
  10746. flipY,
  10747. skipColorSpaceConversion,
  10748. preferImageBitmap
  10749. ) {
  10750. const url = request.url;
  10751. // Passing an Image to createImageBitmap will force it to run on the main thread
  10752. // since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
  10753. // See:
  10754. // https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
  10755. // https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
  10756. Resource.supportsImageBitmapOptions()
  10757. .then(function (supportsImageBitmap) {
  10758. // We can only use ImageBitmap if we can flip on decode.
  10759. // See: https://github.com/CesiumGS/cesium/pull/7579#issuecomment-466146898
  10760. if (!(supportsImageBitmap && preferImageBitmap)) {
  10761. Resource._Implementations.loadImageElement(url, crossOrigin, deferred);
  10762. return;
  10763. }
  10764. const responseType = "blob";
  10765. const method = "GET";
  10766. const xhrDeferred = defer();
  10767. const xhr = Resource._Implementations.loadWithXhr(
  10768. url,
  10769. responseType,
  10770. method,
  10771. undefined,
  10772. undefined,
  10773. xhrDeferred,
  10774. undefined,
  10775. undefined,
  10776. undefined
  10777. );
  10778. if (defaultValue.defined(xhr) && defaultValue.defined(xhr.abort)) {
  10779. request.cancelFunction = function () {
  10780. xhr.abort();
  10781. };
  10782. }
  10783. return xhrDeferred.promise
  10784. .then(function (blob) {
  10785. if (!defaultValue.defined(blob)) {
  10786. deferred.reject(
  10787. new RuntimeError.RuntimeError(
  10788. `Successfully retrieved ${url} but it contained no content.`
  10789. )
  10790. );
  10791. return;
  10792. }
  10793. return Resource.createImageBitmapFromBlob(blob, {
  10794. flipY: flipY,
  10795. premultiplyAlpha: false,
  10796. skipColorSpaceConversion: skipColorSpaceConversion,
  10797. });
  10798. })
  10799. .then(function (image) {
  10800. deferred.resolve(image);
  10801. });
  10802. })
  10803. .catch(function (e) {
  10804. deferred.reject(e);
  10805. });
  10806. };
  10807. /**
  10808. * Wrapper for createImageBitmap
  10809. *
  10810. * @private
  10811. */
  10812. Resource.createImageBitmapFromBlob = function (blob, options) {
  10813. RuntimeError.Check.defined("options", options);
  10814. RuntimeError.Check.typeOf.bool("options.flipY", options.flipY);
  10815. RuntimeError.Check.typeOf.bool("options.premultiplyAlpha", options.premultiplyAlpha);
  10816. RuntimeError.Check.typeOf.bool(
  10817. "options.skipColorSpaceConversion",
  10818. options.skipColorSpaceConversion
  10819. );
  10820. return createImageBitmap(blob, {
  10821. imageOrientation: options.flipY ? "flipY" : "none",
  10822. premultiplyAlpha: options.premultiplyAlpha ? "premultiply" : "none",
  10823. colorSpaceConversion: options.skipColorSpaceConversion ? "none" : "default",
  10824. });
  10825. };
  10826. function decodeResponse(loadWithHttpResponse, responseType) {
  10827. switch (responseType) {
  10828. case "text":
  10829. return loadWithHttpResponse.toString("utf8");
  10830. case "json":
  10831. return JSON.parse(loadWithHttpResponse.toString("utf8"));
  10832. default:
  10833. return new Uint8Array(loadWithHttpResponse).buffer;
  10834. }
  10835. }
  10836. function loadWithHttpRequest(
  10837. url,
  10838. responseType,
  10839. method,
  10840. data,
  10841. headers,
  10842. deferred,
  10843. overrideMimeType
  10844. ) {
  10845. // Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
  10846. /* eslint-disable no-undef */
  10847. const URL = require("url").parse(url);
  10848. const http = URL.protocol === "https:" ? require("https") : require("http");
  10849. const zlib = require("zlib");
  10850. /* eslint-enable no-undef */
  10851. const options = {
  10852. protocol: URL.protocol,
  10853. hostname: URL.hostname,
  10854. port: URL.port,
  10855. path: URL.path,
  10856. query: URL.query,
  10857. method: method,
  10858. headers: headers,
  10859. };
  10860. http
  10861. .request(options)
  10862. .on("response", function (res) {
  10863. if (res.statusCode < 200 || res.statusCode >= 300) {
  10864. deferred.reject(
  10865. new RequestErrorEvent(res.statusCode, res, res.headers)
  10866. );
  10867. return;
  10868. }
  10869. const chunkArray = [];
  10870. res.on("data", function (chunk) {
  10871. chunkArray.push(chunk);
  10872. });
  10873. res.on("end", function () {
  10874. // eslint-disable-next-line no-undef
  10875. const result = Buffer.concat(chunkArray);
  10876. if (res.headers["content-encoding"] === "gzip") {
  10877. zlib.gunzip(result, function (error, resultUnzipped) {
  10878. if (error) {
  10879. deferred.reject(
  10880. new RuntimeError.RuntimeError("Error decompressing response.")
  10881. );
  10882. } else {
  10883. deferred.resolve(decodeResponse(resultUnzipped, responseType));
  10884. }
  10885. });
  10886. } else {
  10887. deferred.resolve(decodeResponse(result, responseType));
  10888. }
  10889. });
  10890. })
  10891. .on("error", function (e) {
  10892. deferred.reject(new RequestErrorEvent());
  10893. })
  10894. .end();
  10895. }
  10896. const noXMLHttpRequest = typeof XMLHttpRequest === "undefined";
  10897. Resource._Implementations.loadWithXhr = function (
  10898. url,
  10899. responseType,
  10900. method,
  10901. data,
  10902. headers,
  10903. deferred,
  10904. overrideMimeType
  10905. ) {
  10906. const dataUriRegexResult = dataUriRegex.exec(url);
  10907. if (dataUriRegexResult !== null) {
  10908. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  10909. return;
  10910. }
  10911. if (noXMLHttpRequest) {
  10912. loadWithHttpRequest(
  10913. url,
  10914. responseType,
  10915. method,
  10916. data,
  10917. headers,
  10918. deferred);
  10919. return;
  10920. }
  10921. const xhr = new XMLHttpRequest();
  10922. if (TrustedServers.contains(url)) {
  10923. xhr.withCredentials = true;
  10924. }
  10925. xhr.open(method, url, true);
  10926. if (defaultValue.defined(overrideMimeType) && defaultValue.defined(xhr.overrideMimeType)) {
  10927. xhr.overrideMimeType(overrideMimeType);
  10928. }
  10929. if (defaultValue.defined(headers)) {
  10930. for (const key in headers) {
  10931. if (headers.hasOwnProperty(key)) {
  10932. xhr.setRequestHeader(key, headers[key]);
  10933. }
  10934. }
  10935. }
  10936. if (defaultValue.defined(responseType)) {
  10937. xhr.responseType = responseType;
  10938. }
  10939. // While non-standard, file protocol always returns a status of 0 on success
  10940. let localFile = false;
  10941. if (typeof url === "string") {
  10942. localFile =
  10943. url.indexOf("file://") === 0 ||
  10944. (typeof window !== "undefined" && window.location.origin === "file://");
  10945. }
  10946. xhr.onload = function () {
  10947. if (
  10948. (xhr.status < 200 || xhr.status >= 300) &&
  10949. !(localFile && xhr.status === 0)
  10950. ) {
  10951. deferred.reject(
  10952. new RequestErrorEvent(
  10953. xhr.status,
  10954. xhr.response,
  10955. xhr.getAllResponseHeaders()
  10956. )
  10957. );
  10958. return;
  10959. }
  10960. const response = xhr.response;
  10961. const browserResponseType = xhr.responseType;
  10962. if (method === "HEAD" || method === "OPTIONS") {
  10963. const responseHeaderString = xhr.getAllResponseHeaders();
  10964. const splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
  10965. const responseHeaders = {};
  10966. splitHeaders.forEach(function (line) {
  10967. const parts = line.split(": ");
  10968. const header = parts.shift();
  10969. responseHeaders[header] = parts.join(": ");
  10970. });
  10971. deferred.resolve(responseHeaders);
  10972. return;
  10973. }
  10974. //All modern browsers will go into either the first or second if block or last else block.
  10975. //Other code paths support older browsers that either do not support the supplied responseType
  10976. //or do not support the xhr.response property.
  10977. if (xhr.status === 204) {
  10978. // accept no content
  10979. deferred.resolve();
  10980. } else if (
  10981. defaultValue.defined(response) &&
  10982. (!defaultValue.defined(responseType) || browserResponseType === responseType)
  10983. ) {
  10984. deferred.resolve(response);
  10985. } else if (responseType === "json" && typeof response === "string") {
  10986. try {
  10987. deferred.resolve(JSON.parse(response));
  10988. } catch (e) {
  10989. deferred.reject(e);
  10990. }
  10991. } else if (
  10992. (browserResponseType === "" || browserResponseType === "document") &&
  10993. defaultValue.defined(xhr.responseXML) &&
  10994. xhr.responseXML.hasChildNodes()
  10995. ) {
  10996. deferred.resolve(xhr.responseXML);
  10997. } else if (
  10998. (browserResponseType === "" || browserResponseType === "text") &&
  10999. defaultValue.defined(xhr.responseText)
  11000. ) {
  11001. deferred.resolve(xhr.responseText);
  11002. } else {
  11003. deferred.reject(
  11004. new RuntimeError.RuntimeError("Invalid XMLHttpRequest response type.")
  11005. );
  11006. }
  11007. };
  11008. xhr.onerror = function (e) {
  11009. deferred.reject(new RequestErrorEvent());
  11010. };
  11011. xhr.send(data);
  11012. return xhr;
  11013. };
  11014. Resource._Implementations.loadAndExecuteScript = function (
  11015. url,
  11016. functionName,
  11017. deferred
  11018. ) {
  11019. return loadAndExecuteScript(url).catch(function (e) {
  11020. deferred.reject(e);
  11021. });
  11022. };
  11023. /**
  11024. * The default implementations
  11025. *
  11026. * @private
  11027. */
  11028. Resource._DefaultImplementations = {};
  11029. Resource._DefaultImplementations.createImage =
  11030. Resource._Implementations.createImage;
  11031. Resource._DefaultImplementations.loadWithXhr =
  11032. Resource._Implementations.loadWithXhr;
  11033. Resource._DefaultImplementations.loadAndExecuteScript =
  11034. Resource._Implementations.loadAndExecuteScript;
  11035. /**
  11036. * A resource instance initialized to the current browser location
  11037. *
  11038. * @type {Resource}
  11039. * @constant
  11040. */
  11041. Resource.DEFAULT = Object.freeze(
  11042. new Resource({
  11043. url:
  11044. typeof document === "undefined"
  11045. ? ""
  11046. : document.location.href.split("?")[0],
  11047. })
  11048. );
  11049. /**
  11050. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  11051. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  11052. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  11053. * Reference Frame (ITRF).
  11054. *
  11055. * @alias EarthOrientationParameters
  11056. * @constructor
  11057. *
  11058. * @param {Object} [options] Object with the following properties:
  11059. * @param {Resource|String} [options.url] The URL from which to obtain EOP data. If neither this
  11060. * parameter nor options.data is specified, all EOP values are assumed
  11061. * to be 0.0. If options.data is specified, this parameter is
  11062. * ignored.
  11063. * @param {Object} [options.data] The actual EOP data. If neither this
  11064. * parameter nor options.data is specified, all EOP values are assumed
  11065. * to be 0.0.
  11066. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  11067. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  11068. * should be added to {@link JulianDate.leapSeconds}. False if
  11069. * new leap seconds should be handled correctly in the context
  11070. * of the EOP data but otherwise ignored.
  11071. *
  11072. * @example
  11073. * // An example EOP data file, EOP.json:
  11074. * {
  11075. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  11076. * "samples" : [
  11077. * "2011-07-01T00:00:00Z",55743.0,2.117957047295119e-7,2.111518721609984e-6,-0.2908948,-2.956e-4,3.393695767766752e-11,3.3452143996557983e-10,34.0,
  11078. * "2011-07-02T00:00:00Z",55744.0,2.193297093339541e-7,2.115460256837405e-6,-0.29065,-1.824e-4,-8.241832578862112e-11,5.623838700870617e-10,34.0,
  11079. * "2011-07-03T00:00:00Z",55745.0,2.262286080161428e-7,2.1191157519929706e-6,-0.2905572,1.9e-6,-3.490658503988659e-10,6.981317007977318e-10,34.0
  11080. * ]
  11081. * }
  11082. *
  11083. * @example
  11084. * // Loading the EOP data
  11085. * const eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  11086. * Cesium.Transforms.earthOrientationParameters = eop;
  11087. *
  11088. * @private
  11089. */
  11090. function EarthOrientationParameters(options) {
  11091. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  11092. this._dates = undefined;
  11093. this._samples = undefined;
  11094. this._dateColumn = -1;
  11095. this._xPoleWanderRadiansColumn = -1;
  11096. this._yPoleWanderRadiansColumn = -1;
  11097. this._ut1MinusUtcSecondsColumn = -1;
  11098. this._xCelestialPoleOffsetRadiansColumn = -1;
  11099. this._yCelestialPoleOffsetRadiansColumn = -1;
  11100. this._taiMinusUtcSecondsColumn = -1;
  11101. this._columnCount = 0;
  11102. this._lastIndex = -1;
  11103. this._downloadPromise = undefined;
  11104. this._dataError = undefined;
  11105. this._addNewLeapSeconds = defaultValue.defaultValue(options.addNewLeapSeconds, true);
  11106. if (defaultValue.defined(options.data)) {
  11107. // Use supplied EOP data.
  11108. onDataReady(this, options.data);
  11109. } else if (defaultValue.defined(options.url)) {
  11110. const resource = Resource.createIfNeeded(options.url);
  11111. // Download EOP data.
  11112. const that = this;
  11113. this._downloadPromise = resource
  11114. .fetchJson()
  11115. .then(function (eopData) {
  11116. onDataReady(that, eopData);
  11117. })
  11118. .catch(function () {
  11119. that._dataError = `An error occurred while retrieving the EOP data from the URL ${resource.url}.`;
  11120. });
  11121. } else {
  11122. // Use all zeros for EOP data.
  11123. onDataReady(this, {
  11124. columnNames: [
  11125. "dateIso8601",
  11126. "modifiedJulianDateUtc",
  11127. "xPoleWanderRadians",
  11128. "yPoleWanderRadians",
  11129. "ut1MinusUtcSeconds",
  11130. "lengthOfDayCorrectionSeconds",
  11131. "xCelestialPoleOffsetRadians",
  11132. "yCelestialPoleOffsetRadians",
  11133. "taiMinusUtcSeconds",
  11134. ],
  11135. samples: [],
  11136. });
  11137. }
  11138. }
  11139. /**
  11140. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  11141. */
  11142. EarthOrientationParameters.NONE = Object.freeze({
  11143. getPromiseToLoad: function () {
  11144. return Promise.resolve();
  11145. },
  11146. compute: function (date, result) {
  11147. if (!defaultValue.defined(result)) {
  11148. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  11149. } else {
  11150. result.xPoleWander = 0.0;
  11151. result.yPoleWander = 0.0;
  11152. result.xPoleOffset = 0.0;
  11153. result.yPoleOffset = 0.0;
  11154. result.ut1MinusUtc = 0.0;
  11155. }
  11156. return result;
  11157. },
  11158. });
  11159. /**
  11160. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  11161. * ready to use.
  11162. *
  11163. * @returns {Promise<void>} The promise.
  11164. */
  11165. EarthOrientationParameters.prototype.getPromiseToLoad = function () {
  11166. return Promise.resolve(this._downloadPromise);
  11167. };
  11168. /**
  11169. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  11170. * If the EOP data has not yet been download, this method returns undefined.
  11171. *
  11172. * @param {JulianDate} date The date for each to evaluate the EOP.
  11173. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  11174. * If this parameter is undefined, a new instance is created and returned.
  11175. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  11176. * undefined if the data necessary to evaluate EOP at the date has not yet been
  11177. * downloaded.
  11178. *
  11179. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  11180. *
  11181. * @see EarthOrientationParameters#getPromiseToLoad
  11182. */
  11183. EarthOrientationParameters.prototype.compute = function (date, result) {
  11184. // We cannot compute until the samples are available.
  11185. if (!defaultValue.defined(this._samples)) {
  11186. if (defaultValue.defined(this._dataError)) {
  11187. throw new RuntimeError.RuntimeError(this._dataError);
  11188. }
  11189. return undefined;
  11190. }
  11191. if (!defaultValue.defined(result)) {
  11192. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  11193. }
  11194. if (this._samples.length === 0) {
  11195. result.xPoleWander = 0.0;
  11196. result.yPoleWander = 0.0;
  11197. result.xPoleOffset = 0.0;
  11198. result.yPoleOffset = 0.0;
  11199. result.ut1MinusUtc = 0.0;
  11200. return result;
  11201. }
  11202. const dates = this._dates;
  11203. const lastIndex = this._lastIndex;
  11204. let before = 0;
  11205. let after = 0;
  11206. if (defaultValue.defined(lastIndex)) {
  11207. const previousIndexDate = dates[lastIndex];
  11208. const nextIndexDate = dates[lastIndex + 1];
  11209. const isAfterPrevious = JulianDate.lessThanOrEquals(
  11210. previousIndexDate,
  11211. date
  11212. );
  11213. const isAfterLastSample = !defaultValue.defined(nextIndexDate);
  11214. const isBeforeNext =
  11215. isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  11216. if (isAfterPrevious && isBeforeNext) {
  11217. before = lastIndex;
  11218. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  11219. ++before;
  11220. }
  11221. after = before + 1;
  11222. interpolate(this, dates, this._samples, date, before, after, result);
  11223. return result;
  11224. }
  11225. }
  11226. let index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  11227. if (index >= 0) {
  11228. // If the next entry is the same date, use the later entry. This way, if two entries
  11229. // describe the same moment, one before a leap second and the other after, then we will use
  11230. // the post-leap second data.
  11231. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  11232. ++index;
  11233. }
  11234. before = index;
  11235. after = index;
  11236. } else {
  11237. after = ~index;
  11238. before = after - 1;
  11239. // Use the first entry if the date requested is before the beginning of the data.
  11240. if (before < 0) {
  11241. before = 0;
  11242. }
  11243. }
  11244. this._lastIndex = before;
  11245. interpolate(this, dates, this._samples, date, before, after, result);
  11246. return result;
  11247. };
  11248. function compareLeapSecondDates(leapSecond, dateToFind) {
  11249. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  11250. }
  11251. function onDataReady(eop, eopData) {
  11252. if (!defaultValue.defined(eopData.columnNames)) {
  11253. eop._dataError =
  11254. "Error in loaded EOP data: The columnNames property is required.";
  11255. return;
  11256. }
  11257. if (!defaultValue.defined(eopData.samples)) {
  11258. eop._dataError =
  11259. "Error in loaded EOP data: The samples property is required.";
  11260. return;
  11261. }
  11262. const dateColumn = eopData.columnNames.indexOf("modifiedJulianDateUtc");
  11263. const xPoleWanderRadiansColumn = eopData.columnNames.indexOf(
  11264. "xPoleWanderRadians"
  11265. );
  11266. const yPoleWanderRadiansColumn = eopData.columnNames.indexOf(
  11267. "yPoleWanderRadians"
  11268. );
  11269. const ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf(
  11270. "ut1MinusUtcSeconds"
  11271. );
  11272. const xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
  11273. "xCelestialPoleOffsetRadians"
  11274. );
  11275. const yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
  11276. "yCelestialPoleOffsetRadians"
  11277. );
  11278. const taiMinusUtcSecondsColumn = eopData.columnNames.indexOf(
  11279. "taiMinusUtcSeconds"
  11280. );
  11281. if (
  11282. dateColumn < 0 ||
  11283. xPoleWanderRadiansColumn < 0 ||
  11284. yPoleWanderRadiansColumn < 0 ||
  11285. ut1MinusUtcSecondsColumn < 0 ||
  11286. xCelestialPoleOffsetRadiansColumn < 0 ||
  11287. yCelestialPoleOffsetRadiansColumn < 0 ||
  11288. taiMinusUtcSecondsColumn < 0
  11289. ) {
  11290. eop._dataError =
  11291. "Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns";
  11292. return;
  11293. }
  11294. const samples = (eop._samples = eopData.samples);
  11295. const dates = (eop._dates = []);
  11296. eop._dateColumn = dateColumn;
  11297. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  11298. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  11299. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  11300. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  11301. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  11302. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  11303. eop._columnCount = eopData.columnNames.length;
  11304. eop._lastIndex = undefined;
  11305. let lastTaiMinusUtc;
  11306. const addNewLeapSeconds = eop._addNewLeapSeconds;
  11307. // Convert the ISO8601 dates to JulianDates.
  11308. for (let i = 0, len = samples.length; i < len; i += eop._columnCount) {
  11309. const mjd = samples[i + dateColumn];
  11310. const taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  11311. const day = mjd + TimeConstants$1.MODIFIED_JULIAN_DATE_DIFFERENCE;
  11312. const date = new JulianDate(day, taiMinusUtc, TimeStandard$1.TAI);
  11313. dates.push(date);
  11314. if (addNewLeapSeconds) {
  11315. if (taiMinusUtc !== lastTaiMinusUtc && defaultValue.defined(lastTaiMinusUtc)) {
  11316. // We crossed a leap second boundary, so add the leap second
  11317. // if it does not already exist.
  11318. const leapSeconds = JulianDate.leapSeconds;
  11319. const leapSecondIndex = binarySearch(
  11320. leapSeconds,
  11321. date,
  11322. compareLeapSecondDates
  11323. );
  11324. if (leapSecondIndex < 0) {
  11325. const leapSecond = new LeapSecond(date, taiMinusUtc);
  11326. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  11327. }
  11328. }
  11329. lastTaiMinusUtc = taiMinusUtc;
  11330. }
  11331. }
  11332. }
  11333. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  11334. const start = index * columnCount;
  11335. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  11336. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  11337. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  11338. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  11339. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  11340. }
  11341. function linearInterp(dx, y1, y2) {
  11342. return y1 + dx * (y2 - y1);
  11343. }
  11344. function interpolate(eop, dates, samples, date, before, after, result) {
  11345. const columnCount = eop._columnCount;
  11346. // First check the bounds on the EOP data
  11347. // If we are after the bounds of the data, return zeros.
  11348. // The 'before' index should never be less than zero.
  11349. if (after > dates.length - 1) {
  11350. result.xPoleWander = 0;
  11351. result.yPoleWander = 0;
  11352. result.xPoleOffset = 0;
  11353. result.yPoleOffset = 0;
  11354. result.ut1MinusUtc = 0;
  11355. return result;
  11356. }
  11357. const beforeDate = dates[before];
  11358. const afterDate = dates[after];
  11359. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  11360. fillResultFromIndex(eop, samples, before, columnCount, result);
  11361. return result;
  11362. } else if (date.equals(afterDate)) {
  11363. fillResultFromIndex(eop, samples, after, columnCount, result);
  11364. return result;
  11365. }
  11366. const factor =
  11367. JulianDate.secondsDifference(date, beforeDate) /
  11368. JulianDate.secondsDifference(afterDate, beforeDate);
  11369. const startBefore = before * columnCount;
  11370. const startAfter = after * columnCount;
  11371. // Handle UT1 leap second edge case
  11372. let beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  11373. let afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  11374. const offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  11375. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  11376. // The absolute difference between the values is more than 0.5, so we may have
  11377. // crossed a leap second. Check if this is the case and, if so, adjust the
  11378. // afterValue to account for the leap second. This way, our interpolation will
  11379. // produce reasonable results.
  11380. const beforeTaiMinusUtc =
  11381. samples[startBefore + eop._taiMinusUtcSecondsColumn];
  11382. const afterTaiMinusUtc =
  11383. samples[startAfter + eop._taiMinusUtcSecondsColumn];
  11384. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  11385. if (afterDate.equals(date)) {
  11386. // If we are at the end of the leap second interval, take the second value
  11387. // Otherwise, the interpolation below will yield the wrong side of the
  11388. // discontinuity
  11389. // At the end of the leap second, we need to start accounting for the jump
  11390. beforeUt1MinusUtc = afterUt1MinusUtc;
  11391. } else {
  11392. // Otherwise, remove the leap second so that the interpolation is correct
  11393. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  11394. }
  11395. }
  11396. }
  11397. result.xPoleWander = linearInterp(
  11398. factor,
  11399. samples[startBefore + eop._xPoleWanderRadiansColumn],
  11400. samples[startAfter + eop._xPoleWanderRadiansColumn]
  11401. );
  11402. result.yPoleWander = linearInterp(
  11403. factor,
  11404. samples[startBefore + eop._yPoleWanderRadiansColumn],
  11405. samples[startAfter + eop._yPoleWanderRadiansColumn]
  11406. );
  11407. result.xPoleOffset = linearInterp(
  11408. factor,
  11409. samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn],
  11410. samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]
  11411. );
  11412. result.yPoleOffset = linearInterp(
  11413. factor,
  11414. samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn],
  11415. samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]
  11416. );
  11417. result.ut1MinusUtc = linearInterp(
  11418. factor,
  11419. beforeUt1MinusUtc,
  11420. afterUt1MinusUtc
  11421. );
  11422. return result;
  11423. }
  11424. /**
  11425. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  11426. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  11427. * the positive x axis.
  11428. * @alias HeadingPitchRoll
  11429. * @constructor
  11430. *
  11431. * @param {Number} [heading=0.0] The heading component in radians.
  11432. * @param {Number} [pitch=0.0] The pitch component in radians.
  11433. * @param {Number} [roll=0.0] The roll component in radians.
  11434. */
  11435. function HeadingPitchRoll(heading, pitch, roll) {
  11436. /**
  11437. * Gets or sets the heading.
  11438. * @type {Number}
  11439. * @default 0.0
  11440. */
  11441. this.heading = defaultValue.defaultValue(heading, 0.0);
  11442. /**
  11443. * Gets or sets the pitch.
  11444. * @type {Number}
  11445. * @default 0.0
  11446. */
  11447. this.pitch = defaultValue.defaultValue(pitch, 0.0);
  11448. /**
  11449. * Gets or sets the roll.
  11450. * @type {Number}
  11451. * @default 0.0
  11452. */
  11453. this.roll = defaultValue.defaultValue(roll, 0.0);
  11454. }
  11455. /**
  11456. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  11457. *
  11458. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  11459. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  11460. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  11461. */
  11462. HeadingPitchRoll.fromQuaternion = function (quaternion, result) {
  11463. //>>includeStart('debug', pragmas.debug);
  11464. if (!defaultValue.defined(quaternion)) {
  11465. throw new RuntimeError.DeveloperError("quaternion is required");
  11466. }
  11467. //>>includeEnd('debug');
  11468. if (!defaultValue.defined(result)) {
  11469. result = new HeadingPitchRoll();
  11470. }
  11471. const test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  11472. const denominatorRoll =
  11473. 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  11474. const numeratorRoll =
  11475. 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  11476. const denominatorHeading =
  11477. 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  11478. const numeratorHeading =
  11479. 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  11480. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  11481. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  11482. result.pitch = -ComponentDatatype.CesiumMath.asinClamped(test);
  11483. return result;
  11484. };
  11485. /**
  11486. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  11487. *
  11488. * @param {Number} heading the heading in degrees
  11489. * @param {Number} pitch the pitch in degrees
  11490. * @param {Number} roll the heading in degrees
  11491. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  11492. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  11493. */
  11494. HeadingPitchRoll.fromDegrees = function (heading, pitch, roll, result) {
  11495. //>>includeStart('debug', pragmas.debug);
  11496. if (!defaultValue.defined(heading)) {
  11497. throw new RuntimeError.DeveloperError("heading is required");
  11498. }
  11499. if (!defaultValue.defined(pitch)) {
  11500. throw new RuntimeError.DeveloperError("pitch is required");
  11501. }
  11502. if (!defaultValue.defined(roll)) {
  11503. throw new RuntimeError.DeveloperError("roll is required");
  11504. }
  11505. //>>includeEnd('debug');
  11506. if (!defaultValue.defined(result)) {
  11507. result = new HeadingPitchRoll();
  11508. }
  11509. result.heading = heading * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE;
  11510. result.pitch = pitch * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE;
  11511. result.roll = roll * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE;
  11512. return result;
  11513. };
  11514. /**
  11515. * Duplicates a HeadingPitchRoll instance.
  11516. *
  11517. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  11518. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  11519. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  11520. */
  11521. HeadingPitchRoll.clone = function (headingPitchRoll, result) {
  11522. if (!defaultValue.defined(headingPitchRoll)) {
  11523. return undefined;
  11524. }
  11525. if (!defaultValue.defined(result)) {
  11526. return new HeadingPitchRoll(
  11527. headingPitchRoll.heading,
  11528. headingPitchRoll.pitch,
  11529. headingPitchRoll.roll
  11530. );
  11531. }
  11532. result.heading = headingPitchRoll.heading;
  11533. result.pitch = headingPitchRoll.pitch;
  11534. result.roll = headingPitchRoll.roll;
  11535. return result;
  11536. };
  11537. /**
  11538. * Compares the provided HeadingPitchRolls componentwise and returns
  11539. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11540. *
  11541. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  11542. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  11543. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  11544. */
  11545. HeadingPitchRoll.equals = function (left, right) {
  11546. return (
  11547. left === right ||
  11548. (defaultValue.defined(left) &&
  11549. defaultValue.defined(right) &&
  11550. left.heading === right.heading &&
  11551. left.pitch === right.pitch &&
  11552. left.roll === right.roll)
  11553. );
  11554. };
  11555. /**
  11556. * Compares the provided HeadingPitchRolls componentwise and returns
  11557. * <code>true</code> if they pass an absolute or relative tolerance test,
  11558. * <code>false</code> otherwise.
  11559. *
  11560. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  11561. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  11562. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  11563. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  11564. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  11565. */
  11566. HeadingPitchRoll.equalsEpsilon = function (
  11567. left,
  11568. right,
  11569. relativeEpsilon,
  11570. absoluteEpsilon
  11571. ) {
  11572. return (
  11573. left === right ||
  11574. (defaultValue.defined(left) &&
  11575. defaultValue.defined(right) &&
  11576. ComponentDatatype.CesiumMath.equalsEpsilon(
  11577. left.heading,
  11578. right.heading,
  11579. relativeEpsilon,
  11580. absoluteEpsilon
  11581. ) &&
  11582. ComponentDatatype.CesiumMath.equalsEpsilon(
  11583. left.pitch,
  11584. right.pitch,
  11585. relativeEpsilon,
  11586. absoluteEpsilon
  11587. ) &&
  11588. ComponentDatatype.CesiumMath.equalsEpsilon(
  11589. left.roll,
  11590. right.roll,
  11591. relativeEpsilon,
  11592. absoluteEpsilon
  11593. ))
  11594. );
  11595. };
  11596. /**
  11597. * Duplicates this HeadingPitchRoll instance.
  11598. *
  11599. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  11600. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  11601. */
  11602. HeadingPitchRoll.prototype.clone = function (result) {
  11603. return HeadingPitchRoll.clone(this, result);
  11604. };
  11605. /**
  11606. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  11607. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11608. *
  11609. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  11610. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  11611. */
  11612. HeadingPitchRoll.prototype.equals = function (right) {
  11613. return HeadingPitchRoll.equals(this, right);
  11614. };
  11615. /**
  11616. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  11617. * <code>true</code> if they pass an absolute or relative tolerance test,
  11618. * <code>false</code> otherwise.
  11619. *
  11620. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  11621. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  11622. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  11623. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  11624. */
  11625. HeadingPitchRoll.prototype.equalsEpsilon = function (
  11626. right,
  11627. relativeEpsilon,
  11628. absoluteEpsilon
  11629. ) {
  11630. return HeadingPitchRoll.equalsEpsilon(
  11631. this,
  11632. right,
  11633. relativeEpsilon,
  11634. absoluteEpsilon
  11635. );
  11636. };
  11637. /**
  11638. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  11639. *
  11640. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  11641. */
  11642. HeadingPitchRoll.prototype.toString = function () {
  11643. return `(${this.heading}, ${this.pitch}, ${this.roll})`;
  11644. };
  11645. /*global CESIUM_BASE_URL,define,require*/
  11646. const cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js(?:\?|\#|$)/;
  11647. function getBaseUrlFromCesiumScript() {
  11648. const scripts = document.getElementsByTagName("script");
  11649. for (let i = 0, len = scripts.length; i < len; ++i) {
  11650. const src = scripts[i].getAttribute("src");
  11651. const result = cesiumScriptRegex.exec(src);
  11652. if (result !== null) {
  11653. return result[1];
  11654. }
  11655. }
  11656. return undefined;
  11657. }
  11658. let a;
  11659. function tryMakeAbsolute(url) {
  11660. if (typeof document === "undefined") {
  11661. //Node.js and Web Workers. In both cases, the URL will already be absolute.
  11662. return url;
  11663. }
  11664. if (!defaultValue.defined(a)) {
  11665. a = document.createElement("a");
  11666. }
  11667. a.href = url;
  11668. // IE only absolutizes href on get, not set
  11669. // eslint-disable-next-line no-self-assign
  11670. a.href = a.href;
  11671. return a.href;
  11672. }
  11673. let baseResource;
  11674. function getCesiumBaseUrl() {
  11675. if (defaultValue.defined(baseResource)) {
  11676. return baseResource;
  11677. }
  11678. let baseUrlString;
  11679. if (typeof CESIUM_BASE_URL !== "undefined") {
  11680. baseUrlString = CESIUM_BASE_URL;
  11681. } else if (
  11682. typeof define === "object" &&
  11683. defaultValue.defined(define.amd) &&
  11684. !define.amd.toUrlUndefined &&
  11685. defaultValue.defined(require.toUrl)
  11686. ) {
  11687. baseUrlString = getAbsoluteUri(
  11688. "..",
  11689. buildModuleUrl("Core/buildModuleUrl.js")
  11690. );
  11691. } else {
  11692. baseUrlString = getBaseUrlFromCesiumScript();
  11693. }
  11694. //>>includeStart('debug', pragmas.debug);
  11695. if (!defaultValue.defined(baseUrlString)) {
  11696. throw new RuntimeError.DeveloperError(
  11697. "Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL."
  11698. );
  11699. }
  11700. //>>includeEnd('debug');
  11701. baseResource = new Resource({
  11702. url: tryMakeAbsolute(baseUrlString),
  11703. });
  11704. baseResource.appendForwardSlash();
  11705. return baseResource;
  11706. }
  11707. function buildModuleUrlFromRequireToUrl(moduleID) {
  11708. //moduleID will be non-relative, so require it relative to this module, in Core.
  11709. return tryMakeAbsolute(require.toUrl(`../${moduleID}`));
  11710. }
  11711. function buildModuleUrlFromBaseUrl(moduleID) {
  11712. const resource = getCesiumBaseUrl().getDerivedResource({
  11713. url: moduleID,
  11714. });
  11715. return resource.url;
  11716. }
  11717. let implementation;
  11718. /**
  11719. * Given a relative URL under the Cesium base URL, returns an absolute URL.
  11720. * @function
  11721. *
  11722. * @param {String} relativeUrl The relative path.
  11723. * @returns {String} The absolutely URL representation of the provided path.
  11724. *
  11725. * @example
  11726. * const viewer = new Cesium.Viewer("cesiumContainer", {
  11727. * imageryProvider: new Cesium.TileMapServiceImageryProvider({
  11728. * url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
  11729. * }),
  11730. * baseLayerPicker: false,
  11731. * });
  11732. */
  11733. function buildModuleUrl(relativeUrl) {
  11734. if (!defaultValue.defined(implementation)) {
  11735. //select implementation
  11736. if (
  11737. typeof define === "object" &&
  11738. defaultValue.defined(define.amd) &&
  11739. !define.amd.toUrlUndefined &&
  11740. defaultValue.defined(require.toUrl)
  11741. ) {
  11742. implementation = buildModuleUrlFromRequireToUrl;
  11743. } else {
  11744. implementation = buildModuleUrlFromBaseUrl;
  11745. }
  11746. }
  11747. const url = implementation(relativeUrl);
  11748. return url;
  11749. }
  11750. // exposed for testing
  11751. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  11752. buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
  11753. buildModuleUrl._clearBaseResource = function () {
  11754. baseResource = undefined;
  11755. };
  11756. /**
  11757. * Sets the base URL for resolving modules.
  11758. * @param {String} value The new base URL.
  11759. */
  11760. buildModuleUrl.setBaseUrl = function (value) {
  11761. baseResource = Resource.DEFAULT.getDerivedResource({
  11762. url: value,
  11763. });
  11764. };
  11765. /**
  11766. * Gets the base URL for resolving modules.
  11767. *
  11768. * @function
  11769. * @returns {String} The configured base URL
  11770. */
  11771. buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
  11772. /**
  11773. * An IAU 2006 XYS value sampled at a particular time.
  11774. *
  11775. * @alias Iau2006XysSample
  11776. * @constructor
  11777. *
  11778. * @param {Number} x The X value.
  11779. * @param {Number} y The Y value.
  11780. * @param {Number} s The S value.
  11781. *
  11782. * @private
  11783. */
  11784. function Iau2006XysSample(x, y, s) {
  11785. /**
  11786. * The X value.
  11787. * @type {Number}
  11788. */
  11789. this.x = x;
  11790. /**
  11791. * The Y value.
  11792. * @type {Number}
  11793. */
  11794. this.y = y;
  11795. /**
  11796. * The S value.
  11797. * @type {Number}
  11798. */
  11799. this.s = s;
  11800. }
  11801. /**
  11802. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  11803. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  11804. *
  11805. * @alias Iau2006XysData
  11806. * @constructor
  11807. *
  11808. * @param {Object} [options] Object with the following properties:
  11809. * @param {Resource|String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  11810. * `{0}` will be replaced with the file index.
  11811. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  11812. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  11813. * first XYS sample.
  11814. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  11815. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  11816. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  11817. *
  11818. * @private
  11819. */
  11820. function Iau2006XysData(options) {
  11821. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  11822. this._xysFileUrlTemplate = Resource.createIfNeeded(
  11823. options.xysFileUrlTemplate
  11824. );
  11825. this._interpolationOrder = defaultValue.defaultValue(options.interpolationOrder, 9);
  11826. this._sampleZeroJulianEphemerisDate = defaultValue.defaultValue(
  11827. options.sampleZeroJulianEphemerisDate,
  11828. 2442396.5
  11829. );
  11830. this._sampleZeroDateTT = new JulianDate(
  11831. this._sampleZeroJulianEphemerisDate,
  11832. 0.0,
  11833. TimeStandard$1.TAI
  11834. );
  11835. this._stepSizeDays = defaultValue.defaultValue(options.stepSizeDays, 1.0);
  11836. this._samplesPerXysFile = defaultValue.defaultValue(options.samplesPerXysFile, 1000);
  11837. this._totalSamples = defaultValue.defaultValue(options.totalSamples, 27426);
  11838. this._samples = new Array(this._totalSamples * 3);
  11839. this._chunkDownloadsInProgress = [];
  11840. const order = this._interpolationOrder;
  11841. // Compute denominators and X values for interpolation.
  11842. const denom = (this._denominators = new Array(order + 1));
  11843. const xTable = (this._xTable = new Array(order + 1));
  11844. const stepN = Math.pow(this._stepSizeDays, order);
  11845. for (let i = 0; i <= order; ++i) {
  11846. denom[i] = stepN;
  11847. xTable[i] = i * this._stepSizeDays;
  11848. for (let j = 0; j <= order; ++j) {
  11849. if (j !== i) {
  11850. denom[i] *= i - j;
  11851. }
  11852. }
  11853. denom[i] = 1.0 / denom[i];
  11854. }
  11855. // Allocate scratch arrays for interpolation.
  11856. this._work = new Array(order + 1);
  11857. this._coef = new Array(order + 1);
  11858. }
  11859. const julianDateScratch = new JulianDate(0, 0.0, TimeStandard$1.TAI);
  11860. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  11861. const dateTT = julianDateScratch;
  11862. dateTT.dayNumber = dayTT;
  11863. dateTT.secondsOfDay = secondTT;
  11864. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  11865. }
  11866. /**
  11867. * Preloads XYS data for a specified date range.
  11868. *
  11869. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  11870. * the Terrestrial Time (TT) time standard.
  11871. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  11872. * the Terrestrial Time (TT) time standard.
  11873. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  11874. * the Terrestrial Time (TT) time standard.
  11875. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  11876. * the Terrestrial Time (TT) time standard.
  11877. * @returns {Promise<void>} A promise that, when resolved, indicates that the requested interval has been
  11878. * preloaded.
  11879. */
  11880. Iau2006XysData.prototype.preload = function (
  11881. startDayTT,
  11882. startSecondTT,
  11883. stopDayTT,
  11884. stopSecondTT
  11885. ) {
  11886. const startDaysSinceEpoch = getDaysSinceEpoch(
  11887. this,
  11888. startDayTT,
  11889. startSecondTT
  11890. );
  11891. const stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  11892. let startIndex =
  11893. (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
  11894. 0;
  11895. if (startIndex < 0) {
  11896. startIndex = 0;
  11897. }
  11898. let stopIndex =
  11899. (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
  11900. (0 + this._interpolationOrder);
  11901. if (stopIndex >= this._totalSamples) {
  11902. stopIndex = this._totalSamples - 1;
  11903. }
  11904. const startChunk = (startIndex / this._samplesPerXysFile) | 0;
  11905. const stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  11906. const promises = [];
  11907. for (let i = startChunk; i <= stopChunk; ++i) {
  11908. promises.push(requestXysChunk(this, i));
  11909. }
  11910. return Promise.all(promises);
  11911. };
  11912. /**
  11913. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  11914. * this method will return undefined.
  11915. *
  11916. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  11917. * the Terrestrial Time (TT) time standard.
  11918. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  11919. * the Terrestrial Time (TT) time standard.
  11920. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  11921. * is undefined, a new instance is allocated and returned.
  11922. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  11923. * computation has not yet been downloaded.
  11924. *
  11925. * @see Iau2006XysData#preload
  11926. */
  11927. Iau2006XysData.prototype.computeXysRadians = function (
  11928. dayTT,
  11929. secondTT,
  11930. result
  11931. ) {
  11932. const daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  11933. if (daysSinceEpoch < 0.0) {
  11934. // Can't evaluate prior to the epoch of the data.
  11935. return undefined;
  11936. }
  11937. const centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  11938. if (centerIndex >= this._totalSamples) {
  11939. // Can't evaluate after the last sample in the data.
  11940. return undefined;
  11941. }
  11942. const degree = this._interpolationOrder;
  11943. let firstIndex = centerIndex - ((degree / 2) | 0);
  11944. if (firstIndex < 0) {
  11945. firstIndex = 0;
  11946. }
  11947. let lastIndex = firstIndex + degree;
  11948. if (lastIndex >= this._totalSamples) {
  11949. lastIndex = this._totalSamples - 1;
  11950. firstIndex = lastIndex - degree;
  11951. if (firstIndex < 0) {
  11952. firstIndex = 0;
  11953. }
  11954. }
  11955. // Are all the samples we need present?
  11956. // We can assume so if the first and last are present
  11957. let isDataMissing = false;
  11958. const samples = this._samples;
  11959. if (!defaultValue.defined(samples[firstIndex * 3])) {
  11960. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  11961. isDataMissing = true;
  11962. }
  11963. if (!defaultValue.defined(samples[lastIndex * 3])) {
  11964. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  11965. isDataMissing = true;
  11966. }
  11967. if (isDataMissing) {
  11968. return undefined;
  11969. }
  11970. if (!defaultValue.defined(result)) {
  11971. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  11972. } else {
  11973. result.x = 0.0;
  11974. result.y = 0.0;
  11975. result.s = 0.0;
  11976. }
  11977. const x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  11978. const work = this._work;
  11979. const denom = this._denominators;
  11980. const coef = this._coef;
  11981. const xTable = this._xTable;
  11982. let i, j;
  11983. for (i = 0; i <= degree; ++i) {
  11984. work[i] = x - xTable[i];
  11985. }
  11986. for (i = 0; i <= degree; ++i) {
  11987. coef[i] = 1.0;
  11988. for (j = 0; j <= degree; ++j) {
  11989. if (j !== i) {
  11990. coef[i] *= work[j];
  11991. }
  11992. }
  11993. coef[i] *= denom[i];
  11994. let sampleIndex = (firstIndex + i) * 3;
  11995. result.x += coef[i] * samples[sampleIndex++];
  11996. result.y += coef[i] * samples[sampleIndex++];
  11997. result.s += coef[i] * samples[sampleIndex];
  11998. }
  11999. return result;
  12000. };
  12001. function requestXysChunk(xysData, chunkIndex) {
  12002. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  12003. // Chunk has already been requested.
  12004. return xysData._chunkDownloadsInProgress[chunkIndex];
  12005. }
  12006. const deferred = defer();
  12007. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  12008. let chunkUrl;
  12009. const xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  12010. if (defaultValue.defined(xysFileUrlTemplate)) {
  12011. chunkUrl = xysFileUrlTemplate.getDerivedResource({
  12012. templateValues: {
  12013. 0: chunkIndex,
  12014. },
  12015. });
  12016. } else {
  12017. chunkUrl = new Resource({
  12018. url: buildModuleUrl(`Assets/IAU2006_XYS/IAU2006_XYS_${chunkIndex}.json`),
  12019. });
  12020. }
  12021. chunkUrl.fetchJson().then(function (chunk) {
  12022. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  12023. const samples = xysData._samples;
  12024. const newSamples = chunk.samples;
  12025. const startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  12026. for (let i = 0, len = newSamples.length; i < len; ++i) {
  12027. samples[startIndex + i] = newSamples[i];
  12028. }
  12029. deferred.resolve();
  12030. });
  12031. return deferred.promise;
  12032. }
  12033. /**
  12034. * Contains functions for transforming positions to various reference frames.
  12035. *
  12036. * @namespace Transforms
  12037. */
  12038. const Transforms = {};
  12039. const vectorProductLocalFrame = {
  12040. up: {
  12041. south: "east",
  12042. north: "west",
  12043. west: "south",
  12044. east: "north",
  12045. },
  12046. down: {
  12047. south: "west",
  12048. north: "east",
  12049. west: "north",
  12050. east: "south",
  12051. },
  12052. south: {
  12053. up: "west",
  12054. down: "east",
  12055. west: "down",
  12056. east: "up",
  12057. },
  12058. north: {
  12059. up: "east",
  12060. down: "west",
  12061. west: "up",
  12062. east: "down",
  12063. },
  12064. west: {
  12065. up: "north",
  12066. down: "south",
  12067. north: "down",
  12068. south: "up",
  12069. },
  12070. east: {
  12071. up: "south",
  12072. down: "north",
  12073. north: "up",
  12074. south: "down",
  12075. },
  12076. };
  12077. const degeneratePositionLocalFrame = {
  12078. north: [-1, 0, 0],
  12079. east: [0, 1, 0],
  12080. up: [0, 0, 1],
  12081. south: [1, 0, 0],
  12082. west: [0, -1, 0],
  12083. down: [0, 0, -1],
  12084. };
  12085. const localFrameToFixedFrameCache = {};
  12086. const scratchCalculateCartesian = {
  12087. east: new Matrix2.Cartesian3(),
  12088. north: new Matrix2.Cartesian3(),
  12089. up: new Matrix2.Cartesian3(),
  12090. west: new Matrix2.Cartesian3(),
  12091. south: new Matrix2.Cartesian3(),
  12092. down: new Matrix2.Cartesian3(),
  12093. };
  12094. let scratchFirstCartesian = new Matrix2.Cartesian3();
  12095. let scratchSecondCartesian = new Matrix2.Cartesian3();
  12096. let scratchThirdCartesian = new Matrix2.Cartesian3();
  12097. /**
  12098. * Generates a function that computes a 4x4 transformation matrix from a reference frame
  12099. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12100. * @param {String} firstAxis name of the first axis of the local reference frame. Must be
  12101. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  12102. * @param {String} secondAxis name of the second axis of the local reference frame. Must be
  12103. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  12104. * @return {Transforms.LocalFrameToFixedFrame} The function that will computes a
  12105. * 4x4 transformation matrix from a reference frame, with first axis and second axis compliant with the parameters,
  12106. */
  12107. Transforms.localFrameToFixedFrameGenerator = function (firstAxis, secondAxis) {
  12108. if (
  12109. !vectorProductLocalFrame.hasOwnProperty(firstAxis) ||
  12110. !vectorProductLocalFrame[firstAxis].hasOwnProperty(secondAxis)
  12111. ) {
  12112. throw new RuntimeError.DeveloperError(
  12113. "firstAxis and secondAxis must be east, north, up, west, south or down."
  12114. );
  12115. }
  12116. const thirdAxis = vectorProductLocalFrame[firstAxis][secondAxis];
  12117. /**
  12118. * Computes a 4x4 transformation matrix from a reference frame
  12119. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12120. * @callback Transforms.LocalFrameToFixedFrame
  12121. * @param {Cartesian3} origin The center point of the local reference frame.
  12122. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12123. * @param {Matrix4} [result] The object onto which to store the result.
  12124. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12125. */
  12126. let resultat;
  12127. const hashAxis = firstAxis + secondAxis;
  12128. if (defaultValue.defined(localFrameToFixedFrameCache[hashAxis])) {
  12129. resultat = localFrameToFixedFrameCache[hashAxis];
  12130. } else {
  12131. resultat = function (origin, ellipsoid, result) {
  12132. //>>includeStart('debug', pragmas.debug);
  12133. if (!defaultValue.defined(origin)) {
  12134. throw new RuntimeError.DeveloperError("origin is required.");
  12135. }
  12136. //>>includeEnd('debug');
  12137. if (!defaultValue.defined(result)) {
  12138. result = new Matrix2.Matrix4();
  12139. }
  12140. if (
  12141. Matrix2.Cartesian3.equalsEpsilon(origin, Matrix2.Cartesian3.ZERO, ComponentDatatype.CesiumMath.EPSILON14)
  12142. ) {
  12143. // If x, y, and z are zero, use the degenerate local frame, which is a special case
  12144. Matrix2.Cartesian3.unpack(
  12145. degeneratePositionLocalFrame[firstAxis],
  12146. 0,
  12147. scratchFirstCartesian
  12148. );
  12149. Matrix2.Cartesian3.unpack(
  12150. degeneratePositionLocalFrame[secondAxis],
  12151. 0,
  12152. scratchSecondCartesian
  12153. );
  12154. Matrix2.Cartesian3.unpack(
  12155. degeneratePositionLocalFrame[thirdAxis],
  12156. 0,
  12157. scratchThirdCartesian
  12158. );
  12159. } else if (
  12160. ComponentDatatype.CesiumMath.equalsEpsilon(origin.x, 0.0, ComponentDatatype.CesiumMath.EPSILON14) &&
  12161. ComponentDatatype.CesiumMath.equalsEpsilon(origin.y, 0.0, ComponentDatatype.CesiumMath.EPSILON14)
  12162. ) {
  12163. // If x and y are zero, assume origin is at a pole, which is a special case.
  12164. const sign = ComponentDatatype.CesiumMath.sign(origin.z);
  12165. Matrix2.Cartesian3.unpack(
  12166. degeneratePositionLocalFrame[firstAxis],
  12167. 0,
  12168. scratchFirstCartesian
  12169. );
  12170. if (firstAxis !== "east" && firstAxis !== "west") {
  12171. Matrix2.Cartesian3.multiplyByScalar(
  12172. scratchFirstCartesian,
  12173. sign,
  12174. scratchFirstCartesian
  12175. );
  12176. }
  12177. Matrix2.Cartesian3.unpack(
  12178. degeneratePositionLocalFrame[secondAxis],
  12179. 0,
  12180. scratchSecondCartesian
  12181. );
  12182. if (secondAxis !== "east" && secondAxis !== "west") {
  12183. Matrix2.Cartesian3.multiplyByScalar(
  12184. scratchSecondCartesian,
  12185. sign,
  12186. scratchSecondCartesian
  12187. );
  12188. }
  12189. Matrix2.Cartesian3.unpack(
  12190. degeneratePositionLocalFrame[thirdAxis],
  12191. 0,
  12192. scratchThirdCartesian
  12193. );
  12194. if (thirdAxis !== "east" && thirdAxis !== "west") {
  12195. Matrix2.Cartesian3.multiplyByScalar(
  12196. scratchThirdCartesian,
  12197. sign,
  12198. scratchThirdCartesian
  12199. );
  12200. }
  12201. } else {
  12202. ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  12203. ellipsoid.geodeticSurfaceNormal(origin, scratchCalculateCartesian.up);
  12204. const up = scratchCalculateCartesian.up;
  12205. const east = scratchCalculateCartesian.east;
  12206. east.x = -origin.y;
  12207. east.y = origin.x;
  12208. east.z = 0.0;
  12209. Matrix2.Cartesian3.normalize(east, scratchCalculateCartesian.east);
  12210. Matrix2.Cartesian3.cross(up, east, scratchCalculateCartesian.north);
  12211. Matrix2.Cartesian3.multiplyByScalar(
  12212. scratchCalculateCartesian.up,
  12213. -1,
  12214. scratchCalculateCartesian.down
  12215. );
  12216. Matrix2.Cartesian3.multiplyByScalar(
  12217. scratchCalculateCartesian.east,
  12218. -1,
  12219. scratchCalculateCartesian.west
  12220. );
  12221. Matrix2.Cartesian3.multiplyByScalar(
  12222. scratchCalculateCartesian.north,
  12223. -1,
  12224. scratchCalculateCartesian.south
  12225. );
  12226. scratchFirstCartesian = scratchCalculateCartesian[firstAxis];
  12227. scratchSecondCartesian = scratchCalculateCartesian[secondAxis];
  12228. scratchThirdCartesian = scratchCalculateCartesian[thirdAxis];
  12229. }
  12230. result[0] = scratchFirstCartesian.x;
  12231. result[1] = scratchFirstCartesian.y;
  12232. result[2] = scratchFirstCartesian.z;
  12233. result[3] = 0.0;
  12234. result[4] = scratchSecondCartesian.x;
  12235. result[5] = scratchSecondCartesian.y;
  12236. result[6] = scratchSecondCartesian.z;
  12237. result[7] = 0.0;
  12238. result[8] = scratchThirdCartesian.x;
  12239. result[9] = scratchThirdCartesian.y;
  12240. result[10] = scratchThirdCartesian.z;
  12241. result[11] = 0.0;
  12242. result[12] = origin.x;
  12243. result[13] = origin.y;
  12244. result[14] = origin.z;
  12245. result[15] = 1.0;
  12246. return result;
  12247. };
  12248. localFrameToFixedFrameCache[hashAxis] = resultat;
  12249. }
  12250. return resultat;
  12251. };
  12252. /**
  12253. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  12254. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12255. * The local axes are defined as:
  12256. * <ul>
  12257. * <li>The <code>x</code> axis points in the local east direction.</li>
  12258. * <li>The <code>y</code> axis points in the local north direction.</li>
  12259. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  12260. * </ul>
  12261. *
  12262. * @function
  12263. * @param {Cartesian3} origin The center point of the local reference frame.
  12264. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12265. * @param {Matrix4} [result] The object onto which to store the result.
  12266. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12267. *
  12268. * @example
  12269. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  12270. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12271. * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  12272. */
  12273. Transforms.eastNorthUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12274. "east",
  12275. "north"
  12276. );
  12277. /**
  12278. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  12279. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12280. * The local axes are defined as:
  12281. * <ul>
  12282. * <li>The <code>x</code> axis points in the local north direction.</li>
  12283. * <li>The <code>y</code> axis points in the local east direction.</li>
  12284. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  12285. * </ul>
  12286. *
  12287. * @function
  12288. * @param {Cartesian3} origin The center point of the local reference frame.
  12289. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12290. * @param {Matrix4} [result] The object onto which to store the result.
  12291. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12292. *
  12293. * @example
  12294. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  12295. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12296. * const transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  12297. */
  12298. Transforms.northEastDownToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12299. "north",
  12300. "east"
  12301. );
  12302. /**
  12303. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  12304. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12305. * The local axes are defined as:
  12306. * <ul>
  12307. * <li>The <code>x</code> axis points in the local north direction.</li>
  12308. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  12309. * <li>The <code>z</code> axis points in the local east direction.</li>
  12310. * </ul>
  12311. *
  12312. * @function
  12313. * @param {Cartesian3} origin The center point of the local reference frame.
  12314. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12315. * @param {Matrix4} [result] The object onto which to store the result.
  12316. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12317. *
  12318. * @example
  12319. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  12320. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12321. * const transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  12322. */
  12323. Transforms.northUpEastToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12324. "north",
  12325. "up"
  12326. );
  12327. /**
  12328. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  12329. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12330. * The local axes are defined as:
  12331. * <ul>
  12332. * <li>The <code>x</code> axis points in the local north direction.</li>
  12333. * <li>The <code>y</code> axis points in the local west direction.</li>
  12334. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  12335. * </ul>
  12336. *
  12337. * @function
  12338. * @param {Cartesian3} origin The center point of the local reference frame.
  12339. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12340. * @param {Matrix4} [result] The object onto which to store the result.
  12341. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12342. *
  12343. * @example
  12344. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  12345. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12346. * const transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  12347. */
  12348. Transforms.northWestUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12349. "north",
  12350. "west"
  12351. );
  12352. const scratchHPRQuaternion = new Quaternion();
  12353. const scratchScale = new Matrix2.Cartesian3(1.0, 1.0, 1.0);
  12354. const scratchHPRMatrix4 = new Matrix2.Matrix4();
  12355. /**
  12356. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  12357. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  12358. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  12359. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  12360. *
  12361. * @param {Cartesian3} origin The center point of the local reference frame.
  12362. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  12363. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12364. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  12365. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  12366. * @param {Matrix4} [result] The object onto which to store the result.
  12367. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12368. *
  12369. * @example
  12370. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  12371. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12372. * const heading = -Cesium.Math.PI_OVER_TWO;
  12373. * const pitch = Cesium.Math.PI_OVER_FOUR;
  12374. * const roll = 0.0;
  12375. * const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  12376. * const transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  12377. */
  12378. Transforms.headingPitchRollToFixedFrame = function (
  12379. origin,
  12380. headingPitchRoll,
  12381. ellipsoid,
  12382. fixedFrameTransform,
  12383. result
  12384. ) {
  12385. //>>includeStart('debug', pragmas.debug);
  12386. RuntimeError.Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
  12387. //>>includeEnd('debug');
  12388. fixedFrameTransform = defaultValue.defaultValue(
  12389. fixedFrameTransform,
  12390. Transforms.eastNorthUpToFixedFrame
  12391. );
  12392. const hprQuaternion = Quaternion.fromHeadingPitchRoll(
  12393. headingPitchRoll,
  12394. scratchHPRQuaternion
  12395. );
  12396. const hprMatrix = Matrix2.Matrix4.fromTranslationQuaternionRotationScale(
  12397. Matrix2.Cartesian3.ZERO,
  12398. hprQuaternion,
  12399. scratchScale,
  12400. scratchHPRMatrix4
  12401. );
  12402. result = fixedFrameTransform(origin, ellipsoid, result);
  12403. return Matrix2.Matrix4.multiply(result, hprMatrix, result);
  12404. };
  12405. const scratchENUMatrix4 = new Matrix2.Matrix4();
  12406. const scratchHPRMatrix3 = new Matrix2.Matrix3();
  12407. /**
  12408. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  12409. * centered at the provided origin. Heading is the rotation from the local north
  12410. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  12411. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  12412. *
  12413. * @param {Cartesian3} origin The center point of the local reference frame.
  12414. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  12415. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12416. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  12417. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  12418. * @param {Quaternion} [result] The object onto which to store the result.
  12419. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  12420. *
  12421. * @example
  12422. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  12423. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12424. * const heading = -Cesium.Math.PI_OVER_TWO;
  12425. * const pitch = Cesium.Math.PI_OVER_FOUR;
  12426. * const roll = 0.0;
  12427. * const hpr = new HeadingPitchRoll(heading, pitch, roll);
  12428. * const quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  12429. */
  12430. Transforms.headingPitchRollQuaternion = function (
  12431. origin,
  12432. headingPitchRoll,
  12433. ellipsoid,
  12434. fixedFrameTransform,
  12435. result
  12436. ) {
  12437. //>>includeStart('debug', pragmas.debug);
  12438. RuntimeError.Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
  12439. //>>includeEnd('debug');
  12440. const transform = Transforms.headingPitchRollToFixedFrame(
  12441. origin,
  12442. headingPitchRoll,
  12443. ellipsoid,
  12444. fixedFrameTransform,
  12445. scratchENUMatrix4
  12446. );
  12447. const rotation = Matrix2.Matrix4.getMatrix3(transform, scratchHPRMatrix3);
  12448. return Quaternion.fromRotationMatrix(rotation, result);
  12449. };
  12450. const noScale = new Matrix2.Cartesian3(1.0, 1.0, 1.0);
  12451. const hprCenterScratch = new Matrix2.Cartesian3();
  12452. const ffScratch = new Matrix2.Matrix4();
  12453. const hprTransformScratch = new Matrix2.Matrix4();
  12454. const hprRotationScratch = new Matrix2.Matrix3();
  12455. const hprQuaternionScratch = new Quaternion();
  12456. /**
  12457. * Computes heading-pitch-roll angles from a transform in a particular reference frame. Heading is the rotation from the local north
  12458. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  12459. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  12460. *
  12461. * @param {Matrix4} transform The transform
  12462. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12463. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  12464. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  12465. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  12466. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if none was provided.
  12467. */
  12468. Transforms.fixedFrameToHeadingPitchRoll = function (
  12469. transform,
  12470. ellipsoid,
  12471. fixedFrameTransform,
  12472. result
  12473. ) {
  12474. //>>includeStart('debug', pragmas.debug);
  12475. RuntimeError.Check.defined("transform", transform);
  12476. //>>includeEnd('debug');
  12477. ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  12478. fixedFrameTransform = defaultValue.defaultValue(
  12479. fixedFrameTransform,
  12480. Transforms.eastNorthUpToFixedFrame
  12481. );
  12482. if (!defaultValue.defined(result)) {
  12483. result = new HeadingPitchRoll();
  12484. }
  12485. const center = Matrix2.Matrix4.getTranslation(transform, hprCenterScratch);
  12486. if (Matrix2.Cartesian3.equals(center, Matrix2.Cartesian3.ZERO)) {
  12487. result.heading = 0;
  12488. result.pitch = 0;
  12489. result.roll = 0;
  12490. return result;
  12491. }
  12492. let toFixedFrame = Matrix2.Matrix4.inverseTransformation(
  12493. fixedFrameTransform(center, ellipsoid, ffScratch),
  12494. ffScratch
  12495. );
  12496. let transformCopy = Matrix2.Matrix4.setScale(transform, noScale, hprTransformScratch);
  12497. transformCopy = Matrix2.Matrix4.setTranslation(
  12498. transformCopy,
  12499. Matrix2.Cartesian3.ZERO,
  12500. transformCopy
  12501. );
  12502. toFixedFrame = Matrix2.Matrix4.multiply(toFixedFrame, transformCopy, toFixedFrame);
  12503. let quaternionRotation = Quaternion.fromRotationMatrix(
  12504. Matrix2.Matrix4.getMatrix3(toFixedFrame, hprRotationScratch),
  12505. hprQuaternionScratch
  12506. );
  12507. quaternionRotation = Quaternion.normalize(
  12508. quaternionRotation,
  12509. quaternionRotation
  12510. );
  12511. return HeadingPitchRoll.fromQuaternion(quaternionRotation, result);
  12512. };
  12513. const gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  12514. const gmstConstant1 = 8640184.812866;
  12515. const gmstConstant2 = 0.093104;
  12516. const gmstConstant3 = -6.2e-6;
  12517. const rateCoef = 1.1772758384668e-19;
  12518. const wgs84WRPrecessing = 7.2921158553e-5;
  12519. const twoPiOverSecondsInDay = ComponentDatatype.CesiumMath.TWO_PI / 86400.0;
  12520. let dateInUtc = new JulianDate();
  12521. /**
  12522. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  12523. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  12524. *
  12525. * @param {JulianDate} date The time at which to compute the rotation matrix.
  12526. * @param {Matrix3} [result] The object onto which to store the result.
  12527. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  12528. *
  12529. * @example
  12530. * //Set the view to the inertial frame.
  12531. * scene.postUpdate.addEventListener(function(scene, time) {
  12532. * const now = Cesium.JulianDate.now();
  12533. * const offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  12534. * const transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  12535. * const inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  12536. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  12537. * camera.lookAtTransform(transform, offset);
  12538. * });
  12539. */
  12540. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  12541. //>>includeStart('debug', pragmas.debug);
  12542. if (!defaultValue.defined(date)) {
  12543. throw new RuntimeError.DeveloperError("date is required.");
  12544. }
  12545. //>>includeEnd('debug');
  12546. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  12547. // We do not want to use the function like convertTaiToUtc in JulianDate because
  12548. // we explicitly do not want to fail when inside the leap second.
  12549. dateInUtc = JulianDate.addSeconds(
  12550. date,
  12551. -JulianDate.computeTaiMinusUtc(date),
  12552. dateInUtc
  12553. );
  12554. const utcDayNumber = dateInUtc.dayNumber;
  12555. const utcSecondsIntoDay = dateInUtc.secondsOfDay;
  12556. let t;
  12557. const diffDays = utcDayNumber - 2451545;
  12558. if (utcSecondsIntoDay >= 43200.0) {
  12559. t = (diffDays + 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  12560. } else {
  12561. t = (diffDays - 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  12562. }
  12563. const gmst0 =
  12564. gmstConstant0 +
  12565. t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  12566. const angle = (gmst0 * twoPiOverSecondsInDay) % ComponentDatatype.CesiumMath.TWO_PI;
  12567. const ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  12568. const secondsSinceMidnight =
  12569. (utcSecondsIntoDay + TimeConstants$1.SECONDS_PER_DAY * 0.5) %
  12570. TimeConstants$1.SECONDS_PER_DAY;
  12571. const gha = angle + ratio * secondsSinceMidnight;
  12572. const cosGha = Math.cos(gha);
  12573. const sinGha = Math.sin(gha);
  12574. if (!defaultValue.defined(result)) {
  12575. return new Matrix2.Matrix3(
  12576. cosGha,
  12577. sinGha,
  12578. 0.0,
  12579. -sinGha,
  12580. cosGha,
  12581. 0.0,
  12582. 0.0,
  12583. 0.0,
  12584. 1.0
  12585. );
  12586. }
  12587. result[0] = cosGha;
  12588. result[1] = -sinGha;
  12589. result[2] = 0.0;
  12590. result[3] = sinGha;
  12591. result[4] = cosGha;
  12592. result[5] = 0.0;
  12593. result[6] = 0.0;
  12594. result[7] = 0.0;
  12595. result[8] = 1.0;
  12596. return result;
  12597. };
  12598. /**
  12599. * The source of IAU 2006 XYS data, used for computing the transformation between the
  12600. * Fixed and ICRF axes.
  12601. * @type {Iau2006XysData}
  12602. *
  12603. * @see Transforms.computeIcrfToFixedMatrix
  12604. * @see Transforms.computeFixedToIcrfMatrix
  12605. *
  12606. * @private
  12607. */
  12608. Transforms.iau2006XysData = new Iau2006XysData();
  12609. /**
  12610. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  12611. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  12612. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  12613. * @type {EarthOrientationParameters}
  12614. *
  12615. * @see Transforms.computeIcrfToFixedMatrix
  12616. * @see Transforms.computeFixedToIcrfMatrix
  12617. *
  12618. * @private
  12619. */
  12620. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  12621. const ttMinusTai = 32.184;
  12622. const j2000ttDays = 2451545.0;
  12623. /**
  12624. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  12625. * direction, over a given interval. This function returns a promise that, when resolved,
  12626. * indicates that the preload has completed.
  12627. *
  12628. * @param {TimeInterval} timeInterval The interval to preload.
  12629. * @returns {Promise<void>} A promise that, when resolved, indicates that the preload has completed
  12630. * and evaluation of the transformation between the fixed and ICRF axes will
  12631. * no longer return undefined for a time inside the interval.
  12632. *
  12633. *
  12634. * @example
  12635. * const interval = new Cesium.TimeInterval(...);
  12636. * Promise.resolve(Cesium.Transforms.preloadIcrfFixed(interval)).then(function() {
  12637. * // the data is now loaded
  12638. * });
  12639. *
  12640. * @see Transforms.computeIcrfToFixedMatrix
  12641. * @see Transforms.computeFixedToIcrfMatrix
  12642. */
  12643. Transforms.preloadIcrfFixed = function (timeInterval) {
  12644. const startDayTT = timeInterval.start.dayNumber;
  12645. const startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  12646. const stopDayTT = timeInterval.stop.dayNumber;
  12647. const stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  12648. const xysPromise = Transforms.iau2006XysData.preload(
  12649. startDayTT,
  12650. startSecondTT,
  12651. stopDayTT,
  12652. stopSecondTT
  12653. );
  12654. const eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  12655. return Promise.all([xysPromise, eopPromise]);
  12656. };
  12657. /**
  12658. * Computes a rotation matrix to transform a point or vector from the International Celestial
  12659. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  12660. * at a given time. This function may return undefined if the data necessary to
  12661. * do the transformation is not yet loaded.
  12662. *
  12663. * @param {JulianDate} date The time at which to compute the rotation matrix.
  12664. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  12665. * not specified, a new instance is created and returned.
  12666. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  12667. * transformation is not yet loaded.
  12668. *
  12669. *
  12670. * @example
  12671. * scene.postUpdate.addEventListener(function(scene, time) {
  12672. * // View in ICRF.
  12673. * const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  12674. * if (Cesium.defined(icrfToFixed)) {
  12675. * const offset = Cesium.Cartesian3.clone(camera.position);
  12676. * const transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
  12677. * camera.lookAtTransform(transform, offset);
  12678. * }
  12679. * });
  12680. *
  12681. * @see Transforms.preloadIcrfFixed
  12682. */
  12683. Transforms.computeIcrfToFixedMatrix = function (date, result) {
  12684. //>>includeStart('debug', pragmas.debug);
  12685. if (!defaultValue.defined(date)) {
  12686. throw new RuntimeError.DeveloperError("date is required.");
  12687. }
  12688. //>>includeEnd('debug');
  12689. if (!defaultValue.defined(result)) {
  12690. result = new Matrix2.Matrix3();
  12691. }
  12692. const fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  12693. if (!defaultValue.defined(fixedToIcrfMtx)) {
  12694. return undefined;
  12695. }
  12696. return Matrix2.Matrix3.transpose(fixedToIcrfMtx, result);
  12697. };
  12698. const xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  12699. const eopScratch = new EarthOrientationParametersSample(
  12700. 0.0,
  12701. 0.0,
  12702. 0.0,
  12703. 0.0,
  12704. 0.0);
  12705. const rotation1Scratch = new Matrix2.Matrix3();
  12706. const rotation2Scratch = new Matrix2.Matrix3();
  12707. /**
  12708. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  12709. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  12710. * at a given time. This function may return undefined if the data necessary to
  12711. * do the transformation is not yet loaded.
  12712. *
  12713. * @param {JulianDate} date The time at which to compute the rotation matrix.
  12714. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  12715. * not specified, a new instance is created and returned.
  12716. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  12717. * transformation is not yet loaded.
  12718. *
  12719. *
  12720. * @example
  12721. * // Transform a point from the ICRF axes to the Fixed axes.
  12722. * const now = Cesium.JulianDate.now();
  12723. * const pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12724. * const fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  12725. * let pointInInertial = new Cesium.Cartesian3();
  12726. * if (Cesium.defined(fixedToIcrf)) {
  12727. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  12728. * }
  12729. *
  12730. * @see Transforms.preloadIcrfFixed
  12731. */
  12732. Transforms.computeFixedToIcrfMatrix = function (date, result) {
  12733. //>>includeStart('debug', pragmas.debug);
  12734. if (!defaultValue.defined(date)) {
  12735. throw new RuntimeError.DeveloperError("date is required.");
  12736. }
  12737. //>>includeEnd('debug');
  12738. if (!defaultValue.defined(result)) {
  12739. result = new Matrix2.Matrix3();
  12740. }
  12741. // Compute pole wander
  12742. const eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  12743. if (!defaultValue.defined(eop)) {
  12744. return undefined;
  12745. }
  12746. // There is no external conversion to Terrestrial Time (TT).
  12747. // So use International Atomic Time (TAI) and convert using offsets.
  12748. // Here we are assuming that dayTT and secondTT are positive
  12749. const dayTT = date.dayNumber;
  12750. // It's possible here that secondTT could roll over 86400
  12751. // This does not seem to affect the precision (unit tests check for this)
  12752. const secondTT = date.secondsOfDay + ttMinusTai;
  12753. const xys = Transforms.iau2006XysData.computeXysRadians(
  12754. dayTT,
  12755. secondTT,
  12756. xysScratch
  12757. );
  12758. if (!defaultValue.defined(xys)) {
  12759. return undefined;
  12760. }
  12761. const x = xys.x + eop.xPoleOffset;
  12762. const y = xys.y + eop.yPoleOffset;
  12763. // Compute XYS rotation
  12764. const a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  12765. const rotation1 = rotation1Scratch;
  12766. rotation1[0] = 1.0 - a * x * x;
  12767. rotation1[3] = -a * x * y;
  12768. rotation1[6] = x;
  12769. rotation1[1] = -a * x * y;
  12770. rotation1[4] = 1 - a * y * y;
  12771. rotation1[7] = y;
  12772. rotation1[2] = -x;
  12773. rotation1[5] = -y;
  12774. rotation1[8] = 1 - a * (x * x + y * y);
  12775. const rotation2 = Matrix2.Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  12776. const matrixQ = Matrix2.Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  12777. // Similar to TT conversions above
  12778. // It's possible here that secondTT could roll over 86400
  12779. // This does not seem to affect the precision (unit tests check for this)
  12780. const dateUt1day = date.dayNumber;
  12781. const dateUt1sec =
  12782. date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  12783. // Compute Earth rotation angle
  12784. // The IERS standard for era is
  12785. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  12786. // where
  12787. // Tu = JulianDateInUt1 - 2451545.0
  12788. // However, you get much more precision if you make the following simplification
  12789. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  12790. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  12791. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  12792. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  12793. const daysSinceJ2000 = dateUt1day - 2451545;
  12794. const fractionOfDay = dateUt1sec / TimeConstants$1.SECONDS_PER_DAY;
  12795. let era =
  12796. 0.779057273264 +
  12797. fractionOfDay +
  12798. 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  12799. era = (era % 1.0) * ComponentDatatype.CesiumMath.TWO_PI;
  12800. const earthRotation = Matrix2.Matrix3.fromRotationZ(era, rotation2Scratch);
  12801. // pseudoFixed to ICRF
  12802. const pfToIcrf = Matrix2.Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  12803. // Compute pole wander matrix
  12804. const cosxp = Math.cos(eop.xPoleWander);
  12805. const cosyp = Math.cos(eop.yPoleWander);
  12806. const sinxp = Math.sin(eop.xPoleWander);
  12807. const sinyp = Math.sin(eop.yPoleWander);
  12808. let ttt = dayTT - j2000ttDays + secondTT / TimeConstants$1.SECONDS_PER_DAY;
  12809. ttt /= 36525.0;
  12810. // approximate sp value in rad
  12811. const sp = (-47.0e-6 * ttt * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE) / 3600.0;
  12812. const cossp = Math.cos(sp);
  12813. const sinsp = Math.sin(sp);
  12814. const fToPfMtx = rotation2Scratch;
  12815. fToPfMtx[0] = cosxp * cossp;
  12816. fToPfMtx[1] = cosxp * sinsp;
  12817. fToPfMtx[2] = sinxp;
  12818. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  12819. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  12820. fToPfMtx[5] = -sinyp * cosxp;
  12821. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  12822. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  12823. fToPfMtx[8] = cosyp * cosxp;
  12824. return Matrix2.Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  12825. };
  12826. const pointToWindowCoordinatesTemp = new Matrix2.Cartesian4();
  12827. /**
  12828. * Transform a point from model coordinates to window coordinates.
  12829. *
  12830. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  12831. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  12832. * @param {Cartesian3} point The point to transform.
  12833. * @param {Cartesian2} [result] The object onto which to store the result.
  12834. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  12835. */
  12836. Transforms.pointToWindowCoordinates = function (
  12837. modelViewProjectionMatrix,
  12838. viewportTransformation,
  12839. point,
  12840. result
  12841. ) {
  12842. result = Transforms.pointToGLWindowCoordinates(
  12843. modelViewProjectionMatrix,
  12844. viewportTransformation,
  12845. point,
  12846. result
  12847. );
  12848. result.y = 2.0 * viewportTransformation[5] - result.y;
  12849. return result;
  12850. };
  12851. /**
  12852. * @private
  12853. */
  12854. Transforms.pointToGLWindowCoordinates = function (
  12855. modelViewProjectionMatrix,
  12856. viewportTransformation,
  12857. point,
  12858. result
  12859. ) {
  12860. //>>includeStart('debug', pragmas.debug);
  12861. if (!defaultValue.defined(modelViewProjectionMatrix)) {
  12862. throw new RuntimeError.DeveloperError("modelViewProjectionMatrix is required.");
  12863. }
  12864. if (!defaultValue.defined(viewportTransformation)) {
  12865. throw new RuntimeError.DeveloperError("viewportTransformation is required.");
  12866. }
  12867. if (!defaultValue.defined(point)) {
  12868. throw new RuntimeError.DeveloperError("point is required.");
  12869. }
  12870. //>>includeEnd('debug');
  12871. if (!defaultValue.defined(result)) {
  12872. result = new Matrix2.Cartesian2();
  12873. }
  12874. const tmp = pointToWindowCoordinatesTemp;
  12875. Matrix2.Matrix4.multiplyByVector(
  12876. modelViewProjectionMatrix,
  12877. Matrix2.Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp),
  12878. tmp
  12879. );
  12880. Matrix2.Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  12881. Matrix2.Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  12882. return Matrix2.Cartesian2.fromCartesian4(tmp, result);
  12883. };
  12884. const normalScratch = new Matrix2.Cartesian3();
  12885. const rightScratch = new Matrix2.Cartesian3();
  12886. const upScratch = new Matrix2.Cartesian3();
  12887. /**
  12888. * Transform a position and velocity to a rotation matrix.
  12889. *
  12890. * @param {Cartesian3} position The position to transform.
  12891. * @param {Cartesian3} velocity The velocity vector to transform.
  12892. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12893. * @param {Matrix3} [result] The object onto which to store the result.
  12894. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  12895. */
  12896. Transforms.rotationMatrixFromPositionVelocity = function (
  12897. position,
  12898. velocity,
  12899. ellipsoid,
  12900. result
  12901. ) {
  12902. //>>includeStart('debug', pragmas.debug);
  12903. if (!defaultValue.defined(position)) {
  12904. throw new RuntimeError.DeveloperError("position is required.");
  12905. }
  12906. if (!defaultValue.defined(velocity)) {
  12907. throw new RuntimeError.DeveloperError("velocity is required.");
  12908. }
  12909. //>>includeEnd('debug');
  12910. const normal = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84).geodeticSurfaceNormal(
  12911. position,
  12912. normalScratch
  12913. );
  12914. let right = Matrix2.Cartesian3.cross(velocity, normal, rightScratch);
  12915. if (Matrix2.Cartesian3.equalsEpsilon(right, Matrix2.Cartesian3.ZERO, ComponentDatatype.CesiumMath.EPSILON6)) {
  12916. right = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, right);
  12917. }
  12918. const up = Matrix2.Cartesian3.cross(right, velocity, upScratch);
  12919. Matrix2.Cartesian3.normalize(up, up);
  12920. Matrix2.Cartesian3.cross(velocity, up, right);
  12921. Matrix2.Cartesian3.negate(right, right);
  12922. Matrix2.Cartesian3.normalize(right, right);
  12923. if (!defaultValue.defined(result)) {
  12924. result = new Matrix2.Matrix3();
  12925. }
  12926. result[0] = velocity.x;
  12927. result[1] = velocity.y;
  12928. result[2] = velocity.z;
  12929. result[3] = right.x;
  12930. result[4] = right.y;
  12931. result[5] = right.z;
  12932. result[6] = up.x;
  12933. result[7] = up.y;
  12934. result[8] = up.z;
  12935. return result;
  12936. };
  12937. const swizzleMatrix = new Matrix2.Matrix4(
  12938. 0.0,
  12939. 0.0,
  12940. 1.0,
  12941. 0.0,
  12942. 1.0,
  12943. 0.0,
  12944. 0.0,
  12945. 0.0,
  12946. 0.0,
  12947. 1.0,
  12948. 0.0,
  12949. 0.0,
  12950. 0.0,
  12951. 0.0,
  12952. 0.0,
  12953. 1.0
  12954. );
  12955. const scratchCartographic = new Matrix2.Cartographic();
  12956. const scratchCartesian3Projection = new Matrix2.Cartesian3();
  12957. const scratchCenter = new Matrix2.Cartesian3();
  12958. const scratchRotation = new Matrix2.Matrix3();
  12959. const scratchFromENU = new Matrix2.Matrix4();
  12960. const scratchToENU = new Matrix2.Matrix4();
  12961. /**
  12962. * @private
  12963. */
  12964. Transforms.basisTo2D = function (projection, matrix, result) {
  12965. //>>includeStart('debug', pragmas.debug);
  12966. if (!defaultValue.defined(projection)) {
  12967. throw new RuntimeError.DeveloperError("projection is required.");
  12968. }
  12969. if (!defaultValue.defined(matrix)) {
  12970. throw new RuntimeError.DeveloperError("matrix is required.");
  12971. }
  12972. if (!defaultValue.defined(result)) {
  12973. throw new RuntimeError.DeveloperError("result is required.");
  12974. }
  12975. //>>includeEnd('debug');
  12976. const rtcCenter = Matrix2.Matrix4.getTranslation(matrix, scratchCenter);
  12977. const ellipsoid = projection.ellipsoid;
  12978. // Get the 2D Center
  12979. const cartographic = ellipsoid.cartesianToCartographic(
  12980. rtcCenter,
  12981. scratchCartographic
  12982. );
  12983. const projectedPosition = projection.project(
  12984. cartographic,
  12985. scratchCartesian3Projection
  12986. );
  12987. Matrix2.Cartesian3.fromElements(
  12988. projectedPosition.z,
  12989. projectedPosition.x,
  12990. projectedPosition.y,
  12991. projectedPosition
  12992. );
  12993. // Assuming the instance are positioned in WGS84, invert the WGS84 transform to get the local transform and then convert to 2D
  12994. const fromENU = Transforms.eastNorthUpToFixedFrame(
  12995. rtcCenter,
  12996. ellipsoid,
  12997. scratchFromENU
  12998. );
  12999. const toENU = Matrix2.Matrix4.inverseTransformation(fromENU, scratchToENU);
  13000. const rotation = Matrix2.Matrix4.getMatrix3(matrix, scratchRotation);
  13001. const local = Matrix2.Matrix4.multiplyByMatrix3(toENU, rotation, result);
  13002. Matrix2.Matrix4.multiply(swizzleMatrix, local, result); // Swap x, y, z for 2D
  13003. Matrix2.Matrix4.setTranslation(result, projectedPosition, result); // Use the projected center
  13004. return result;
  13005. };
  13006. /**
  13007. * @private
  13008. */
  13009. Transforms.wgs84To2DModelMatrix = function (projection, center, result) {
  13010. //>>includeStart('debug', pragmas.debug);
  13011. if (!defaultValue.defined(projection)) {
  13012. throw new RuntimeError.DeveloperError("projection is required.");
  13013. }
  13014. if (!defaultValue.defined(center)) {
  13015. throw new RuntimeError.DeveloperError("center is required.");
  13016. }
  13017. if (!defaultValue.defined(result)) {
  13018. throw new RuntimeError.DeveloperError("result is required.");
  13019. }
  13020. //>>includeEnd('debug');
  13021. const ellipsoid = projection.ellipsoid;
  13022. const fromENU = Transforms.eastNorthUpToFixedFrame(
  13023. center,
  13024. ellipsoid,
  13025. scratchFromENU
  13026. );
  13027. const toENU = Matrix2.Matrix4.inverseTransformation(fromENU, scratchToENU);
  13028. const cartographic = ellipsoid.cartesianToCartographic(
  13029. center,
  13030. scratchCartographic
  13031. );
  13032. const projectedPosition = projection.project(
  13033. cartographic,
  13034. scratchCartesian3Projection
  13035. );
  13036. Matrix2.Cartesian3.fromElements(
  13037. projectedPosition.z,
  13038. projectedPosition.x,
  13039. projectedPosition.y,
  13040. projectedPosition
  13041. );
  13042. const translation = Matrix2.Matrix4.fromTranslation(
  13043. projectedPosition,
  13044. scratchFromENU
  13045. );
  13046. Matrix2.Matrix4.multiply(swizzleMatrix, toENU, result);
  13047. Matrix2.Matrix4.multiply(translation, result, result);
  13048. return result;
  13049. };
  13050. exports.BoundingSphere = BoundingSphere;
  13051. exports.FeatureDetection = FeatureDetection;
  13052. exports.GeographicProjection = GeographicProjection;
  13053. exports.Intersect = Intersect$1;
  13054. exports.Interval = Interval;
  13055. exports.Quaternion = Quaternion;
  13056. exports.Resource = Resource;
  13057. exports.Transforms = Transforms;
  13058. exports.buildModuleUrl = buildModuleUrl;
  13059. }));
  13060. //# sourceMappingURL=Transforms-273eeb44.js.map