Transforms-a076dbe6.js 491 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632
  1. /* This file is automatically rebuilt by the Cesium build process. */
  2. define(['exports', './Matrix2-fc7e9822', './RuntimeError-c581ca93', './defaultValue-94c3e563', './ComponentDatatype-4a60b8d6', './_commonjsHelpers-3aae1032-f55dc0c4', './combine-761d9c3f'], (function (exports, Matrix2, RuntimeError, defaultValue, ComponentDatatype, _commonjsHelpers3aae1032, combine) { 'use strict';
  3. /**
  4. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  5. * them by the {@link Ellipsoid#maximumRadius}. This projection
  6. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  7. * is also known as EPSG:4326.
  8. *
  9. * @alias GeographicProjection
  10. * @constructor
  11. *
  12. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  13. *
  14. * @see WebMercatorProjection
  15. */
  16. function GeographicProjection(ellipsoid) {
  17. this._ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  18. this._semimajorAxis = this._ellipsoid.maximumRadius;
  19. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  20. }
  21. Object.defineProperties(GeographicProjection.prototype, {
  22. /**
  23. * Gets the {@link Ellipsoid}.
  24. *
  25. * @memberof GeographicProjection.prototype
  26. *
  27. * @type {Ellipsoid}
  28. * @readonly
  29. */
  30. ellipsoid: {
  31. get: function () {
  32. return this._ellipsoid;
  33. },
  34. },
  35. });
  36. /**
  37. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  38. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  39. * ellipsoid. Z is the unmodified height.
  40. *
  41. * @param {Cartographic} cartographic The coordinates to project.
  42. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  43. * undefined, a new instance is created and returned.
  44. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  45. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  46. * created and returned.
  47. */
  48. GeographicProjection.prototype.project = function (cartographic, result) {
  49. // Actually this is the special case of equidistant cylindrical called the plate carree
  50. const semimajorAxis = this._semimajorAxis;
  51. const x = cartographic.longitude * semimajorAxis;
  52. const y = cartographic.latitude * semimajorAxis;
  53. const z = cartographic.height;
  54. if (!defaultValue.defined(result)) {
  55. return new Matrix2.Cartesian3(x, y, z);
  56. }
  57. result.x = x;
  58. result.y = y;
  59. result.z = z;
  60. return result;
  61. };
  62. /**
  63. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  64. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  65. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  66. *
  67. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  68. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  69. * undefined, a new instance is created and returned.
  70. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  71. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  72. * created and returned.
  73. */
  74. GeographicProjection.prototype.unproject = function (cartesian, result) {
  75. //>>includeStart('debug', pragmas.debug);
  76. if (!defaultValue.defined(cartesian)) {
  77. throw new RuntimeError.DeveloperError("cartesian is required");
  78. }
  79. //>>includeEnd('debug');
  80. const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  81. const longitude = cartesian.x * oneOverEarthSemimajorAxis;
  82. const latitude = cartesian.y * oneOverEarthSemimajorAxis;
  83. const height = cartesian.z;
  84. if (!defaultValue.defined(result)) {
  85. return new Matrix2.Cartographic(longitude, latitude, height);
  86. }
  87. result.longitude = longitude;
  88. result.latitude = latitude;
  89. result.height = height;
  90. return result;
  91. };
  92. /**
  93. * This enumerated type is used in determining where, relative to the frustum, an
  94. * object is located. The object can either be fully contained within the frustum (INSIDE),
  95. * partially inside the frustum and partially outside (INTERSECTING), or somewhere entirely
  96. * outside of the frustum's 6 planes (OUTSIDE).
  97. *
  98. * @enum {Number}
  99. */
  100. const Intersect = {
  101. /**
  102. * Represents that an object is not contained within the frustum.
  103. *
  104. * @type {Number}
  105. * @constant
  106. */
  107. OUTSIDE: -1,
  108. /**
  109. * Represents that an object intersects one of the frustum's planes.
  110. *
  111. * @type {Number}
  112. * @constant
  113. */
  114. INTERSECTING: 0,
  115. /**
  116. * Represents that an object is fully within the frustum.
  117. *
  118. * @type {Number}
  119. * @constant
  120. */
  121. INSIDE: 1,
  122. };
  123. var Intersect$1 = Object.freeze(Intersect);
  124. /**
  125. * Represents the closed interval [start, stop].
  126. * @alias Interval
  127. * @constructor
  128. *
  129. * @param {Number} [start=0.0] The beginning of the interval.
  130. * @param {Number} [stop=0.0] The end of the interval.
  131. */
  132. function Interval(start, stop) {
  133. /**
  134. * The beginning of the interval.
  135. * @type {Number}
  136. * @default 0.0
  137. */
  138. this.start = defaultValue.defaultValue(start, 0.0);
  139. /**
  140. * The end of the interval.
  141. * @type {Number}
  142. * @default 0.0
  143. */
  144. this.stop = defaultValue.defaultValue(stop, 0.0);
  145. }
  146. /**
  147. * A bounding sphere with a center and a radius.
  148. * @alias BoundingSphere
  149. * @constructor
  150. *
  151. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  152. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  153. *
  154. * @see AxisAlignedBoundingBox
  155. * @see BoundingRectangle
  156. * @see Packable
  157. */
  158. function BoundingSphere(center, radius) {
  159. /**
  160. * The center point of the sphere.
  161. * @type {Cartesian3}
  162. * @default {@link Cartesian3.ZERO}
  163. */
  164. this.center = Matrix2.Cartesian3.clone(defaultValue.defaultValue(center, Matrix2.Cartesian3.ZERO));
  165. /**
  166. * The radius of the sphere.
  167. * @type {Number}
  168. * @default 0.0
  169. */
  170. this.radius = defaultValue.defaultValue(radius, 0.0);
  171. }
  172. const fromPointsXMin = new Matrix2.Cartesian3();
  173. const fromPointsYMin = new Matrix2.Cartesian3();
  174. const fromPointsZMin = new Matrix2.Cartesian3();
  175. const fromPointsXMax = new Matrix2.Cartesian3();
  176. const fromPointsYMax = new Matrix2.Cartesian3();
  177. const fromPointsZMax = new Matrix2.Cartesian3();
  178. const fromPointsCurrentPos = new Matrix2.Cartesian3();
  179. const fromPointsScratch = new Matrix2.Cartesian3();
  180. const fromPointsRitterCenter = new Matrix2.Cartesian3();
  181. const fromPointsMinBoxPt = new Matrix2.Cartesian3();
  182. const fromPointsMaxBoxPt = new Matrix2.Cartesian3();
  183. const fromPointsNaiveCenterScratch = new Matrix2.Cartesian3();
  184. const volumeConstant = (4.0 / 3.0) * ComponentDatatype.CesiumMath.PI;
  185. /**
  186. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  187. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  188. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  189. *
  190. * @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.
  191. * @param {BoundingSphere} [result] The object onto which to store the result.
  192. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  193. *
  194. * @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
  195. */
  196. BoundingSphere.fromPoints = function (positions, result) {
  197. if (!defaultValue.defined(result)) {
  198. result = new BoundingSphere();
  199. }
  200. if (!defaultValue.defined(positions) || positions.length === 0) {
  201. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  202. result.radius = 0.0;
  203. return result;
  204. }
  205. const currentPos = Matrix2.Cartesian3.clone(positions[0], fromPointsCurrentPos);
  206. const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
  207. const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
  208. const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
  209. const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
  210. const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
  211. const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
  212. const numPositions = positions.length;
  213. let i;
  214. for (i = 1; i < numPositions; i++) {
  215. Matrix2.Cartesian3.clone(positions[i], currentPos);
  216. const x = currentPos.x;
  217. const y = currentPos.y;
  218. const z = currentPos.z;
  219. // Store points containing the the smallest and largest components
  220. if (x < xMin.x) {
  221. Matrix2.Cartesian3.clone(currentPos, xMin);
  222. }
  223. if (x > xMax.x) {
  224. Matrix2.Cartesian3.clone(currentPos, xMax);
  225. }
  226. if (y < yMin.y) {
  227. Matrix2.Cartesian3.clone(currentPos, yMin);
  228. }
  229. if (y > yMax.y) {
  230. Matrix2.Cartesian3.clone(currentPos, yMax);
  231. }
  232. if (z < zMin.z) {
  233. Matrix2.Cartesian3.clone(currentPos, zMin);
  234. }
  235. if (z > zMax.z) {
  236. Matrix2.Cartesian3.clone(currentPos, zMax);
  237. }
  238. }
  239. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  240. const xSpan = Matrix2.Cartesian3.magnitudeSquared(
  241. Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  242. );
  243. const ySpan = Matrix2.Cartesian3.magnitudeSquared(
  244. Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  245. );
  246. const zSpan = Matrix2.Cartesian3.magnitudeSquared(
  247. Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  248. );
  249. // Set the diameter endpoints to the largest span.
  250. let diameter1 = xMin;
  251. let diameter2 = xMax;
  252. let maxSpan = xSpan;
  253. if (ySpan > maxSpan) {
  254. maxSpan = ySpan;
  255. diameter1 = yMin;
  256. diameter2 = yMax;
  257. }
  258. if (zSpan > maxSpan) {
  259. maxSpan = zSpan;
  260. diameter1 = zMin;
  261. diameter2 = zMax;
  262. }
  263. // Calculate the center of the initial sphere found by Ritter's algorithm
  264. const ritterCenter = fromPointsRitterCenter;
  265. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  266. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  267. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  268. // Calculate the radius of the initial sphere found by Ritter's algorithm
  269. let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
  270. Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  271. );
  272. let ritterRadius = Math.sqrt(radiusSquared);
  273. // Find the center of the sphere found using the Naive method.
  274. const minBoxPt = fromPointsMinBoxPt;
  275. minBoxPt.x = xMin.x;
  276. minBoxPt.y = yMin.y;
  277. minBoxPt.z = zMin.z;
  278. const maxBoxPt = fromPointsMaxBoxPt;
  279. maxBoxPt.x = xMax.x;
  280. maxBoxPt.y = yMax.y;
  281. maxBoxPt.z = zMax.z;
  282. const naiveCenter = Matrix2.Cartesian3.midpoint(
  283. minBoxPt,
  284. maxBoxPt,
  285. fromPointsNaiveCenterScratch
  286. );
  287. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  288. let naiveRadius = 0;
  289. for (i = 0; i < numPositions; i++) {
  290. Matrix2.Cartesian3.clone(positions[i], currentPos);
  291. // Find the furthest point from the naive center to calculate the naive radius.
  292. const r = Matrix2.Cartesian3.magnitude(
  293. Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  294. );
  295. if (r > naiveRadius) {
  296. naiveRadius = r;
  297. }
  298. // Make adjustments to the Ritter Sphere to include all points.
  299. const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
  300. Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  301. );
  302. if (oldCenterToPointSquared > radiusSquared) {
  303. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  304. // Calculate new radius to include the point that lies outside
  305. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  306. radiusSquared = ritterRadius * ritterRadius;
  307. // Calculate center of new Ritter sphere
  308. const oldToNew = oldCenterToPoint - ritterRadius;
  309. ritterCenter.x =
  310. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  311. oldCenterToPoint;
  312. ritterCenter.y =
  313. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  314. oldCenterToPoint;
  315. ritterCenter.z =
  316. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  317. oldCenterToPoint;
  318. }
  319. }
  320. if (ritterRadius < naiveRadius) {
  321. Matrix2.Cartesian3.clone(ritterCenter, result.center);
  322. result.radius = ritterRadius;
  323. } else {
  324. Matrix2.Cartesian3.clone(naiveCenter, result.center);
  325. result.radius = naiveRadius;
  326. }
  327. return result;
  328. };
  329. const defaultProjection = new GeographicProjection();
  330. const fromRectangle2DLowerLeft = new Matrix2.Cartesian3();
  331. const fromRectangle2DUpperRight = new Matrix2.Cartesian3();
  332. const fromRectangle2DSouthwest = new Matrix2.Cartographic();
  333. const fromRectangle2DNortheast = new Matrix2.Cartographic();
  334. /**
  335. * Computes a bounding sphere from a rectangle projected in 2D.
  336. *
  337. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  338. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  339. * @param {BoundingSphere} [result] The object onto which to store the result.
  340. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  341. */
  342. BoundingSphere.fromRectangle2D = function (rectangle, projection, result) {
  343. return BoundingSphere.fromRectangleWithHeights2D(
  344. rectangle,
  345. projection,
  346. 0.0,
  347. 0.0,
  348. result
  349. );
  350. };
  351. /**
  352. * Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
  353. * object's minimum and maximum heights over the rectangle.
  354. *
  355. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  356. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  357. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  358. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  359. * @param {BoundingSphere} [result] The object onto which to store the result.
  360. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  361. */
  362. BoundingSphere.fromRectangleWithHeights2D = function (
  363. rectangle,
  364. projection,
  365. minimumHeight,
  366. maximumHeight,
  367. result
  368. ) {
  369. if (!defaultValue.defined(result)) {
  370. result = new BoundingSphere();
  371. }
  372. if (!defaultValue.defined(rectangle)) {
  373. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  374. result.radius = 0.0;
  375. return result;
  376. }
  377. projection = defaultValue.defaultValue(projection, defaultProjection);
  378. Matrix2.Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  379. fromRectangle2DSouthwest.height = minimumHeight;
  380. Matrix2.Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  381. fromRectangle2DNortheast.height = maximumHeight;
  382. const lowerLeft = projection.project(
  383. fromRectangle2DSouthwest,
  384. fromRectangle2DLowerLeft
  385. );
  386. const upperRight = projection.project(
  387. fromRectangle2DNortheast,
  388. fromRectangle2DUpperRight
  389. );
  390. const width = upperRight.x - lowerLeft.x;
  391. const height = upperRight.y - lowerLeft.y;
  392. const elevation = upperRight.z - lowerLeft.z;
  393. result.radius =
  394. Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  395. const center = result.center;
  396. center.x = lowerLeft.x + width * 0.5;
  397. center.y = lowerLeft.y + height * 0.5;
  398. center.z = lowerLeft.z + elevation * 0.5;
  399. return result;
  400. };
  401. const fromRectangle3DScratch = [];
  402. /**
  403. * Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
  404. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  405. *
  406. * @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
  407. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  408. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  409. * @param {BoundingSphere} [result] The object onto which to store the result.
  410. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  411. */
  412. BoundingSphere.fromRectangle3D = function (
  413. rectangle,
  414. ellipsoid,
  415. surfaceHeight,
  416. result
  417. ) {
  418. ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  419. surfaceHeight = defaultValue.defaultValue(surfaceHeight, 0.0);
  420. if (!defaultValue.defined(result)) {
  421. result = new BoundingSphere();
  422. }
  423. if (!defaultValue.defined(rectangle)) {
  424. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  425. result.radius = 0.0;
  426. return result;
  427. }
  428. const positions = Matrix2.Rectangle.subsample(
  429. rectangle,
  430. ellipsoid,
  431. surfaceHeight,
  432. fromRectangle3DScratch
  433. );
  434. return BoundingSphere.fromPoints(positions, result);
  435. };
  436. /**
  437. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  438. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  439. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  440. * ensure a tight fit.
  441. *
  442. * @param {Number[]} [positions] An array of points that the bounding sphere will enclose. Each point
  443. * is formed from three elements in the array in the order X, Y, Z.
  444. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  445. * origin of the coordinate system. This is useful when the positions are to be used for
  446. * relative-to-center (RTC) rendering.
  447. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  448. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  449. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  450. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  451. * the stride is 5, however, two array elements are skipped and the next position begins at array
  452. * index 5.
  453. * @param {BoundingSphere} [result] The object onto which to store the result.
  454. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  455. *
  456. * @example
  457. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  458. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  459. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  460. * const center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  461. * const points = [1.0, 2.0, 3.0, 0.1, 0.2,
  462. * 4.0, 5.0, 6.0, 0.1, 0.2,
  463. * 7.0, 8.0, 9.0, 0.1, 0.2];
  464. * const sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  465. *
  466. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  467. */
  468. BoundingSphere.fromVertices = function (positions, center, stride, result) {
  469. if (!defaultValue.defined(result)) {
  470. result = new BoundingSphere();
  471. }
  472. if (!defaultValue.defined(positions) || positions.length === 0) {
  473. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  474. result.radius = 0.0;
  475. return result;
  476. }
  477. center = defaultValue.defaultValue(center, Matrix2.Cartesian3.ZERO);
  478. stride = defaultValue.defaultValue(stride, 3);
  479. //>>includeStart('debug', pragmas.debug);
  480. RuntimeError.Check.typeOf.number.greaterThanOrEquals("stride", stride, 3);
  481. //>>includeEnd('debug');
  482. const currentPos = fromPointsCurrentPos;
  483. currentPos.x = positions[0] + center.x;
  484. currentPos.y = positions[1] + center.y;
  485. currentPos.z = positions[2] + center.z;
  486. const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
  487. const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
  488. const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
  489. const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
  490. const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
  491. const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
  492. const numElements = positions.length;
  493. let i;
  494. for (i = 0; i < numElements; i += stride) {
  495. const x = positions[i] + center.x;
  496. const y = positions[i + 1] + center.y;
  497. const z = positions[i + 2] + center.z;
  498. currentPos.x = x;
  499. currentPos.y = y;
  500. currentPos.z = z;
  501. // Store points containing the the smallest and largest components
  502. if (x < xMin.x) {
  503. Matrix2.Cartesian3.clone(currentPos, xMin);
  504. }
  505. if (x > xMax.x) {
  506. Matrix2.Cartesian3.clone(currentPos, xMax);
  507. }
  508. if (y < yMin.y) {
  509. Matrix2.Cartesian3.clone(currentPos, yMin);
  510. }
  511. if (y > yMax.y) {
  512. Matrix2.Cartesian3.clone(currentPos, yMax);
  513. }
  514. if (z < zMin.z) {
  515. Matrix2.Cartesian3.clone(currentPos, zMin);
  516. }
  517. if (z > zMax.z) {
  518. Matrix2.Cartesian3.clone(currentPos, zMax);
  519. }
  520. }
  521. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  522. const xSpan = Matrix2.Cartesian3.magnitudeSquared(
  523. Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  524. );
  525. const ySpan = Matrix2.Cartesian3.magnitudeSquared(
  526. Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  527. );
  528. const zSpan = Matrix2.Cartesian3.magnitudeSquared(
  529. Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  530. );
  531. // Set the diameter endpoints to the largest span.
  532. let diameter1 = xMin;
  533. let diameter2 = xMax;
  534. let maxSpan = xSpan;
  535. if (ySpan > maxSpan) {
  536. maxSpan = ySpan;
  537. diameter1 = yMin;
  538. diameter2 = yMax;
  539. }
  540. if (zSpan > maxSpan) {
  541. maxSpan = zSpan;
  542. diameter1 = zMin;
  543. diameter2 = zMax;
  544. }
  545. // Calculate the center of the initial sphere found by Ritter's algorithm
  546. const ritterCenter = fromPointsRitterCenter;
  547. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  548. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  549. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  550. // Calculate the radius of the initial sphere found by Ritter's algorithm
  551. let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
  552. Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  553. );
  554. let ritterRadius = Math.sqrt(radiusSquared);
  555. // Find the center of the sphere found using the Naive method.
  556. const minBoxPt = fromPointsMinBoxPt;
  557. minBoxPt.x = xMin.x;
  558. minBoxPt.y = yMin.y;
  559. minBoxPt.z = zMin.z;
  560. const maxBoxPt = fromPointsMaxBoxPt;
  561. maxBoxPt.x = xMax.x;
  562. maxBoxPt.y = yMax.y;
  563. maxBoxPt.z = zMax.z;
  564. const naiveCenter = Matrix2.Cartesian3.midpoint(
  565. minBoxPt,
  566. maxBoxPt,
  567. fromPointsNaiveCenterScratch
  568. );
  569. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  570. let naiveRadius = 0;
  571. for (i = 0; i < numElements; i += stride) {
  572. currentPos.x = positions[i] + center.x;
  573. currentPos.y = positions[i + 1] + center.y;
  574. currentPos.z = positions[i + 2] + center.z;
  575. // Find the furthest point from the naive center to calculate the naive radius.
  576. const r = Matrix2.Cartesian3.magnitude(
  577. Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  578. );
  579. if (r > naiveRadius) {
  580. naiveRadius = r;
  581. }
  582. // Make adjustments to the Ritter Sphere to include all points.
  583. const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
  584. Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  585. );
  586. if (oldCenterToPointSquared > radiusSquared) {
  587. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  588. // Calculate new radius to include the point that lies outside
  589. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  590. radiusSquared = ritterRadius * ritterRadius;
  591. // Calculate center of new Ritter sphere
  592. const oldToNew = oldCenterToPoint - ritterRadius;
  593. ritterCenter.x =
  594. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  595. oldCenterToPoint;
  596. ritterCenter.y =
  597. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  598. oldCenterToPoint;
  599. ritterCenter.z =
  600. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  601. oldCenterToPoint;
  602. }
  603. }
  604. if (ritterRadius < naiveRadius) {
  605. Matrix2.Cartesian3.clone(ritterCenter, result.center);
  606. result.radius = ritterRadius;
  607. } else {
  608. Matrix2.Cartesian3.clone(naiveCenter, result.center);
  609. result.radius = naiveRadius;
  610. }
  611. return result;
  612. };
  613. /**
  614. * Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
  615. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  616. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  617. * ensure a tight fit.
  618. *
  619. * @param {Number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  620. * is formed from three elements in the array in the order X, Y, Z.
  621. * @param {Number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  622. * is formed from three elements in the array in the order X, Y, Z.
  623. * @param {BoundingSphere} [result] The object onto which to store the result.
  624. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  625. *
  626. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  627. */
  628. BoundingSphere.fromEncodedCartesianVertices = function (
  629. positionsHigh,
  630. positionsLow,
  631. result
  632. ) {
  633. if (!defaultValue.defined(result)) {
  634. result = new BoundingSphere();
  635. }
  636. if (
  637. !defaultValue.defined(positionsHigh) ||
  638. !defaultValue.defined(positionsLow) ||
  639. positionsHigh.length !== positionsLow.length ||
  640. positionsHigh.length === 0
  641. ) {
  642. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  643. result.radius = 0.0;
  644. return result;
  645. }
  646. const currentPos = fromPointsCurrentPos;
  647. currentPos.x = positionsHigh[0] + positionsLow[0];
  648. currentPos.y = positionsHigh[1] + positionsLow[1];
  649. currentPos.z = positionsHigh[2] + positionsLow[2];
  650. const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
  651. const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
  652. const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
  653. const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
  654. const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
  655. const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
  656. const numElements = positionsHigh.length;
  657. let i;
  658. for (i = 0; i < numElements; i += 3) {
  659. const x = positionsHigh[i] + positionsLow[i];
  660. const y = positionsHigh[i + 1] + positionsLow[i + 1];
  661. const z = positionsHigh[i + 2] + positionsLow[i + 2];
  662. currentPos.x = x;
  663. currentPos.y = y;
  664. currentPos.z = z;
  665. // Store points containing the the smallest and largest components
  666. if (x < xMin.x) {
  667. Matrix2.Cartesian3.clone(currentPos, xMin);
  668. }
  669. if (x > xMax.x) {
  670. Matrix2.Cartesian3.clone(currentPos, xMax);
  671. }
  672. if (y < yMin.y) {
  673. Matrix2.Cartesian3.clone(currentPos, yMin);
  674. }
  675. if (y > yMax.y) {
  676. Matrix2.Cartesian3.clone(currentPos, yMax);
  677. }
  678. if (z < zMin.z) {
  679. Matrix2.Cartesian3.clone(currentPos, zMin);
  680. }
  681. if (z > zMax.z) {
  682. Matrix2.Cartesian3.clone(currentPos, zMax);
  683. }
  684. }
  685. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  686. const xSpan = Matrix2.Cartesian3.magnitudeSquared(
  687. Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  688. );
  689. const ySpan = Matrix2.Cartesian3.magnitudeSquared(
  690. Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  691. );
  692. const zSpan = Matrix2.Cartesian3.magnitudeSquared(
  693. Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  694. );
  695. // Set the diameter endpoints to the largest span.
  696. let diameter1 = xMin;
  697. let diameter2 = xMax;
  698. let maxSpan = xSpan;
  699. if (ySpan > maxSpan) {
  700. maxSpan = ySpan;
  701. diameter1 = yMin;
  702. diameter2 = yMax;
  703. }
  704. if (zSpan > maxSpan) {
  705. maxSpan = zSpan;
  706. diameter1 = zMin;
  707. diameter2 = zMax;
  708. }
  709. // Calculate the center of the initial sphere found by Ritter's algorithm
  710. const ritterCenter = fromPointsRitterCenter;
  711. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  712. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  713. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  714. // Calculate the radius of the initial sphere found by Ritter's algorithm
  715. let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
  716. Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  717. );
  718. let ritterRadius = Math.sqrt(radiusSquared);
  719. // Find the center of the sphere found using the Naive method.
  720. const minBoxPt = fromPointsMinBoxPt;
  721. minBoxPt.x = xMin.x;
  722. minBoxPt.y = yMin.y;
  723. minBoxPt.z = zMin.z;
  724. const maxBoxPt = fromPointsMaxBoxPt;
  725. maxBoxPt.x = xMax.x;
  726. maxBoxPt.y = yMax.y;
  727. maxBoxPt.z = zMax.z;
  728. const naiveCenter = Matrix2.Cartesian3.midpoint(
  729. minBoxPt,
  730. maxBoxPt,
  731. fromPointsNaiveCenterScratch
  732. );
  733. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  734. let naiveRadius = 0;
  735. for (i = 0; i < numElements; i += 3) {
  736. currentPos.x = positionsHigh[i] + positionsLow[i];
  737. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  738. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  739. // Find the furthest point from the naive center to calculate the naive radius.
  740. const r = Matrix2.Cartesian3.magnitude(
  741. Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  742. );
  743. if (r > naiveRadius) {
  744. naiveRadius = r;
  745. }
  746. // Make adjustments to the Ritter Sphere to include all points.
  747. const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
  748. Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  749. );
  750. if (oldCenterToPointSquared > radiusSquared) {
  751. const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  752. // Calculate new radius to include the point that lies outside
  753. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  754. radiusSquared = ritterRadius * ritterRadius;
  755. // Calculate center of new Ritter sphere
  756. const oldToNew = oldCenterToPoint - ritterRadius;
  757. ritterCenter.x =
  758. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  759. oldCenterToPoint;
  760. ritterCenter.y =
  761. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  762. oldCenterToPoint;
  763. ritterCenter.z =
  764. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  765. oldCenterToPoint;
  766. }
  767. }
  768. if (ritterRadius < naiveRadius) {
  769. Matrix2.Cartesian3.clone(ritterCenter, result.center);
  770. result.radius = ritterRadius;
  771. } else {
  772. Matrix2.Cartesian3.clone(naiveCenter, result.center);
  773. result.radius = naiveRadius;
  774. }
  775. return result;
  776. };
  777. /**
  778. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  779. * tightly and fully encompasses the box.
  780. *
  781. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  782. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  783. * @param {BoundingSphere} [result] The object onto which to store the result.
  784. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  785. *
  786. * @example
  787. * // Create a bounding sphere around the unit cube
  788. * const sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  789. */
  790. BoundingSphere.fromCornerPoints = function (corner, oppositeCorner, result) {
  791. //>>includeStart('debug', pragmas.debug);
  792. RuntimeError.Check.typeOf.object("corner", corner);
  793. RuntimeError.Check.typeOf.object("oppositeCorner", oppositeCorner);
  794. //>>includeEnd('debug');
  795. if (!defaultValue.defined(result)) {
  796. result = new BoundingSphere();
  797. }
  798. const center = Matrix2.Cartesian3.midpoint(corner, oppositeCorner, result.center);
  799. result.radius = Matrix2.Cartesian3.distance(center, oppositeCorner);
  800. return result;
  801. };
  802. /**
  803. * Creates a bounding sphere encompassing an ellipsoid.
  804. *
  805. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  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. * const boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  811. */
  812. BoundingSphere.fromEllipsoid = function (ellipsoid, result) {
  813. //>>includeStart('debug', pragmas.debug);
  814. RuntimeError.Check.typeOf.object("ellipsoid", ellipsoid);
  815. //>>includeEnd('debug');
  816. if (!defaultValue.defined(result)) {
  817. result = new BoundingSphere();
  818. }
  819. Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  820. result.radius = ellipsoid.maximumRadius;
  821. return result;
  822. };
  823. const fromBoundingSpheresScratch = new Matrix2.Cartesian3();
  824. /**
  825. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  826. *
  827. * @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
  828. * @param {BoundingSphere} [result] The object onto which to store the result.
  829. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  830. */
  831. BoundingSphere.fromBoundingSpheres = function (boundingSpheres, result) {
  832. if (!defaultValue.defined(result)) {
  833. result = new BoundingSphere();
  834. }
  835. if (!defaultValue.defined(boundingSpheres) || boundingSpheres.length === 0) {
  836. result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
  837. result.radius = 0.0;
  838. return result;
  839. }
  840. const length = boundingSpheres.length;
  841. if (length === 1) {
  842. return BoundingSphere.clone(boundingSpheres[0], result);
  843. }
  844. if (length === 2) {
  845. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  846. }
  847. const positions = [];
  848. let i;
  849. for (i = 0; i < length; i++) {
  850. positions.push(boundingSpheres[i].center);
  851. }
  852. result = BoundingSphere.fromPoints(positions, result);
  853. const center = result.center;
  854. let radius = result.radius;
  855. for (i = 0; i < length; i++) {
  856. const tmp = boundingSpheres[i];
  857. radius = Math.max(
  858. radius,
  859. Matrix2.Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) +
  860. tmp.radius
  861. );
  862. }
  863. result.radius = radius;
  864. return result;
  865. };
  866. const fromOrientedBoundingBoxScratchU = new Matrix2.Cartesian3();
  867. const fromOrientedBoundingBoxScratchV = new Matrix2.Cartesian3();
  868. const fromOrientedBoundingBoxScratchW = new Matrix2.Cartesian3();
  869. /**
  870. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  871. *
  872. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  873. * @param {BoundingSphere} [result] The object onto which to store the result.
  874. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  875. */
  876. BoundingSphere.fromOrientedBoundingBox = function (
  877. orientedBoundingBox,
  878. result
  879. ) {
  880. //>>includeStart('debug', pragmas.debug);
  881. RuntimeError.Check.defined("orientedBoundingBox", orientedBoundingBox);
  882. //>>includeEnd('debug');
  883. if (!defaultValue.defined(result)) {
  884. result = new BoundingSphere();
  885. }
  886. const halfAxes = orientedBoundingBox.halfAxes;
  887. const u = Matrix2.Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  888. const v = Matrix2.Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  889. const w = Matrix2.Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  890. Matrix2.Cartesian3.add(u, v, u);
  891. Matrix2.Cartesian3.add(u, w, u);
  892. result.center = Matrix2.Cartesian3.clone(orientedBoundingBox.center, result.center);
  893. result.radius = Matrix2.Cartesian3.magnitude(u);
  894. return result;
  895. };
  896. const scratchFromTransformationCenter = new Matrix2.Cartesian3();
  897. const scratchFromTransformationScale = new Matrix2.Cartesian3();
  898. /**
  899. * Computes a tight-fitting bounding sphere enclosing the provided affine transformation.
  900. *
  901. * @param {Matrix4} transformation The affine transformation.
  902. * @param {BoundingSphere} [result] The object onto which to store the result.
  903. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  904. */
  905. BoundingSphere.fromTransformation = function (transformation, result) {
  906. //>>includeStart('debug', pragmas.debug);
  907. RuntimeError.Check.typeOf.object("transformation", transformation);
  908. //>>includeEnd('debug');
  909. if (!defaultValue.defined(result)) {
  910. result = new BoundingSphere();
  911. }
  912. const center = Matrix2.Matrix4.getTranslation(
  913. transformation,
  914. scratchFromTransformationCenter
  915. );
  916. const scale = Matrix2.Matrix4.getScale(
  917. transformation,
  918. scratchFromTransformationScale
  919. );
  920. const radius = 0.5 * Matrix2.Cartesian3.magnitude(scale);
  921. result.center = Matrix2.Cartesian3.clone(center, result.center);
  922. result.radius = radius;
  923. return result;
  924. };
  925. /**
  926. * Duplicates a BoundingSphere instance.
  927. *
  928. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  929. * @param {BoundingSphere} [result] The object onto which to store the result.
  930. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  931. */
  932. BoundingSphere.clone = function (sphere, result) {
  933. if (!defaultValue.defined(sphere)) {
  934. return undefined;
  935. }
  936. if (!defaultValue.defined(result)) {
  937. return new BoundingSphere(sphere.center, sphere.radius);
  938. }
  939. result.center = Matrix2.Cartesian3.clone(sphere.center, result.center);
  940. result.radius = sphere.radius;
  941. return result;
  942. };
  943. /**
  944. * The number of elements used to pack the object into an array.
  945. * @type {Number}
  946. */
  947. BoundingSphere.packedLength = 4;
  948. /**
  949. * Stores the provided instance into the provided array.
  950. *
  951. * @param {BoundingSphere} value The value to pack.
  952. * @param {Number[]} array The array to pack into.
  953. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  954. *
  955. * @returns {Number[]} The array that was packed into
  956. */
  957. BoundingSphere.pack = function (value, array, startingIndex) {
  958. //>>includeStart('debug', pragmas.debug);
  959. RuntimeError.Check.typeOf.object("value", value);
  960. RuntimeError.Check.defined("array", array);
  961. //>>includeEnd('debug');
  962. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  963. const center = value.center;
  964. array[startingIndex++] = center.x;
  965. array[startingIndex++] = center.y;
  966. array[startingIndex++] = center.z;
  967. array[startingIndex] = value.radius;
  968. return array;
  969. };
  970. /**
  971. * Retrieves an instance from a packed array.
  972. *
  973. * @param {Number[]} array The packed array.
  974. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  975. * @param {BoundingSphere} [result] The object into which to store the result.
  976. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  977. */
  978. BoundingSphere.unpack = function (array, startingIndex, result) {
  979. //>>includeStart('debug', pragmas.debug);
  980. RuntimeError.Check.defined("array", array);
  981. //>>includeEnd('debug');
  982. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  983. if (!defaultValue.defined(result)) {
  984. result = new BoundingSphere();
  985. }
  986. const center = result.center;
  987. center.x = array[startingIndex++];
  988. center.y = array[startingIndex++];
  989. center.z = array[startingIndex++];
  990. result.radius = array[startingIndex];
  991. return result;
  992. };
  993. const unionScratch = new Matrix2.Cartesian3();
  994. const unionScratchCenter = new Matrix2.Cartesian3();
  995. /**
  996. * Computes a bounding sphere that contains both the left and right bounding spheres.
  997. *
  998. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  999. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  1000. * @param {BoundingSphere} [result] The object onto which to store the result.
  1001. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1002. */
  1003. BoundingSphere.union = function (left, right, result) {
  1004. //>>includeStart('debug', pragmas.debug);
  1005. RuntimeError.Check.typeOf.object("left", left);
  1006. RuntimeError.Check.typeOf.object("right", right);
  1007. //>>includeEnd('debug');
  1008. if (!defaultValue.defined(result)) {
  1009. result = new BoundingSphere();
  1010. }
  1011. const leftCenter = left.center;
  1012. const leftRadius = left.radius;
  1013. const rightCenter = right.center;
  1014. const rightRadius = right.radius;
  1015. const toRightCenter = Matrix2.Cartesian3.subtract(
  1016. rightCenter,
  1017. leftCenter,
  1018. unionScratch
  1019. );
  1020. const centerSeparation = Matrix2.Cartesian3.magnitude(toRightCenter);
  1021. if (leftRadius >= centerSeparation + rightRadius) {
  1022. // Left sphere wins.
  1023. left.clone(result);
  1024. return result;
  1025. }
  1026. if (rightRadius >= centerSeparation + leftRadius) {
  1027. // Right sphere wins.
  1028. right.clone(result);
  1029. return result;
  1030. }
  1031. // There are two tangent points, one on far side of each sphere.
  1032. const halfDistanceBetweenTangentPoints =
  1033. (leftRadius + centerSeparation + rightRadius) * 0.5;
  1034. // Compute the center point halfway between the two tangent points.
  1035. const center = Matrix2.Cartesian3.multiplyByScalar(
  1036. toRightCenter,
  1037. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
  1038. unionScratchCenter
  1039. );
  1040. Matrix2.Cartesian3.add(center, leftCenter, center);
  1041. Matrix2.Cartesian3.clone(center, result.center);
  1042. result.radius = halfDistanceBetweenTangentPoints;
  1043. return result;
  1044. };
  1045. const expandScratch = new Matrix2.Cartesian3();
  1046. /**
  1047. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  1048. *
  1049. * @param {BoundingSphere} sphere A sphere to expand.
  1050. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  1051. * @param {BoundingSphere} [result] The object onto which to store the result.
  1052. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1053. */
  1054. BoundingSphere.expand = function (sphere, point, result) {
  1055. //>>includeStart('debug', pragmas.debug);
  1056. RuntimeError.Check.typeOf.object("sphere", sphere);
  1057. RuntimeError.Check.typeOf.object("point", point);
  1058. //>>includeEnd('debug');
  1059. result = BoundingSphere.clone(sphere, result);
  1060. const radius = Matrix2.Cartesian3.magnitude(
  1061. Matrix2.Cartesian3.subtract(point, result.center, expandScratch)
  1062. );
  1063. if (radius > result.radius) {
  1064. result.radius = radius;
  1065. }
  1066. return result;
  1067. };
  1068. /**
  1069. * Determines which side of a plane a sphere is located.
  1070. *
  1071. * @param {BoundingSphere} sphere The bounding sphere to test.
  1072. * @param {Plane} plane The plane to test against.
  1073. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  1074. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  1075. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  1076. * intersects the plane.
  1077. */
  1078. BoundingSphere.intersectPlane = function (sphere, plane) {
  1079. //>>includeStart('debug', pragmas.debug);
  1080. RuntimeError.Check.typeOf.object("sphere", sphere);
  1081. RuntimeError.Check.typeOf.object("plane", plane);
  1082. //>>includeEnd('debug');
  1083. const center = sphere.center;
  1084. const radius = sphere.radius;
  1085. const normal = plane.normal;
  1086. const distanceToPlane = Matrix2.Cartesian3.dot(normal, center) + plane.distance;
  1087. if (distanceToPlane < -radius) {
  1088. // The center point is negative side of the plane normal
  1089. return Intersect$1.OUTSIDE;
  1090. } else if (distanceToPlane < radius) {
  1091. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  1092. return Intersect$1.INTERSECTING;
  1093. }
  1094. return Intersect$1.INSIDE;
  1095. };
  1096. /**
  1097. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  1098. *
  1099. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  1100. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  1101. * @param {BoundingSphere} [result] The object onto which to store the result.
  1102. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1103. */
  1104. BoundingSphere.transform = function (sphere, transform, result) {
  1105. //>>includeStart('debug', pragmas.debug);
  1106. RuntimeError.Check.typeOf.object("sphere", sphere);
  1107. RuntimeError.Check.typeOf.object("transform", transform);
  1108. //>>includeEnd('debug');
  1109. if (!defaultValue.defined(result)) {
  1110. result = new BoundingSphere();
  1111. }
  1112. result.center = Matrix2.Matrix4.multiplyByPoint(
  1113. transform,
  1114. sphere.center,
  1115. result.center
  1116. );
  1117. result.radius = Matrix2.Matrix4.getMaximumScale(transform) * sphere.radius;
  1118. return result;
  1119. };
  1120. const distanceSquaredToScratch = new Matrix2.Cartesian3();
  1121. /**
  1122. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  1123. *
  1124. * @param {BoundingSphere} sphere The sphere.
  1125. * @param {Cartesian3} cartesian The point
  1126. * @returns {Number} The distance squared from the bounding sphere to the point. Returns 0 if the point is inside the sphere.
  1127. *
  1128. * @example
  1129. * // Sort bounding spheres from back to front
  1130. * spheres.sort(function(a, b) {
  1131. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  1132. * });
  1133. */
  1134. BoundingSphere.distanceSquaredTo = function (sphere, cartesian) {
  1135. //>>includeStart('debug', pragmas.debug);
  1136. RuntimeError.Check.typeOf.object("sphere", sphere);
  1137. RuntimeError.Check.typeOf.object("cartesian", cartesian);
  1138. //>>includeEnd('debug');
  1139. const diff = Matrix2.Cartesian3.subtract(
  1140. sphere.center,
  1141. cartesian,
  1142. distanceSquaredToScratch
  1143. );
  1144. const distance = Matrix2.Cartesian3.magnitude(diff) - sphere.radius;
  1145. if (distance <= 0.0) {
  1146. return 0.0;
  1147. }
  1148. return distance * distance;
  1149. };
  1150. /**
  1151. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  1152. * The transformation matrix is not verified to have a uniform scale of 1.
  1153. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  1154. *
  1155. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  1156. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  1157. * @param {BoundingSphere} [result] The object onto which to store the result.
  1158. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1159. *
  1160. * @example
  1161. * const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  1162. * const boundingSphere = new Cesium.BoundingSphere();
  1163. * const newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  1164. */
  1165. BoundingSphere.transformWithoutScale = function (sphere, transform, result) {
  1166. //>>includeStart('debug', pragmas.debug);
  1167. RuntimeError.Check.typeOf.object("sphere", sphere);
  1168. RuntimeError.Check.typeOf.object("transform", transform);
  1169. //>>includeEnd('debug');
  1170. if (!defaultValue.defined(result)) {
  1171. result = new BoundingSphere();
  1172. }
  1173. result.center = Matrix2.Matrix4.multiplyByPoint(
  1174. transform,
  1175. sphere.center,
  1176. result.center
  1177. );
  1178. result.radius = sphere.radius;
  1179. return result;
  1180. };
  1181. const scratchCartesian3 = new Matrix2.Cartesian3();
  1182. /**
  1183. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  1184. * plus/minus the radius of the bounding sphere.
  1185. * <br>
  1186. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  1187. * closest and farthest planes from position that intersect the bounding sphere.
  1188. *
  1189. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  1190. * @param {Cartesian3} position The position to calculate the distance from.
  1191. * @param {Cartesian3} direction The direction from position.
  1192. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  1193. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  1194. */
  1195. BoundingSphere.computePlaneDistances = function (
  1196. sphere,
  1197. position,
  1198. direction,
  1199. result
  1200. ) {
  1201. //>>includeStart('debug', pragmas.debug);
  1202. RuntimeError.Check.typeOf.object("sphere", sphere);
  1203. RuntimeError.Check.typeOf.object("position", position);
  1204. RuntimeError.Check.typeOf.object("direction", direction);
  1205. //>>includeEnd('debug');
  1206. if (!defaultValue.defined(result)) {
  1207. result = new Interval();
  1208. }
  1209. const toCenter = Matrix2.Cartesian3.subtract(
  1210. sphere.center,
  1211. position,
  1212. scratchCartesian3
  1213. );
  1214. const mag = Matrix2.Cartesian3.dot(direction, toCenter);
  1215. result.start = mag - sphere.radius;
  1216. result.stop = mag + sphere.radius;
  1217. return result;
  1218. };
  1219. const projectTo2DNormalScratch = new Matrix2.Cartesian3();
  1220. const projectTo2DEastScratch = new Matrix2.Cartesian3();
  1221. const projectTo2DNorthScratch = new Matrix2.Cartesian3();
  1222. const projectTo2DWestScratch = new Matrix2.Cartesian3();
  1223. const projectTo2DSouthScratch = new Matrix2.Cartesian3();
  1224. const projectTo2DCartographicScratch = new Matrix2.Cartographic();
  1225. const projectTo2DPositionsScratch = new Array(8);
  1226. for (let n = 0; n < 8; ++n) {
  1227. projectTo2DPositionsScratch[n] = new Matrix2.Cartesian3();
  1228. }
  1229. const projectTo2DProjection = new GeographicProjection();
  1230. /**
  1231. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  1232. *
  1233. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  1234. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  1235. * @param {BoundingSphere} [result] The object onto which to store the result.
  1236. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1237. */
  1238. BoundingSphere.projectTo2D = function (sphere, projection, result) {
  1239. //>>includeStart('debug', pragmas.debug);
  1240. RuntimeError.Check.typeOf.object("sphere", sphere);
  1241. //>>includeEnd('debug');
  1242. projection = defaultValue.defaultValue(projection, projectTo2DProjection);
  1243. const ellipsoid = projection.ellipsoid;
  1244. let center = sphere.center;
  1245. const radius = sphere.radius;
  1246. let normal;
  1247. if (Matrix2.Cartesian3.equals(center, Matrix2.Cartesian3.ZERO)) {
  1248. // Bounding sphere is at the center. The geodetic surface normal is not
  1249. // defined here so pick the x-axis as a fallback.
  1250. normal = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, projectTo2DNormalScratch);
  1251. } else {
  1252. normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  1253. }
  1254. const east = Matrix2.Cartesian3.cross(
  1255. Matrix2.Cartesian3.UNIT_Z,
  1256. normal,
  1257. projectTo2DEastScratch
  1258. );
  1259. Matrix2.Cartesian3.normalize(east, east);
  1260. const north = Matrix2.Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  1261. Matrix2.Cartesian3.normalize(north, north);
  1262. Matrix2.Cartesian3.multiplyByScalar(normal, radius, normal);
  1263. Matrix2.Cartesian3.multiplyByScalar(north, radius, north);
  1264. Matrix2.Cartesian3.multiplyByScalar(east, radius, east);
  1265. const south = Matrix2.Cartesian3.negate(north, projectTo2DSouthScratch);
  1266. const west = Matrix2.Cartesian3.negate(east, projectTo2DWestScratch);
  1267. const positions = projectTo2DPositionsScratch;
  1268. // top NE corner
  1269. let corner = positions[0];
  1270. Matrix2.Cartesian3.add(normal, north, corner);
  1271. Matrix2.Cartesian3.add(corner, east, corner);
  1272. // top NW corner
  1273. corner = positions[1];
  1274. Matrix2.Cartesian3.add(normal, north, corner);
  1275. Matrix2.Cartesian3.add(corner, west, corner);
  1276. // top SW corner
  1277. corner = positions[2];
  1278. Matrix2.Cartesian3.add(normal, south, corner);
  1279. Matrix2.Cartesian3.add(corner, west, corner);
  1280. // top SE corner
  1281. corner = positions[3];
  1282. Matrix2.Cartesian3.add(normal, south, corner);
  1283. Matrix2.Cartesian3.add(corner, east, corner);
  1284. Matrix2.Cartesian3.negate(normal, normal);
  1285. // bottom NE corner
  1286. corner = positions[4];
  1287. Matrix2.Cartesian3.add(normal, north, corner);
  1288. Matrix2.Cartesian3.add(corner, east, corner);
  1289. // bottom NW corner
  1290. corner = positions[5];
  1291. Matrix2.Cartesian3.add(normal, north, corner);
  1292. Matrix2.Cartesian3.add(corner, west, corner);
  1293. // bottom SW corner
  1294. corner = positions[6];
  1295. Matrix2.Cartesian3.add(normal, south, corner);
  1296. Matrix2.Cartesian3.add(corner, west, corner);
  1297. // bottom SE corner
  1298. corner = positions[7];
  1299. Matrix2.Cartesian3.add(normal, south, corner);
  1300. Matrix2.Cartesian3.add(corner, east, corner);
  1301. const length = positions.length;
  1302. for (let i = 0; i < length; ++i) {
  1303. const position = positions[i];
  1304. Matrix2.Cartesian3.add(center, position, position);
  1305. const cartographic = ellipsoid.cartesianToCartographic(
  1306. position,
  1307. projectTo2DCartographicScratch
  1308. );
  1309. projection.project(cartographic, position);
  1310. }
  1311. result = BoundingSphere.fromPoints(positions, result);
  1312. // swizzle center components
  1313. center = result.center;
  1314. const x = center.x;
  1315. const y = center.y;
  1316. const z = center.z;
  1317. center.x = z;
  1318. center.y = x;
  1319. center.z = y;
  1320. return result;
  1321. };
  1322. /**
  1323. * Determines whether or not a sphere is hidden from view by the occluder.
  1324. *
  1325. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  1326. * @param {Occluder} occluder The occluder.
  1327. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  1328. */
  1329. BoundingSphere.isOccluded = function (sphere, occluder) {
  1330. //>>includeStart('debug', pragmas.debug);
  1331. RuntimeError.Check.typeOf.object("sphere", sphere);
  1332. RuntimeError.Check.typeOf.object("occluder", occluder);
  1333. //>>includeEnd('debug');
  1334. return !occluder.isBoundingSphereVisible(sphere);
  1335. };
  1336. /**
  1337. * Compares the provided BoundingSphere componentwise and returns
  1338. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1339. *
  1340. * @param {BoundingSphere} [left] The first BoundingSphere.
  1341. * @param {BoundingSphere} [right] The second BoundingSphere.
  1342. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1343. */
  1344. BoundingSphere.equals = function (left, right) {
  1345. return (
  1346. left === right ||
  1347. (defaultValue.defined(left) &&
  1348. defaultValue.defined(right) &&
  1349. Matrix2.Cartesian3.equals(left.center, right.center) &&
  1350. left.radius === right.radius)
  1351. );
  1352. };
  1353. /**
  1354. * Determines which side of a plane the sphere is located.
  1355. *
  1356. * @param {Plane} plane The plane to test against.
  1357. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  1358. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  1359. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  1360. * intersects the plane.
  1361. */
  1362. BoundingSphere.prototype.intersectPlane = function (plane) {
  1363. return BoundingSphere.intersectPlane(this, plane);
  1364. };
  1365. /**
  1366. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  1367. *
  1368. * @param {Cartesian3} cartesian The point
  1369. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  1370. *
  1371. * @example
  1372. * // Sort bounding spheres from back to front
  1373. * spheres.sort(function(a, b) {
  1374. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  1375. * });
  1376. */
  1377. BoundingSphere.prototype.distanceSquaredTo = function (cartesian) {
  1378. return BoundingSphere.distanceSquaredTo(this, cartesian);
  1379. };
  1380. /**
  1381. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  1382. * plus/minus the radius of the bounding sphere.
  1383. * <br>
  1384. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  1385. * closest and farthest planes from position that intersect the bounding sphere.
  1386. *
  1387. * @param {Cartesian3} position The position to calculate the distance from.
  1388. * @param {Cartesian3} direction The direction from position.
  1389. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  1390. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  1391. */
  1392. BoundingSphere.prototype.computePlaneDistances = function (
  1393. position,
  1394. direction,
  1395. result
  1396. ) {
  1397. return BoundingSphere.computePlaneDistances(
  1398. this,
  1399. position,
  1400. direction,
  1401. result
  1402. );
  1403. };
  1404. /**
  1405. * Determines whether or not a sphere is hidden from view by the occluder.
  1406. *
  1407. * @param {Occluder} occluder The occluder.
  1408. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  1409. */
  1410. BoundingSphere.prototype.isOccluded = function (occluder) {
  1411. return BoundingSphere.isOccluded(this, occluder);
  1412. };
  1413. /**
  1414. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  1415. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1416. *
  1417. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  1418. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  1419. */
  1420. BoundingSphere.prototype.equals = function (right) {
  1421. return BoundingSphere.equals(this, right);
  1422. };
  1423. /**
  1424. * Duplicates this BoundingSphere instance.
  1425. *
  1426. * @param {BoundingSphere} [result] The object onto which to store the result.
  1427. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  1428. */
  1429. BoundingSphere.prototype.clone = function (result) {
  1430. return BoundingSphere.clone(this, result);
  1431. };
  1432. /**
  1433. * Computes the radius of the BoundingSphere.
  1434. * @returns {Number} The radius of the BoundingSphere.
  1435. */
  1436. BoundingSphere.prototype.volume = function () {
  1437. const radius = this.radius;
  1438. return volumeConstant * radius * radius * radius;
  1439. };
  1440. /**
  1441. * A function used to resolve a promise upon completion .
  1442. * @callback defer.resolve
  1443. *
  1444. * @param {*} value The resulting value.
  1445. */
  1446. /**
  1447. * A function used to reject a promise upon failure.
  1448. * @callback defer.reject
  1449. *
  1450. * @param {*} error The error.
  1451. */
  1452. /**
  1453. * An object which contains a promise object, and functions to resolve or reject the promise.
  1454. *
  1455. * @typedef {Object} defer.deferred
  1456. * @property {defer.resolve} resolve Resolves the promise when called.
  1457. * @property {defer.reject} reject Rejects the promise when called.
  1458. * @property {Promise} promise Promise object.
  1459. */
  1460. /**
  1461. * Creates a deferred object, containing a promise object, and functions to resolve or reject the promise.
  1462. * @returns {defer.deferred}
  1463. * @private
  1464. */
  1465. function defer() {
  1466. let resolve;
  1467. let reject;
  1468. const promise = new Promise(function (res, rej) {
  1469. resolve = res;
  1470. reject = rej;
  1471. });
  1472. return {
  1473. resolve: resolve,
  1474. reject: reject,
  1475. promise: promise,
  1476. };
  1477. }
  1478. let _supportsFullscreen;
  1479. const _names = {
  1480. requestFullscreen: undefined,
  1481. exitFullscreen: undefined,
  1482. fullscreenEnabled: undefined,
  1483. fullscreenElement: undefined,
  1484. fullscreenchange: undefined,
  1485. fullscreenerror: undefined,
  1486. };
  1487. /**
  1488. * Browser-independent functions for working with the standard fullscreen API.
  1489. *
  1490. * @namespace Fullscreen
  1491. *
  1492. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  1493. */
  1494. const Fullscreen = {};
  1495. Object.defineProperties(Fullscreen, {
  1496. /**
  1497. * The element that is currently fullscreen, if any. To simply check if the
  1498. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  1499. * @memberof Fullscreen
  1500. * @type {Object}
  1501. * @readonly
  1502. */
  1503. element: {
  1504. get: function () {
  1505. if (!Fullscreen.supportsFullscreen()) {
  1506. return undefined;
  1507. }
  1508. return document[_names.fullscreenElement];
  1509. },
  1510. },
  1511. /**
  1512. * The name of the event on the document that is fired when fullscreen is
  1513. * entered or exited. This event name is intended for use with addEventListener.
  1514. * In your event handler, to determine if the browser is in fullscreen mode or not,
  1515. * use {@link Fullscreen#fullscreen}.
  1516. * @memberof Fullscreen
  1517. * @type {String}
  1518. * @readonly
  1519. */
  1520. changeEventName: {
  1521. get: function () {
  1522. if (!Fullscreen.supportsFullscreen()) {
  1523. return undefined;
  1524. }
  1525. return _names.fullscreenchange;
  1526. },
  1527. },
  1528. /**
  1529. * The name of the event that is fired when a fullscreen error
  1530. * occurs. This event name is intended for use with addEventListener.
  1531. * @memberof Fullscreen
  1532. * @type {String}
  1533. * @readonly
  1534. */
  1535. errorEventName: {
  1536. get: function () {
  1537. if (!Fullscreen.supportsFullscreen()) {
  1538. return undefined;
  1539. }
  1540. return _names.fullscreenerror;
  1541. },
  1542. },
  1543. /**
  1544. * Determine whether the browser will allow an element to be made fullscreen, or not.
  1545. * For example, by default, iframes cannot go fullscreen unless the containing page
  1546. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  1547. * @memberof Fullscreen
  1548. * @type {Boolean}
  1549. * @readonly
  1550. */
  1551. enabled: {
  1552. get: function () {
  1553. if (!Fullscreen.supportsFullscreen()) {
  1554. return undefined;
  1555. }
  1556. return document[_names.fullscreenEnabled];
  1557. },
  1558. },
  1559. /**
  1560. * Determines if the browser is currently in fullscreen mode.
  1561. * @memberof Fullscreen
  1562. * @type {Boolean}
  1563. * @readonly
  1564. */
  1565. fullscreen: {
  1566. get: function () {
  1567. if (!Fullscreen.supportsFullscreen()) {
  1568. return undefined;
  1569. }
  1570. return Fullscreen.element !== null;
  1571. },
  1572. },
  1573. });
  1574. /**
  1575. * Detects whether the browser supports the standard fullscreen API.
  1576. *
  1577. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  1578. * <code>false</code> otherwise.
  1579. */
  1580. Fullscreen.supportsFullscreen = function () {
  1581. if (defaultValue.defined(_supportsFullscreen)) {
  1582. return _supportsFullscreen;
  1583. }
  1584. _supportsFullscreen = false;
  1585. const body = document.body;
  1586. if (typeof body.requestFullscreen === "function") {
  1587. // go with the unprefixed, standard set of names
  1588. _names.requestFullscreen = "requestFullscreen";
  1589. _names.exitFullscreen = "exitFullscreen";
  1590. _names.fullscreenEnabled = "fullscreenEnabled";
  1591. _names.fullscreenElement = "fullscreenElement";
  1592. _names.fullscreenchange = "fullscreenchange";
  1593. _names.fullscreenerror = "fullscreenerror";
  1594. _supportsFullscreen = true;
  1595. return _supportsFullscreen;
  1596. }
  1597. //check for the correct combination of prefix plus the various names that browsers use
  1598. const prefixes = ["webkit", "moz", "o", "ms", "khtml"];
  1599. let name;
  1600. for (let i = 0, len = prefixes.length; i < len; ++i) {
  1601. const prefix = prefixes[i];
  1602. // casing of Fullscreen differs across browsers
  1603. name = `${prefix}RequestFullscreen`;
  1604. if (typeof body[name] === "function") {
  1605. _names.requestFullscreen = name;
  1606. _supportsFullscreen = true;
  1607. } else {
  1608. name = `${prefix}RequestFullScreen`;
  1609. if (typeof body[name] === "function") {
  1610. _names.requestFullscreen = name;
  1611. _supportsFullscreen = true;
  1612. }
  1613. }
  1614. // disagreement about whether it's "exit" as per spec, or "cancel"
  1615. name = `${prefix}ExitFullscreen`;
  1616. if (typeof document[name] === "function") {
  1617. _names.exitFullscreen = name;
  1618. } else {
  1619. name = `${prefix}CancelFullScreen`;
  1620. if (typeof document[name] === "function") {
  1621. _names.exitFullscreen = name;
  1622. }
  1623. }
  1624. // casing of Fullscreen differs across browsers
  1625. name = `${prefix}FullscreenEnabled`;
  1626. if (document[name] !== undefined) {
  1627. _names.fullscreenEnabled = name;
  1628. } else {
  1629. name = `${prefix}FullScreenEnabled`;
  1630. if (document[name] !== undefined) {
  1631. _names.fullscreenEnabled = name;
  1632. }
  1633. }
  1634. // casing of Fullscreen differs across browsers
  1635. name = `${prefix}FullscreenElement`;
  1636. if (document[name] !== undefined) {
  1637. _names.fullscreenElement = name;
  1638. } else {
  1639. name = `${prefix}FullScreenElement`;
  1640. if (document[name] !== undefined) {
  1641. _names.fullscreenElement = name;
  1642. }
  1643. }
  1644. // thankfully, event names are all lowercase per spec
  1645. name = `${prefix}fullscreenchange`;
  1646. // event names do not have 'on' in the front, but the property on the document does
  1647. if (document[`on${name}`] !== undefined) {
  1648. //except on IE
  1649. if (prefix === "ms") {
  1650. name = "MSFullscreenChange";
  1651. }
  1652. _names.fullscreenchange = name;
  1653. }
  1654. name = `${prefix}fullscreenerror`;
  1655. if (document[`on${name}`] !== undefined) {
  1656. //except on IE
  1657. if (prefix === "ms") {
  1658. name = "MSFullscreenError";
  1659. }
  1660. _names.fullscreenerror = name;
  1661. }
  1662. }
  1663. return _supportsFullscreen;
  1664. };
  1665. /**
  1666. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  1667. * If fullscreen mode is not supported by the browser, does nothing.
  1668. *
  1669. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  1670. * @param {Object} [vrDevice] The HMDVRDevice device.
  1671. *
  1672. * @example
  1673. * // Put the entire page into fullscreen.
  1674. * Cesium.Fullscreen.requestFullscreen(document.body)
  1675. *
  1676. * // Place only the Cesium canvas into fullscreen.
  1677. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  1678. */
  1679. Fullscreen.requestFullscreen = function (element, vrDevice) {
  1680. if (!Fullscreen.supportsFullscreen()) {
  1681. return;
  1682. }
  1683. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  1684. };
  1685. /**
  1686. * Asynchronously exits fullscreen mode. If the browser is not currently
  1687. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  1688. */
  1689. Fullscreen.exitFullscreen = function () {
  1690. if (!Fullscreen.supportsFullscreen()) {
  1691. return;
  1692. }
  1693. document[_names.exitFullscreen]();
  1694. };
  1695. //For unit tests
  1696. Fullscreen._names = _names;
  1697. let theNavigator;
  1698. if (typeof navigator !== "undefined") {
  1699. theNavigator = navigator;
  1700. } else {
  1701. theNavigator = {};
  1702. }
  1703. function extractVersion(versionString) {
  1704. const parts = versionString.split(".");
  1705. for (let i = 0, len = parts.length; i < len; ++i) {
  1706. parts[i] = parseInt(parts[i], 10);
  1707. }
  1708. return parts;
  1709. }
  1710. let isChromeResult;
  1711. let chromeVersionResult;
  1712. function isChrome() {
  1713. if (!defaultValue.defined(isChromeResult)) {
  1714. isChromeResult = false;
  1715. // Edge contains Chrome in the user agent too
  1716. if (!isEdge()) {
  1717. const fields = / Chrome\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1718. if (fields !== null) {
  1719. isChromeResult = true;
  1720. chromeVersionResult = extractVersion(fields[1]);
  1721. }
  1722. }
  1723. }
  1724. return isChromeResult;
  1725. }
  1726. function chromeVersion() {
  1727. return isChrome() && chromeVersionResult;
  1728. }
  1729. let isSafariResult;
  1730. let safariVersionResult;
  1731. function isSafari() {
  1732. if (!defaultValue.defined(isSafariResult)) {
  1733. isSafariResult = false;
  1734. // Chrome and Edge contain Safari in the user agent too
  1735. if (
  1736. !isChrome() &&
  1737. !isEdge() &&
  1738. / Safari\/[\.0-9]+/.test(theNavigator.userAgent)
  1739. ) {
  1740. const fields = / Version\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1741. if (fields !== null) {
  1742. isSafariResult = true;
  1743. safariVersionResult = extractVersion(fields[1]);
  1744. }
  1745. }
  1746. }
  1747. return isSafariResult;
  1748. }
  1749. function safariVersion() {
  1750. return isSafari() && safariVersionResult;
  1751. }
  1752. let isWebkitResult;
  1753. let webkitVersionResult;
  1754. function isWebkit() {
  1755. if (!defaultValue.defined(isWebkitResult)) {
  1756. isWebkitResult = false;
  1757. const fields = / AppleWebKit\/([\.0-9]+)(\+?)/.exec(theNavigator.userAgent);
  1758. if (fields !== null) {
  1759. isWebkitResult = true;
  1760. webkitVersionResult = extractVersion(fields[1]);
  1761. webkitVersionResult.isNightly = !!fields[2];
  1762. }
  1763. }
  1764. return isWebkitResult;
  1765. }
  1766. function webkitVersion() {
  1767. return isWebkit() && webkitVersionResult;
  1768. }
  1769. let isInternetExplorerResult;
  1770. let internetExplorerVersionResult;
  1771. function isInternetExplorer() {
  1772. if (!defaultValue.defined(isInternetExplorerResult)) {
  1773. isInternetExplorerResult = false;
  1774. let fields;
  1775. if (theNavigator.appName === "Microsoft Internet Explorer") {
  1776. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  1777. if (fields !== null) {
  1778. isInternetExplorerResult = true;
  1779. internetExplorerVersionResult = extractVersion(fields[1]);
  1780. }
  1781. } else if (theNavigator.appName === "Netscape") {
  1782. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(
  1783. theNavigator.userAgent
  1784. );
  1785. if (fields !== null) {
  1786. isInternetExplorerResult = true;
  1787. internetExplorerVersionResult = extractVersion(fields[1]);
  1788. }
  1789. }
  1790. }
  1791. return isInternetExplorerResult;
  1792. }
  1793. function internetExplorerVersion() {
  1794. return isInternetExplorer() && internetExplorerVersionResult;
  1795. }
  1796. let isEdgeResult;
  1797. let edgeVersionResult;
  1798. function isEdge() {
  1799. if (!defaultValue.defined(isEdgeResult)) {
  1800. isEdgeResult = false;
  1801. const fields = / Edge\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1802. if (fields !== null) {
  1803. isEdgeResult = true;
  1804. edgeVersionResult = extractVersion(fields[1]);
  1805. }
  1806. }
  1807. return isEdgeResult;
  1808. }
  1809. function edgeVersion() {
  1810. return isEdge() && edgeVersionResult;
  1811. }
  1812. let isFirefoxResult;
  1813. let firefoxVersionResult;
  1814. function isFirefox() {
  1815. if (!defaultValue.defined(isFirefoxResult)) {
  1816. isFirefoxResult = false;
  1817. const fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  1818. if (fields !== null) {
  1819. isFirefoxResult = true;
  1820. firefoxVersionResult = extractVersion(fields[1]);
  1821. }
  1822. }
  1823. return isFirefoxResult;
  1824. }
  1825. let isWindowsResult;
  1826. function isWindows() {
  1827. if (!defaultValue.defined(isWindowsResult)) {
  1828. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  1829. }
  1830. return isWindowsResult;
  1831. }
  1832. let isIPadOrIOSResult;
  1833. function isIPadOrIOS() {
  1834. if (!defaultValue.defined(isIPadOrIOSResult)) {
  1835. isIPadOrIOSResult =
  1836. navigator.platform === "iPhone" ||
  1837. navigator.platform === "iPod" ||
  1838. navigator.platform === "iPad";
  1839. }
  1840. return isIPadOrIOSResult;
  1841. }
  1842. function firefoxVersion() {
  1843. return isFirefox() && firefoxVersionResult;
  1844. }
  1845. let hasPointerEvents;
  1846. function supportsPointerEvents() {
  1847. if (!defaultValue.defined(hasPointerEvents)) {
  1848. //While navigator.pointerEnabled is deprecated in the W3C specification
  1849. //we still need to use it if it exists in order to support browsers
  1850. //that rely on it, such as the Windows WebBrowser control which defines
  1851. //PointerEvent but sets navigator.pointerEnabled to false.
  1852. //Firefox disabled because of https://github.com/CesiumGS/cesium/issues/6372
  1853. hasPointerEvents =
  1854. !isFirefox() &&
  1855. typeof PointerEvent !== "undefined" &&
  1856. (!defaultValue.defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  1857. }
  1858. return hasPointerEvents;
  1859. }
  1860. let imageRenderingValueResult;
  1861. let supportsImageRenderingPixelatedResult;
  1862. function supportsImageRenderingPixelated() {
  1863. if (!defaultValue.defined(supportsImageRenderingPixelatedResult)) {
  1864. const canvas = document.createElement("canvas");
  1865. canvas.setAttribute(
  1866. "style",
  1867. "image-rendering: -moz-crisp-edges;" + "image-rendering: pixelated;"
  1868. );
  1869. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  1870. const tmp = canvas.style.imageRendering;
  1871. supportsImageRenderingPixelatedResult = defaultValue.defined(tmp) && tmp !== "";
  1872. if (supportsImageRenderingPixelatedResult) {
  1873. imageRenderingValueResult = tmp;
  1874. }
  1875. }
  1876. return supportsImageRenderingPixelatedResult;
  1877. }
  1878. function imageRenderingValue() {
  1879. return supportsImageRenderingPixelated()
  1880. ? imageRenderingValueResult
  1881. : undefined;
  1882. }
  1883. function supportsWebP() {
  1884. //>>includeStart('debug', pragmas.debug);
  1885. if (!supportsWebP.initialized) {
  1886. throw new RuntimeError.DeveloperError(
  1887. "You must call FeatureDetection.supportsWebP.initialize and wait for the promise to resolve before calling FeatureDetection.supportsWebP"
  1888. );
  1889. }
  1890. //>>includeEnd('debug');
  1891. return supportsWebP._result;
  1892. }
  1893. supportsWebP._promise = undefined;
  1894. supportsWebP._result = undefined;
  1895. supportsWebP.initialize = function () {
  1896. // From https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp
  1897. if (defaultValue.defined(supportsWebP._promise)) {
  1898. return supportsWebP._promise;
  1899. }
  1900. const supportsWebPDeferred = defer();
  1901. supportsWebP._promise = supportsWebPDeferred.promise;
  1902. if (isEdge()) {
  1903. // Edge's WebP support with WebGL is incomplete.
  1904. // See bug report: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/19221241/
  1905. supportsWebP._result = false;
  1906. supportsWebPDeferred.resolve(supportsWebP._result);
  1907. return supportsWebPDeferred.promise;
  1908. }
  1909. const image = new Image();
  1910. image.onload = function () {
  1911. supportsWebP._result = image.width > 0 && image.height > 0;
  1912. supportsWebPDeferred.resolve(supportsWebP._result);
  1913. };
  1914. image.onerror = function () {
  1915. supportsWebP._result = false;
  1916. supportsWebPDeferred.resolve(supportsWebP._result);
  1917. };
  1918. image.src =
  1919. "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
  1920. return supportsWebPDeferred.promise;
  1921. };
  1922. Object.defineProperties(supportsWebP, {
  1923. initialized: {
  1924. get: function () {
  1925. return defaultValue.defined(supportsWebP._result);
  1926. },
  1927. },
  1928. });
  1929. const typedArrayTypes = [];
  1930. if (typeof ArrayBuffer !== "undefined") {
  1931. typedArrayTypes.push(
  1932. Int8Array,
  1933. Uint8Array,
  1934. Int16Array,
  1935. Uint16Array,
  1936. Int32Array,
  1937. Uint32Array,
  1938. Float32Array,
  1939. Float64Array
  1940. );
  1941. if (typeof Uint8ClampedArray !== "undefined") {
  1942. typedArrayTypes.push(Uint8ClampedArray);
  1943. }
  1944. if (typeof Uint8ClampedArray !== "undefined") {
  1945. typedArrayTypes.push(Uint8ClampedArray);
  1946. }
  1947. if (typeof BigInt64Array !== "undefined") {
  1948. // eslint-disable-next-line no-undef
  1949. typedArrayTypes.push(BigInt64Array);
  1950. }
  1951. if (typeof BigUint64Array !== "undefined") {
  1952. // eslint-disable-next-line no-undef
  1953. typedArrayTypes.push(BigUint64Array);
  1954. }
  1955. }
  1956. /**
  1957. * A set of functions to detect whether the current browser supports
  1958. * various features.
  1959. *
  1960. * @namespace FeatureDetection
  1961. */
  1962. const FeatureDetection = {
  1963. isChrome: isChrome,
  1964. chromeVersion: chromeVersion,
  1965. isSafari: isSafari,
  1966. safariVersion: safariVersion,
  1967. isWebkit: isWebkit,
  1968. webkitVersion: webkitVersion,
  1969. isInternetExplorer: isInternetExplorer,
  1970. internetExplorerVersion: internetExplorerVersion,
  1971. isEdge: isEdge,
  1972. edgeVersion: edgeVersion,
  1973. isFirefox: isFirefox,
  1974. firefoxVersion: firefoxVersion,
  1975. isWindows: isWindows,
  1976. isIPadOrIOS: isIPadOrIOS,
  1977. hardwareConcurrency: defaultValue.defaultValue(theNavigator.hardwareConcurrency, 3),
  1978. supportsPointerEvents: supportsPointerEvents,
  1979. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  1980. supportsWebP: supportsWebP,
  1981. imageRenderingValue: imageRenderingValue,
  1982. typedArrayTypes: typedArrayTypes,
  1983. };
  1984. /**
  1985. * Detects whether the current browser supports Basis Universal textures and the web assembly modules needed to transcode them.
  1986. *
  1987. * @param {Scene} scene
  1988. * @returns {Boolean} true if the browser supports web assembly modules and the scene supports Basis Universal textures, false if not.
  1989. */
  1990. FeatureDetection.supportsBasis = function (scene) {
  1991. return FeatureDetection.supportsWebAssembly() && scene.context.supportsBasis;
  1992. };
  1993. /**
  1994. * Detects whether the current browser supports the full screen standard.
  1995. *
  1996. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  1997. *
  1998. * @see Fullscreen
  1999. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  2000. */
  2001. FeatureDetection.supportsFullscreen = function () {
  2002. return Fullscreen.supportsFullscreen();
  2003. };
  2004. /**
  2005. * Detects whether the current browser supports typed arrays.
  2006. *
  2007. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  2008. *
  2009. * @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
  2010. */
  2011. FeatureDetection.supportsTypedArrays = function () {
  2012. return typeof ArrayBuffer !== "undefined";
  2013. };
  2014. /**
  2015. * Detects whether the current browser supports BigInt64Array typed arrays.
  2016. *
  2017. * @returns {Boolean} true if the browser supports BigInt64Array typed arrays, false if not.
  2018. *
  2019. * @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
  2020. */
  2021. FeatureDetection.supportsBigInt64Array = function () {
  2022. return typeof BigInt64Array !== "undefined";
  2023. };
  2024. /**
  2025. * Detects whether the current browser supports BigUint64Array typed arrays.
  2026. *
  2027. * @returns {Boolean} true if the browser supports BigUint64Array typed arrays, false if not.
  2028. *
  2029. * @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
  2030. */
  2031. FeatureDetection.supportsBigUint64Array = function () {
  2032. return typeof BigUint64Array !== "undefined";
  2033. };
  2034. /**
  2035. * Detects whether the current browser supports BigInt.
  2036. *
  2037. * @returns {Boolean} true if the browser supports BigInt, false if not.
  2038. *
  2039. * @see {@link https://tc39.es/ecma262/#sec-bigint-objects|BigInt Specification}
  2040. */
  2041. FeatureDetection.supportsBigInt = function () {
  2042. return typeof BigInt !== "undefined";
  2043. };
  2044. /**
  2045. * Detects whether the current browser supports Web Workers.
  2046. *
  2047. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  2048. *
  2049. * @see {@link http://www.w3.org/TR/workers/}
  2050. */
  2051. FeatureDetection.supportsWebWorkers = function () {
  2052. return typeof Worker !== "undefined";
  2053. };
  2054. /**
  2055. * Detects whether the current browser supports Web Assembly.
  2056. *
  2057. * @returns {Boolean} true if the browsers supports Web Assembly, false if not.
  2058. *
  2059. * @see {@link https://developer.mozilla.org/en-US/docs/WebAssembly}
  2060. */
  2061. FeatureDetection.supportsWebAssembly = function () {
  2062. return typeof WebAssembly !== "undefined";
  2063. };
  2064. /**
  2065. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  2066. * @alias Quaternion
  2067. * @constructor
  2068. *
  2069. * @param {Number} [x=0.0] The X component.
  2070. * @param {Number} [y=0.0] The Y component.
  2071. * @param {Number} [z=0.0] The Z component.
  2072. * @param {Number} [w=0.0] The W component.
  2073. *
  2074. * @see PackableForInterpolation
  2075. */
  2076. function Quaternion(x, y, z, w) {
  2077. /**
  2078. * The X component.
  2079. * @type {Number}
  2080. * @default 0.0
  2081. */
  2082. this.x = defaultValue.defaultValue(x, 0.0);
  2083. /**
  2084. * The Y component.
  2085. * @type {Number}
  2086. * @default 0.0
  2087. */
  2088. this.y = defaultValue.defaultValue(y, 0.0);
  2089. /**
  2090. * The Z component.
  2091. * @type {Number}
  2092. * @default 0.0
  2093. */
  2094. this.z = defaultValue.defaultValue(z, 0.0);
  2095. /**
  2096. * The W component.
  2097. * @type {Number}
  2098. * @default 0.0
  2099. */
  2100. this.w = defaultValue.defaultValue(w, 0.0);
  2101. }
  2102. let fromAxisAngleScratch = new Matrix2.Cartesian3();
  2103. /**
  2104. * Computes a quaternion representing a rotation around an axis.
  2105. *
  2106. * @param {Cartesian3} axis The axis of rotation.
  2107. * @param {Number} angle The angle in radians to rotate around the axis.
  2108. * @param {Quaternion} [result] The object onto which to store the result.
  2109. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2110. */
  2111. Quaternion.fromAxisAngle = function (axis, angle, result) {
  2112. //>>includeStart('debug', pragmas.debug);
  2113. RuntimeError.Check.typeOf.object("axis", axis);
  2114. RuntimeError.Check.typeOf.number("angle", angle);
  2115. //>>includeEnd('debug');
  2116. const halfAngle = angle / 2.0;
  2117. const s = Math.sin(halfAngle);
  2118. fromAxisAngleScratch = Matrix2.Cartesian3.normalize(axis, fromAxisAngleScratch);
  2119. const x = fromAxisAngleScratch.x * s;
  2120. const y = fromAxisAngleScratch.y * s;
  2121. const z = fromAxisAngleScratch.z * s;
  2122. const w = Math.cos(halfAngle);
  2123. if (!defaultValue.defined(result)) {
  2124. return new Quaternion(x, y, z, w);
  2125. }
  2126. result.x = x;
  2127. result.y = y;
  2128. result.z = z;
  2129. result.w = w;
  2130. return result;
  2131. };
  2132. const fromRotationMatrixNext = [1, 2, 0];
  2133. const fromRotationMatrixQuat = new Array(3);
  2134. /**
  2135. * Computes a Quaternion from the provided Matrix3 instance.
  2136. *
  2137. * @param {Matrix3} matrix The rotation matrix.
  2138. * @param {Quaternion} [result] The object onto which to store the result.
  2139. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2140. *
  2141. * @see Matrix3.fromQuaternion
  2142. */
  2143. Quaternion.fromRotationMatrix = function (matrix, result) {
  2144. //>>includeStart('debug', pragmas.debug);
  2145. RuntimeError.Check.typeOf.object("matrix", matrix);
  2146. //>>includeEnd('debug');
  2147. let root;
  2148. let x;
  2149. let y;
  2150. let z;
  2151. let w;
  2152. const m00 = matrix[Matrix2.Matrix3.COLUMN0ROW0];
  2153. const m11 = matrix[Matrix2.Matrix3.COLUMN1ROW1];
  2154. const m22 = matrix[Matrix2.Matrix3.COLUMN2ROW2];
  2155. const trace = m00 + m11 + m22;
  2156. if (trace > 0.0) {
  2157. // |w| > 1/2, may as well choose w > 1/2
  2158. root = Math.sqrt(trace + 1.0); // 2w
  2159. w = 0.5 * root;
  2160. root = 0.5 / root; // 1/(4w)
  2161. x = (matrix[Matrix2.Matrix3.COLUMN1ROW2] - matrix[Matrix2.Matrix3.COLUMN2ROW1]) * root;
  2162. y = (matrix[Matrix2.Matrix3.COLUMN2ROW0] - matrix[Matrix2.Matrix3.COLUMN0ROW2]) * root;
  2163. z = (matrix[Matrix2.Matrix3.COLUMN0ROW1] - matrix[Matrix2.Matrix3.COLUMN1ROW0]) * root;
  2164. } else {
  2165. // |w| <= 1/2
  2166. const next = fromRotationMatrixNext;
  2167. let i = 0;
  2168. if (m11 > m00) {
  2169. i = 1;
  2170. }
  2171. if (m22 > m00 && m22 > m11) {
  2172. i = 2;
  2173. }
  2174. const j = next[i];
  2175. const k = next[j];
  2176. root = Math.sqrt(
  2177. matrix[Matrix2.Matrix3.getElementIndex(i, i)] -
  2178. matrix[Matrix2.Matrix3.getElementIndex(j, j)] -
  2179. matrix[Matrix2.Matrix3.getElementIndex(k, k)] +
  2180. 1.0
  2181. );
  2182. const quat = fromRotationMatrixQuat;
  2183. quat[i] = 0.5 * root;
  2184. root = 0.5 / root;
  2185. w =
  2186. (matrix[Matrix2.Matrix3.getElementIndex(k, j)] -
  2187. matrix[Matrix2.Matrix3.getElementIndex(j, k)]) *
  2188. root;
  2189. quat[j] =
  2190. (matrix[Matrix2.Matrix3.getElementIndex(j, i)] +
  2191. matrix[Matrix2.Matrix3.getElementIndex(i, j)]) *
  2192. root;
  2193. quat[k] =
  2194. (matrix[Matrix2.Matrix3.getElementIndex(k, i)] +
  2195. matrix[Matrix2.Matrix3.getElementIndex(i, k)]) *
  2196. root;
  2197. x = -quat[0];
  2198. y = -quat[1];
  2199. z = -quat[2];
  2200. }
  2201. if (!defaultValue.defined(result)) {
  2202. return new Quaternion(x, y, z, w);
  2203. }
  2204. result.x = x;
  2205. result.y = y;
  2206. result.z = z;
  2207. result.w = w;
  2208. return result;
  2209. };
  2210. const scratchHPRQuaternion$1 = new Quaternion();
  2211. let scratchHeadingQuaternion = new Quaternion();
  2212. let scratchPitchQuaternion = new Quaternion();
  2213. let scratchRollQuaternion = new Quaternion();
  2214. /**
  2215. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  2216. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  2217. * the positive x axis.
  2218. *
  2219. * @param {HeadingPitchRoll} headingPitchRoll The rotation expressed as a heading, pitch and roll.
  2220. * @param {Quaternion} [result] The object onto which to store the result.
  2221. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  2222. */
  2223. Quaternion.fromHeadingPitchRoll = function (headingPitchRoll, result) {
  2224. //>>includeStart('debug', pragmas.debug);
  2225. RuntimeError.Check.typeOf.object("headingPitchRoll", headingPitchRoll);
  2226. //>>includeEnd('debug');
  2227. scratchRollQuaternion = Quaternion.fromAxisAngle(
  2228. Matrix2.Cartesian3.UNIT_X,
  2229. headingPitchRoll.roll,
  2230. scratchHPRQuaternion$1
  2231. );
  2232. scratchPitchQuaternion = Quaternion.fromAxisAngle(
  2233. Matrix2.Cartesian3.UNIT_Y,
  2234. -headingPitchRoll.pitch,
  2235. result
  2236. );
  2237. result = Quaternion.multiply(
  2238. scratchPitchQuaternion,
  2239. scratchRollQuaternion,
  2240. scratchPitchQuaternion
  2241. );
  2242. scratchHeadingQuaternion = Quaternion.fromAxisAngle(
  2243. Matrix2.Cartesian3.UNIT_Z,
  2244. -headingPitchRoll.heading,
  2245. scratchHPRQuaternion$1
  2246. );
  2247. return Quaternion.multiply(scratchHeadingQuaternion, result, result);
  2248. };
  2249. const sampledQuaternionAxis = new Matrix2.Cartesian3();
  2250. const sampledQuaternionRotation = new Matrix2.Cartesian3();
  2251. const sampledQuaternionTempQuaternion = new Quaternion();
  2252. const sampledQuaternionQuaternion0 = new Quaternion();
  2253. const sampledQuaternionQuaternion0Conjugate = new Quaternion();
  2254. /**
  2255. * The number of elements used to pack the object into an array.
  2256. * @type {Number}
  2257. */
  2258. Quaternion.packedLength = 4;
  2259. /**
  2260. * Stores the provided instance into the provided array.
  2261. *
  2262. * @param {Quaternion} value The value to pack.
  2263. * @param {Number[]} array The array to pack into.
  2264. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2265. *
  2266. * @returns {Number[]} The array that was packed into
  2267. */
  2268. Quaternion.pack = function (value, array, startingIndex) {
  2269. //>>includeStart('debug', pragmas.debug);
  2270. RuntimeError.Check.typeOf.object("value", value);
  2271. RuntimeError.Check.defined("array", array);
  2272. //>>includeEnd('debug');
  2273. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  2274. array[startingIndex++] = value.x;
  2275. array[startingIndex++] = value.y;
  2276. array[startingIndex++] = value.z;
  2277. array[startingIndex] = value.w;
  2278. return array;
  2279. };
  2280. /**
  2281. * Retrieves an instance from a packed array.
  2282. *
  2283. * @param {Number[]} array The packed array.
  2284. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2285. * @param {Quaternion} [result] The object into which to store the result.
  2286. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2287. */
  2288. Quaternion.unpack = function (array, startingIndex, result) {
  2289. //>>includeStart('debug', pragmas.debug);
  2290. RuntimeError.Check.defined("array", array);
  2291. //>>includeEnd('debug');
  2292. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  2293. if (!defaultValue.defined(result)) {
  2294. result = new Quaternion();
  2295. }
  2296. result.x = array[startingIndex];
  2297. result.y = array[startingIndex + 1];
  2298. result.z = array[startingIndex + 2];
  2299. result.w = array[startingIndex + 3];
  2300. return result;
  2301. };
  2302. /**
  2303. * The number of elements used to store the object into an array in its interpolatable form.
  2304. * @type {Number}
  2305. */
  2306. Quaternion.packedInterpolationLength = 3;
  2307. /**
  2308. * Converts a packed array into a form suitable for interpolation.
  2309. *
  2310. * @param {Number[]} packedArray The packed array.
  2311. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  2312. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  2313. * @param {Number[]} [result] The object into which to store the result.
  2314. */
  2315. Quaternion.convertPackedArrayForInterpolation = function (
  2316. packedArray,
  2317. startingIndex,
  2318. lastIndex,
  2319. result
  2320. ) {
  2321. Quaternion.unpack(
  2322. packedArray,
  2323. lastIndex * 4,
  2324. sampledQuaternionQuaternion0Conjugate
  2325. );
  2326. Quaternion.conjugate(
  2327. sampledQuaternionQuaternion0Conjugate,
  2328. sampledQuaternionQuaternion0Conjugate
  2329. );
  2330. for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  2331. const offset = i * 3;
  2332. Quaternion.unpack(
  2333. packedArray,
  2334. (startingIndex + i) * 4,
  2335. sampledQuaternionTempQuaternion
  2336. );
  2337. Quaternion.multiply(
  2338. sampledQuaternionTempQuaternion,
  2339. sampledQuaternionQuaternion0Conjugate,
  2340. sampledQuaternionTempQuaternion
  2341. );
  2342. if (sampledQuaternionTempQuaternion.w < 0) {
  2343. Quaternion.negate(
  2344. sampledQuaternionTempQuaternion,
  2345. sampledQuaternionTempQuaternion
  2346. );
  2347. }
  2348. Quaternion.computeAxis(
  2349. sampledQuaternionTempQuaternion,
  2350. sampledQuaternionAxis
  2351. );
  2352. const angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  2353. if (!defaultValue.defined(result)) {
  2354. result = [];
  2355. }
  2356. result[offset] = sampledQuaternionAxis.x * angle;
  2357. result[offset + 1] = sampledQuaternionAxis.y * angle;
  2358. result[offset + 2] = sampledQuaternionAxis.z * angle;
  2359. }
  2360. };
  2361. /**
  2362. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  2363. *
  2364. * @param {Number[]} array The array previously packed for interpolation.
  2365. * @param {Number[]} sourceArray The original packed array.
  2366. * @param {Number} [firstIndex=0] The firstIndex used to convert the array.
  2367. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  2368. * @param {Quaternion} [result] The object into which to store the result.
  2369. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  2370. */
  2371. Quaternion.unpackInterpolationResult = function (
  2372. array,
  2373. sourceArray,
  2374. firstIndex,
  2375. lastIndex,
  2376. result
  2377. ) {
  2378. if (!defaultValue.defined(result)) {
  2379. result = new Quaternion();
  2380. }
  2381. Matrix2.Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  2382. const magnitude = Matrix2.Cartesian3.magnitude(sampledQuaternionRotation);
  2383. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  2384. if (magnitude === 0) {
  2385. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  2386. } else {
  2387. Quaternion.fromAxisAngle(
  2388. sampledQuaternionRotation,
  2389. magnitude,
  2390. sampledQuaternionTempQuaternion
  2391. );
  2392. }
  2393. return Quaternion.multiply(
  2394. sampledQuaternionTempQuaternion,
  2395. sampledQuaternionQuaternion0,
  2396. result
  2397. );
  2398. };
  2399. /**
  2400. * Duplicates a Quaternion instance.
  2401. *
  2402. * @param {Quaternion} quaternion The quaternion to duplicate.
  2403. * @param {Quaternion} [result] The object onto which to store the result.
  2404. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  2405. */
  2406. Quaternion.clone = function (quaternion, result) {
  2407. if (!defaultValue.defined(quaternion)) {
  2408. return undefined;
  2409. }
  2410. if (!defaultValue.defined(result)) {
  2411. return new Quaternion(
  2412. quaternion.x,
  2413. quaternion.y,
  2414. quaternion.z,
  2415. quaternion.w
  2416. );
  2417. }
  2418. result.x = quaternion.x;
  2419. result.y = quaternion.y;
  2420. result.z = quaternion.z;
  2421. result.w = quaternion.w;
  2422. return result;
  2423. };
  2424. /**
  2425. * Computes the conjugate of the provided quaternion.
  2426. *
  2427. * @param {Quaternion} quaternion The quaternion to conjugate.
  2428. * @param {Quaternion} result The object onto which to store the result.
  2429. * @returns {Quaternion} The modified result parameter.
  2430. */
  2431. Quaternion.conjugate = function (quaternion, result) {
  2432. //>>includeStart('debug', pragmas.debug);
  2433. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2434. RuntimeError.Check.typeOf.object("result", result);
  2435. //>>includeEnd('debug');
  2436. result.x = -quaternion.x;
  2437. result.y = -quaternion.y;
  2438. result.z = -quaternion.z;
  2439. result.w = quaternion.w;
  2440. return result;
  2441. };
  2442. /**
  2443. * Computes magnitude squared for the provided quaternion.
  2444. *
  2445. * @param {Quaternion} quaternion The quaternion to conjugate.
  2446. * @returns {Number} The magnitude squared.
  2447. */
  2448. Quaternion.magnitudeSquared = function (quaternion) {
  2449. //>>includeStart('debug', pragmas.debug);
  2450. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2451. //>>includeEnd('debug');
  2452. return (
  2453. quaternion.x * quaternion.x +
  2454. quaternion.y * quaternion.y +
  2455. quaternion.z * quaternion.z +
  2456. quaternion.w * quaternion.w
  2457. );
  2458. };
  2459. /**
  2460. * Computes magnitude for the provided quaternion.
  2461. *
  2462. * @param {Quaternion} quaternion The quaternion to conjugate.
  2463. * @returns {Number} The magnitude.
  2464. */
  2465. Quaternion.magnitude = function (quaternion) {
  2466. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  2467. };
  2468. /**
  2469. * Computes the normalized form of the provided quaternion.
  2470. *
  2471. * @param {Quaternion} quaternion The quaternion to normalize.
  2472. * @param {Quaternion} result The object onto which to store the result.
  2473. * @returns {Quaternion} The modified result parameter.
  2474. */
  2475. Quaternion.normalize = function (quaternion, result) {
  2476. //>>includeStart('debug', pragmas.debug);
  2477. RuntimeError.Check.typeOf.object("result", result);
  2478. //>>includeEnd('debug');
  2479. const inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  2480. const x = quaternion.x * inverseMagnitude;
  2481. const y = quaternion.y * inverseMagnitude;
  2482. const z = quaternion.z * inverseMagnitude;
  2483. const w = quaternion.w * inverseMagnitude;
  2484. result.x = x;
  2485. result.y = y;
  2486. result.z = z;
  2487. result.w = w;
  2488. return result;
  2489. };
  2490. /**
  2491. * Computes the inverse of the provided quaternion.
  2492. *
  2493. * @param {Quaternion} quaternion The quaternion to normalize.
  2494. * @param {Quaternion} result The object onto which to store the result.
  2495. * @returns {Quaternion} The modified result parameter.
  2496. */
  2497. Quaternion.inverse = function (quaternion, result) {
  2498. //>>includeStart('debug', pragmas.debug);
  2499. RuntimeError.Check.typeOf.object("result", result);
  2500. //>>includeEnd('debug');
  2501. const magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  2502. result = Quaternion.conjugate(quaternion, result);
  2503. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  2504. };
  2505. /**
  2506. * Computes the componentwise sum of two quaternions.
  2507. *
  2508. * @param {Quaternion} left The first quaternion.
  2509. * @param {Quaternion} right The second quaternion.
  2510. * @param {Quaternion} result The object onto which to store the result.
  2511. * @returns {Quaternion} The modified result parameter.
  2512. */
  2513. Quaternion.add = function (left, right, result) {
  2514. //>>includeStart('debug', pragmas.debug);
  2515. RuntimeError.Check.typeOf.object("left", left);
  2516. RuntimeError.Check.typeOf.object("right", right);
  2517. RuntimeError.Check.typeOf.object("result", result);
  2518. //>>includeEnd('debug');
  2519. result.x = left.x + right.x;
  2520. result.y = left.y + right.y;
  2521. result.z = left.z + right.z;
  2522. result.w = left.w + right.w;
  2523. return result;
  2524. };
  2525. /**
  2526. * Computes the componentwise difference of two quaternions.
  2527. *
  2528. * @param {Quaternion} left The first quaternion.
  2529. * @param {Quaternion} right The second quaternion.
  2530. * @param {Quaternion} result The object onto which to store the result.
  2531. * @returns {Quaternion} The modified result parameter.
  2532. */
  2533. Quaternion.subtract = function (left, right, result) {
  2534. //>>includeStart('debug', pragmas.debug);
  2535. RuntimeError.Check.typeOf.object("left", left);
  2536. RuntimeError.Check.typeOf.object("right", right);
  2537. RuntimeError.Check.typeOf.object("result", result);
  2538. //>>includeEnd('debug');
  2539. result.x = left.x - right.x;
  2540. result.y = left.y - right.y;
  2541. result.z = left.z - right.z;
  2542. result.w = left.w - right.w;
  2543. return result;
  2544. };
  2545. /**
  2546. * Negates the provided quaternion.
  2547. *
  2548. * @param {Quaternion} quaternion The quaternion to be negated.
  2549. * @param {Quaternion} result The object onto which to store the result.
  2550. * @returns {Quaternion} The modified result parameter.
  2551. */
  2552. Quaternion.negate = function (quaternion, result) {
  2553. //>>includeStart('debug', pragmas.debug);
  2554. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2555. RuntimeError.Check.typeOf.object("result", result);
  2556. //>>includeEnd('debug');
  2557. result.x = -quaternion.x;
  2558. result.y = -quaternion.y;
  2559. result.z = -quaternion.z;
  2560. result.w = -quaternion.w;
  2561. return result;
  2562. };
  2563. /**
  2564. * Computes the dot (scalar) product of two quaternions.
  2565. *
  2566. * @param {Quaternion} left The first quaternion.
  2567. * @param {Quaternion} right The second quaternion.
  2568. * @returns {Number} The dot product.
  2569. */
  2570. Quaternion.dot = function (left, right) {
  2571. //>>includeStart('debug', pragmas.debug);
  2572. RuntimeError.Check.typeOf.object("left", left);
  2573. RuntimeError.Check.typeOf.object("right", right);
  2574. //>>includeEnd('debug');
  2575. return (
  2576. left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
  2577. );
  2578. };
  2579. /**
  2580. * Computes the product of two quaternions.
  2581. *
  2582. * @param {Quaternion} left The first quaternion.
  2583. * @param {Quaternion} right The second quaternion.
  2584. * @param {Quaternion} result The object onto which to store the result.
  2585. * @returns {Quaternion} The modified result parameter.
  2586. */
  2587. Quaternion.multiply = function (left, right, result) {
  2588. //>>includeStart('debug', pragmas.debug);
  2589. RuntimeError.Check.typeOf.object("left", left);
  2590. RuntimeError.Check.typeOf.object("right", right);
  2591. RuntimeError.Check.typeOf.object("result", result);
  2592. //>>includeEnd('debug');
  2593. const leftX = left.x;
  2594. const leftY = left.y;
  2595. const leftZ = left.z;
  2596. const leftW = left.w;
  2597. const rightX = right.x;
  2598. const rightY = right.y;
  2599. const rightZ = right.z;
  2600. const rightW = right.w;
  2601. const x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  2602. const y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  2603. const z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  2604. const w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  2605. result.x = x;
  2606. result.y = y;
  2607. result.z = z;
  2608. result.w = w;
  2609. return result;
  2610. };
  2611. /**
  2612. * Multiplies the provided quaternion componentwise by the provided scalar.
  2613. *
  2614. * @param {Quaternion} quaternion The quaternion to be scaled.
  2615. * @param {Number} scalar The scalar to multiply with.
  2616. * @param {Quaternion} result The object onto which to store the result.
  2617. * @returns {Quaternion} The modified result parameter.
  2618. */
  2619. Quaternion.multiplyByScalar = function (quaternion, scalar, result) {
  2620. //>>includeStart('debug', pragmas.debug);
  2621. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2622. RuntimeError.Check.typeOf.number("scalar", scalar);
  2623. RuntimeError.Check.typeOf.object("result", result);
  2624. //>>includeEnd('debug');
  2625. result.x = quaternion.x * scalar;
  2626. result.y = quaternion.y * scalar;
  2627. result.z = quaternion.z * scalar;
  2628. result.w = quaternion.w * scalar;
  2629. return result;
  2630. };
  2631. /**
  2632. * Divides the provided quaternion componentwise by the provided scalar.
  2633. *
  2634. * @param {Quaternion} quaternion The quaternion to be divided.
  2635. * @param {Number} scalar The scalar to divide by.
  2636. * @param {Quaternion} result The object onto which to store the result.
  2637. * @returns {Quaternion} The modified result parameter.
  2638. */
  2639. Quaternion.divideByScalar = function (quaternion, scalar, result) {
  2640. //>>includeStart('debug', pragmas.debug);
  2641. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2642. RuntimeError.Check.typeOf.number("scalar", scalar);
  2643. RuntimeError.Check.typeOf.object("result", result);
  2644. //>>includeEnd('debug');
  2645. result.x = quaternion.x / scalar;
  2646. result.y = quaternion.y / scalar;
  2647. result.z = quaternion.z / scalar;
  2648. result.w = quaternion.w / scalar;
  2649. return result;
  2650. };
  2651. /**
  2652. * Computes the axis of rotation of the provided quaternion.
  2653. *
  2654. * @param {Quaternion} quaternion The quaternion to use.
  2655. * @param {Cartesian3} result The object onto which to store the result.
  2656. * @returns {Cartesian3} The modified result parameter.
  2657. */
  2658. Quaternion.computeAxis = function (quaternion, result) {
  2659. //>>includeStart('debug', pragmas.debug);
  2660. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2661. RuntimeError.Check.typeOf.object("result", result);
  2662. //>>includeEnd('debug');
  2663. const w = quaternion.w;
  2664. if (Math.abs(w - 1.0) < ComponentDatatype.CesiumMath.EPSILON6) {
  2665. result.x = result.y = result.z = 0;
  2666. return result;
  2667. }
  2668. const scalar = 1.0 / Math.sqrt(1.0 - w * w);
  2669. result.x = quaternion.x * scalar;
  2670. result.y = quaternion.y * scalar;
  2671. result.z = quaternion.z * scalar;
  2672. return result;
  2673. };
  2674. /**
  2675. * Computes the angle of rotation of the provided quaternion.
  2676. *
  2677. * @param {Quaternion} quaternion The quaternion to use.
  2678. * @returns {Number} The angle of rotation.
  2679. */
  2680. Quaternion.computeAngle = function (quaternion) {
  2681. //>>includeStart('debug', pragmas.debug);
  2682. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2683. //>>includeEnd('debug');
  2684. if (Math.abs(quaternion.w - 1.0) < ComponentDatatype.CesiumMath.EPSILON6) {
  2685. return 0.0;
  2686. }
  2687. return 2.0 * Math.acos(quaternion.w);
  2688. };
  2689. let lerpScratch = new Quaternion();
  2690. /**
  2691. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  2692. *
  2693. * @param {Quaternion} start The value corresponding to t at 0.0.
  2694. * @param {Quaternion} end The value corresponding to t at 1.0.
  2695. * @param {Number} t The point along t at which to interpolate.
  2696. * @param {Quaternion} result The object onto which to store the result.
  2697. * @returns {Quaternion} The modified result parameter.
  2698. */
  2699. Quaternion.lerp = function (start, end, t, result) {
  2700. //>>includeStart('debug', pragmas.debug);
  2701. RuntimeError.Check.typeOf.object("start", start);
  2702. RuntimeError.Check.typeOf.object("end", end);
  2703. RuntimeError.Check.typeOf.number("t", t);
  2704. RuntimeError.Check.typeOf.object("result", result);
  2705. //>>includeEnd('debug');
  2706. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  2707. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  2708. return Quaternion.add(lerpScratch, result, result);
  2709. };
  2710. let slerpEndNegated = new Quaternion();
  2711. let slerpScaledP = new Quaternion();
  2712. let slerpScaledR = new Quaternion();
  2713. /**
  2714. * Computes the spherical 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. * @see Quaternion#fastSlerp
  2723. */
  2724. Quaternion.slerp = function (start, end, t, result) {
  2725. //>>includeStart('debug', pragmas.debug);
  2726. RuntimeError.Check.typeOf.object("start", start);
  2727. RuntimeError.Check.typeOf.object("end", end);
  2728. RuntimeError.Check.typeOf.number("t", t);
  2729. RuntimeError.Check.typeOf.object("result", result);
  2730. //>>includeEnd('debug');
  2731. let dot = Quaternion.dot(start, end);
  2732. // The angle between start must be acute. Since q and -q represent
  2733. // the same rotation, negate q to get the acute angle.
  2734. let r = end;
  2735. if (dot < 0.0) {
  2736. dot = -dot;
  2737. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  2738. }
  2739. // dot > 0, as the dot product approaches 1, the angle between the
  2740. // quaternions vanishes. use linear interpolation.
  2741. if (1.0 - dot < ComponentDatatype.CesiumMath.EPSILON6) {
  2742. return Quaternion.lerp(start, r, t, result);
  2743. }
  2744. const theta = Math.acos(dot);
  2745. slerpScaledP = Quaternion.multiplyByScalar(
  2746. start,
  2747. Math.sin((1 - t) * theta),
  2748. slerpScaledP
  2749. );
  2750. slerpScaledR = Quaternion.multiplyByScalar(
  2751. r,
  2752. Math.sin(t * theta),
  2753. slerpScaledR
  2754. );
  2755. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  2756. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  2757. };
  2758. /**
  2759. * The logarithmic quaternion function.
  2760. *
  2761. * @param {Quaternion} quaternion The unit quaternion.
  2762. * @param {Cartesian3} result The object onto which to store the result.
  2763. * @returns {Cartesian3} The modified result parameter.
  2764. */
  2765. Quaternion.log = function (quaternion, result) {
  2766. //>>includeStart('debug', pragmas.debug);
  2767. RuntimeError.Check.typeOf.object("quaternion", quaternion);
  2768. RuntimeError.Check.typeOf.object("result", result);
  2769. //>>includeEnd('debug');
  2770. const theta = ComponentDatatype.CesiumMath.acosClamped(quaternion.w);
  2771. let thetaOverSinTheta = 0.0;
  2772. if (theta !== 0.0) {
  2773. thetaOverSinTheta = theta / Math.sin(theta);
  2774. }
  2775. return Matrix2.Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  2776. };
  2777. /**
  2778. * The exponential quaternion function.
  2779. *
  2780. * @param {Cartesian3} cartesian The cartesian.
  2781. * @param {Quaternion} result The object onto which to store the result.
  2782. * @returns {Quaternion} The modified result parameter.
  2783. */
  2784. Quaternion.exp = function (cartesian, result) {
  2785. //>>includeStart('debug', pragmas.debug);
  2786. RuntimeError.Check.typeOf.object("cartesian", cartesian);
  2787. RuntimeError.Check.typeOf.object("result", result);
  2788. //>>includeEnd('debug');
  2789. const theta = Matrix2.Cartesian3.magnitude(cartesian);
  2790. let sinThetaOverTheta = 0.0;
  2791. if (theta !== 0.0) {
  2792. sinThetaOverTheta = Math.sin(theta) / theta;
  2793. }
  2794. result.x = cartesian.x * sinThetaOverTheta;
  2795. result.y = cartesian.y * sinThetaOverTheta;
  2796. result.z = cartesian.z * sinThetaOverTheta;
  2797. result.w = Math.cos(theta);
  2798. return result;
  2799. };
  2800. const squadScratchCartesian0 = new Matrix2.Cartesian3();
  2801. const squadScratchCartesian1 = new Matrix2.Cartesian3();
  2802. const squadScratchQuaternion0 = new Quaternion();
  2803. const squadScratchQuaternion1 = new Quaternion();
  2804. /**
  2805. * Computes an inner quadrangle point.
  2806. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  2807. *
  2808. * @param {Quaternion} q0 The first quaternion.
  2809. * @param {Quaternion} q1 The second quaternion.
  2810. * @param {Quaternion} q2 The third quaternion.
  2811. * @param {Quaternion} result The object onto which to store the result.
  2812. * @returns {Quaternion} The modified result parameter.
  2813. *
  2814. * @see Quaternion#squad
  2815. */
  2816. Quaternion.computeInnerQuadrangle = function (q0, q1, q2, result) {
  2817. //>>includeStart('debug', pragmas.debug);
  2818. RuntimeError.Check.typeOf.object("q0", q0);
  2819. RuntimeError.Check.typeOf.object("q1", q1);
  2820. RuntimeError.Check.typeOf.object("q2", q2);
  2821. RuntimeError.Check.typeOf.object("result", result);
  2822. //>>includeEnd('debug');
  2823. const qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  2824. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  2825. const cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  2826. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  2827. const cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  2828. Matrix2.Cartesian3.add(cart0, cart1, cart0);
  2829. Matrix2.Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  2830. Matrix2.Cartesian3.negate(cart0, cart0);
  2831. Quaternion.exp(cart0, squadScratchQuaternion0);
  2832. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  2833. };
  2834. /**
  2835. * Computes the spherical quadrangle interpolation between quaternions.
  2836. *
  2837. * @param {Quaternion} q0 The first quaternion.
  2838. * @param {Quaternion} q1 The second quaternion.
  2839. * @param {Quaternion} s0 The first inner quadrangle.
  2840. * @param {Quaternion} s1 The second inner quadrangle.
  2841. * @param {Number} t The time in [0,1] used to interpolate.
  2842. * @param {Quaternion} result The object onto which to store the result.
  2843. * @returns {Quaternion} The modified result parameter.
  2844. *
  2845. *
  2846. * @example
  2847. * // 1. compute the squad interpolation between two quaternions on a curve
  2848. * const s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  2849. * const s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  2850. * const q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  2851. *
  2852. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  2853. * const s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  2854. * const q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  2855. *
  2856. * @see Quaternion#computeInnerQuadrangle
  2857. */
  2858. Quaternion.squad = function (q0, q1, s0, s1, t, result) {
  2859. //>>includeStart('debug', pragmas.debug);
  2860. RuntimeError.Check.typeOf.object("q0", q0);
  2861. RuntimeError.Check.typeOf.object("q1", q1);
  2862. RuntimeError.Check.typeOf.object("s0", s0);
  2863. RuntimeError.Check.typeOf.object("s1", s1);
  2864. RuntimeError.Check.typeOf.number("t", t);
  2865. RuntimeError.Check.typeOf.object("result", result);
  2866. //>>includeEnd('debug');
  2867. const slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  2868. const slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  2869. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  2870. };
  2871. const fastSlerpScratchQuaternion = new Quaternion();
  2872. const opmu = 1.90110745351730037;
  2873. const u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2874. const v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2875. const bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2876. const bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  2877. for (let i = 0; i < 7; ++i) {
  2878. const s = i + 1.0;
  2879. const t = 2.0 * s + 1.0;
  2880. u[i] = 1.0 / (s * t);
  2881. v[i] = s / t;
  2882. }
  2883. u[7] = opmu / (8.0 * 17.0);
  2884. v[7] = (opmu * 8.0) / 17.0;
  2885. /**
  2886. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  2887. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  2888. *
  2889. * @param {Quaternion} start The value corresponding to t at 0.0.
  2890. * @param {Quaternion} end The value corresponding to t at 1.0.
  2891. * @param {Number} t The point along t at which to interpolate.
  2892. * @param {Quaternion} result The object onto which to store the result.
  2893. * @returns {Quaternion} The modified result parameter.
  2894. *
  2895. * @see Quaternion#slerp
  2896. */
  2897. Quaternion.fastSlerp = function (start, end, t, result) {
  2898. //>>includeStart('debug', pragmas.debug);
  2899. RuntimeError.Check.typeOf.object("start", start);
  2900. RuntimeError.Check.typeOf.object("end", end);
  2901. RuntimeError.Check.typeOf.number("t", t);
  2902. RuntimeError.Check.typeOf.object("result", result);
  2903. //>>includeEnd('debug');
  2904. let x = Quaternion.dot(start, end);
  2905. let sign;
  2906. if (x >= 0) {
  2907. sign = 1.0;
  2908. } else {
  2909. sign = -1.0;
  2910. x = -x;
  2911. }
  2912. const xm1 = x - 1.0;
  2913. const d = 1.0 - t;
  2914. const sqrT = t * t;
  2915. const sqrD = d * d;
  2916. for (let i = 7; i >= 0; --i) {
  2917. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  2918. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  2919. }
  2920. const cT =
  2921. sign *
  2922. t *
  2923. (1.0 +
  2924. bT[0] *
  2925. (1.0 +
  2926. bT[1] *
  2927. (1.0 +
  2928. bT[2] *
  2929. (1.0 +
  2930. bT[3] *
  2931. (1.0 +
  2932. bT[4] *
  2933. (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  2934. const cD =
  2935. d *
  2936. (1.0 +
  2937. bD[0] *
  2938. (1.0 +
  2939. bD[1] *
  2940. (1.0 +
  2941. bD[2] *
  2942. (1.0 +
  2943. bD[3] *
  2944. (1.0 +
  2945. bD[4] *
  2946. (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  2947. const temp = Quaternion.multiplyByScalar(
  2948. start,
  2949. cD,
  2950. fastSlerpScratchQuaternion
  2951. );
  2952. Quaternion.multiplyByScalar(end, cT, result);
  2953. return Quaternion.add(temp, result, result);
  2954. };
  2955. /**
  2956. * Computes the spherical quadrangle interpolation between quaternions.
  2957. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  2958. *
  2959. * @param {Quaternion} q0 The first quaternion.
  2960. * @param {Quaternion} q1 The second quaternion.
  2961. * @param {Quaternion} s0 The first inner quadrangle.
  2962. * @param {Quaternion} s1 The second inner quadrangle.
  2963. * @param {Number} t The time in [0,1] used to interpolate.
  2964. * @param {Quaternion} result The object onto which to store the result.
  2965. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  2966. *
  2967. * @see Quaternion#squad
  2968. */
  2969. Quaternion.fastSquad = function (q0, q1, s0, s1, t, result) {
  2970. //>>includeStart('debug', pragmas.debug);
  2971. RuntimeError.Check.typeOf.object("q0", q0);
  2972. RuntimeError.Check.typeOf.object("q1", q1);
  2973. RuntimeError.Check.typeOf.object("s0", s0);
  2974. RuntimeError.Check.typeOf.object("s1", s1);
  2975. RuntimeError.Check.typeOf.number("t", t);
  2976. RuntimeError.Check.typeOf.object("result", result);
  2977. //>>includeEnd('debug');
  2978. const slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  2979. const slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  2980. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  2981. };
  2982. /**
  2983. * Compares the provided quaternions componentwise and returns
  2984. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2985. *
  2986. * @param {Quaternion} [left] The first quaternion.
  2987. * @param {Quaternion} [right] The second quaternion.
  2988. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2989. */
  2990. Quaternion.equals = function (left, right) {
  2991. return (
  2992. left === right ||
  2993. (defaultValue.defined(left) &&
  2994. defaultValue.defined(right) &&
  2995. left.x === right.x &&
  2996. left.y === right.y &&
  2997. left.z === right.z &&
  2998. left.w === right.w)
  2999. );
  3000. };
  3001. /**
  3002. * Compares the provided quaternions componentwise and returns
  3003. * <code>true</code> if they are within the provided epsilon,
  3004. * <code>false</code> otherwise.
  3005. *
  3006. * @param {Quaternion} [left] The first quaternion.
  3007. * @param {Quaternion} [right] The second quaternion.
  3008. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  3009. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3010. */
  3011. Quaternion.equalsEpsilon = function (left, right, epsilon) {
  3012. epsilon = defaultValue.defaultValue(epsilon, 0);
  3013. return (
  3014. left === right ||
  3015. (defaultValue.defined(left) &&
  3016. defaultValue.defined(right) &&
  3017. Math.abs(left.x - right.x) <= epsilon &&
  3018. Math.abs(left.y - right.y) <= epsilon &&
  3019. Math.abs(left.z - right.z) <= epsilon &&
  3020. Math.abs(left.w - right.w) <= epsilon)
  3021. );
  3022. };
  3023. /**
  3024. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  3025. *
  3026. * @type {Quaternion}
  3027. * @constant
  3028. */
  3029. Quaternion.ZERO = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 0.0));
  3030. /**
  3031. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  3032. *
  3033. * @type {Quaternion}
  3034. * @constant
  3035. */
  3036. Quaternion.IDENTITY = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 1.0));
  3037. /**
  3038. * Duplicates this Quaternion instance.
  3039. *
  3040. * @param {Quaternion} [result] The object onto which to store the result.
  3041. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  3042. */
  3043. Quaternion.prototype.clone = function (result) {
  3044. return Quaternion.clone(this, result);
  3045. };
  3046. /**
  3047. * Compares this and the provided quaternion componentwise and returns
  3048. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3049. *
  3050. * @param {Quaternion} [right] The right hand side quaternion.
  3051. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3052. */
  3053. Quaternion.prototype.equals = function (right) {
  3054. return Quaternion.equals(this, right);
  3055. };
  3056. /**
  3057. * Compares this and the provided quaternion componentwise and returns
  3058. * <code>true</code> if they are within the provided epsilon,
  3059. * <code>false</code> otherwise.
  3060. *
  3061. * @param {Quaternion} [right] The right hand side quaternion.
  3062. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  3063. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3064. */
  3065. Quaternion.prototype.equalsEpsilon = function (right, epsilon) {
  3066. return Quaternion.equalsEpsilon(this, right, epsilon);
  3067. };
  3068. /**
  3069. * Returns a string representing this quaternion in the format (x, y, z, w).
  3070. *
  3071. * @returns {String} A string representing this Quaternion.
  3072. */
  3073. Quaternion.prototype.toString = function () {
  3074. return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`;
  3075. };
  3076. /**
  3077. * Finds an item in a sorted array.
  3078. *
  3079. * @function
  3080. * @param {Array} array The sorted array to search.
  3081. * @param {*} itemToFind The item to find in the array.
  3082. * @param {binarySearchComparator} comparator The function to use to compare the item to
  3083. * elements in the array.
  3084. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  3085. * does not exist, the return value is a negative number which is the bitwise complement (~)
  3086. * of the index before which the itemToFind should be inserted in order to maintain the
  3087. * sorted order of the array.
  3088. *
  3089. * @example
  3090. * // Create a comparator function to search through an array of numbers.
  3091. * function comparator(a, b) {
  3092. * return a - b;
  3093. * };
  3094. * const numbers = [0, 2, 4, 6, 8];
  3095. * const index = Cesium.binarySearch(numbers, 6, comparator); // 3
  3096. */
  3097. function binarySearch(array, itemToFind, comparator) {
  3098. //>>includeStart('debug', pragmas.debug);
  3099. RuntimeError.Check.defined("array", array);
  3100. RuntimeError.Check.defined("itemToFind", itemToFind);
  3101. RuntimeError.Check.defined("comparator", comparator);
  3102. //>>includeEnd('debug');
  3103. let low = 0;
  3104. let high = array.length - 1;
  3105. let i;
  3106. let comparison;
  3107. while (low <= high) {
  3108. i = ~~((low + high) / 2);
  3109. comparison = comparator(array[i], itemToFind);
  3110. if (comparison < 0) {
  3111. low = i + 1;
  3112. continue;
  3113. }
  3114. if (comparison > 0) {
  3115. high = i - 1;
  3116. continue;
  3117. }
  3118. return i;
  3119. }
  3120. return ~(high + 1);
  3121. }
  3122. /**
  3123. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  3124. *
  3125. * @alias EarthOrientationParametersSample
  3126. * @constructor
  3127. *
  3128. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  3129. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  3130. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  3131. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  3132. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  3133. *
  3134. * @private
  3135. */
  3136. function EarthOrientationParametersSample(
  3137. xPoleWander,
  3138. yPoleWander,
  3139. xPoleOffset,
  3140. yPoleOffset,
  3141. ut1MinusUtc
  3142. ) {
  3143. /**
  3144. * The pole wander about the X axis, in radians.
  3145. * @type {Number}
  3146. */
  3147. this.xPoleWander = xPoleWander;
  3148. /**
  3149. * The pole wander about the Y axis, in radians.
  3150. * @type {Number}
  3151. */
  3152. this.yPoleWander = yPoleWander;
  3153. /**
  3154. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  3155. * @type {Number}
  3156. */
  3157. this.xPoleOffset = xPoleOffset;
  3158. /**
  3159. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  3160. * @type {Number}
  3161. */
  3162. this.yPoleOffset = yPoleOffset;
  3163. /**
  3164. * The difference in time standards, UT1 - UTC, in seconds.
  3165. * @type {Number}
  3166. */
  3167. this.ut1MinusUtc = ut1MinusUtc;
  3168. }
  3169. /**
  3170. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  3171. * In addition to submillisecond precision, this object can also represent leap seconds.
  3172. * @alias GregorianDate
  3173. * @constructor
  3174. *
  3175. * @param {Number} [year] The year as a whole number.
  3176. * @param {Number} [month] The month as a whole number with range [1, 12].
  3177. * @param {Number} [day] The day of the month as a whole number starting at 1.
  3178. * @param {Number} [hour] The hour as a whole number with range [0, 23].
  3179. * @param {Number} [minute] The minute of the hour as a whole number with range [0, 59].
  3180. * @param {Number} [second] The second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  3181. * @param {Number} [millisecond] The millisecond of the second as a floating point number with range [0.0, 1000.0).
  3182. * @param {Boolean} [isLeapSecond] Whether this time is during a leap second.
  3183. *
  3184. * @see JulianDate#toGregorianDate
  3185. */
  3186. function GregorianDate(
  3187. year,
  3188. month,
  3189. day,
  3190. hour,
  3191. minute,
  3192. second,
  3193. millisecond,
  3194. isLeapSecond
  3195. ) {
  3196. /**
  3197. * Gets or sets the year as a whole number.
  3198. * @type {Number}
  3199. */
  3200. this.year = year;
  3201. /**
  3202. * Gets or sets the month as a whole number with range [1, 12].
  3203. * @type {Number}
  3204. */
  3205. this.month = month;
  3206. /**
  3207. * Gets or sets the day of the month as a whole number starting at 1.
  3208. * @type {Number}
  3209. */
  3210. this.day = day;
  3211. /**
  3212. * Gets or sets the hour as a whole number with range [0, 23].
  3213. * @type {Number}
  3214. */
  3215. this.hour = hour;
  3216. /**
  3217. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  3218. * @type {Number}
  3219. */
  3220. this.minute = minute;
  3221. /**
  3222. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  3223. * @type {Number}
  3224. */
  3225. this.second = second;
  3226. /**
  3227. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  3228. * @type {Number}
  3229. */
  3230. this.millisecond = millisecond;
  3231. /**
  3232. * Gets or sets whether this time is during a leap second.
  3233. * @type {Boolean}
  3234. */
  3235. this.isLeapSecond = isLeapSecond;
  3236. }
  3237. /**
  3238. * Determines if a given date is a leap year.
  3239. *
  3240. * @function isLeapYear
  3241. *
  3242. * @param {Number} year The year to be tested.
  3243. * @returns {Boolean} True if <code>year</code> is a leap year.
  3244. *
  3245. * @example
  3246. * const leapYear = Cesium.isLeapYear(2000); // true
  3247. */
  3248. function isLeapYear(year) {
  3249. //>>includeStart('debug', pragmas.debug);
  3250. if (year === null || isNaN(year)) {
  3251. throw new RuntimeError.DeveloperError("year is required and must be a number.");
  3252. }
  3253. //>>includeEnd('debug');
  3254. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  3255. }
  3256. /**
  3257. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  3258. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  3259. * @alias LeapSecond
  3260. * @constructor
  3261. *
  3262. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  3263. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  3264. */
  3265. function LeapSecond(date, offset) {
  3266. /**
  3267. * Gets or sets the date at which this leap second occurs.
  3268. * @type {JulianDate}
  3269. */
  3270. this.julianDate = date;
  3271. /**
  3272. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  3273. * of this leap second.
  3274. * @type {Number}
  3275. */
  3276. this.offset = offset;
  3277. }
  3278. /**
  3279. * Constants for time conversions like those done by {@link JulianDate}.
  3280. *
  3281. * @namespace TimeConstants
  3282. *
  3283. * @see JulianDate
  3284. *
  3285. * @private
  3286. */
  3287. const TimeConstants = {
  3288. /**
  3289. * The number of seconds in one millisecond: <code>0.001</code>
  3290. * @type {Number}
  3291. * @constant
  3292. */
  3293. SECONDS_PER_MILLISECOND: 0.001,
  3294. /**
  3295. * The number of seconds in one minute: <code>60</code>.
  3296. * @type {Number}
  3297. * @constant
  3298. */
  3299. SECONDS_PER_MINUTE: 60.0,
  3300. /**
  3301. * The number of minutes in one hour: <code>60</code>.
  3302. * @type {Number}
  3303. * @constant
  3304. */
  3305. MINUTES_PER_HOUR: 60.0,
  3306. /**
  3307. * The number of hours in one day: <code>24</code>.
  3308. * @type {Number}
  3309. * @constant
  3310. */
  3311. HOURS_PER_DAY: 24.0,
  3312. /**
  3313. * The number of seconds in one hour: <code>3600</code>.
  3314. * @type {Number}
  3315. * @constant
  3316. */
  3317. SECONDS_PER_HOUR: 3600.0,
  3318. /**
  3319. * The number of minutes in one day: <code>1440</code>.
  3320. * @type {Number}
  3321. * @constant
  3322. */
  3323. MINUTES_PER_DAY: 1440.0,
  3324. /**
  3325. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  3326. * @type {Number}
  3327. * @constant
  3328. */
  3329. SECONDS_PER_DAY: 86400.0,
  3330. /**
  3331. * The number of days in one Julian century: <code>36525</code>.
  3332. * @type {Number}
  3333. * @constant
  3334. */
  3335. DAYS_PER_JULIAN_CENTURY: 36525.0,
  3336. /**
  3337. * One trillionth of a second.
  3338. * @type {Number}
  3339. * @constant
  3340. */
  3341. PICOSECOND: 0.000000001,
  3342. /**
  3343. * The number of days to subtract from a Julian date to determine the
  3344. * modified Julian date, which gives the number of days since midnight
  3345. * on November 17, 1858.
  3346. * @type {Number}
  3347. * @constant
  3348. */
  3349. MODIFIED_JULIAN_DATE_DIFFERENCE: 2400000.5,
  3350. };
  3351. var TimeConstants$1 = Object.freeze(TimeConstants);
  3352. /**
  3353. * Provides the type of time standards which JulianDate can take as input.
  3354. *
  3355. * @enum {Number}
  3356. *
  3357. * @see JulianDate
  3358. */
  3359. const TimeStandard = {
  3360. /**
  3361. * Represents the coordinated Universal Time (UTC) time standard.
  3362. *
  3363. * UTC is related to TAI according to the relationship
  3364. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  3365. * seconds which have been introduced as of the time in TAI.
  3366. *
  3367. * @type {Number}
  3368. * @constant
  3369. */
  3370. UTC: 0,
  3371. /**
  3372. * Represents the International Atomic Time (TAI) time standard.
  3373. * TAI is the principal time standard to which the other time standards are related.
  3374. *
  3375. * @type {Number}
  3376. * @constant
  3377. */
  3378. TAI: 1,
  3379. };
  3380. var TimeStandard$1 = Object.freeze(TimeStandard);
  3381. const gregorianDateScratch = new GregorianDate();
  3382. const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  3383. const daysInLeapFeburary = 29;
  3384. function compareLeapSecondDates$1(leapSecond, dateToFind) {
  3385. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  3386. }
  3387. // we don't really need a leap second instance, anything with a julianDate property will do
  3388. const binarySearchScratchLeapSecond = new LeapSecond();
  3389. function convertUtcToTai(julianDate) {
  3390. //Even though julianDate is in UTC, we'll treat it as TAI and
  3391. //search the leap second table for it.
  3392. binarySearchScratchLeapSecond.julianDate = julianDate;
  3393. const leapSeconds = JulianDate.leapSeconds;
  3394. let index = binarySearch(
  3395. leapSeconds,
  3396. binarySearchScratchLeapSecond,
  3397. compareLeapSecondDates$1
  3398. );
  3399. if (index < 0) {
  3400. index = ~index;
  3401. }
  3402. if (index >= leapSeconds.length) {
  3403. index = leapSeconds.length - 1;
  3404. }
  3405. let offset = leapSeconds[index].offset;
  3406. if (index > 0) {
  3407. //Now we have the index of the closest leap second that comes on or after our UTC time.
  3408. //However, if the difference between the UTC date being converted and the TAI
  3409. //defined leap second is greater than the offset, we are off by one and need to use
  3410. //the previous leap second.
  3411. const difference = JulianDate.secondsDifference(
  3412. leapSeconds[index].julianDate,
  3413. julianDate
  3414. );
  3415. if (difference > offset) {
  3416. index--;
  3417. offset = leapSeconds[index].offset;
  3418. }
  3419. }
  3420. JulianDate.addSeconds(julianDate, offset, julianDate);
  3421. }
  3422. function convertTaiToUtc(julianDate, result) {
  3423. binarySearchScratchLeapSecond.julianDate = julianDate;
  3424. const leapSeconds = JulianDate.leapSeconds;
  3425. let index = binarySearch(
  3426. leapSeconds,
  3427. binarySearchScratchLeapSecond,
  3428. compareLeapSecondDates$1
  3429. );
  3430. if (index < 0) {
  3431. index = ~index;
  3432. }
  3433. //All times before our first leap second get the first offset.
  3434. if (index === 0) {
  3435. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  3436. }
  3437. //All times after our leap second get the last offset.
  3438. if (index >= leapSeconds.length) {
  3439. return JulianDate.addSeconds(
  3440. julianDate,
  3441. -leapSeconds[index - 1].offset,
  3442. result
  3443. );
  3444. }
  3445. //Compute the difference between the found leap second and the time we are converting.
  3446. const difference = JulianDate.secondsDifference(
  3447. leapSeconds[index].julianDate,
  3448. julianDate
  3449. );
  3450. if (difference === 0) {
  3451. //The date is in our leap second table.
  3452. return JulianDate.addSeconds(
  3453. julianDate,
  3454. -leapSeconds[index].offset,
  3455. result
  3456. );
  3457. }
  3458. if (difference <= 1.0) {
  3459. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  3460. return undefined;
  3461. }
  3462. //The time is in between two leap seconds, index is the leap second after the date
  3463. //we're converting, so we subtract one to get the correct LeapSecond instance.
  3464. return JulianDate.addSeconds(
  3465. julianDate,
  3466. -leapSeconds[--index].offset,
  3467. result
  3468. );
  3469. }
  3470. function setComponents(wholeDays, secondsOfDay, julianDate) {
  3471. const extraDays = (secondsOfDay / TimeConstants$1.SECONDS_PER_DAY) | 0;
  3472. wholeDays += extraDays;
  3473. secondsOfDay -= TimeConstants$1.SECONDS_PER_DAY * extraDays;
  3474. if (secondsOfDay < 0) {
  3475. wholeDays--;
  3476. secondsOfDay += TimeConstants$1.SECONDS_PER_DAY;
  3477. }
  3478. julianDate.dayNumber = wholeDays;
  3479. julianDate.secondsOfDay = secondsOfDay;
  3480. return julianDate;
  3481. }
  3482. function computeJulianDateComponents(
  3483. year,
  3484. month,
  3485. day,
  3486. hour,
  3487. minute,
  3488. second,
  3489. millisecond
  3490. ) {
  3491. // Algorithm from page 604 of the Explanatory Supplement to the
  3492. // Astronomical Almanac (Seidelmann 1992).
  3493. const a = ((month - 14) / 12) | 0;
  3494. const b = year + 4800 + a;
  3495. let dayNumber =
  3496. (((1461 * b) / 4) | 0) +
  3497. (((367 * (month - 2 - 12 * a)) / 12) | 0) -
  3498. (((3 * (((b + 100) / 100) | 0)) / 4) | 0) +
  3499. day -
  3500. 32075;
  3501. // JulianDates are noon-based
  3502. hour = hour - 12;
  3503. if (hour < 0) {
  3504. hour += 24;
  3505. }
  3506. const secondsOfDay =
  3507. second +
  3508. (hour * TimeConstants$1.SECONDS_PER_HOUR +
  3509. minute * TimeConstants$1.SECONDS_PER_MINUTE +
  3510. millisecond * TimeConstants$1.SECONDS_PER_MILLISECOND);
  3511. if (secondsOfDay >= 43200.0) {
  3512. dayNumber -= 1;
  3513. }
  3514. return [dayNumber, secondsOfDay];
  3515. }
  3516. //Regular expressions used for ISO8601 date parsing.
  3517. //YYYY
  3518. const matchCalendarYear = /^(\d{4})$/;
  3519. //YYYY-MM (YYYYMM is invalid)
  3520. const matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  3521. //YYYY-DDD or YYYYDDD
  3522. const matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  3523. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  3524. const matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  3525. //YYYY-MM-DD or YYYYMMDD
  3526. const matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  3527. // Match utc offset
  3528. const utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  3529. // Match hours HH or HH.xxxxx
  3530. const matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  3531. // Match hours/minutes HH:MM HHMM.xxxxx
  3532. const matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  3533. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  3534. const matchHoursMinutesSeconds =
  3535. /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  3536. const iso8601ErrorMessage = "Invalid ISO 8601 date.";
  3537. /**
  3538. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  3539. * For increased precision, this class stores the whole number part of the date and the seconds
  3540. * part of the date in separate components. In order to be safe for arithmetic and represent
  3541. * leap seconds, the date is always stored in the International Atomic Time standard
  3542. * {@link TimeStandard.TAI}.
  3543. * @alias JulianDate
  3544. * @constructor
  3545. *
  3546. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  3547. * @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.
  3548. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  3549. */
  3550. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  3551. /**
  3552. * Gets or sets the number of whole days.
  3553. * @type {Number}
  3554. */
  3555. this.dayNumber = undefined;
  3556. /**
  3557. * Gets or sets the number of seconds into the current day.
  3558. * @type {Number}
  3559. */
  3560. this.secondsOfDay = undefined;
  3561. julianDayNumber = defaultValue.defaultValue(julianDayNumber, 0.0);
  3562. secondsOfDay = defaultValue.defaultValue(secondsOfDay, 0.0);
  3563. timeStandard = defaultValue.defaultValue(timeStandard, TimeStandard$1.UTC);
  3564. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  3565. const wholeDays = julianDayNumber | 0;
  3566. secondsOfDay =
  3567. secondsOfDay +
  3568. (julianDayNumber - wholeDays) * TimeConstants$1.SECONDS_PER_DAY;
  3569. setComponents(wholeDays, secondsOfDay, this);
  3570. if (timeStandard === TimeStandard$1.UTC) {
  3571. convertUtcToTai(this);
  3572. }
  3573. }
  3574. /**
  3575. * Creates a new instance from a GregorianDate.
  3576. *
  3577. * @param {GregorianDate} date A GregorianDate.
  3578. * @param {JulianDate} [result] An existing instance to use for the result.
  3579. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3580. *
  3581. * @exception {DeveloperError} date must be a valid GregorianDate.
  3582. */
  3583. JulianDate.fromGregorianDate = function (date, result) {
  3584. //>>includeStart('debug', pragmas.debug);
  3585. if (!(date instanceof GregorianDate)) {
  3586. throw new RuntimeError.DeveloperError("date must be a valid GregorianDate.");
  3587. }
  3588. //>>includeEnd('debug');
  3589. const components = computeJulianDateComponents(
  3590. date.year,
  3591. date.month,
  3592. date.day,
  3593. date.hour,
  3594. date.minute,
  3595. date.second,
  3596. date.millisecond
  3597. );
  3598. if (!defaultValue.defined(result)) {
  3599. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  3600. }
  3601. setComponents(components[0], components[1], result);
  3602. convertUtcToTai(result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Creates a new instance from a JavaScript Date.
  3607. *
  3608. * @param {Date} date A JavaScript Date.
  3609. * @param {JulianDate} [result] An existing instance to use for the result.
  3610. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3611. *
  3612. * @exception {DeveloperError} date must be a valid JavaScript Date.
  3613. */
  3614. JulianDate.fromDate = function (date, result) {
  3615. //>>includeStart('debug', pragmas.debug);
  3616. if (!(date instanceof Date) || isNaN(date.getTime())) {
  3617. throw new RuntimeError.DeveloperError("date must be a valid JavaScript Date.");
  3618. }
  3619. //>>includeEnd('debug');
  3620. const components = computeJulianDateComponents(
  3621. date.getUTCFullYear(),
  3622. date.getUTCMonth() + 1,
  3623. date.getUTCDate(),
  3624. date.getUTCHours(),
  3625. date.getUTCMinutes(),
  3626. date.getUTCSeconds(),
  3627. date.getUTCMilliseconds()
  3628. );
  3629. if (!defaultValue.defined(result)) {
  3630. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  3631. }
  3632. setComponents(components[0], components[1], result);
  3633. convertUtcToTai(result);
  3634. return result;
  3635. };
  3636. /**
  3637. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  3638. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  3639. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  3640. *
  3641. * @param {String} iso8601String An ISO 8601 date.
  3642. * @param {JulianDate} [result] An existing instance to use for the result.
  3643. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3644. *
  3645. * @exception {DeveloperError} Invalid ISO 8601 date.
  3646. */
  3647. JulianDate.fromIso8601 = function (iso8601String, result) {
  3648. //>>includeStart('debug', pragmas.debug);
  3649. if (typeof iso8601String !== "string") {
  3650. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3651. }
  3652. //>>includeEnd('debug');
  3653. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  3654. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  3655. iso8601String = iso8601String.replace(",", ".");
  3656. //Split the string into its date and time components, denoted by a mandatory T
  3657. let tokens = iso8601String.split("T");
  3658. let year;
  3659. let month = 1;
  3660. let day = 1;
  3661. let hour = 0;
  3662. let minute = 0;
  3663. let second = 0;
  3664. let millisecond = 0;
  3665. //Lacking a time is okay, but a missing date is illegal.
  3666. const date = tokens[0];
  3667. const time = tokens[1];
  3668. let tmp;
  3669. let inLeapYear;
  3670. //>>includeStart('debug', pragmas.debug);
  3671. if (!defaultValue.defined(date)) {
  3672. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3673. }
  3674. let dashCount;
  3675. //>>includeEnd('debug');
  3676. //First match the date against possible regular expressions.
  3677. tokens = date.match(matchCalendarDate);
  3678. if (tokens !== null) {
  3679. //>>includeStart('debug', pragmas.debug);
  3680. dashCount = date.split("-").length - 1;
  3681. if (dashCount > 0 && dashCount !== 2) {
  3682. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3683. }
  3684. //>>includeEnd('debug');
  3685. year = +tokens[1];
  3686. month = +tokens[2];
  3687. day = +tokens[3];
  3688. } else {
  3689. tokens = date.match(matchCalendarMonth);
  3690. if (tokens !== null) {
  3691. year = +tokens[1];
  3692. month = +tokens[2];
  3693. } else {
  3694. tokens = date.match(matchCalendarYear);
  3695. if (tokens !== null) {
  3696. year = +tokens[1];
  3697. } else {
  3698. //Not a year/month/day so it must be an ordinal date.
  3699. let dayOfYear;
  3700. tokens = date.match(matchOrdinalDate);
  3701. if (tokens !== null) {
  3702. year = +tokens[1];
  3703. dayOfYear = +tokens[2];
  3704. inLeapYear = isLeapYear(year);
  3705. //This validation is only applicable for this format.
  3706. //>>includeStart('debug', pragmas.debug);
  3707. if (
  3708. dayOfYear < 1 ||
  3709. (inLeapYear && dayOfYear > 366) ||
  3710. (!inLeapYear && dayOfYear > 365)
  3711. ) {
  3712. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3713. }
  3714. //>>includeEnd('debug')
  3715. } else {
  3716. tokens = date.match(matchWeekDate);
  3717. if (tokens !== null) {
  3718. //ISO week date to ordinal date from
  3719. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  3720. year = +tokens[1];
  3721. const weekNumber = +tokens[2];
  3722. const dayOfWeek = +tokens[3] || 0;
  3723. //>>includeStart('debug', pragmas.debug);
  3724. dashCount = date.split("-").length - 1;
  3725. if (
  3726. dashCount > 0 &&
  3727. ((!defaultValue.defined(tokens[3]) && dashCount !== 1) ||
  3728. (defaultValue.defined(tokens[3]) && dashCount !== 2))
  3729. ) {
  3730. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3731. }
  3732. //>>includeEnd('debug')
  3733. const january4 = new Date(Date.UTC(year, 0, 4));
  3734. dayOfYear = weekNumber * 7 + dayOfWeek - january4.getUTCDay() - 3;
  3735. } else {
  3736. //None of our regular expressions succeeded in parsing the date properly.
  3737. //>>includeStart('debug', pragmas.debug);
  3738. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3739. //>>includeEnd('debug')
  3740. }
  3741. }
  3742. //Split an ordinal date into month/day.
  3743. tmp = new Date(Date.UTC(year, 0, 1));
  3744. tmp.setUTCDate(dayOfYear);
  3745. month = tmp.getUTCMonth() + 1;
  3746. day = tmp.getUTCDate();
  3747. }
  3748. }
  3749. }
  3750. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  3751. inLeapYear = isLeapYear(year);
  3752. //>>includeStart('debug', pragmas.debug);
  3753. if (
  3754. month < 1 ||
  3755. month > 12 ||
  3756. day < 1 ||
  3757. ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) ||
  3758. (inLeapYear && month === 2 && day > daysInLeapFeburary)
  3759. ) {
  3760. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3761. }
  3762. //>>includeEnd('debug')
  3763. //Now move onto the time string, which is much simpler.
  3764. //If no time is specified, it is considered the beginning of the day, UTC to match Javascript's implementation.
  3765. let offsetIndex;
  3766. if (defaultValue.defined(time)) {
  3767. tokens = time.match(matchHoursMinutesSeconds);
  3768. if (tokens !== null) {
  3769. //>>includeStart('debug', pragmas.debug);
  3770. dashCount = time.split(":").length - 1;
  3771. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  3772. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3773. }
  3774. //>>includeEnd('debug')
  3775. hour = +tokens[1];
  3776. minute = +tokens[2];
  3777. second = +tokens[3];
  3778. millisecond = +(tokens[4] || 0) * 1000.0;
  3779. offsetIndex = 5;
  3780. } else {
  3781. tokens = time.match(matchHoursMinutes);
  3782. if (tokens !== null) {
  3783. //>>includeStart('debug', pragmas.debug);
  3784. dashCount = time.split(":").length - 1;
  3785. if (dashCount > 2) {
  3786. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3787. }
  3788. //>>includeEnd('debug')
  3789. hour = +tokens[1];
  3790. minute = +tokens[2];
  3791. second = +(tokens[3] || 0) * 60.0;
  3792. offsetIndex = 4;
  3793. } else {
  3794. tokens = time.match(matchHours);
  3795. if (tokens !== null) {
  3796. hour = +tokens[1];
  3797. minute = +(tokens[2] || 0) * 60.0;
  3798. offsetIndex = 3;
  3799. } else {
  3800. //>>includeStart('debug', pragmas.debug);
  3801. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3802. //>>includeEnd('debug')
  3803. }
  3804. }
  3805. }
  3806. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  3807. //>>includeStart('debug', pragmas.debug);
  3808. if (
  3809. minute >= 60 ||
  3810. second >= 61 ||
  3811. hour > 24 ||
  3812. (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))
  3813. ) {
  3814. throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
  3815. }
  3816. //>>includeEnd('debug');
  3817. //Check the UTC offset value, if no value exists, use local time
  3818. //a Z indicates UTC, + or - are offsets.
  3819. const offset = tokens[offsetIndex];
  3820. const offsetHours = +tokens[offsetIndex + 1];
  3821. const offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  3822. switch (offset) {
  3823. case "+":
  3824. hour = hour - offsetHours;
  3825. minute = minute - offsetMinutes;
  3826. break;
  3827. case "-":
  3828. hour = hour + offsetHours;
  3829. minute = minute + offsetMinutes;
  3830. break;
  3831. case "Z":
  3832. break;
  3833. default:
  3834. minute =
  3835. minute +
  3836. new Date(
  3837. Date.UTC(year, month - 1, day, hour, minute)
  3838. ).getTimezoneOffset();
  3839. break;
  3840. }
  3841. }
  3842. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  3843. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  3844. //Then we add it back in after converting to TAI.
  3845. const isLeapSecond = second === 60;
  3846. if (isLeapSecond) {
  3847. second--;
  3848. }
  3849. //Even if we successfully parsed the string into its components, after applying UTC offset or
  3850. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  3851. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  3852. while (minute >= 60) {
  3853. minute -= 60;
  3854. hour++;
  3855. }
  3856. while (hour >= 24) {
  3857. hour -= 24;
  3858. day++;
  3859. }
  3860. tmp = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  3861. while (day > tmp) {
  3862. day -= tmp;
  3863. month++;
  3864. if (month > 12) {
  3865. month -= 12;
  3866. year++;
  3867. }
  3868. tmp =
  3869. inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  3870. }
  3871. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  3872. while (minute < 0) {
  3873. minute += 60;
  3874. hour--;
  3875. }
  3876. while (hour < 0) {
  3877. hour += 24;
  3878. day--;
  3879. }
  3880. while (day < 1) {
  3881. month--;
  3882. if (month < 1) {
  3883. month += 12;
  3884. year--;
  3885. }
  3886. tmp =
  3887. inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  3888. day += tmp;
  3889. }
  3890. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  3891. const components = computeJulianDateComponents(
  3892. year,
  3893. month,
  3894. day,
  3895. hour,
  3896. minute,
  3897. second,
  3898. millisecond
  3899. );
  3900. if (!defaultValue.defined(result)) {
  3901. result = new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  3902. } else {
  3903. setComponents(components[0], components[1], result);
  3904. convertUtcToTai(result);
  3905. }
  3906. //If we were on a leap second, add it back.
  3907. if (isLeapSecond) {
  3908. JulianDate.addSeconds(result, 1, result);
  3909. }
  3910. return result;
  3911. };
  3912. /**
  3913. * Creates a new instance that represents the current system time.
  3914. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  3915. *
  3916. * @param {JulianDate} [result] An existing instance to use for the result.
  3917. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  3918. */
  3919. JulianDate.now = function (result) {
  3920. return JulianDate.fromDate(new Date(), result);
  3921. };
  3922. const toGregorianDateScratch = new JulianDate(0, 0, TimeStandard$1.TAI);
  3923. /**
  3924. * Creates a {@link GregorianDate} from the provided instance.
  3925. *
  3926. * @param {JulianDate} julianDate The date to be converted.
  3927. * @param {GregorianDate} [result] An existing instance to use for the result.
  3928. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  3929. */
  3930. JulianDate.toGregorianDate = function (julianDate, result) {
  3931. //>>includeStart('debug', pragmas.debug);
  3932. if (!defaultValue.defined(julianDate)) {
  3933. throw new RuntimeError.DeveloperError("julianDate is required.");
  3934. }
  3935. //>>includeEnd('debug');
  3936. let isLeapSecond = false;
  3937. let thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  3938. if (!defaultValue.defined(thisUtc)) {
  3939. //Conversion to UTC will fail if we are during a leap second.
  3940. //If that's the case, subtract a second and convert again.
  3941. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  3942. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  3943. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  3944. isLeapSecond = true;
  3945. }
  3946. let julianDayNumber = thisUtc.dayNumber;
  3947. const secondsOfDay = thisUtc.secondsOfDay;
  3948. if (secondsOfDay >= 43200.0) {
  3949. julianDayNumber += 1;
  3950. }
  3951. // Algorithm from page 604 of the Explanatory Supplement to the
  3952. // Astronomical Almanac (Seidelmann 1992).
  3953. let L = (julianDayNumber + 68569) | 0;
  3954. const N = ((4 * L) / 146097) | 0;
  3955. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  3956. const I = ((4000 * (L + 1)) / 1461001) | 0;
  3957. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  3958. const J = ((80 * L) / 2447) | 0;
  3959. const day = (L - (((2447 * J) / 80) | 0)) | 0;
  3960. L = (J / 11) | 0;
  3961. const month = (J + 2 - 12 * L) | 0;
  3962. const year = (100 * (N - 49) + I + L) | 0;
  3963. let hour = (secondsOfDay / TimeConstants$1.SECONDS_PER_HOUR) | 0;
  3964. let remainingSeconds = secondsOfDay - hour * TimeConstants$1.SECONDS_PER_HOUR;
  3965. const minute = (remainingSeconds / TimeConstants$1.SECONDS_PER_MINUTE) | 0;
  3966. remainingSeconds =
  3967. remainingSeconds - minute * TimeConstants$1.SECONDS_PER_MINUTE;
  3968. let second = remainingSeconds | 0;
  3969. const millisecond =
  3970. (remainingSeconds - second) / TimeConstants$1.SECONDS_PER_MILLISECOND;
  3971. // JulianDates are noon-based
  3972. hour += 12;
  3973. if (hour > 23) {
  3974. hour -= 24;
  3975. }
  3976. //If we were on a leap second, add it back.
  3977. if (isLeapSecond) {
  3978. second += 1;
  3979. }
  3980. if (!defaultValue.defined(result)) {
  3981. return new GregorianDate(
  3982. year,
  3983. month,
  3984. day,
  3985. hour,
  3986. minute,
  3987. second,
  3988. millisecond,
  3989. isLeapSecond
  3990. );
  3991. }
  3992. result.year = year;
  3993. result.month = month;
  3994. result.day = day;
  3995. result.hour = hour;
  3996. result.minute = minute;
  3997. result.second = second;
  3998. result.millisecond = millisecond;
  3999. result.isLeapSecond = isLeapSecond;
  4000. return result;
  4001. };
  4002. /**
  4003. * Creates a JavaScript Date from the provided instance.
  4004. * Since JavaScript dates are only accurate to the nearest millisecond and
  4005. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  4006. * If the provided JulianDate is during a leap second, the previous second is used.
  4007. *
  4008. * @param {JulianDate} julianDate The date to be converted.
  4009. * @returns {Date} A new instance representing the provided date.
  4010. */
  4011. JulianDate.toDate = function (julianDate) {
  4012. //>>includeStart('debug', pragmas.debug);
  4013. if (!defaultValue.defined(julianDate)) {
  4014. throw new RuntimeError.DeveloperError("julianDate is required.");
  4015. }
  4016. //>>includeEnd('debug');
  4017. const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  4018. let second = gDate.second;
  4019. if (gDate.isLeapSecond) {
  4020. second -= 1;
  4021. }
  4022. return new Date(
  4023. Date.UTC(
  4024. gDate.year,
  4025. gDate.month - 1,
  4026. gDate.day,
  4027. gDate.hour,
  4028. gDate.minute,
  4029. second,
  4030. gDate.millisecond
  4031. )
  4032. );
  4033. };
  4034. /**
  4035. * Creates an ISO8601 representation of the provided date.
  4036. *
  4037. * @param {JulianDate} julianDate The date to be converted.
  4038. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  4039. * @returns {String} The ISO8601 representation of the provided date.
  4040. */
  4041. JulianDate.toIso8601 = function (julianDate, precision) {
  4042. //>>includeStart('debug', pragmas.debug);
  4043. if (!defaultValue.defined(julianDate)) {
  4044. throw new RuntimeError.DeveloperError("julianDate is required.");
  4045. }
  4046. //>>includeEnd('debug');
  4047. const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  4048. let year = gDate.year;
  4049. let month = gDate.month;
  4050. let day = gDate.day;
  4051. let hour = gDate.hour;
  4052. const minute = gDate.minute;
  4053. const second = gDate.second;
  4054. const millisecond = gDate.millisecond;
  4055. // special case - Iso8601.MAXIMUM_VALUE produces a string which we can't parse unless we adjust.
  4056. // 10000-01-01T00:00:00 is the same instant as 9999-12-31T24:00:00
  4057. if (
  4058. year === 10000 &&
  4059. month === 1 &&
  4060. day === 1 &&
  4061. hour === 0 &&
  4062. minute === 0 &&
  4063. second === 0 &&
  4064. millisecond === 0
  4065. ) {
  4066. year = 9999;
  4067. month = 12;
  4068. day = 31;
  4069. hour = 24;
  4070. }
  4071. let millisecondStr;
  4072. if (!defaultValue.defined(precision) && millisecond !== 0) {
  4073. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  4074. millisecondStr = (millisecond * 0.01).toString().replace(".", "");
  4075. return `${year.toString().padStart(4, "0")}-${month
  4076. .toString()
  4077. .padStart(2, "0")}-${day
  4078. .toString()
  4079. .padStart(2, "0")}T${hour
  4080. .toString()
  4081. .padStart(2, "0")}:${minute
  4082. .toString()
  4083. .padStart(2, "0")}:${second
  4084. .toString()
  4085. .padStart(2, "0")}.${millisecondStr}Z`;
  4086. }
  4087. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  4088. if (!defaultValue.defined(precision) || precision === 0) {
  4089. return `${year.toString().padStart(4, "0")}-${month
  4090. .toString()
  4091. .padStart(2, "0")}-${day
  4092. .toString()
  4093. .padStart(2, "0")}T${hour
  4094. .toString()
  4095. .padStart(2, "0")}:${minute
  4096. .toString()
  4097. .padStart(2, "0")}:${second.toString().padStart(2, "0")}Z`;
  4098. }
  4099. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  4100. millisecondStr = (millisecond * 0.01)
  4101. .toFixed(precision)
  4102. .replace(".", "")
  4103. .slice(0, precision);
  4104. return `${year.toString().padStart(4, "0")}-${month
  4105. .toString()
  4106. .padStart(2, "0")}-${day
  4107. .toString()
  4108. .padStart(2, "0")}T${hour
  4109. .toString()
  4110. .padStart(2, "0")}:${minute
  4111. .toString()
  4112. .padStart(2, "0")}:${second
  4113. .toString()
  4114. .padStart(2, "0")}.${millisecondStr}Z`;
  4115. };
  4116. /**
  4117. * Duplicates a JulianDate instance.
  4118. *
  4119. * @param {JulianDate} julianDate The date to duplicate.
  4120. * @param {JulianDate} [result] An existing instance to use for the result.
  4121. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  4122. */
  4123. JulianDate.clone = function (julianDate, result) {
  4124. if (!defaultValue.defined(julianDate)) {
  4125. return undefined;
  4126. }
  4127. if (!defaultValue.defined(result)) {
  4128. return new JulianDate(
  4129. julianDate.dayNumber,
  4130. julianDate.secondsOfDay,
  4131. TimeStandard$1.TAI
  4132. );
  4133. }
  4134. result.dayNumber = julianDate.dayNumber;
  4135. result.secondsOfDay = julianDate.secondsOfDay;
  4136. return result;
  4137. };
  4138. /**
  4139. * Compares two instances.
  4140. *
  4141. * @param {JulianDate} left The first instance.
  4142. * @param {JulianDate} right The second instance.
  4143. * @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.
  4144. */
  4145. JulianDate.compare = function (left, right) {
  4146. //>>includeStart('debug', pragmas.debug);
  4147. if (!defaultValue.defined(left)) {
  4148. throw new RuntimeError.DeveloperError("left is required.");
  4149. }
  4150. if (!defaultValue.defined(right)) {
  4151. throw new RuntimeError.DeveloperError("right is required.");
  4152. }
  4153. //>>includeEnd('debug');
  4154. const julianDayNumberDifference = left.dayNumber - right.dayNumber;
  4155. if (julianDayNumberDifference !== 0) {
  4156. return julianDayNumberDifference;
  4157. }
  4158. return left.secondsOfDay - right.secondsOfDay;
  4159. };
  4160. /**
  4161. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  4162. *
  4163. * @param {JulianDate} [left] The first instance.
  4164. * @param {JulianDate} [right] The second instance.
  4165. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  4166. */
  4167. JulianDate.equals = function (left, right) {
  4168. return (
  4169. left === right ||
  4170. (defaultValue.defined(left) &&
  4171. defaultValue.defined(right) &&
  4172. left.dayNumber === right.dayNumber &&
  4173. left.secondsOfDay === right.secondsOfDay)
  4174. );
  4175. };
  4176. /**
  4177. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  4178. * each other. That is, in order for the dates to be considered equal (and for
  4179. * this function to return <code>true</code>), the absolute value of the difference between them, in
  4180. * seconds, must be less than <code>epsilon</code>.
  4181. *
  4182. * @param {JulianDate} [left] The first instance.
  4183. * @param {JulianDate} [right] The second instance.
  4184. * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
  4185. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  4186. */
  4187. JulianDate.equalsEpsilon = function (left, right, epsilon) {
  4188. epsilon = defaultValue.defaultValue(epsilon, 0);
  4189. return (
  4190. left === right ||
  4191. (defaultValue.defined(left) &&
  4192. defaultValue.defined(right) &&
  4193. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon)
  4194. );
  4195. };
  4196. /**
  4197. * Computes the total number of whole and fractional days represented by the provided instance.
  4198. *
  4199. * @param {JulianDate} julianDate The date.
  4200. * @returns {Number} The Julian date as single floating point number.
  4201. */
  4202. JulianDate.totalDays = function (julianDate) {
  4203. //>>includeStart('debug', pragmas.debug);
  4204. if (!defaultValue.defined(julianDate)) {
  4205. throw new RuntimeError.DeveloperError("julianDate is required.");
  4206. }
  4207. //>>includeEnd('debug');
  4208. return (
  4209. julianDate.dayNumber +
  4210. julianDate.secondsOfDay / TimeConstants$1.SECONDS_PER_DAY
  4211. );
  4212. };
  4213. /**
  4214. * Computes the difference in seconds between the provided instance.
  4215. *
  4216. * @param {JulianDate} left The first instance.
  4217. * @param {JulianDate} right The second instance.
  4218. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  4219. */
  4220. JulianDate.secondsDifference = function (left, right) {
  4221. //>>includeStart('debug', pragmas.debug);
  4222. if (!defaultValue.defined(left)) {
  4223. throw new RuntimeError.DeveloperError("left is required.");
  4224. }
  4225. if (!defaultValue.defined(right)) {
  4226. throw new RuntimeError.DeveloperError("right is required.");
  4227. }
  4228. //>>includeEnd('debug');
  4229. const dayDifference =
  4230. (left.dayNumber - right.dayNumber) * TimeConstants$1.SECONDS_PER_DAY;
  4231. return dayDifference + (left.secondsOfDay - right.secondsOfDay);
  4232. };
  4233. /**
  4234. * Computes the difference in days between the provided instance.
  4235. *
  4236. * @param {JulianDate} left The first instance.
  4237. * @param {JulianDate} right The second instance.
  4238. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  4239. */
  4240. JulianDate.daysDifference = function (left, right) {
  4241. //>>includeStart('debug', pragmas.debug);
  4242. if (!defaultValue.defined(left)) {
  4243. throw new RuntimeError.DeveloperError("left is required.");
  4244. }
  4245. if (!defaultValue.defined(right)) {
  4246. throw new RuntimeError.DeveloperError("right is required.");
  4247. }
  4248. //>>includeEnd('debug');
  4249. const dayDifference = left.dayNumber - right.dayNumber;
  4250. const secondDifference =
  4251. (left.secondsOfDay - right.secondsOfDay) / TimeConstants$1.SECONDS_PER_DAY;
  4252. return dayDifference + secondDifference;
  4253. };
  4254. /**
  4255. * Computes the number of seconds the provided instance is ahead of UTC.
  4256. *
  4257. * @param {JulianDate} julianDate The date.
  4258. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  4259. */
  4260. JulianDate.computeTaiMinusUtc = function (julianDate) {
  4261. binarySearchScratchLeapSecond.julianDate = julianDate;
  4262. const leapSeconds = JulianDate.leapSeconds;
  4263. let index = binarySearch(
  4264. leapSeconds,
  4265. binarySearchScratchLeapSecond,
  4266. compareLeapSecondDates$1
  4267. );
  4268. if (index < 0) {
  4269. index = ~index;
  4270. --index;
  4271. if (index < 0) {
  4272. index = 0;
  4273. }
  4274. }
  4275. return leapSeconds[index].offset;
  4276. };
  4277. /**
  4278. * Adds the provided number of seconds to the provided date instance.
  4279. *
  4280. * @param {JulianDate} julianDate The date.
  4281. * @param {Number} seconds The number of seconds to add or subtract.
  4282. * @param {JulianDate} result An existing instance to use for the result.
  4283. * @returns {JulianDate} The modified result parameter.
  4284. */
  4285. JulianDate.addSeconds = function (julianDate, seconds, result) {
  4286. //>>includeStart('debug', pragmas.debug);
  4287. if (!defaultValue.defined(julianDate)) {
  4288. throw new RuntimeError.DeveloperError("julianDate is required.");
  4289. }
  4290. if (!defaultValue.defined(seconds)) {
  4291. throw new RuntimeError.DeveloperError("seconds is required.");
  4292. }
  4293. if (!defaultValue.defined(result)) {
  4294. throw new RuntimeError.DeveloperError("result is required.");
  4295. }
  4296. //>>includeEnd('debug');
  4297. return setComponents(
  4298. julianDate.dayNumber,
  4299. julianDate.secondsOfDay + seconds,
  4300. result
  4301. );
  4302. };
  4303. /**
  4304. * Adds the provided number of minutes to the provided date instance.
  4305. *
  4306. * @param {JulianDate} julianDate The date.
  4307. * @param {Number} minutes The number of minutes to add or subtract.
  4308. * @param {JulianDate} result An existing instance to use for the result.
  4309. * @returns {JulianDate} The modified result parameter.
  4310. */
  4311. JulianDate.addMinutes = function (julianDate, minutes, result) {
  4312. //>>includeStart('debug', pragmas.debug);
  4313. if (!defaultValue.defined(julianDate)) {
  4314. throw new RuntimeError.DeveloperError("julianDate is required.");
  4315. }
  4316. if (!defaultValue.defined(minutes)) {
  4317. throw new RuntimeError.DeveloperError("minutes is required.");
  4318. }
  4319. if (!defaultValue.defined(result)) {
  4320. throw new RuntimeError.DeveloperError("result is required.");
  4321. }
  4322. //>>includeEnd('debug');
  4323. const newSecondsOfDay =
  4324. julianDate.secondsOfDay + minutes * TimeConstants$1.SECONDS_PER_MINUTE;
  4325. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  4326. };
  4327. /**
  4328. * Adds the provided number of hours to the provided date instance.
  4329. *
  4330. * @param {JulianDate} julianDate The date.
  4331. * @param {Number} hours The number of hours to add or subtract.
  4332. * @param {JulianDate} result An existing instance to use for the result.
  4333. * @returns {JulianDate} The modified result parameter.
  4334. */
  4335. JulianDate.addHours = function (julianDate, hours, result) {
  4336. //>>includeStart('debug', pragmas.debug);
  4337. if (!defaultValue.defined(julianDate)) {
  4338. throw new RuntimeError.DeveloperError("julianDate is required.");
  4339. }
  4340. if (!defaultValue.defined(hours)) {
  4341. throw new RuntimeError.DeveloperError("hours is required.");
  4342. }
  4343. if (!defaultValue.defined(result)) {
  4344. throw new RuntimeError.DeveloperError("result is required.");
  4345. }
  4346. //>>includeEnd('debug');
  4347. const newSecondsOfDay =
  4348. julianDate.secondsOfDay + hours * TimeConstants$1.SECONDS_PER_HOUR;
  4349. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  4350. };
  4351. /**
  4352. * Adds the provided number of days to the provided date instance.
  4353. *
  4354. * @param {JulianDate} julianDate The date.
  4355. * @param {Number} days The number of days to add or subtract.
  4356. * @param {JulianDate} result An existing instance to use for the result.
  4357. * @returns {JulianDate} The modified result parameter.
  4358. */
  4359. JulianDate.addDays = function (julianDate, days, result) {
  4360. //>>includeStart('debug', pragmas.debug);
  4361. if (!defaultValue.defined(julianDate)) {
  4362. throw new RuntimeError.DeveloperError("julianDate is required.");
  4363. }
  4364. if (!defaultValue.defined(days)) {
  4365. throw new RuntimeError.DeveloperError("days is required.");
  4366. }
  4367. if (!defaultValue.defined(result)) {
  4368. throw new RuntimeError.DeveloperError("result is required.");
  4369. }
  4370. //>>includeEnd('debug');
  4371. const newJulianDayNumber = julianDate.dayNumber + days;
  4372. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  4373. };
  4374. /**
  4375. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  4376. *
  4377. * @param {JulianDate} left The first instance.
  4378. * @param {JulianDate} right The second instance.
  4379. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  4380. */
  4381. JulianDate.lessThan = function (left, right) {
  4382. return JulianDate.compare(left, right) < 0;
  4383. };
  4384. /**
  4385. * 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.
  4386. *
  4387. * @param {JulianDate} left The first instance.
  4388. * @param {JulianDate} right The second instance.
  4389. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  4390. */
  4391. JulianDate.lessThanOrEquals = function (left, right) {
  4392. return JulianDate.compare(left, right) <= 0;
  4393. };
  4394. /**
  4395. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  4396. *
  4397. * @param {JulianDate} left The first instance.
  4398. * @param {JulianDate} right The second instance.
  4399. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  4400. */
  4401. JulianDate.greaterThan = function (left, right) {
  4402. return JulianDate.compare(left, right) > 0;
  4403. };
  4404. /**
  4405. * 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.
  4406. *
  4407. * @param {JulianDate} left The first instance.
  4408. * @param {JulianDate} right The second instance.
  4409. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  4410. */
  4411. JulianDate.greaterThanOrEquals = function (left, right) {
  4412. return JulianDate.compare(left, right) >= 0;
  4413. };
  4414. /**
  4415. * Duplicates this instance.
  4416. *
  4417. * @param {JulianDate} [result] An existing instance to use for the result.
  4418. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  4419. */
  4420. JulianDate.prototype.clone = function (result) {
  4421. return JulianDate.clone(this, result);
  4422. };
  4423. /**
  4424. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  4425. *
  4426. * @param {JulianDate} [right] The second instance.
  4427. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  4428. */
  4429. JulianDate.prototype.equals = function (right) {
  4430. return JulianDate.equals(this, right);
  4431. };
  4432. /**
  4433. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  4434. * each other. That is, in order for the dates to be considered equal (and for
  4435. * this function to return <code>true</code>), the absolute value of the difference between them, in
  4436. * seconds, must be less than <code>epsilon</code>.
  4437. *
  4438. * @param {JulianDate} [right] The second instance.
  4439. * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
  4440. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  4441. */
  4442. JulianDate.prototype.equalsEpsilon = function (right, epsilon) {
  4443. return JulianDate.equalsEpsilon(this, right, epsilon);
  4444. };
  4445. /**
  4446. * Creates a string representing this date in ISO8601 format.
  4447. *
  4448. * @returns {String} A string representing this date in ISO8601 format.
  4449. */
  4450. JulianDate.prototype.toString = function () {
  4451. return JulianDate.toIso8601(this);
  4452. };
  4453. /**
  4454. * Gets or sets the list of leap seconds used throughout Cesium.
  4455. * @memberof JulianDate
  4456. * @type {LeapSecond[]}
  4457. */
  4458. JulianDate.leapSeconds = [
  4459. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard$1.TAI), 10), // January 1, 1972 00:00:00 UTC
  4460. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard$1.TAI), 11), // July 1, 1972 00:00:00 UTC
  4461. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard$1.TAI), 12), // January 1, 1973 00:00:00 UTC
  4462. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard$1.TAI), 13), // January 1, 1974 00:00:00 UTC
  4463. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard$1.TAI), 14), // January 1, 1975 00:00:00 UTC
  4464. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard$1.TAI), 15), // January 1, 1976 00:00:00 UTC
  4465. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard$1.TAI), 16), // January 1, 1977 00:00:00 UTC
  4466. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard$1.TAI), 17), // January 1, 1978 00:00:00 UTC
  4467. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard$1.TAI), 18), // January 1, 1979 00:00:00 UTC
  4468. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard$1.TAI), 19), // January 1, 1980 00:00:00 UTC
  4469. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard$1.TAI), 20), // July 1, 1981 00:00:00 UTC
  4470. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard$1.TAI), 21), // July 1, 1982 00:00:00 UTC
  4471. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard$1.TAI), 22), // July 1, 1983 00:00:00 UTC
  4472. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard$1.TAI), 23), // July 1, 1985 00:00:00 UTC
  4473. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard$1.TAI), 24), // January 1, 1988 00:00:00 UTC
  4474. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard$1.TAI), 25), // January 1, 1990 00:00:00 UTC
  4475. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard$1.TAI), 26), // January 1, 1991 00:00:00 UTC
  4476. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard$1.TAI), 27), // July 1, 1992 00:00:00 UTC
  4477. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard$1.TAI), 28), // July 1, 1993 00:00:00 UTC
  4478. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard$1.TAI), 29), // July 1, 1994 00:00:00 UTC
  4479. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard$1.TAI), 30), // January 1, 1996 00:00:00 UTC
  4480. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard$1.TAI), 31), // July 1, 1997 00:00:00 UTC
  4481. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard$1.TAI), 32), // January 1, 1999 00:00:00 UTC
  4482. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard$1.TAI), 33), // January 1, 2006 00:00:00 UTC
  4483. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard$1.TAI), 34), // January 1, 2009 00:00:00 UTC
  4484. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard$1.TAI), 35), // July 1, 2012 00:00:00 UTC
  4485. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard$1.TAI), 36), // July 1, 2015 00:00:00 UTC
  4486. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard$1.TAI), 37), // January 1, 2017 00:00:00 UTC
  4487. ];
  4488. /* This file is automatically rebuilt by the Cesium build process. */
  4489. var punycode = _commonjsHelpers3aae1032.createCommonjsModule(function (module, exports) {
  4490. (function(root) {
  4491. /** Detect free variables */
  4492. var freeExports = exports &&
  4493. !exports.nodeType && exports;
  4494. var freeModule = module &&
  4495. !module.nodeType && module;
  4496. var freeGlobal = typeof _commonjsHelpers3aae1032.commonjsGlobal == 'object' && _commonjsHelpers3aae1032.commonjsGlobal;
  4497. if (
  4498. freeGlobal.global === freeGlobal ||
  4499. freeGlobal.window === freeGlobal ||
  4500. freeGlobal.self === freeGlobal
  4501. ) {
  4502. root = freeGlobal;
  4503. }
  4504. /**
  4505. * The `punycode` object.
  4506. * @name punycode
  4507. * @type Object
  4508. */
  4509. var punycode,
  4510. /** Highest positive signed 32-bit float value */
  4511. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  4512. /** Bootstring parameters */
  4513. base = 36,
  4514. tMin = 1,
  4515. tMax = 26,
  4516. skew = 38,
  4517. damp = 700,
  4518. initialBias = 72,
  4519. initialN = 128, // 0x80
  4520. delimiter = '-', // '\x2D'
  4521. /** Regular expressions */
  4522. regexPunycode = /^xn--/,
  4523. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  4524. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  4525. /** Error messages */
  4526. errors = {
  4527. 'overflow': 'Overflow: input needs wider integers to process',
  4528. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  4529. 'invalid-input': 'Invalid input'
  4530. },
  4531. /** Convenience shortcuts */
  4532. baseMinusTMin = base - tMin,
  4533. floor = Math.floor,
  4534. stringFromCharCode = String.fromCharCode,
  4535. /** Temporary variable */
  4536. key;
  4537. /*--------------------------------------------------------------------------*/
  4538. /**
  4539. * A generic error utility function.
  4540. * @private
  4541. * @param {String} type The error type.
  4542. * @returns {Error} Throws a `RangeError` with the applicable error message.
  4543. */
  4544. function error(type) {
  4545. throw new RangeError(errors[type]);
  4546. }
  4547. /**
  4548. * A generic `Array#map` utility function.
  4549. * @private
  4550. * @param {Array} array The array to iterate over.
  4551. * @param {Function} callback The function that gets called for every array
  4552. * item.
  4553. * @returns {Array} A new array of values returned by the callback function.
  4554. */
  4555. function map(array, fn) {
  4556. var length = array.length;
  4557. var result = [];
  4558. while (length--) {
  4559. result[length] = fn(array[length]);
  4560. }
  4561. return result;
  4562. }
  4563. /**
  4564. * A simple `Array#map`-like wrapper to work with domain name strings or email
  4565. * addresses.
  4566. * @private
  4567. * @param {String} domain The domain name or email address.
  4568. * @param {Function} callback The function that gets called for every
  4569. * character.
  4570. * @returns {Array} A new string of characters returned by the callback
  4571. * function.
  4572. */
  4573. function mapDomain(string, fn) {
  4574. var parts = string.split('@');
  4575. var result = '';
  4576. if (parts.length > 1) {
  4577. // In email addresses, only the domain name should be punycoded. Leave
  4578. // the local part (i.e. everything up to `@`) intact.
  4579. result = parts[0] + '@';
  4580. string = parts[1];
  4581. }
  4582. // Avoid `split(regex)` for IE8 compatibility. See #17.
  4583. string = string.replace(regexSeparators, '\x2E');
  4584. var labels = string.split('.');
  4585. var encoded = map(labels, fn).join('.');
  4586. return result + encoded;
  4587. }
  4588. /**
  4589. * Creates an array containing the numeric code points of each Unicode
  4590. * character in the string. While JavaScript uses UCS-2 internally,
  4591. * this function will convert a pair of surrogate halves (each of which
  4592. * UCS-2 exposes as separate characters) into a single code point,
  4593. * matching UTF-16.
  4594. * @see `punycode.ucs2.encode`
  4595. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  4596. * @memberOf punycode.ucs2
  4597. * @name decode
  4598. * @param {String} string The Unicode input string (UCS-2).
  4599. * @returns {Array} The new array of code points.
  4600. */
  4601. function ucs2decode(string) {
  4602. var output = [],
  4603. counter = 0,
  4604. length = string.length,
  4605. value,
  4606. extra;
  4607. while (counter < length) {
  4608. value = string.charCodeAt(counter++);
  4609. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  4610. // high surrogate, and there is a next character
  4611. extra = string.charCodeAt(counter++);
  4612. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  4613. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  4614. } else {
  4615. // unmatched surrogate; only append this code unit, in case the next
  4616. // code unit is the high surrogate of a surrogate pair
  4617. output.push(value);
  4618. counter--;
  4619. }
  4620. } else {
  4621. output.push(value);
  4622. }
  4623. }
  4624. return output;
  4625. }
  4626. /**
  4627. * Creates a string based on an array of numeric code points.
  4628. * @see `punycode.ucs2.decode`
  4629. * @memberOf punycode.ucs2
  4630. * @name encode
  4631. * @param {Array} codePoints The array of numeric code points.
  4632. * @returns {String} The new Unicode string (UCS-2).
  4633. */
  4634. function ucs2encode(array) {
  4635. return map(array, function(value) {
  4636. var output = '';
  4637. if (value > 0xFFFF) {
  4638. value -= 0x10000;
  4639. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  4640. value = 0xDC00 | value & 0x3FF;
  4641. }
  4642. output += stringFromCharCode(value);
  4643. return output;
  4644. }).join('');
  4645. }
  4646. /**
  4647. * Converts a basic code point into a digit/integer.
  4648. * @see `digitToBasic()`
  4649. * @private
  4650. * @param {Number} codePoint The basic numeric code point value.
  4651. * @returns {Number} The numeric value of a basic code point (for use in
  4652. * representing integers) in the range `0` to `base - 1`, or `base` if
  4653. * the code point does not represent a value.
  4654. */
  4655. function basicToDigit(codePoint) {
  4656. if (codePoint - 48 < 10) {
  4657. return codePoint - 22;
  4658. }
  4659. if (codePoint - 65 < 26) {
  4660. return codePoint - 65;
  4661. }
  4662. if (codePoint - 97 < 26) {
  4663. return codePoint - 97;
  4664. }
  4665. return base;
  4666. }
  4667. /**
  4668. * Converts a digit/integer into a basic code point.
  4669. * @see `basicToDigit()`
  4670. * @private
  4671. * @param {Number} digit The numeric value of a basic code point.
  4672. * @returns {Number} The basic code point whose value (when used for
  4673. * representing integers) is `digit`, which needs to be in the range
  4674. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  4675. * used; else, the lowercase form is used. The behavior is undefined
  4676. * if `flag` is non-zero and `digit` has no uppercase form.
  4677. */
  4678. function digitToBasic(digit, flag) {
  4679. // 0..25 map to ASCII a..z or A..Z
  4680. // 26..35 map to ASCII 0..9
  4681. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  4682. }
  4683. /**
  4684. * Bias adaptation function as per section 3.4 of RFC 3492.
  4685. * https://tools.ietf.org/html/rfc3492#section-3.4
  4686. * @private
  4687. */
  4688. function adapt(delta, numPoints, firstTime) {
  4689. var k = 0;
  4690. delta = firstTime ? floor(delta / damp) : delta >> 1;
  4691. delta += floor(delta / numPoints);
  4692. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  4693. delta = floor(delta / baseMinusTMin);
  4694. }
  4695. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  4696. }
  4697. /**
  4698. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  4699. * symbols.
  4700. * @memberOf punycode
  4701. * @param {String} input The Punycode string of ASCII-only symbols.
  4702. * @returns {String} The resulting string of Unicode symbols.
  4703. */
  4704. function decode(input) {
  4705. // Don't use UCS-2
  4706. var output = [],
  4707. inputLength = input.length,
  4708. out,
  4709. i = 0,
  4710. n = initialN,
  4711. bias = initialBias,
  4712. basic,
  4713. j,
  4714. index,
  4715. oldi,
  4716. w,
  4717. k,
  4718. digit,
  4719. t,
  4720. /** Cached calculation results */
  4721. baseMinusT;
  4722. // Handle the basic code points: let `basic` be the number of input code
  4723. // points before the last delimiter, or `0` if there is none, then copy
  4724. // the first basic code points to the output.
  4725. basic = input.lastIndexOf(delimiter);
  4726. if (basic < 0) {
  4727. basic = 0;
  4728. }
  4729. for (j = 0; j < basic; ++j) {
  4730. // if it's not a basic code point
  4731. if (input.charCodeAt(j) >= 0x80) {
  4732. error('not-basic');
  4733. }
  4734. output.push(input.charCodeAt(j));
  4735. }
  4736. // Main decoding loop: start just after the last delimiter if any basic code
  4737. // points were copied; start at the beginning otherwise.
  4738. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  4739. // `index` is the index of the next character to be consumed.
  4740. // Decode a generalized variable-length integer into `delta`,
  4741. // which gets added to `i`. The overflow checking is easier
  4742. // if we increase `i` as we go, then subtract off its starting
  4743. // value at the end to obtain `delta`.
  4744. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  4745. if (index >= inputLength) {
  4746. error('invalid-input');
  4747. }
  4748. digit = basicToDigit(input.charCodeAt(index++));
  4749. if (digit >= base || digit > floor((maxInt - i) / w)) {
  4750. error('overflow');
  4751. }
  4752. i += digit * w;
  4753. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  4754. if (digit < t) {
  4755. break;
  4756. }
  4757. baseMinusT = base - t;
  4758. if (w > floor(maxInt / baseMinusT)) {
  4759. error('overflow');
  4760. }
  4761. w *= baseMinusT;
  4762. }
  4763. out = output.length + 1;
  4764. bias = adapt(i - oldi, out, oldi == 0);
  4765. // `i` was supposed to wrap around from `out` to `0`,
  4766. // incrementing `n` each time, so we'll fix that now:
  4767. if (floor(i / out) > maxInt - n) {
  4768. error('overflow');
  4769. }
  4770. n += floor(i / out);
  4771. i %= out;
  4772. // Insert `n` at position `i` of the output
  4773. output.splice(i++, 0, n);
  4774. }
  4775. return ucs2encode(output);
  4776. }
  4777. /**
  4778. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  4779. * Punycode string of ASCII-only symbols.
  4780. * @memberOf punycode
  4781. * @param {String} input The string of Unicode symbols.
  4782. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  4783. */
  4784. function encode(input) {
  4785. var n,
  4786. delta,
  4787. handledCPCount,
  4788. basicLength,
  4789. bias,
  4790. j,
  4791. m,
  4792. q,
  4793. k,
  4794. t,
  4795. currentValue,
  4796. output = [],
  4797. /** `inputLength` will hold the number of code points in `input`. */
  4798. inputLength,
  4799. /** Cached calculation results */
  4800. handledCPCountPlusOne,
  4801. baseMinusT,
  4802. qMinusT;
  4803. // Convert the input in UCS-2 to Unicode
  4804. input = ucs2decode(input);
  4805. // Cache the length
  4806. inputLength = input.length;
  4807. // Initialize the state
  4808. n = initialN;
  4809. delta = 0;
  4810. bias = initialBias;
  4811. // Handle the basic code points
  4812. for (j = 0; j < inputLength; ++j) {
  4813. currentValue = input[j];
  4814. if (currentValue < 0x80) {
  4815. output.push(stringFromCharCode(currentValue));
  4816. }
  4817. }
  4818. handledCPCount = basicLength = output.length;
  4819. // `handledCPCount` is the number of code points that have been handled;
  4820. // `basicLength` is the number of basic code points.
  4821. // Finish the basic string - if it is not empty - with a delimiter
  4822. if (basicLength) {
  4823. output.push(delimiter);
  4824. }
  4825. // Main encoding loop:
  4826. while (handledCPCount < inputLength) {
  4827. // All non-basic code points < n have been handled already. Find the next
  4828. // larger one:
  4829. for (m = maxInt, j = 0; j < inputLength; ++j) {
  4830. currentValue = input[j];
  4831. if (currentValue >= n && currentValue < m) {
  4832. m = currentValue;
  4833. }
  4834. }
  4835. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  4836. // but guard against overflow
  4837. handledCPCountPlusOne = handledCPCount + 1;
  4838. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  4839. error('overflow');
  4840. }
  4841. delta += (m - n) * handledCPCountPlusOne;
  4842. n = m;
  4843. for (j = 0; j < inputLength; ++j) {
  4844. currentValue = input[j];
  4845. if (currentValue < n && ++delta > maxInt) {
  4846. error('overflow');
  4847. }
  4848. if (currentValue == n) {
  4849. // Represent delta as a generalized variable-length integer
  4850. for (q = delta, k = base; /* no condition */; k += base) {
  4851. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  4852. if (q < t) {
  4853. break;
  4854. }
  4855. qMinusT = q - t;
  4856. baseMinusT = base - t;
  4857. output.push(
  4858. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  4859. );
  4860. q = floor(qMinusT / baseMinusT);
  4861. }
  4862. output.push(stringFromCharCode(digitToBasic(q, 0)));
  4863. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  4864. delta = 0;
  4865. ++handledCPCount;
  4866. }
  4867. }
  4868. ++delta;
  4869. ++n;
  4870. }
  4871. return output.join('');
  4872. }
  4873. /**
  4874. * Converts a Punycode string representing a domain name or an email address
  4875. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  4876. * it doesn't matter if you call it on a string that has already been
  4877. * converted to Unicode.
  4878. * @memberOf punycode
  4879. * @param {String} input The Punycoded domain name or email address to
  4880. * convert to Unicode.
  4881. * @returns {String} The Unicode representation of the given Punycode
  4882. * string.
  4883. */
  4884. function toUnicode(input) {
  4885. return mapDomain(input, function(string) {
  4886. return regexPunycode.test(string)
  4887. ? decode(string.slice(4).toLowerCase())
  4888. : string;
  4889. });
  4890. }
  4891. /**
  4892. * Converts a Unicode string representing a domain name or an email address to
  4893. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  4894. * i.e. it doesn't matter if you call it with a domain that's already in
  4895. * ASCII.
  4896. * @memberOf punycode
  4897. * @param {String} input The domain name or email address to convert, as a
  4898. * Unicode string.
  4899. * @returns {String} The Punycode representation of the given domain name or
  4900. * email address.
  4901. */
  4902. function toASCII(input) {
  4903. return mapDomain(input, function(string) {
  4904. return regexNonASCII.test(string)
  4905. ? 'xn--' + encode(string)
  4906. : string;
  4907. });
  4908. }
  4909. /*--------------------------------------------------------------------------*/
  4910. /** Define the public API */
  4911. punycode = {
  4912. /**
  4913. * A string representing the current Punycode.js version number.
  4914. * @memberOf punycode
  4915. * @type String
  4916. */
  4917. 'version': '1.3.2',
  4918. /**
  4919. * An object of methods to convert from JavaScript's internal character
  4920. * representation (UCS-2) to Unicode code points, and back.
  4921. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  4922. * @memberOf punycode
  4923. * @type Object
  4924. */
  4925. 'ucs2': {
  4926. 'decode': ucs2decode,
  4927. 'encode': ucs2encode
  4928. },
  4929. 'decode': decode,
  4930. 'encode': encode,
  4931. 'toASCII': toASCII,
  4932. 'toUnicode': toUnicode
  4933. };
  4934. /** Expose `punycode` */
  4935. // Some AMD build optimizers, like r.js, check for specific condition patterns
  4936. // like the following:
  4937. if (freeExports && freeModule) {
  4938. if (module.exports == freeExports) {
  4939. // in Node.js, io.js, or RingoJS v0.8.0+
  4940. freeModule.exports = punycode;
  4941. } else {
  4942. // in Narwhal or RingoJS v0.7.0-
  4943. for (key in punycode) {
  4944. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  4945. }
  4946. }
  4947. } else {
  4948. // in Rhino or a web browser
  4949. root.punycode = punycode;
  4950. }
  4951. }(_commonjsHelpers3aae1032.commonjsGlobal));
  4952. });
  4953. var IPv6 = _commonjsHelpers3aae1032.createCommonjsModule(function (module) {
  4954. /*!
  4955. * URI.js - Mutating URLs
  4956. * IPv6 Support
  4957. *
  4958. * Version: 1.19.11
  4959. *
  4960. * Author: Rodney Rehm
  4961. * Web: http://medialize.github.io/URI.js/
  4962. *
  4963. * Licensed under
  4964. * MIT License http://www.opensource.org/licenses/mit-license
  4965. *
  4966. */
  4967. (function (root, factory) {
  4968. // https://github.com/umdjs/umd/blob/master/returnExports.js
  4969. if (module.exports) {
  4970. // Node
  4971. module.exports = factory();
  4972. } else {
  4973. // Browser globals (root is window)
  4974. root.IPv6 = factory(root);
  4975. }
  4976. }(_commonjsHelpers3aae1032.commonjsGlobal, function (root) {
  4977. /*
  4978. var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
  4979. var _out = IPv6.best(_in);
  4980. var _expected = "fe80::204:61ff:fe9d:f156";
  4981. console.log(_in, _out, _expected, _out === _expected);
  4982. */
  4983. // save current IPv6 variable, if any
  4984. var _IPv6 = root && root.IPv6;
  4985. function bestPresentation(address) {
  4986. // based on:
  4987. // Javascript to test an IPv6 address for proper format, and to
  4988. // present the "best text representation" according to IETF Draft RFC at
  4989. // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
  4990. // 8 Feb 2010 Rich Brown, Dartware, LLC
  4991. // Please feel free to use this code as long as you provide a link to
  4992. // http://www.intermapper.com
  4993. // http://intermapper.com/support/tools/IPV6-Validator.aspx
  4994. // http://download.dartware.com/thirdparty/ipv6validator.js
  4995. var _address = address.toLowerCase();
  4996. var segments = _address.split(':');
  4997. var length = segments.length;
  4998. var total = 8;
  4999. // trim colons (:: or ::a:b:c… or …a:b:c::)
  5000. if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
  5001. // must have been ::
  5002. // remove first two items
  5003. segments.shift();
  5004. segments.shift();
  5005. } else if (segments[0] === '' && segments[1] === '') {
  5006. // must have been ::xxxx
  5007. // remove the first item
  5008. segments.shift();
  5009. } else if (segments[length - 1] === '' && segments[length - 2] === '') {
  5010. // must have been xxxx::
  5011. segments.pop();
  5012. }
  5013. length = segments.length;
  5014. // adjust total segments for IPv4 trailer
  5015. if (segments[length - 1].indexOf('.') !== -1) {
  5016. // found a "." which means IPv4
  5017. total = 7;
  5018. }
  5019. // fill empty segments them with "0000"
  5020. var pos;
  5021. for (pos = 0; pos < length; pos++) {
  5022. if (segments[pos] === '') {
  5023. break;
  5024. }
  5025. }
  5026. if (pos < total) {
  5027. segments.splice(pos, 1, '0000');
  5028. while (segments.length < total) {
  5029. segments.splice(pos, 0, '0000');
  5030. }
  5031. }
  5032. // strip leading zeros
  5033. var _segments;
  5034. for (var i = 0; i < total; i++) {
  5035. _segments = segments[i].split('');
  5036. for (var j = 0; j < 3 ; j++) {
  5037. if (_segments[0] === '0' && _segments.length > 1) {
  5038. _segments.splice(0,1);
  5039. } else {
  5040. break;
  5041. }
  5042. }
  5043. segments[i] = _segments.join('');
  5044. }
  5045. // find longest sequence of zeroes and coalesce them into one segment
  5046. var best = -1;
  5047. var _best = 0;
  5048. var _current = 0;
  5049. var current = -1;
  5050. var inzeroes = false;
  5051. // i; already declared
  5052. for (i = 0; i < total; i++) {
  5053. if (inzeroes) {
  5054. if (segments[i] === '0') {
  5055. _current += 1;
  5056. } else {
  5057. inzeroes = false;
  5058. if (_current > _best) {
  5059. best = current;
  5060. _best = _current;
  5061. }
  5062. }
  5063. } else {
  5064. if (segments[i] === '0') {
  5065. inzeroes = true;
  5066. current = i;
  5067. _current = 1;
  5068. }
  5069. }
  5070. }
  5071. if (_current > _best) {
  5072. best = current;
  5073. _best = _current;
  5074. }
  5075. if (_best > 1) {
  5076. segments.splice(best, _best, '');
  5077. }
  5078. length = segments.length;
  5079. // assemble remaining segments
  5080. var result = '';
  5081. if (segments[0] === '') {
  5082. result = ':';
  5083. }
  5084. for (i = 0; i < length; i++) {
  5085. result += segments[i];
  5086. if (i === length - 1) {
  5087. break;
  5088. }
  5089. result += ':';
  5090. }
  5091. if (segments[length - 1] === '') {
  5092. result += ':';
  5093. }
  5094. return result;
  5095. }
  5096. function noConflict() {
  5097. /*jshint validthis: true */
  5098. if (root.IPv6 === this) {
  5099. root.IPv6 = _IPv6;
  5100. }
  5101. return this;
  5102. }
  5103. return {
  5104. best: bestPresentation,
  5105. noConflict: noConflict
  5106. };
  5107. }));
  5108. });
  5109. var SecondLevelDomains = _commonjsHelpers3aae1032.createCommonjsModule(function (module) {
  5110. /*!
  5111. * URI.js - Mutating URLs
  5112. * Second Level Domain (SLD) Support
  5113. *
  5114. * Version: 1.19.11
  5115. *
  5116. * Author: Rodney Rehm
  5117. * Web: http://medialize.github.io/URI.js/
  5118. *
  5119. * Licensed under
  5120. * MIT License http://www.opensource.org/licenses/mit-license
  5121. *
  5122. */
  5123. (function (root, factory) {
  5124. // https://github.com/umdjs/umd/blob/master/returnExports.js
  5125. if (module.exports) {
  5126. // Node
  5127. module.exports = factory();
  5128. } else {
  5129. // Browser globals (root is window)
  5130. root.SecondLevelDomains = factory(root);
  5131. }
  5132. }(_commonjsHelpers3aae1032.commonjsGlobal, function (root) {
  5133. // save current SecondLevelDomains variable, if any
  5134. var _SecondLevelDomains = root && root.SecondLevelDomains;
  5135. var SLD = {
  5136. // list of known Second Level Domains
  5137. // converted list of SLDs from https://github.com/gavingmiller/second-level-domains
  5138. // ----
  5139. // publicsuffix.org is more current and actually used by a couple of browsers internally.
  5140. // downside is it also contains domains like "dyndns.org" - which is fine for the security
  5141. // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
  5142. // ----
  5143. list: {
  5144. 'ac':' com gov mil net org ',
  5145. 'ae':' ac co gov mil name net org pro sch ',
  5146. 'af':' com edu gov net org ',
  5147. 'al':' com edu gov mil net org ',
  5148. 'ao':' co ed gv it og pb ',
  5149. 'ar':' com edu gob gov int mil net org tur ',
  5150. 'at':' ac co gv or ',
  5151. 'au':' asn com csiro edu gov id net org ',
  5152. 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
  5153. 'bb':' biz co com edu gov info net org store tv ',
  5154. 'bh':' biz cc com edu gov info net org ',
  5155. 'bn':' com edu gov net org ',
  5156. 'bo':' com edu gob gov int mil net org tv ',
  5157. '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 ',
  5158. 'bs':' com edu gov net org ',
  5159. 'bz':' du et om ov rg ',
  5160. 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
  5161. 'ck':' biz co edu gen gov info net org ',
  5162. '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 ',
  5163. 'co':' com edu gov mil net nom org ',
  5164. 'cr':' ac c co ed fi go or sa ',
  5165. 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
  5166. 'do':' art com edu gob gov mil net org sld web ',
  5167. 'dz':' art asso com edu gov net org pol ',
  5168. 'ec':' com edu fin gov info med mil net org pro ',
  5169. 'eg':' com edu eun gov mil name net org sci ',
  5170. 'er':' com edu gov ind mil net org rochest w ',
  5171. 'es':' com edu gob nom org ',
  5172. 'et':' biz com edu gov info name net org ',
  5173. 'fj':' ac biz com info mil name net org pro ',
  5174. 'fk':' ac co gov net nom org ',
  5175. 'fr':' asso com f gouv nom prd presse tm ',
  5176. 'gg':' co net org ',
  5177. 'gh':' com edu gov mil org ',
  5178. 'gn':' ac com gov net org ',
  5179. 'gr':' com edu gov mil net org ',
  5180. 'gt':' com edu gob ind mil net org ',
  5181. 'gu':' com edu gov net org ',
  5182. 'hk':' com edu gov idv net org ',
  5183. '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 ',
  5184. 'id':' ac co go mil net or sch web ',
  5185. 'il':' ac co gov idf k12 muni net org ',
  5186. 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
  5187. 'iq':' com edu gov i mil net org ',
  5188. 'ir':' ac co dnssec gov i id net org sch ',
  5189. 'it':' edu gov ',
  5190. 'je':' co net org ',
  5191. 'jo':' com edu gov mil name net org sch ',
  5192. 'jp':' ac ad co ed go gr lg ne or ',
  5193. 'ke':' ac co go info me mobi ne or sc ',
  5194. 'kh':' com edu gov mil net org per ',
  5195. 'ki':' biz com de edu gov info mob net org tel ',
  5196. 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
  5197. 'kn':' edu gov net org ',
  5198. '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 ',
  5199. 'kw':' com edu gov net org ',
  5200. 'ky':' com edu gov net org ',
  5201. 'kz':' com edu gov mil net org ',
  5202. 'lb':' com edu gov net org ',
  5203. 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
  5204. 'lr':' com edu gov net org ',
  5205. 'lv':' asn com conf edu gov id mil net org ',
  5206. 'ly':' com edu gov id med net org plc sch ',
  5207. 'ma':' ac co gov m net org press ',
  5208. 'mc':' asso tm ',
  5209. 'me':' ac co edu gov its net org priv ',
  5210. 'mg':' com edu gov mil nom org prd tm ',
  5211. 'mk':' com edu gov inf name net org pro ',
  5212. 'ml':' com edu gov net org presse ',
  5213. 'mn':' edu gov org ',
  5214. 'mo':' com edu gov net org ',
  5215. 'mt':' com edu gov net org ',
  5216. 'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
  5217. 'mw':' ac co com coop edu gov int museum net org ',
  5218. 'mx':' com edu gob net org ',
  5219. 'my':' com edu gov mil name net org sch ',
  5220. 'nf':' arts com firm info net other per rec store web ',
  5221. 'ng':' biz com edu gov mil mobi name net org sch ',
  5222. 'ni':' ac co com edu gob mil net nom org ',
  5223. 'np':' com edu gov mil net org ',
  5224. 'nr':' biz com edu gov info net org ',
  5225. 'om':' ac biz co com edu gov med mil museum net org pro sch ',
  5226. 'pe':' com edu gob mil net nom org sld ',
  5227. 'ph':' com edu gov i mil net ngo org ',
  5228. 'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
  5229. '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 ',
  5230. 'pr':' ac biz com edu est gov info isla name net org pro prof ',
  5231. 'ps':' com edu gov net org plo sec ',
  5232. 'pw':' belau co ed go ne or ',
  5233. 'ro':' arts com firm info nom nt org rec store tm www ',
  5234. 'rs':' ac co edu gov in org ',
  5235. 'sb':' com edu gov net org ',
  5236. 'sc':' com edu gov net org ',
  5237. 'sh':' co com edu gov net nom org ',
  5238. 'sl':' com edu gov net org ',
  5239. 'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
  5240. 'sv':' com edu gob org red ',
  5241. 'sz':' ac co org ',
  5242. 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
  5243. 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
  5244. 'tw':' club com ebiz edu game gov idv mil net org ',
  5245. 'mu':' ac co com gov net or org ',
  5246. 'mz':' ac co edu gov org ',
  5247. 'na':' co com ',
  5248. 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
  5249. 'pa':' abo ac com edu gob ing med net nom org sld ',
  5250. 'pt':' com edu gov int net nome org publ ',
  5251. 'py':' com edu gov mil net org ',
  5252. 'qa':' com edu gov mil net org ',
  5253. 're':' asso com nom ',
  5254. '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 ',
  5255. 'rw':' ac co com edu gouv gov int mil net ',
  5256. 'sa':' com edu gov med net org pub sch ',
  5257. 'sd':' com edu gov info med net org tv ',
  5258. '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 ',
  5259. 'sg':' com edu gov idn net org per ',
  5260. 'sn':' art com edu gouv org perso univ ',
  5261. 'sy':' com edu gov mil net news org ',
  5262. 'th':' ac co go in mi net or ',
  5263. 'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
  5264. 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
  5265. 'tz':' ac co go ne or ',
  5266. '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 ',
  5267. 'ug':' ac co go ne or org sc ',
  5268. '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 ',
  5269. 'us':' dni fed isa kids nsn ',
  5270. 'uy':' com edu gub mil net org ',
  5271. 've':' co com edu gob info mil net org web ',
  5272. 'vi':' co com k12 net org ',
  5273. 'vn':' ac biz com edu gov health info int name net org pro ',
  5274. 'ye':' co com gov ltd me net org plc ',
  5275. 'yu':' ac co edu gov org ',
  5276. '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 ',
  5277. 'zm':' ac co com edu gov net org sch ',
  5278. // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
  5279. 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
  5280. 'net': 'gb jp se uk ',
  5281. 'org': 'ae',
  5282. 'de': 'com '
  5283. },
  5284. // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
  5285. // in both performance and memory footprint. No initialization required.
  5286. // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
  5287. // Following methods use lastIndexOf() rather than array.split() in order
  5288. // to avoid any memory allocations.
  5289. has: function(domain) {
  5290. var tldOffset = domain.lastIndexOf('.');
  5291. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  5292. return false;
  5293. }
  5294. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  5295. if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
  5296. return false;
  5297. }
  5298. var sldList = SLD.list[domain.slice(tldOffset+1)];
  5299. if (!sldList) {
  5300. return false;
  5301. }
  5302. return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
  5303. },
  5304. is: function(domain) {
  5305. var tldOffset = domain.lastIndexOf('.');
  5306. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  5307. return false;
  5308. }
  5309. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  5310. if (sldOffset >= 0) {
  5311. return false;
  5312. }
  5313. var sldList = SLD.list[domain.slice(tldOffset+1)];
  5314. if (!sldList) {
  5315. return false;
  5316. }
  5317. return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
  5318. },
  5319. get: function(domain) {
  5320. var tldOffset = domain.lastIndexOf('.');
  5321. if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
  5322. return null;
  5323. }
  5324. var sldOffset = domain.lastIndexOf('.', tldOffset-1);
  5325. if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
  5326. return null;
  5327. }
  5328. var sldList = SLD.list[domain.slice(tldOffset+1)];
  5329. if (!sldList) {
  5330. return null;
  5331. }
  5332. if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
  5333. return null;
  5334. }
  5335. return domain.slice(sldOffset+1);
  5336. },
  5337. noConflict: function(){
  5338. if (root.SecondLevelDomains === this) {
  5339. root.SecondLevelDomains = _SecondLevelDomains;
  5340. }
  5341. return this;
  5342. }
  5343. };
  5344. return SLD;
  5345. }));
  5346. });
  5347. var URI = _commonjsHelpers3aae1032.createCommonjsModule(function (module) {
  5348. /*!
  5349. * URI.js - Mutating URLs
  5350. *
  5351. * Version: 1.19.11
  5352. *
  5353. * Author: Rodney Rehm
  5354. * Web: http://medialize.github.io/URI.js/
  5355. *
  5356. * Licensed under
  5357. * MIT License http://www.opensource.org/licenses/mit-license
  5358. *
  5359. */
  5360. (function (root, factory) {
  5361. // https://github.com/umdjs/umd/blob/master/returnExports.js
  5362. if (module.exports) {
  5363. // Node
  5364. module.exports = factory(punycode, IPv6, SecondLevelDomains);
  5365. } else {
  5366. // Browser globals (root is window)
  5367. root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);
  5368. }
  5369. }(_commonjsHelpers3aae1032.commonjsGlobal, function (punycode, IPv6, SLD, root) {
  5370. /*global location, escape, unescape */
  5371. // FIXME: v2.0.0 renamce non-camelCase properties to uppercase
  5372. /*jshint camelcase: false */
  5373. // save current URI variable, if any
  5374. var _URI = root && root.URI;
  5375. function URI(url, base) {
  5376. var _urlSupplied = arguments.length >= 1;
  5377. var _baseSupplied = arguments.length >= 2;
  5378. // Allow instantiation without the 'new' keyword
  5379. if (!(this instanceof URI)) {
  5380. if (_urlSupplied) {
  5381. if (_baseSupplied) {
  5382. return new URI(url, base);
  5383. }
  5384. return new URI(url);
  5385. }
  5386. return new URI();
  5387. }
  5388. if (url === undefined) {
  5389. if (_urlSupplied) {
  5390. throw new TypeError('undefined is not a valid argument for URI');
  5391. }
  5392. if (typeof location !== 'undefined') {
  5393. url = location.href + '';
  5394. } else {
  5395. url = '';
  5396. }
  5397. }
  5398. if (url === null) {
  5399. if (_urlSupplied) {
  5400. throw new TypeError('null is not a valid argument for URI');
  5401. }
  5402. }
  5403. this.href(url);
  5404. // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
  5405. if (base !== undefined) {
  5406. return this.absoluteTo(base);
  5407. }
  5408. return this;
  5409. }
  5410. function isInteger(value) {
  5411. return /^[0-9]+$/.test(value);
  5412. }
  5413. URI.version = '1.19.11';
  5414. var p = URI.prototype;
  5415. var hasOwn = Object.prototype.hasOwnProperty;
  5416. function escapeRegEx(string) {
  5417. // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
  5418. return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  5419. }
  5420. function getType(value) {
  5421. // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
  5422. if (value === undefined) {
  5423. return 'Undefined';
  5424. }
  5425. return String(Object.prototype.toString.call(value)).slice(8, -1);
  5426. }
  5427. function isArray(obj) {
  5428. return getType(obj) === 'Array';
  5429. }
  5430. function filterArrayValues(data, value) {
  5431. var lookup = {};
  5432. var i, length;
  5433. if (getType(value) === 'RegExp') {
  5434. lookup = null;
  5435. } else if (isArray(value)) {
  5436. for (i = 0, length = value.length; i < length; i++) {
  5437. lookup[value[i]] = true;
  5438. }
  5439. } else {
  5440. lookup[value] = true;
  5441. }
  5442. for (i = 0, length = data.length; i < length; i++) {
  5443. /*jshint laxbreak: true */
  5444. var _match = lookup && lookup[data[i]] !== undefined
  5445. || !lookup && value.test(data[i]);
  5446. /*jshint laxbreak: false */
  5447. if (_match) {
  5448. data.splice(i, 1);
  5449. length--;
  5450. i--;
  5451. }
  5452. }
  5453. return data;
  5454. }
  5455. function arrayContains(list, value) {
  5456. var i, length;
  5457. // value may be string, number, array, regexp
  5458. if (isArray(value)) {
  5459. // Note: this can be optimized to O(n) (instead of current O(m * n))
  5460. for (i = 0, length = value.length; i < length; i++) {
  5461. if (!arrayContains(list, value[i])) {
  5462. return false;
  5463. }
  5464. }
  5465. return true;
  5466. }
  5467. var _type = getType(value);
  5468. for (i = 0, length = list.length; i < length; i++) {
  5469. if (_type === 'RegExp') {
  5470. if (typeof list[i] === 'string' && list[i].match(value)) {
  5471. return true;
  5472. }
  5473. } else if (list[i] === value) {
  5474. return true;
  5475. }
  5476. }
  5477. return false;
  5478. }
  5479. function arraysEqual(one, two) {
  5480. if (!isArray(one) || !isArray(two)) {
  5481. return false;
  5482. }
  5483. // arrays can't be equal if they have different amount of content
  5484. if (one.length !== two.length) {
  5485. return false;
  5486. }
  5487. one.sort();
  5488. two.sort();
  5489. for (var i = 0, l = one.length; i < l; i++) {
  5490. if (one[i] !== two[i]) {
  5491. return false;
  5492. }
  5493. }
  5494. return true;
  5495. }
  5496. function trimSlashes(text) {
  5497. var trim_expression = /^\/+|\/+$/g;
  5498. return text.replace(trim_expression, '');
  5499. }
  5500. URI._parts = function() {
  5501. return {
  5502. protocol: null,
  5503. username: null,
  5504. password: null,
  5505. hostname: null,
  5506. urn: null,
  5507. port: null,
  5508. path: null,
  5509. query: null,
  5510. fragment: null,
  5511. // state
  5512. preventInvalidHostname: URI.preventInvalidHostname,
  5513. duplicateQueryParameters: URI.duplicateQueryParameters,
  5514. escapeQuerySpace: URI.escapeQuerySpace
  5515. };
  5516. };
  5517. // state: throw on invalid hostname
  5518. // see https://github.com/medialize/URI.js/pull/345
  5519. // and https://github.com/medialize/URI.js/issues/354
  5520. URI.preventInvalidHostname = false;
  5521. // state: allow duplicate query parameters (a=1&a=1)
  5522. URI.duplicateQueryParameters = false;
  5523. // state: replaces + with %20 (space in query strings)
  5524. URI.escapeQuerySpace = true;
  5525. // static properties
  5526. URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
  5527. URI.idn_expression = /[^a-z0-9\._-]/i;
  5528. URI.punycode_expression = /(xn--)/i;
  5529. // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
  5530. URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  5531. // credits to Rich Brown
  5532. // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
  5533. // specification: http://www.ietf.org/rfc/rfc4291.txt
  5534. 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*$/;
  5535. // expression used is "gruber revised" (@gruber v2) determined to be the
  5536. // best solution in a regex-golf we did a couple of ages ago at
  5537. // * http://mathiasbynens.be/demo/url-regex
  5538. // * http://rodneyrehm.de/t/url-regex.html
  5539. 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;
  5540. URI.findUri = {
  5541. // valid "scheme://" or "www."
  5542. start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
  5543. // everything up to the next whitespace
  5544. end: /[\s\r\n]|$/,
  5545. // trim trailing punctuation captured by end RegExp
  5546. trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
  5547. // balanced parens inclusion (), [], {}, <>
  5548. parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
  5549. };
  5550. URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
  5551. // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  5552. URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g;
  5553. // http://www.iana.org/assignments/uri-schemes.html
  5554. // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
  5555. URI.defaultPorts = {
  5556. http: '80',
  5557. https: '443',
  5558. ftp: '21',
  5559. gopher: '70',
  5560. ws: '80',
  5561. wss: '443'
  5562. };
  5563. // list of protocols which always require a hostname
  5564. URI.hostProtocols = [
  5565. 'http',
  5566. 'https'
  5567. ];
  5568. // allowed hostname characters according to RFC 3986
  5569. // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
  5570. // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
  5571. URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
  5572. // map DOM Elements to their URI attribute
  5573. URI.domAttributes = {
  5574. 'a': 'href',
  5575. 'blockquote': 'cite',
  5576. 'link': 'href',
  5577. 'base': 'href',
  5578. 'script': 'src',
  5579. 'form': 'action',
  5580. 'img': 'src',
  5581. 'area': 'href',
  5582. 'iframe': 'src',
  5583. 'embed': 'src',
  5584. 'source': 'src',
  5585. 'track': 'src',
  5586. 'input': 'src', // but only if type="image"
  5587. 'audio': 'src',
  5588. 'video': 'src'
  5589. };
  5590. URI.getDomAttribute = function(node) {
  5591. if (!node || !node.nodeName) {
  5592. return undefined;
  5593. }
  5594. var nodeName = node.nodeName.toLowerCase();
  5595. // <input> should only expose src for type="image"
  5596. if (nodeName === 'input' && node.type !== 'image') {
  5597. return undefined;
  5598. }
  5599. return URI.domAttributes[nodeName];
  5600. };
  5601. function escapeForDumbFirefox36(value) {
  5602. // https://github.com/medialize/URI.js/issues/91
  5603. return escape(value);
  5604. }
  5605. // encoding / decoding according to RFC3986
  5606. function strictEncodeURIComponent(string) {
  5607. // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
  5608. return encodeURIComponent(string)
  5609. .replace(/[!'()*]/g, escapeForDumbFirefox36)
  5610. .replace(/\*/g, '%2A');
  5611. }
  5612. URI.encode = strictEncodeURIComponent;
  5613. URI.decode = decodeURIComponent;
  5614. URI.iso8859 = function() {
  5615. URI.encode = escape;
  5616. URI.decode = unescape;
  5617. };
  5618. URI.unicode = function() {
  5619. URI.encode = strictEncodeURIComponent;
  5620. URI.decode = decodeURIComponent;
  5621. };
  5622. URI.characters = {
  5623. pathname: {
  5624. encode: {
  5625. // RFC3986 2.1: For consistency, URI producers and normalizers should
  5626. // use uppercase hexadecimal digits for all percent-encodings.
  5627. expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
  5628. map: {
  5629. // -._~!'()*
  5630. '%24': '$',
  5631. '%26': '&',
  5632. '%2B': '+',
  5633. '%2C': ',',
  5634. '%3B': ';',
  5635. '%3D': '=',
  5636. '%3A': ':',
  5637. '%40': '@'
  5638. }
  5639. },
  5640. decode: {
  5641. expression: /[\/\?#]/g,
  5642. map: {
  5643. '/': '%2F',
  5644. '?': '%3F',
  5645. '#': '%23'
  5646. }
  5647. }
  5648. },
  5649. reserved: {
  5650. encode: {
  5651. // RFC3986 2.1: For consistency, URI producers and normalizers should
  5652. // use uppercase hexadecimal digits for all percent-encodings.
  5653. expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
  5654. map: {
  5655. // gen-delims
  5656. '%3A': ':',
  5657. '%2F': '/',
  5658. '%3F': '?',
  5659. '%23': '#',
  5660. '%5B': '[',
  5661. '%5D': ']',
  5662. '%40': '@',
  5663. // sub-delims
  5664. '%21': '!',
  5665. '%24': '$',
  5666. '%26': '&',
  5667. '%27': '\'',
  5668. '%28': '(',
  5669. '%29': ')',
  5670. '%2A': '*',
  5671. '%2B': '+',
  5672. '%2C': ',',
  5673. '%3B': ';',
  5674. '%3D': '='
  5675. }
  5676. }
  5677. },
  5678. urnpath: {
  5679. // The characters under `encode` are the characters called out by RFC 2141 as being acceptable
  5680. // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
  5681. // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
  5682. // note that the colon character is not featured in the encoding map; this is because URI.js
  5683. // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
  5684. // should not appear unencoded in a segment itself.
  5685. // See also the note above about RFC3986 and capitalalized hex digits.
  5686. encode: {
  5687. expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
  5688. map: {
  5689. '%21': '!',
  5690. '%24': '$',
  5691. '%27': '\'',
  5692. '%28': '(',
  5693. '%29': ')',
  5694. '%2A': '*',
  5695. '%2B': '+',
  5696. '%2C': ',',
  5697. '%3B': ';',
  5698. '%3D': '=',
  5699. '%40': '@'
  5700. }
  5701. },
  5702. // These characters are the characters called out by RFC2141 as "reserved" characters that
  5703. // should never appear in a URN, plus the colon character (see note above).
  5704. decode: {
  5705. expression: /[\/\?#:]/g,
  5706. map: {
  5707. '/': '%2F',
  5708. '?': '%3F',
  5709. '#': '%23',
  5710. ':': '%3A'
  5711. }
  5712. }
  5713. }
  5714. };
  5715. URI.encodeQuery = function(string, escapeQuerySpace) {
  5716. var escaped = URI.encode(string + '');
  5717. if (escapeQuerySpace === undefined) {
  5718. escapeQuerySpace = URI.escapeQuerySpace;
  5719. }
  5720. return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
  5721. };
  5722. URI.decodeQuery = function(string, escapeQuerySpace) {
  5723. string += '';
  5724. if (escapeQuerySpace === undefined) {
  5725. escapeQuerySpace = URI.escapeQuerySpace;
  5726. }
  5727. try {
  5728. return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
  5729. } catch(e) {
  5730. // we're not going to mess with weird encodings,
  5731. // give up and return the undecoded original string
  5732. // see https://github.com/medialize/URI.js/issues/87
  5733. // see https://github.com/medialize/URI.js/issues/92
  5734. return string;
  5735. }
  5736. };
  5737. // generate encode/decode path functions
  5738. var _parts = {'encode':'encode', 'decode':'decode'};
  5739. var _part;
  5740. var generateAccessor = function(_group, _part) {
  5741. return function(string) {
  5742. try {
  5743. return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
  5744. return URI.characters[_group][_part].map[c];
  5745. });
  5746. } catch (e) {
  5747. // we're not going to mess with weird encodings,
  5748. // give up and return the undecoded original string
  5749. // see https://github.com/medialize/URI.js/issues/87
  5750. // see https://github.com/medialize/URI.js/issues/92
  5751. return string;
  5752. }
  5753. };
  5754. };
  5755. for (_part in _parts) {
  5756. URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
  5757. URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
  5758. }
  5759. var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
  5760. return function(string) {
  5761. // Why pass in names of functions, rather than the function objects themselves? The
  5762. // definitions of some functions (but in particular, URI.decode) will occasionally change due
  5763. // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
  5764. // that the functions we use here are "fresh".
  5765. var actualCodingFunc;
  5766. if (!_innerCodingFuncName) {
  5767. actualCodingFunc = URI[_codingFuncName];
  5768. } else {
  5769. actualCodingFunc = function(string) {
  5770. return URI[_codingFuncName](URI[_innerCodingFuncName](string));
  5771. };
  5772. }
  5773. var segments = (string + '').split(_sep);
  5774. for (var i = 0, length = segments.length; i < length; i++) {
  5775. segments[i] = actualCodingFunc(segments[i]);
  5776. }
  5777. return segments.join(_sep);
  5778. };
  5779. };
  5780. // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
  5781. URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
  5782. URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
  5783. URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
  5784. URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
  5785. URI.encodeReserved = generateAccessor('reserved', 'encode');
  5786. URI.parse = function(string, parts) {
  5787. var pos;
  5788. if (!parts) {
  5789. parts = {
  5790. preventInvalidHostname: URI.preventInvalidHostname
  5791. };
  5792. }
  5793. string = string.replace(URI.leading_whitespace_expression, '');
  5794. // https://infra.spec.whatwg.org/#ascii-tab-or-newline
  5795. string = string.replace(URI.ascii_tab_whitespace, '');
  5796. // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
  5797. // extract fragment
  5798. pos = string.indexOf('#');
  5799. if (pos > -1) {
  5800. // escaping?
  5801. parts.fragment = string.substring(pos + 1) || null;
  5802. string = string.substring(0, pos);
  5803. }
  5804. // extract query
  5805. pos = string.indexOf('?');
  5806. if (pos > -1) {
  5807. // escaping?
  5808. parts.query = string.substring(pos + 1) || null;
  5809. string = string.substring(0, pos);
  5810. }
  5811. // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
  5812. string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
  5813. // slashes and backslashes have lost all meaning for scheme relative URLs
  5814. string = string.replace(/^[/\\]{2,}/i, '//');
  5815. // extract protocol
  5816. if (string.substring(0, 2) === '//') {
  5817. // relative-scheme
  5818. parts.protocol = null;
  5819. string = string.substring(2);
  5820. // extract "user:pass@host:port"
  5821. string = URI.parseAuthority(string, parts);
  5822. } else {
  5823. pos = string.indexOf(':');
  5824. if (pos > -1) {
  5825. parts.protocol = string.substring(0, pos) || null;
  5826. if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
  5827. // : may be within the path
  5828. parts.protocol = undefined;
  5829. } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
  5830. string = string.substring(pos + 3);
  5831. // extract "user:pass@host:port"
  5832. string = URI.parseAuthority(string, parts);
  5833. } else {
  5834. string = string.substring(pos + 1);
  5835. parts.urn = true;
  5836. }
  5837. }
  5838. }
  5839. // what's left must be the path
  5840. parts.path = string;
  5841. // and we're done
  5842. return parts;
  5843. };
  5844. URI.parseHost = function(string, parts) {
  5845. if (!string) {
  5846. string = '';
  5847. }
  5848. // Copy chrome, IE, opera backslash-handling behavior.
  5849. // Back slashes before the query string get converted to forward slashes
  5850. // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
  5851. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  5852. // https://github.com/medialize/URI.js/pull/233
  5853. string = string.replace(/\\/g, '/');
  5854. // extract host:port
  5855. var pos = string.indexOf('/');
  5856. var bracketPos;
  5857. var t;
  5858. if (pos === -1) {
  5859. pos = string.length;
  5860. }
  5861. if (string.charAt(0) === '[') {
  5862. // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
  5863. // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
  5864. // IPv6+port in the format [2001:db8::1]:80 (for the time being)
  5865. bracketPos = string.indexOf(']');
  5866. parts.hostname = string.substring(1, bracketPos) || null;
  5867. parts.port = string.substring(bracketPos + 2, pos) || null;
  5868. if (parts.port === '/') {
  5869. parts.port = null;
  5870. }
  5871. } else {
  5872. var firstColon = string.indexOf(':');
  5873. var firstSlash = string.indexOf('/');
  5874. var nextColon = string.indexOf(':', firstColon + 1);
  5875. if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
  5876. // IPv6 host contains multiple colons - but no port
  5877. // this notation is actually not allowed by RFC 3986, but we're a liberal parser
  5878. parts.hostname = string.substring(0, pos) || null;
  5879. parts.port = null;
  5880. } else {
  5881. t = string.substring(0, pos).split(':');
  5882. parts.hostname = t[0] || null;
  5883. parts.port = t[1] || null;
  5884. }
  5885. }
  5886. if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
  5887. pos++;
  5888. string = '/' + string;
  5889. }
  5890. if (parts.preventInvalidHostname) {
  5891. URI.ensureValidHostname(parts.hostname, parts.protocol);
  5892. }
  5893. if (parts.port) {
  5894. URI.ensureValidPort(parts.port);
  5895. }
  5896. return string.substring(pos) || '/';
  5897. };
  5898. URI.parseAuthority = function(string, parts) {
  5899. string = URI.parseUserinfo(string, parts);
  5900. return URI.parseHost(string, parts);
  5901. };
  5902. URI.parseUserinfo = function(string, parts) {
  5903. // extract username:password
  5904. var _string = string;
  5905. var firstBackSlash = string.indexOf('\\');
  5906. if (firstBackSlash !== -1) {
  5907. string = string.replace(/\\/g, '/');
  5908. }
  5909. var firstSlash = string.indexOf('/');
  5910. var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
  5911. var t;
  5912. // authority@ must come before /path or \path
  5913. if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
  5914. t = string.substring(0, pos).split(':');
  5915. parts.username = t[0] ? URI.decode(t[0]) : null;
  5916. t.shift();
  5917. parts.password = t[0] ? URI.decode(t.join(':')) : null;
  5918. string = _string.substring(pos + 1);
  5919. } else {
  5920. parts.username = null;
  5921. parts.password = null;
  5922. }
  5923. return string;
  5924. };
  5925. URI.parseQuery = function(string, escapeQuerySpace) {
  5926. if (!string) {
  5927. return {};
  5928. }
  5929. // throw out the funky business - "?"[name"="value"&"]+
  5930. string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
  5931. if (!string) {
  5932. return {};
  5933. }
  5934. var items = {};
  5935. var splits = string.split('&');
  5936. var length = splits.length;
  5937. var v, name, value;
  5938. for (var i = 0; i < length; i++) {
  5939. v = splits[i].split('=');
  5940. name = URI.decodeQuery(v.shift(), escapeQuerySpace);
  5941. // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
  5942. value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
  5943. if (name === '__proto__') {
  5944. // ignore attempt at exploiting JavaScript internals
  5945. continue;
  5946. } else if (hasOwn.call(items, name)) {
  5947. if (typeof items[name] === 'string' || items[name] === null) {
  5948. items[name] = [items[name]];
  5949. }
  5950. items[name].push(value);
  5951. } else {
  5952. items[name] = value;
  5953. }
  5954. }
  5955. return items;
  5956. };
  5957. URI.build = function(parts) {
  5958. var t = '';
  5959. var requireAbsolutePath = false;
  5960. if (parts.protocol) {
  5961. t += parts.protocol + ':';
  5962. }
  5963. if (!parts.urn && (t || parts.hostname)) {
  5964. t += '//';
  5965. requireAbsolutePath = true;
  5966. }
  5967. t += (URI.buildAuthority(parts) || '');
  5968. if (typeof parts.path === 'string') {
  5969. if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
  5970. t += '/';
  5971. }
  5972. t += parts.path;
  5973. }
  5974. if (typeof parts.query === 'string' && parts.query) {
  5975. t += '?' + parts.query;
  5976. }
  5977. if (typeof parts.fragment === 'string' && parts.fragment) {
  5978. t += '#' + parts.fragment;
  5979. }
  5980. return t;
  5981. };
  5982. URI.buildHost = function(parts) {
  5983. var t = '';
  5984. if (!parts.hostname) {
  5985. return '';
  5986. } else if (URI.ip6_expression.test(parts.hostname)) {
  5987. t += '[' + parts.hostname + ']';
  5988. } else {
  5989. t += parts.hostname;
  5990. }
  5991. if (parts.port) {
  5992. t += ':' + parts.port;
  5993. }
  5994. return t;
  5995. };
  5996. URI.buildAuthority = function(parts) {
  5997. return URI.buildUserinfo(parts) + URI.buildHost(parts);
  5998. };
  5999. URI.buildUserinfo = function(parts) {
  6000. var t = '';
  6001. if (parts.username) {
  6002. t += URI.encode(parts.username);
  6003. }
  6004. if (parts.password) {
  6005. t += ':' + URI.encode(parts.password);
  6006. }
  6007. if (t) {
  6008. t += '@';
  6009. }
  6010. return t;
  6011. };
  6012. URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
  6013. // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
  6014. // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
  6015. // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
  6016. // URI.js treats the query string as being application/x-www-form-urlencoded
  6017. // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
  6018. var t = '';
  6019. var unique, key, i, length;
  6020. for (key in data) {
  6021. if (key === '__proto__') {
  6022. // ignore attempt at exploiting JavaScript internals
  6023. continue;
  6024. } else if (hasOwn.call(data, key)) {
  6025. if (isArray(data[key])) {
  6026. unique = {};
  6027. for (i = 0, length = data[key].length; i < length; i++) {
  6028. if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
  6029. t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
  6030. if (duplicateQueryParameters !== true) {
  6031. unique[data[key][i] + ''] = true;
  6032. }
  6033. }
  6034. }
  6035. } else if (data[key] !== undefined) {
  6036. t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
  6037. }
  6038. }
  6039. }
  6040. return t.substring(1);
  6041. };
  6042. URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
  6043. // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
  6044. // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
  6045. return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
  6046. };
  6047. URI.addQuery = function(data, name, value) {
  6048. if (typeof name === 'object') {
  6049. for (var key in name) {
  6050. if (hasOwn.call(name, key)) {
  6051. URI.addQuery(data, key, name[key]);
  6052. }
  6053. }
  6054. } else if (typeof name === 'string') {
  6055. if (data[name] === undefined) {
  6056. data[name] = value;
  6057. return;
  6058. } else if (typeof data[name] === 'string') {
  6059. data[name] = [data[name]];
  6060. }
  6061. if (!isArray(value)) {
  6062. value = [value];
  6063. }
  6064. data[name] = (data[name] || []).concat(value);
  6065. } else {
  6066. throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
  6067. }
  6068. };
  6069. URI.setQuery = function(data, name, value) {
  6070. if (typeof name === 'object') {
  6071. for (var key in name) {
  6072. if (hasOwn.call(name, key)) {
  6073. URI.setQuery(data, key, name[key]);
  6074. }
  6075. }
  6076. } else if (typeof name === 'string') {
  6077. data[name] = value === undefined ? null : value;
  6078. } else {
  6079. throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
  6080. }
  6081. };
  6082. URI.removeQuery = function(data, name, value) {
  6083. var i, length, key;
  6084. if (isArray(name)) {
  6085. for (i = 0, length = name.length; i < length; i++) {
  6086. data[name[i]] = undefined;
  6087. }
  6088. } else if (getType(name) === 'RegExp') {
  6089. for (key in data) {
  6090. if (name.test(key)) {
  6091. data[key] = undefined;
  6092. }
  6093. }
  6094. } else if (typeof name === 'object') {
  6095. for (key in name) {
  6096. if (hasOwn.call(name, key)) {
  6097. URI.removeQuery(data, key, name[key]);
  6098. }
  6099. }
  6100. } else if (typeof name === 'string') {
  6101. if (value !== undefined) {
  6102. if (getType(value) === 'RegExp') {
  6103. if (!isArray(data[name]) && value.test(data[name])) {
  6104. data[name] = undefined;
  6105. } else {
  6106. data[name] = filterArrayValues(data[name], value);
  6107. }
  6108. } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
  6109. data[name] = undefined;
  6110. } else if (isArray(data[name])) {
  6111. data[name] = filterArrayValues(data[name], value);
  6112. }
  6113. } else {
  6114. data[name] = undefined;
  6115. }
  6116. } else {
  6117. throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
  6118. }
  6119. };
  6120. URI.hasQuery = function(data, name, value, withinArray) {
  6121. switch (getType(name)) {
  6122. case 'String':
  6123. // Nothing to do here
  6124. break;
  6125. case 'RegExp':
  6126. for (var key in data) {
  6127. if (hasOwn.call(data, key)) {
  6128. if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
  6129. return true;
  6130. }
  6131. }
  6132. }
  6133. return false;
  6134. case 'Object':
  6135. for (var _key in name) {
  6136. if (hasOwn.call(name, _key)) {
  6137. if (!URI.hasQuery(data, _key, name[_key])) {
  6138. return false;
  6139. }
  6140. }
  6141. }
  6142. return true;
  6143. default:
  6144. throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
  6145. }
  6146. switch (getType(value)) {
  6147. case 'Undefined':
  6148. // true if exists (but may be empty)
  6149. return name in data; // data[name] !== undefined;
  6150. case 'Boolean':
  6151. // true if exists and non-empty
  6152. var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
  6153. return value === _booly;
  6154. case 'Function':
  6155. // allow complex comparison
  6156. return !!value(data[name], name, data);
  6157. case 'Array':
  6158. if (!isArray(data[name])) {
  6159. return false;
  6160. }
  6161. var op = withinArray ? arrayContains : arraysEqual;
  6162. return op(data[name], value);
  6163. case 'RegExp':
  6164. if (!isArray(data[name])) {
  6165. return Boolean(data[name] && data[name].match(value));
  6166. }
  6167. if (!withinArray) {
  6168. return false;
  6169. }
  6170. return arrayContains(data[name], value);
  6171. case 'Number':
  6172. value = String(value);
  6173. /* falls through */
  6174. case 'String':
  6175. if (!isArray(data[name])) {
  6176. return data[name] === value;
  6177. }
  6178. if (!withinArray) {
  6179. return false;
  6180. }
  6181. return arrayContains(data[name], value);
  6182. default:
  6183. throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
  6184. }
  6185. };
  6186. URI.joinPaths = function() {
  6187. var input = [];
  6188. var segments = [];
  6189. var nonEmptySegments = 0;
  6190. for (var i = 0; i < arguments.length; i++) {
  6191. var url = new URI(arguments[i]);
  6192. input.push(url);
  6193. var _segments = url.segment();
  6194. for (var s = 0; s < _segments.length; s++) {
  6195. if (typeof _segments[s] === 'string') {
  6196. segments.push(_segments[s]);
  6197. }
  6198. if (_segments[s]) {
  6199. nonEmptySegments++;
  6200. }
  6201. }
  6202. }
  6203. if (!segments.length || !nonEmptySegments) {
  6204. return new URI('');
  6205. }
  6206. var uri = new URI('').segment(segments);
  6207. if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
  6208. uri.path('/' + uri.path());
  6209. }
  6210. return uri.normalize();
  6211. };
  6212. URI.commonPath = function(one, two) {
  6213. var length = Math.min(one.length, two.length);
  6214. var pos;
  6215. // find first non-matching character
  6216. for (pos = 0; pos < length; pos++) {
  6217. if (one.charAt(pos) !== two.charAt(pos)) {
  6218. pos--;
  6219. break;
  6220. }
  6221. }
  6222. if (pos < 1) {
  6223. return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
  6224. }
  6225. // revert to last /
  6226. if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
  6227. pos = one.substring(0, pos).lastIndexOf('/');
  6228. }
  6229. return one.substring(0, pos + 1);
  6230. };
  6231. URI.withinString = function(string, callback, options) {
  6232. options || (options = {});
  6233. var _start = options.start || URI.findUri.start;
  6234. var _end = options.end || URI.findUri.end;
  6235. var _trim = options.trim || URI.findUri.trim;
  6236. var _parens = options.parens || URI.findUri.parens;
  6237. var _attributeOpen = /[a-z0-9-]=["']?$/i;
  6238. _start.lastIndex = 0;
  6239. while (true) {
  6240. var match = _start.exec(string);
  6241. if (!match) {
  6242. break;
  6243. }
  6244. var start = match.index;
  6245. if (options.ignoreHtml) {
  6246. // attribut(e=["']?$)
  6247. var attributeOpen = string.slice(Math.max(start - 3, 0), start);
  6248. if (attributeOpen && _attributeOpen.test(attributeOpen)) {
  6249. continue;
  6250. }
  6251. }
  6252. var end = start + string.slice(start).search(_end);
  6253. var slice = string.slice(start, end);
  6254. // make sure we include well balanced parens
  6255. var parensEnd = -1;
  6256. while (true) {
  6257. var parensMatch = _parens.exec(slice);
  6258. if (!parensMatch) {
  6259. break;
  6260. }
  6261. var parensMatchEnd = parensMatch.index + parensMatch[0].length;
  6262. parensEnd = Math.max(parensEnd, parensMatchEnd);
  6263. }
  6264. if (parensEnd > -1) {
  6265. slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
  6266. } else {
  6267. slice = slice.replace(_trim, '');
  6268. }
  6269. if (slice.length <= match[0].length) {
  6270. // the extract only contains the starting marker of a URI,
  6271. // e.g. "www" or "http://"
  6272. continue;
  6273. }
  6274. if (options.ignore && options.ignore.test(slice)) {
  6275. continue;
  6276. }
  6277. end = start + slice.length;
  6278. var result = callback(slice, start, end, string);
  6279. if (result === undefined) {
  6280. _start.lastIndex = end;
  6281. continue;
  6282. }
  6283. result = String(result);
  6284. string = string.slice(0, start) + result + string.slice(end);
  6285. _start.lastIndex = start + result.length;
  6286. }
  6287. _start.lastIndex = 0;
  6288. return string;
  6289. };
  6290. URI.ensureValidHostname = function(v, protocol) {
  6291. // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
  6292. // they are not part of DNS and therefore ignored by URI.js
  6293. var hasHostname = !!v; // not null and not an empty string
  6294. var hasProtocol = !!protocol;
  6295. var rejectEmptyHostname = false;
  6296. if (hasProtocol) {
  6297. rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
  6298. }
  6299. if (rejectEmptyHostname && !hasHostname) {
  6300. throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
  6301. } else if (v && v.match(URI.invalid_hostname_characters)) {
  6302. // test punycode
  6303. if (!punycode) {
  6304. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
  6305. }
  6306. if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
  6307. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
  6308. }
  6309. }
  6310. };
  6311. URI.ensureValidPort = function (v) {
  6312. if (!v) {
  6313. return;
  6314. }
  6315. var port = Number(v);
  6316. if (isInteger(port) && (port > 0) && (port < 65536)) {
  6317. return;
  6318. }
  6319. throw new TypeError('Port "' + v + '" is not a valid port');
  6320. };
  6321. // noConflict
  6322. URI.noConflict = function(removeAll) {
  6323. if (removeAll) {
  6324. var unconflicted = {
  6325. URI: this.noConflict()
  6326. };
  6327. if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
  6328. unconflicted.URITemplate = root.URITemplate.noConflict();
  6329. }
  6330. if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
  6331. unconflicted.IPv6 = root.IPv6.noConflict();
  6332. }
  6333. if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
  6334. unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
  6335. }
  6336. return unconflicted;
  6337. } else if (root.URI === this) {
  6338. root.URI = _URI;
  6339. }
  6340. return this;
  6341. };
  6342. p.build = function(deferBuild) {
  6343. if (deferBuild === true) {
  6344. this._deferred_build = true;
  6345. } else if (deferBuild === undefined || this._deferred_build) {
  6346. this._string = URI.build(this._parts);
  6347. this._deferred_build = false;
  6348. }
  6349. return this;
  6350. };
  6351. p.clone = function() {
  6352. return new URI(this);
  6353. };
  6354. p.valueOf = p.toString = function() {
  6355. return this.build(false)._string;
  6356. };
  6357. function generateSimpleAccessor(_part){
  6358. return function(v, build) {
  6359. if (v === undefined) {
  6360. return this._parts[_part] || '';
  6361. } else {
  6362. this._parts[_part] = v || null;
  6363. this.build(!build);
  6364. return this;
  6365. }
  6366. };
  6367. }
  6368. function generatePrefixAccessor(_part, _key){
  6369. return function(v, build) {
  6370. if (v === undefined) {
  6371. return this._parts[_part] || '';
  6372. } else {
  6373. if (v !== null) {
  6374. v = v + '';
  6375. if (v.charAt(0) === _key) {
  6376. v = v.substring(1);
  6377. }
  6378. }
  6379. this._parts[_part] = v;
  6380. this.build(!build);
  6381. return this;
  6382. }
  6383. };
  6384. }
  6385. p.protocol = generateSimpleAccessor('protocol');
  6386. p.username = generateSimpleAccessor('username');
  6387. p.password = generateSimpleAccessor('password');
  6388. p.hostname = generateSimpleAccessor('hostname');
  6389. p.port = generateSimpleAccessor('port');
  6390. p.query = generatePrefixAccessor('query', '?');
  6391. p.fragment = generatePrefixAccessor('fragment', '#');
  6392. p.search = function(v, build) {
  6393. var t = this.query(v, build);
  6394. return typeof t === 'string' && t.length ? ('?' + t) : t;
  6395. };
  6396. p.hash = function(v, build) {
  6397. var t = this.fragment(v, build);
  6398. return typeof t === 'string' && t.length ? ('#' + t) : t;
  6399. };
  6400. p.pathname = function(v, build) {
  6401. if (v === undefined || v === true) {
  6402. var res = this._parts.path || (this._parts.hostname ? '/' : '');
  6403. return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
  6404. } else {
  6405. if (this._parts.urn) {
  6406. this._parts.path = v ? URI.recodeUrnPath(v) : '';
  6407. } else {
  6408. this._parts.path = v ? URI.recodePath(v) : '/';
  6409. }
  6410. this.build(!build);
  6411. return this;
  6412. }
  6413. };
  6414. p.path = p.pathname;
  6415. p.href = function(href, build) {
  6416. var key;
  6417. if (href === undefined) {
  6418. return this.toString();
  6419. }
  6420. this._string = '';
  6421. this._parts = URI._parts();
  6422. var _URI = href instanceof URI;
  6423. var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
  6424. if (href.nodeName) {
  6425. var attribute = URI.getDomAttribute(href);
  6426. href = href[attribute] || '';
  6427. _object = false;
  6428. }
  6429. // window.location is reported to be an object, but it's not the sort
  6430. // of object we're looking for:
  6431. // * location.protocol ends with a colon
  6432. // * location.query != object.search
  6433. // * location.hash != object.fragment
  6434. // simply serializing the unknown object should do the trick
  6435. // (for location, not for everything...)
  6436. if (!_URI && _object && href.pathname !== undefined) {
  6437. href = href.toString();
  6438. }
  6439. if (typeof href === 'string' || href instanceof String) {
  6440. this._parts = URI.parse(String(href), this._parts);
  6441. } else if (_URI || _object) {
  6442. var src = _URI ? href._parts : href;
  6443. for (key in src) {
  6444. if (key === 'query') { continue; }
  6445. if (hasOwn.call(this._parts, key)) {
  6446. this._parts[key] = src[key];
  6447. }
  6448. }
  6449. if (src.query) {
  6450. this.query(src.query, false);
  6451. }
  6452. } else {
  6453. throw new TypeError('invalid input');
  6454. }
  6455. this.build(!build);
  6456. return this;
  6457. };
  6458. // identification accessors
  6459. p.is = function(what) {
  6460. var ip = false;
  6461. var ip4 = false;
  6462. var ip6 = false;
  6463. var name = false;
  6464. var sld = false;
  6465. var idn = false;
  6466. var punycode = false;
  6467. var relative = !this._parts.urn;
  6468. if (this._parts.hostname) {
  6469. relative = false;
  6470. ip4 = URI.ip4_expression.test(this._parts.hostname);
  6471. ip6 = URI.ip6_expression.test(this._parts.hostname);
  6472. ip = ip4 || ip6;
  6473. name = !ip;
  6474. sld = name && SLD && SLD.has(this._parts.hostname);
  6475. idn = name && URI.idn_expression.test(this._parts.hostname);
  6476. punycode = name && URI.punycode_expression.test(this._parts.hostname);
  6477. }
  6478. switch (what.toLowerCase()) {
  6479. case 'relative':
  6480. return relative;
  6481. case 'absolute':
  6482. return !relative;
  6483. // hostname identification
  6484. case 'domain':
  6485. case 'name':
  6486. return name;
  6487. case 'sld':
  6488. return sld;
  6489. case 'ip':
  6490. return ip;
  6491. case 'ip4':
  6492. case 'ipv4':
  6493. case 'inet4':
  6494. return ip4;
  6495. case 'ip6':
  6496. case 'ipv6':
  6497. case 'inet6':
  6498. return ip6;
  6499. case 'idn':
  6500. return idn;
  6501. case 'url':
  6502. return !this._parts.urn;
  6503. case 'urn':
  6504. return !!this._parts.urn;
  6505. case 'punycode':
  6506. return punycode;
  6507. }
  6508. return null;
  6509. };
  6510. // component specific input validation
  6511. var _protocol = p.protocol;
  6512. var _port = p.port;
  6513. var _hostname = p.hostname;
  6514. p.protocol = function(v, build) {
  6515. if (v) {
  6516. // accept trailing ://
  6517. v = v.replace(/:(\/\/)?$/, '');
  6518. if (!v.match(URI.protocol_expression)) {
  6519. throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
  6520. }
  6521. }
  6522. return _protocol.call(this, v, build);
  6523. };
  6524. p.scheme = p.protocol;
  6525. p.port = function(v, build) {
  6526. if (this._parts.urn) {
  6527. return v === undefined ? '' : this;
  6528. }
  6529. if (v !== undefined) {
  6530. if (v === 0) {
  6531. v = null;
  6532. }
  6533. if (v) {
  6534. v += '';
  6535. if (v.charAt(0) === ':') {
  6536. v = v.substring(1);
  6537. }
  6538. URI.ensureValidPort(v);
  6539. }
  6540. }
  6541. return _port.call(this, v, build);
  6542. };
  6543. p.hostname = function(v, build) {
  6544. if (this._parts.urn) {
  6545. return v === undefined ? '' : this;
  6546. }
  6547. if (v !== undefined) {
  6548. var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
  6549. var res = URI.parseHost(v, x);
  6550. if (res !== '/') {
  6551. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  6552. }
  6553. v = x.hostname;
  6554. if (this._parts.preventInvalidHostname) {
  6555. URI.ensureValidHostname(v, this._parts.protocol);
  6556. }
  6557. }
  6558. return _hostname.call(this, v, build);
  6559. };
  6560. // compound accessors
  6561. p.origin = function(v, build) {
  6562. if (this._parts.urn) {
  6563. return v === undefined ? '' : this;
  6564. }
  6565. if (v === undefined) {
  6566. var protocol = this.protocol();
  6567. var authority = this.authority();
  6568. if (!authority) {
  6569. return '';
  6570. }
  6571. return (protocol ? protocol + '://' : '') + this.authority();
  6572. } else {
  6573. var origin = URI(v);
  6574. this
  6575. .protocol(origin.protocol())
  6576. .authority(origin.authority())
  6577. .build(!build);
  6578. return this;
  6579. }
  6580. };
  6581. p.host = function(v, build) {
  6582. if (this._parts.urn) {
  6583. return v === undefined ? '' : this;
  6584. }
  6585. if (v === undefined) {
  6586. return this._parts.hostname ? URI.buildHost(this._parts) : '';
  6587. } else {
  6588. var res = URI.parseHost(v, this._parts);
  6589. if (res !== '/') {
  6590. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  6591. }
  6592. this.build(!build);
  6593. return this;
  6594. }
  6595. };
  6596. p.authority = function(v, build) {
  6597. if (this._parts.urn) {
  6598. return v === undefined ? '' : this;
  6599. }
  6600. if (v === undefined) {
  6601. return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
  6602. } else {
  6603. var res = URI.parseAuthority(v, this._parts);
  6604. if (res !== '/') {
  6605. throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
  6606. }
  6607. this.build(!build);
  6608. return this;
  6609. }
  6610. };
  6611. p.userinfo = function(v, build) {
  6612. if (this._parts.urn) {
  6613. return v === undefined ? '' : this;
  6614. }
  6615. if (v === undefined) {
  6616. var t = URI.buildUserinfo(this._parts);
  6617. return t ? t.substring(0, t.length -1) : t;
  6618. } else {
  6619. if (v[v.length-1] !== '@') {
  6620. v += '@';
  6621. }
  6622. URI.parseUserinfo(v, this._parts);
  6623. this.build(!build);
  6624. return this;
  6625. }
  6626. };
  6627. p.resource = function(v, build) {
  6628. var parts;
  6629. if (v === undefined) {
  6630. return this.path() + this.search() + this.hash();
  6631. }
  6632. parts = URI.parse(v);
  6633. this._parts.path = parts.path;
  6634. this._parts.query = parts.query;
  6635. this._parts.fragment = parts.fragment;
  6636. this.build(!build);
  6637. return this;
  6638. };
  6639. // fraction accessors
  6640. p.subdomain = function(v, build) {
  6641. if (this._parts.urn) {
  6642. return v === undefined ? '' : this;
  6643. }
  6644. // convenience, return "www" from "www.example.org"
  6645. if (v === undefined) {
  6646. if (!this._parts.hostname || this.is('IP')) {
  6647. return '';
  6648. }
  6649. // grab domain and add another segment
  6650. var end = this._parts.hostname.length - this.domain().length - 1;
  6651. return this._parts.hostname.substring(0, end) || '';
  6652. } else {
  6653. var e = this._parts.hostname.length - this.domain().length;
  6654. var sub = this._parts.hostname.substring(0, e);
  6655. var replace = new RegExp('^' + escapeRegEx(sub));
  6656. if (v && v.charAt(v.length - 1) !== '.') {
  6657. v += '.';
  6658. }
  6659. if (v.indexOf(':') !== -1) {
  6660. throw new TypeError('Domains cannot contain colons');
  6661. }
  6662. if (v) {
  6663. URI.ensureValidHostname(v, this._parts.protocol);
  6664. }
  6665. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6666. this.build(!build);
  6667. return this;
  6668. }
  6669. };
  6670. p.domain = function(v, build) {
  6671. if (this._parts.urn) {
  6672. return v === undefined ? '' : this;
  6673. }
  6674. if (typeof v === 'boolean') {
  6675. build = v;
  6676. v = undefined;
  6677. }
  6678. // convenience, return "example.org" from "www.example.org"
  6679. if (v === undefined) {
  6680. if (!this._parts.hostname || this.is('IP')) {
  6681. return '';
  6682. }
  6683. // if hostname consists of 1 or 2 segments, it must be the domain
  6684. var t = this._parts.hostname.match(/\./g);
  6685. if (t && t.length < 2) {
  6686. return this._parts.hostname;
  6687. }
  6688. // grab tld and add another segment
  6689. var end = this._parts.hostname.length - this.tld(build).length - 1;
  6690. end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
  6691. return this._parts.hostname.substring(end) || '';
  6692. } else {
  6693. if (!v) {
  6694. throw new TypeError('cannot set domain empty');
  6695. }
  6696. if (v.indexOf(':') !== -1) {
  6697. throw new TypeError('Domains cannot contain colons');
  6698. }
  6699. URI.ensureValidHostname(v, this._parts.protocol);
  6700. if (!this._parts.hostname || this.is('IP')) {
  6701. this._parts.hostname = v;
  6702. } else {
  6703. var replace = new RegExp(escapeRegEx(this.domain()) + '$');
  6704. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6705. }
  6706. this.build(!build);
  6707. return this;
  6708. }
  6709. };
  6710. p.tld = function(v, build) {
  6711. if (this._parts.urn) {
  6712. return v === undefined ? '' : this;
  6713. }
  6714. if (typeof v === 'boolean') {
  6715. build = v;
  6716. v = undefined;
  6717. }
  6718. // return "org" from "www.example.org"
  6719. if (v === undefined) {
  6720. if (!this._parts.hostname || this.is('IP')) {
  6721. return '';
  6722. }
  6723. var pos = this._parts.hostname.lastIndexOf('.');
  6724. var tld = this._parts.hostname.substring(pos + 1);
  6725. if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
  6726. return SLD.get(this._parts.hostname) || tld;
  6727. }
  6728. return tld;
  6729. } else {
  6730. var replace;
  6731. if (!v) {
  6732. throw new TypeError('cannot set TLD empty');
  6733. } else if (v.match(/[^a-zA-Z0-9-]/)) {
  6734. if (SLD && SLD.is(v)) {
  6735. replace = new RegExp(escapeRegEx(this.tld()) + '$');
  6736. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6737. } else {
  6738. throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
  6739. }
  6740. } else if (!this._parts.hostname || this.is('IP')) {
  6741. throw new ReferenceError('cannot set TLD on non-domain host');
  6742. } else {
  6743. replace = new RegExp(escapeRegEx(this.tld()) + '$');
  6744. this._parts.hostname = this._parts.hostname.replace(replace, v);
  6745. }
  6746. this.build(!build);
  6747. return this;
  6748. }
  6749. };
  6750. p.directory = function(v, build) {
  6751. if (this._parts.urn) {
  6752. return v === undefined ? '' : this;
  6753. }
  6754. if (v === undefined || v === true) {
  6755. if (!this._parts.path && !this._parts.hostname) {
  6756. return '';
  6757. }
  6758. if (this._parts.path === '/') {
  6759. return '/';
  6760. }
  6761. var end = this._parts.path.length - this.filename().length - 1;
  6762. var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
  6763. return v ? URI.decodePath(res) : res;
  6764. } else {
  6765. var e = this._parts.path.length - this.filename().length;
  6766. var directory = this._parts.path.substring(0, e);
  6767. var replace = new RegExp('^' + escapeRegEx(directory));
  6768. // fully qualifier directories begin with a slash
  6769. if (!this.is('relative')) {
  6770. if (!v) {
  6771. v = '/';
  6772. }
  6773. if (v.charAt(0) !== '/') {
  6774. v = '/' + v;
  6775. }
  6776. }
  6777. // directories always end with a slash
  6778. if (v && v.charAt(v.length - 1) !== '/') {
  6779. v += '/';
  6780. }
  6781. v = URI.recodePath(v);
  6782. this._parts.path = this._parts.path.replace(replace, v);
  6783. this.build(!build);
  6784. return this;
  6785. }
  6786. };
  6787. p.filename = function(v, build) {
  6788. if (this._parts.urn) {
  6789. return v === undefined ? '' : this;
  6790. }
  6791. if (typeof v !== 'string') {
  6792. if (!this._parts.path || this._parts.path === '/') {
  6793. return '';
  6794. }
  6795. var pos = this._parts.path.lastIndexOf('/');
  6796. var res = this._parts.path.substring(pos+1);
  6797. return v ? URI.decodePathSegment(res) : res;
  6798. } else {
  6799. var mutatedDirectory = false;
  6800. if (v.charAt(0) === '/') {
  6801. v = v.substring(1);
  6802. }
  6803. if (v.match(/\.?\//)) {
  6804. mutatedDirectory = true;
  6805. }
  6806. var replace = new RegExp(escapeRegEx(this.filename()) + '$');
  6807. v = URI.recodePath(v);
  6808. this._parts.path = this._parts.path.replace(replace, v);
  6809. if (mutatedDirectory) {
  6810. this.normalizePath(build);
  6811. } else {
  6812. this.build(!build);
  6813. }
  6814. return this;
  6815. }
  6816. };
  6817. p.suffix = function(v, build) {
  6818. if (this._parts.urn) {
  6819. return v === undefined ? '' : this;
  6820. }
  6821. if (v === undefined || v === true) {
  6822. if (!this._parts.path || this._parts.path === '/') {
  6823. return '';
  6824. }
  6825. var filename = this.filename();
  6826. var pos = filename.lastIndexOf('.');
  6827. var s, res;
  6828. if (pos === -1) {
  6829. return '';
  6830. }
  6831. // suffix may only contain alnum characters (yup, I made this up.)
  6832. s = filename.substring(pos+1);
  6833. res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
  6834. return v ? URI.decodePathSegment(res) : res;
  6835. } else {
  6836. if (v.charAt(0) === '.') {
  6837. v = v.substring(1);
  6838. }
  6839. var suffix = this.suffix();
  6840. var replace;
  6841. if (!suffix) {
  6842. if (!v) {
  6843. return this;
  6844. }
  6845. this._parts.path += '.' + URI.recodePath(v);
  6846. } else if (!v) {
  6847. replace = new RegExp(escapeRegEx('.' + suffix) + '$');
  6848. } else {
  6849. replace = new RegExp(escapeRegEx(suffix) + '$');
  6850. }
  6851. if (replace) {
  6852. v = URI.recodePath(v);
  6853. this._parts.path = this._parts.path.replace(replace, v);
  6854. }
  6855. this.build(!build);
  6856. return this;
  6857. }
  6858. };
  6859. p.segment = function(segment, v, build) {
  6860. var separator = this._parts.urn ? ':' : '/';
  6861. var path = this.path();
  6862. var absolute = path.substring(0, 1) === '/';
  6863. var segments = path.split(separator);
  6864. if (segment !== undefined && typeof segment !== 'number') {
  6865. build = v;
  6866. v = segment;
  6867. segment = undefined;
  6868. }
  6869. if (segment !== undefined && typeof segment !== 'number') {
  6870. throw new Error('Bad segment "' + segment + '", must be 0-based integer');
  6871. }
  6872. if (absolute) {
  6873. segments.shift();
  6874. }
  6875. if (segment < 0) {
  6876. // allow negative indexes to address from the end
  6877. segment = Math.max(segments.length + segment, 0);
  6878. }
  6879. if (v === undefined) {
  6880. /*jshint laxbreak: true */
  6881. return segment === undefined
  6882. ? segments
  6883. : segments[segment];
  6884. /*jshint laxbreak: false */
  6885. } else if (segment === null || segments[segment] === undefined) {
  6886. if (isArray(v)) {
  6887. segments = [];
  6888. // collapse empty elements within array
  6889. for (var i=0, l=v.length; i < l; i++) {
  6890. if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
  6891. continue;
  6892. }
  6893. if (segments.length && !segments[segments.length -1].length) {
  6894. segments.pop();
  6895. }
  6896. segments.push(trimSlashes(v[i]));
  6897. }
  6898. } else if (v || typeof v === 'string') {
  6899. v = trimSlashes(v);
  6900. if (segments[segments.length -1] === '') {
  6901. // empty trailing elements have to be overwritten
  6902. // to prevent results such as /foo//bar
  6903. segments[segments.length -1] = v;
  6904. } else {
  6905. segments.push(v);
  6906. }
  6907. }
  6908. } else {
  6909. if (v) {
  6910. segments[segment] = trimSlashes(v);
  6911. } else {
  6912. segments.splice(segment, 1);
  6913. }
  6914. }
  6915. if (absolute) {
  6916. segments.unshift('');
  6917. }
  6918. return this.path(segments.join(separator), build);
  6919. };
  6920. p.segmentCoded = function(segment, v, build) {
  6921. var segments, i, l;
  6922. if (typeof segment !== 'number') {
  6923. build = v;
  6924. v = segment;
  6925. segment = undefined;
  6926. }
  6927. if (v === undefined) {
  6928. segments = this.segment(segment, v, build);
  6929. if (!isArray(segments)) {
  6930. segments = segments !== undefined ? URI.decode(segments) : undefined;
  6931. } else {
  6932. for (i = 0, l = segments.length; i < l; i++) {
  6933. segments[i] = URI.decode(segments[i]);
  6934. }
  6935. }
  6936. return segments;
  6937. }
  6938. if (!isArray(v)) {
  6939. v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
  6940. } else {
  6941. for (i = 0, l = v.length; i < l; i++) {
  6942. v[i] = URI.encode(v[i]);
  6943. }
  6944. }
  6945. return this.segment(segment, v, build);
  6946. };
  6947. // mutating query string
  6948. var q = p.query;
  6949. p.query = function(v, build) {
  6950. if (v === true) {
  6951. return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6952. } else if (typeof v === 'function') {
  6953. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6954. var result = v.call(this, data);
  6955. this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  6956. this.build(!build);
  6957. return this;
  6958. } else if (v !== undefined && typeof v !== 'string') {
  6959. this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  6960. this.build(!build);
  6961. return this;
  6962. } else {
  6963. return q.call(this, v, build);
  6964. }
  6965. };
  6966. p.setQuery = function(name, value, build) {
  6967. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6968. if (typeof name === 'string' || name instanceof String) {
  6969. data[name] = value !== undefined ? value : null;
  6970. } else if (typeof name === 'object') {
  6971. for (var key in name) {
  6972. if (hasOwn.call(name, key)) {
  6973. data[key] = name[key];
  6974. }
  6975. }
  6976. } else {
  6977. throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
  6978. }
  6979. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  6980. if (typeof name !== 'string') {
  6981. build = value;
  6982. }
  6983. this.build(!build);
  6984. return this;
  6985. };
  6986. p.addQuery = function(name, value, build) {
  6987. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6988. URI.addQuery(data, name, value === undefined ? null : value);
  6989. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  6990. if (typeof name !== 'string') {
  6991. build = value;
  6992. }
  6993. this.build(!build);
  6994. return this;
  6995. };
  6996. p.removeQuery = function(name, value, build) {
  6997. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  6998. URI.removeQuery(data, name, value);
  6999. this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
  7000. if (typeof name !== 'string') {
  7001. build = value;
  7002. }
  7003. this.build(!build);
  7004. return this;
  7005. };
  7006. p.hasQuery = function(name, value, withinArray) {
  7007. var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
  7008. return URI.hasQuery(data, name, value, withinArray);
  7009. };
  7010. p.setSearch = p.setQuery;
  7011. p.addSearch = p.addQuery;
  7012. p.removeSearch = p.removeQuery;
  7013. p.hasSearch = p.hasQuery;
  7014. // sanitizing URLs
  7015. p.normalize = function() {
  7016. if (this._parts.urn) {
  7017. return this
  7018. .normalizeProtocol(false)
  7019. .normalizePath(false)
  7020. .normalizeQuery(false)
  7021. .normalizeFragment(false)
  7022. .build();
  7023. }
  7024. return this
  7025. .normalizeProtocol(false)
  7026. .normalizeHostname(false)
  7027. .normalizePort(false)
  7028. .normalizePath(false)
  7029. .normalizeQuery(false)
  7030. .normalizeFragment(false)
  7031. .build();
  7032. };
  7033. p.normalizeProtocol = function(build) {
  7034. if (typeof this._parts.protocol === 'string') {
  7035. this._parts.protocol = this._parts.protocol.toLowerCase();
  7036. this.build(!build);
  7037. }
  7038. return this;
  7039. };
  7040. p.normalizeHostname = function(build) {
  7041. if (this._parts.hostname) {
  7042. if (this.is('IDN') && punycode) {
  7043. this._parts.hostname = punycode.toASCII(this._parts.hostname);
  7044. } else if (this.is('IPv6') && IPv6) {
  7045. this._parts.hostname = IPv6.best(this._parts.hostname);
  7046. }
  7047. this._parts.hostname = this._parts.hostname.toLowerCase();
  7048. this.build(!build);
  7049. }
  7050. return this;
  7051. };
  7052. p.normalizePort = function(build) {
  7053. // remove port of it's the protocol's default
  7054. if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
  7055. this._parts.port = null;
  7056. this.build(!build);
  7057. }
  7058. return this;
  7059. };
  7060. p.normalizePath = function(build) {
  7061. var _path = this._parts.path;
  7062. if (!_path) {
  7063. return this;
  7064. }
  7065. if (this._parts.urn) {
  7066. this._parts.path = URI.recodeUrnPath(this._parts.path);
  7067. this.build(!build);
  7068. return this;
  7069. }
  7070. if (this._parts.path === '/') {
  7071. return this;
  7072. }
  7073. _path = URI.recodePath(_path);
  7074. var _was_relative;
  7075. var _leadingParents = '';
  7076. var _parent, _pos;
  7077. // handle relative paths
  7078. if (_path.charAt(0) !== '/') {
  7079. _was_relative = true;
  7080. _path = '/' + _path;
  7081. }
  7082. // handle relative files (as opposed to directories)
  7083. if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
  7084. _path += '/';
  7085. }
  7086. // resolve simples
  7087. _path = _path
  7088. .replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
  7089. .replace(/\/{2,}/g, '/');
  7090. // remember leading parents
  7091. if (_was_relative) {
  7092. _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
  7093. if (_leadingParents) {
  7094. _leadingParents = _leadingParents[0];
  7095. }
  7096. }
  7097. // resolve parents
  7098. while (true) {
  7099. _parent = _path.search(/\/\.\.(\/|$)/);
  7100. if (_parent === -1) {
  7101. // no more ../ to resolve
  7102. break;
  7103. } else if (_parent === 0) {
  7104. // top level cannot be relative, skip it
  7105. _path = _path.substring(3);
  7106. continue;
  7107. }
  7108. _pos = _path.substring(0, _parent).lastIndexOf('/');
  7109. if (_pos === -1) {
  7110. _pos = _parent;
  7111. }
  7112. _path = _path.substring(0, _pos) + _path.substring(_parent + 3);
  7113. }
  7114. // revert to relative
  7115. if (_was_relative && this.is('relative')) {
  7116. _path = _leadingParents + _path.substring(1);
  7117. }
  7118. this._parts.path = _path;
  7119. this.build(!build);
  7120. return this;
  7121. };
  7122. p.normalizePathname = p.normalizePath;
  7123. p.normalizeQuery = function(build) {
  7124. if (typeof this._parts.query === 'string') {
  7125. if (!this._parts.query.length) {
  7126. this._parts.query = null;
  7127. } else {
  7128. this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
  7129. }
  7130. this.build(!build);
  7131. }
  7132. return this;
  7133. };
  7134. p.normalizeFragment = function(build) {
  7135. if (!this._parts.fragment) {
  7136. this._parts.fragment = null;
  7137. this.build(!build);
  7138. }
  7139. return this;
  7140. };
  7141. p.normalizeSearch = p.normalizeQuery;
  7142. p.normalizeHash = p.normalizeFragment;
  7143. p.iso8859 = function() {
  7144. // expect unicode input, iso8859 output
  7145. var e = URI.encode;
  7146. var d = URI.decode;
  7147. URI.encode = escape;
  7148. URI.decode = decodeURIComponent;
  7149. try {
  7150. this.normalize();
  7151. } finally {
  7152. URI.encode = e;
  7153. URI.decode = d;
  7154. }
  7155. return this;
  7156. };
  7157. p.unicode = function() {
  7158. // expect iso8859 input, unicode output
  7159. var e = URI.encode;
  7160. var d = URI.decode;
  7161. URI.encode = strictEncodeURIComponent;
  7162. URI.decode = unescape;
  7163. try {
  7164. this.normalize();
  7165. } finally {
  7166. URI.encode = e;
  7167. URI.decode = d;
  7168. }
  7169. return this;
  7170. };
  7171. p.readable = function() {
  7172. var uri = this.clone();
  7173. // removing username, password, because they shouldn't be displayed according to RFC 3986
  7174. uri.username('').password('').normalize();
  7175. var t = '';
  7176. if (uri._parts.protocol) {
  7177. t += uri._parts.protocol + '://';
  7178. }
  7179. if (uri._parts.hostname) {
  7180. if (uri.is('punycode') && punycode) {
  7181. t += punycode.toUnicode(uri._parts.hostname);
  7182. if (uri._parts.port) {
  7183. t += ':' + uri._parts.port;
  7184. }
  7185. } else {
  7186. t += uri.host();
  7187. }
  7188. }
  7189. if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
  7190. t += '/';
  7191. }
  7192. t += uri.path(true);
  7193. if (uri._parts.query) {
  7194. var q = '';
  7195. for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
  7196. var kv = (qp[i] || '').split('=');
  7197. q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
  7198. .replace(/&/g, '%26');
  7199. if (kv[1] !== undefined) {
  7200. q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
  7201. .replace(/&/g, '%26');
  7202. }
  7203. }
  7204. t += '?' + q.substring(1);
  7205. }
  7206. t += URI.decodeQuery(uri.hash(), true);
  7207. return t;
  7208. };
  7209. // resolving relative and absolute URLs
  7210. p.absoluteTo = function(base) {
  7211. var resolved = this.clone();
  7212. var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
  7213. var basedir, i, p;
  7214. if (this._parts.urn) {
  7215. throw new Error('URNs do not have any generally defined hierarchical components');
  7216. }
  7217. if (!(base instanceof URI)) {
  7218. base = new URI(base);
  7219. }
  7220. if (resolved._parts.protocol) {
  7221. // Directly returns even if this._parts.hostname is empty.
  7222. return resolved;
  7223. } else {
  7224. resolved._parts.protocol = base._parts.protocol;
  7225. }
  7226. if (this._parts.hostname) {
  7227. return resolved;
  7228. }
  7229. for (i = 0; (p = properties[i]); i++) {
  7230. resolved._parts[p] = base._parts[p];
  7231. }
  7232. if (!resolved._parts.path) {
  7233. resolved._parts.path = base._parts.path;
  7234. if (!resolved._parts.query) {
  7235. resolved._parts.query = base._parts.query;
  7236. }
  7237. } else {
  7238. if (resolved._parts.path.substring(-2) === '..') {
  7239. resolved._parts.path += '/';
  7240. }
  7241. if (resolved.path().charAt(0) !== '/') {
  7242. basedir = base.directory();
  7243. basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
  7244. resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
  7245. resolved.normalizePath();
  7246. }
  7247. }
  7248. resolved.build();
  7249. return resolved;
  7250. };
  7251. p.relativeTo = function(base) {
  7252. var relative = this.clone().normalize();
  7253. var relativeParts, baseParts, common, relativePath, basePath;
  7254. if (relative._parts.urn) {
  7255. throw new Error('URNs do not have any generally defined hierarchical components');
  7256. }
  7257. base = new URI(base).normalize();
  7258. relativeParts = relative._parts;
  7259. baseParts = base._parts;
  7260. relativePath = relative.path();
  7261. basePath = base.path();
  7262. if (relativePath.charAt(0) !== '/') {
  7263. throw new Error('URI is already relative');
  7264. }
  7265. if (basePath.charAt(0) !== '/') {
  7266. throw new Error('Cannot calculate a URI relative to another relative URI');
  7267. }
  7268. if (relativeParts.protocol === baseParts.protocol) {
  7269. relativeParts.protocol = null;
  7270. }
  7271. if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
  7272. return relative.build();
  7273. }
  7274. if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
  7275. return relative.build();
  7276. }
  7277. if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
  7278. relativeParts.hostname = null;
  7279. relativeParts.port = null;
  7280. } else {
  7281. return relative.build();
  7282. }
  7283. if (relativePath === basePath) {
  7284. relativeParts.path = '';
  7285. return relative.build();
  7286. }
  7287. // determine common sub path
  7288. common = URI.commonPath(relativePath, basePath);
  7289. // If the paths have nothing in common, return a relative URL with the absolute path.
  7290. if (!common) {
  7291. return relative.build();
  7292. }
  7293. var parents = baseParts.path
  7294. .substring(common.length)
  7295. .replace(/[^\/]*$/, '')
  7296. .replace(/.*?\//g, '../');
  7297. relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
  7298. return relative.build();
  7299. };
  7300. // comparing URIs
  7301. p.equals = function(uri) {
  7302. var one = this.clone();
  7303. var two = new URI(uri);
  7304. var one_map = {};
  7305. var two_map = {};
  7306. var checked = {};
  7307. var one_query, two_query, key;
  7308. one.normalize();
  7309. two.normalize();
  7310. // exact match
  7311. if (one.toString() === two.toString()) {
  7312. return true;
  7313. }
  7314. // extract query string
  7315. one_query = one.query();
  7316. two_query = two.query();
  7317. one.query('');
  7318. two.query('');
  7319. // definitely not equal if not even non-query parts match
  7320. if (one.toString() !== two.toString()) {
  7321. return false;
  7322. }
  7323. // query parameters have the same length, even if they're permuted
  7324. if (one_query.length !== two_query.length) {
  7325. return false;
  7326. }
  7327. one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
  7328. two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
  7329. for (key in one_map) {
  7330. if (hasOwn.call(one_map, key)) {
  7331. if (!isArray(one_map[key])) {
  7332. if (one_map[key] !== two_map[key]) {
  7333. return false;
  7334. }
  7335. } else if (!arraysEqual(one_map[key], two_map[key])) {
  7336. return false;
  7337. }
  7338. checked[key] = true;
  7339. }
  7340. }
  7341. for (key in two_map) {
  7342. if (hasOwn.call(two_map, key)) {
  7343. if (!checked[key]) {
  7344. // two contains a parameter not present in one
  7345. return false;
  7346. }
  7347. }
  7348. }
  7349. return true;
  7350. };
  7351. // state
  7352. p.preventInvalidHostname = function(v) {
  7353. this._parts.preventInvalidHostname = !!v;
  7354. return this;
  7355. };
  7356. p.duplicateQueryParameters = function(v) {
  7357. this._parts.duplicateQueryParameters = !!v;
  7358. return this;
  7359. };
  7360. p.escapeQuerySpace = function(v) {
  7361. this._parts.escapeQuerySpace = !!v;
  7362. return this;
  7363. };
  7364. return URI;
  7365. }));
  7366. });
  7367. /**
  7368. * @private
  7369. */
  7370. function appendForwardSlash(url) {
  7371. if (url.length === 0 || url[url.length - 1] !== "/") {
  7372. url = `${url}/`;
  7373. }
  7374. return url;
  7375. }
  7376. /**
  7377. * Clones an object, returning a new object containing the same properties.
  7378. *
  7379. * @function
  7380. *
  7381. * @param {Object} object The object to clone.
  7382. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  7383. * @returns {Object} The cloned object.
  7384. */
  7385. function clone(object, deep) {
  7386. if (object === null || typeof object !== "object") {
  7387. return object;
  7388. }
  7389. deep = defaultValue.defaultValue(deep, false);
  7390. const result = new object.constructor();
  7391. for (const propertyName in object) {
  7392. if (object.hasOwnProperty(propertyName)) {
  7393. let value = object[propertyName];
  7394. if (deep) {
  7395. value = clone(value, deep);
  7396. }
  7397. result[propertyName] = value;
  7398. }
  7399. }
  7400. return result;
  7401. }
  7402. /**
  7403. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  7404. * @function
  7405. *
  7406. * @param {String} relative The relative Uri.
  7407. * @param {String} [base] The base Uri.
  7408. * @returns {String} The absolute Uri of the given relative Uri.
  7409. *
  7410. * @example
  7411. * //absolute Uri will be "https://test.com/awesome.png";
  7412. * const absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  7413. */
  7414. function getAbsoluteUri(relative, base) {
  7415. let documentObject;
  7416. if (typeof document !== "undefined") {
  7417. documentObject = document;
  7418. }
  7419. return getAbsoluteUri._implementation(relative, base, documentObject);
  7420. }
  7421. getAbsoluteUri._implementation = function (relative, base, documentObject) {
  7422. //>>includeStart('debug', pragmas.debug);
  7423. if (!defaultValue.defined(relative)) {
  7424. throw new RuntimeError.DeveloperError("relative uri is required.");
  7425. }
  7426. //>>includeEnd('debug');
  7427. if (!defaultValue.defined(base)) {
  7428. if (typeof documentObject === "undefined") {
  7429. return relative;
  7430. }
  7431. base = defaultValue.defaultValue(documentObject.baseURI, documentObject.location.href);
  7432. }
  7433. const relativeUri = new URI(relative);
  7434. if (relativeUri.scheme() !== "") {
  7435. return relativeUri.toString();
  7436. }
  7437. return relativeUri.absoluteTo(base).toString();
  7438. };
  7439. /**
  7440. * Given a URI, returns the base path of the URI.
  7441. * @function
  7442. *
  7443. * @param {String} uri The Uri.
  7444. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  7445. * @returns {String} The base path of the Uri.
  7446. *
  7447. * @example
  7448. * // basePath will be "/Gallery/";
  7449. * const basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
  7450. *
  7451. * // basePath will be "/Gallery/?value=true&example=false";
  7452. * const basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
  7453. */
  7454. function getBaseUri(uri, includeQuery) {
  7455. //>>includeStart('debug', pragmas.debug);
  7456. if (!defaultValue.defined(uri)) {
  7457. throw new RuntimeError.DeveloperError("uri is required.");
  7458. }
  7459. //>>includeEnd('debug');
  7460. let basePath = "";
  7461. const i = uri.lastIndexOf("/");
  7462. if (i !== -1) {
  7463. basePath = uri.substring(0, i + 1);
  7464. }
  7465. if (!includeQuery) {
  7466. return basePath;
  7467. }
  7468. uri = new URI(uri);
  7469. if (uri.query().length !== 0) {
  7470. basePath += `?${uri.query()}`;
  7471. }
  7472. if (uri.fragment().length !== 0) {
  7473. basePath += `#${uri.fragment()}`;
  7474. }
  7475. return basePath;
  7476. }
  7477. /**
  7478. * Given a URI, returns the extension of the URI.
  7479. * @function getExtensionFromUri
  7480. *
  7481. * @param {String} uri The Uri.
  7482. * @returns {String} The extension of the Uri.
  7483. *
  7484. * @example
  7485. * //extension will be "czml";
  7486. * const extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
  7487. */
  7488. function getExtensionFromUri(uri) {
  7489. //>>includeStart('debug', pragmas.debug);
  7490. if (!defaultValue.defined(uri)) {
  7491. throw new RuntimeError.DeveloperError("uri is required.");
  7492. }
  7493. //>>includeEnd('debug');
  7494. const uriObject = new URI(uri);
  7495. uriObject.normalize();
  7496. let path = uriObject.path();
  7497. let index = path.lastIndexOf("/");
  7498. if (index !== -1) {
  7499. path = path.substr(index + 1);
  7500. }
  7501. index = path.lastIndexOf(".");
  7502. if (index === -1) {
  7503. path = "";
  7504. } else {
  7505. path = path.substr(index + 1);
  7506. }
  7507. return path;
  7508. }
  7509. const context2DsByWidthAndHeight = {};
  7510. /**
  7511. * Extract a pixel array from a loaded image. Draws the image
  7512. * into a canvas so it can read the pixels back.
  7513. *
  7514. * @function getImagePixels
  7515. *
  7516. * @param {HTMLImageElement|ImageBitmap} image The image to extract pixels from.
  7517. * @param {Number} width The width of the image. If not defined, then image.width is assigned.
  7518. * @param {Number} height The height of the image. If not defined, then image.height is assigned.
  7519. * @returns {ImageData} The pixels of the image.
  7520. */
  7521. function getImagePixels(image, width, height) {
  7522. if (!defaultValue.defined(width)) {
  7523. width = image.width;
  7524. }
  7525. if (!defaultValue.defined(height)) {
  7526. height = image.height;
  7527. }
  7528. let context2DsByHeight = context2DsByWidthAndHeight[width];
  7529. if (!defaultValue.defined(context2DsByHeight)) {
  7530. context2DsByHeight = {};
  7531. context2DsByWidthAndHeight[width] = context2DsByHeight;
  7532. }
  7533. let context2d = context2DsByHeight[height];
  7534. if (!defaultValue.defined(context2d)) {
  7535. const canvas = document.createElement("canvas");
  7536. canvas.width = width;
  7537. canvas.height = height;
  7538. context2d = canvas.getContext("2d");
  7539. context2d.globalCompositeOperation = "copy";
  7540. context2DsByHeight[height] = context2d;
  7541. }
  7542. context2d.drawImage(image, 0, 0, width, height);
  7543. return context2d.getImageData(0, 0, width, height).data;
  7544. }
  7545. const blobUriRegex = /^blob:/i;
  7546. /**
  7547. * Determines if the specified uri is a blob uri.
  7548. *
  7549. * @function isBlobUri
  7550. *
  7551. * @param {String} uri The uri to test.
  7552. * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
  7553. *
  7554. * @private
  7555. */
  7556. function isBlobUri(uri) {
  7557. //>>includeStart('debug', pragmas.debug);
  7558. RuntimeError.Check.typeOf.string("uri", uri);
  7559. //>>includeEnd('debug');
  7560. return blobUriRegex.test(uri);
  7561. }
  7562. let a$1;
  7563. /**
  7564. * Given a URL, determine whether that URL is considered cross-origin to the current page.
  7565. *
  7566. * @private
  7567. */
  7568. function isCrossOriginUrl(url) {
  7569. if (!defaultValue.defined(a$1)) {
  7570. a$1 = document.createElement("a");
  7571. }
  7572. // copy window location into the anchor to get consistent results
  7573. // when the port is default for the protocol (e.g. 80 for HTTP)
  7574. a$1.href = window.location.href;
  7575. // host includes both hostname and port if the port is not standard
  7576. const host = a$1.host;
  7577. const protocol = a$1.protocol;
  7578. a$1.href = url;
  7579. // IE only absolutizes href on get, not set
  7580. // eslint-disable-next-line no-self-assign
  7581. a$1.href = a$1.href;
  7582. return protocol !== a$1.protocol || host !== a$1.host;
  7583. }
  7584. const dataUriRegex$1 = /^data:/i;
  7585. /**
  7586. * Determines if the specified uri is a data uri.
  7587. *
  7588. * @function isDataUri
  7589. *
  7590. * @param {String} uri The uri to test.
  7591. * @returns {Boolean} true when the uri is a data uri; otherwise, false.
  7592. *
  7593. * @private
  7594. */
  7595. function isDataUri(uri) {
  7596. //>>includeStart('debug', pragmas.debug);
  7597. RuntimeError.Check.typeOf.string("uri", uri);
  7598. //>>includeEnd('debug');
  7599. return dataUriRegex$1.test(uri);
  7600. }
  7601. /**
  7602. * @private
  7603. */
  7604. function loadAndExecuteScript(url) {
  7605. const deferred = defer();
  7606. const script = document.createElement("script");
  7607. script.async = true;
  7608. script.src = url;
  7609. const head = document.getElementsByTagName("head")[0];
  7610. script.onload = function () {
  7611. script.onload = undefined;
  7612. head.removeChild(script);
  7613. deferred.resolve();
  7614. };
  7615. script.onerror = function (e) {
  7616. deferred.reject(e);
  7617. };
  7618. head.appendChild(script);
  7619. return deferred.promise;
  7620. }
  7621. /**
  7622. * Converts an object representing a set of name/value pairs into a query string,
  7623. * with names and values encoded properly for use in a URL. Values that are arrays
  7624. * will produce multiple values with the same name.
  7625. * @function objectToQuery
  7626. *
  7627. * @param {Object} obj The object containing data to encode.
  7628. * @returns {String} An encoded query string.
  7629. *
  7630. *
  7631. * @example
  7632. * const str = Cesium.objectToQuery({
  7633. * key1 : 'some value',
  7634. * key2 : 'a/b',
  7635. * key3 : ['x', 'y']
  7636. * });
  7637. *
  7638. * @see queryToObject
  7639. * // str will be:
  7640. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  7641. */
  7642. function objectToQuery(obj) {
  7643. //>>includeStart('debug', pragmas.debug);
  7644. if (!defaultValue.defined(obj)) {
  7645. throw new RuntimeError.DeveloperError("obj is required.");
  7646. }
  7647. //>>includeEnd('debug');
  7648. let result = "";
  7649. for (const propName in obj) {
  7650. if (obj.hasOwnProperty(propName)) {
  7651. const value = obj[propName];
  7652. const part = `${encodeURIComponent(propName)}=`;
  7653. if (Array.isArray(value)) {
  7654. for (let i = 0, len = value.length; i < len; ++i) {
  7655. result += `${part + encodeURIComponent(value[i])}&`;
  7656. }
  7657. } else {
  7658. result += `${part + encodeURIComponent(value)}&`;
  7659. }
  7660. }
  7661. }
  7662. // trim last &
  7663. result = result.slice(0, -1);
  7664. // This function used to replace %20 with + which is more compact and readable.
  7665. // However, some servers didn't properly handle + as a space.
  7666. // https://github.com/CesiumGS/cesium/issues/2192
  7667. return result;
  7668. }
  7669. /**
  7670. * Parses a query string into an object, where the keys and values of the object are the
  7671. * name/value pairs from the query string, decoded. If a name appears multiple times,
  7672. * the value in the object will be an array of values.
  7673. * @function queryToObject
  7674. *
  7675. * @param {String} queryString The query string.
  7676. * @returns {Object} An object containing the parameters parsed from the query string.
  7677. *
  7678. *
  7679. * @example
  7680. * const obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
  7681. * // obj will be:
  7682. * // {
  7683. * // key1 : 'some value',
  7684. * // key2 : 'a/b',
  7685. * // key3 : ['x', 'y']
  7686. * // }
  7687. *
  7688. * @see objectToQuery
  7689. */
  7690. function queryToObject(queryString) {
  7691. //>>includeStart('debug', pragmas.debug);
  7692. if (!defaultValue.defined(queryString)) {
  7693. throw new RuntimeError.DeveloperError("queryString is required.");
  7694. }
  7695. //>>includeEnd('debug');
  7696. const result = {};
  7697. if (queryString === "") {
  7698. return result;
  7699. }
  7700. const parts = queryString.replace(/\+/g, "%20").split(/[&;]/);
  7701. for (let i = 0, len = parts.length; i < len; ++i) {
  7702. const subparts = parts[i].split("=");
  7703. const name = decodeURIComponent(subparts[0]);
  7704. let value = subparts[1];
  7705. if (defaultValue.defined(value)) {
  7706. value = decodeURIComponent(value);
  7707. } else {
  7708. value = "";
  7709. }
  7710. const resultValue = result[name];
  7711. if (typeof resultValue === "string") {
  7712. // expand the single value to an array
  7713. result[name] = [resultValue, value];
  7714. } else if (Array.isArray(resultValue)) {
  7715. resultValue.push(value);
  7716. } else {
  7717. result[name] = value;
  7718. }
  7719. }
  7720. return result;
  7721. }
  7722. /**
  7723. * State of the request.
  7724. *
  7725. * @enum {Number}
  7726. */
  7727. const RequestState = {
  7728. /**
  7729. * Initial unissued state.
  7730. *
  7731. * @type Number
  7732. * @constant
  7733. */
  7734. UNISSUED: 0,
  7735. /**
  7736. * Issued but not yet active. Will become active when open slots are available.
  7737. *
  7738. * @type Number
  7739. * @constant
  7740. */
  7741. ISSUED: 1,
  7742. /**
  7743. * Actual http request has been sent.
  7744. *
  7745. * @type Number
  7746. * @constant
  7747. */
  7748. ACTIVE: 2,
  7749. /**
  7750. * Request completed successfully.
  7751. *
  7752. * @type Number
  7753. * @constant
  7754. */
  7755. RECEIVED: 3,
  7756. /**
  7757. * Request was cancelled, either explicitly or automatically because of low priority.
  7758. *
  7759. * @type Number
  7760. * @constant
  7761. */
  7762. CANCELLED: 4,
  7763. /**
  7764. * Request failed.
  7765. *
  7766. * @type Number
  7767. * @constant
  7768. */
  7769. FAILED: 5,
  7770. };
  7771. var RequestState$1 = Object.freeze(RequestState);
  7772. /**
  7773. * An enum identifying the type of request. Used for finer grained logging and priority sorting.
  7774. *
  7775. * @enum {Number}
  7776. */
  7777. const RequestType = {
  7778. /**
  7779. * Terrain request.
  7780. *
  7781. * @type Number
  7782. * @constant
  7783. */
  7784. TERRAIN: 0,
  7785. /**
  7786. * Imagery request.
  7787. *
  7788. * @type Number
  7789. * @constant
  7790. */
  7791. IMAGERY: 1,
  7792. /**
  7793. * 3D Tiles request.
  7794. *
  7795. * @type Number
  7796. * @constant
  7797. */
  7798. TILES3D: 2,
  7799. /**
  7800. * Other request.
  7801. *
  7802. * @type Number
  7803. * @constant
  7804. */
  7805. OTHER: 3,
  7806. };
  7807. var RequestType$1 = Object.freeze(RequestType);
  7808. /**
  7809. * Stores information for making a request. In general this does not need to be constructed directly.
  7810. *
  7811. * @alias Request
  7812. * @constructor
  7813. * @param {Object} [options] An object with the following properties:
  7814. * @param {String} [options.url] The url to request.
  7815. * @param {Request.RequestCallback} [options.requestFunction] The function that makes the actual data request.
  7816. * @param {Request.CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
  7817. * @param {Request.PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
  7818. * @param {Number} [options.priority=0.0] The initial priority of the request.
  7819. * @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.
  7820. * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
  7821. * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
  7822. */
  7823. function Request(options) {
  7824. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  7825. const throttleByServer = defaultValue.defaultValue(options.throttleByServer, false);
  7826. const throttle = defaultValue.defaultValue(options.throttle, false);
  7827. /**
  7828. * The URL to request.
  7829. *
  7830. * @type {String}
  7831. */
  7832. this.url = options.url;
  7833. /**
  7834. * The function that makes the actual data request.
  7835. *
  7836. * @type {Request.RequestCallback}
  7837. */
  7838. this.requestFunction = options.requestFunction;
  7839. /**
  7840. * The function that is called when the request is cancelled.
  7841. *
  7842. * @type {Request.CancelCallback}
  7843. */
  7844. this.cancelFunction = options.cancelFunction;
  7845. /**
  7846. * The function that is called to update the request's priority, which occurs once per frame.
  7847. *
  7848. * @type {Request.PriorityCallback}
  7849. */
  7850. this.priorityFunction = options.priorityFunction;
  7851. /**
  7852. * Priority is a unit-less value where lower values represent higher priority.
  7853. * For world-based objects, this is usually the distance from the camera.
  7854. * A request that does not have a priority function defaults to a priority of 0.
  7855. *
  7856. * If priorityFunction is defined, this value is updated every frame with the result of that call.
  7857. *
  7858. * @type {Number}
  7859. * @default 0.0
  7860. */
  7861. this.priority = defaultValue.defaultValue(options.priority, 0.0);
  7862. /**
  7863. * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
  7864. * request will be throttled and sent based on priority.
  7865. *
  7866. * @type {Boolean}
  7867. * @readonly
  7868. *
  7869. * @default false
  7870. */
  7871. this.throttle = throttle;
  7872. /**
  7873. * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
  7874. * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
  7875. * to <code>true</code> is preferable for requests going through HTTP/1 servers.
  7876. *
  7877. * @type {Boolean}
  7878. * @readonly
  7879. *
  7880. * @default false
  7881. */
  7882. this.throttleByServer = throttleByServer;
  7883. /**
  7884. * Type of request.
  7885. *
  7886. * @type {RequestType}
  7887. * @readonly
  7888. *
  7889. * @default RequestType.OTHER
  7890. */
  7891. this.type = defaultValue.defaultValue(options.type, RequestType$1.OTHER);
  7892. /**
  7893. * A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
  7894. *
  7895. * @type {String}
  7896. *
  7897. * @private
  7898. */
  7899. this.serverKey = undefined;
  7900. /**
  7901. * The current state of the request.
  7902. *
  7903. * @type {RequestState}
  7904. * @readonly
  7905. */
  7906. this.state = RequestState$1.UNISSUED;
  7907. /**
  7908. * The requests's deferred promise.
  7909. *
  7910. * @type {Object}
  7911. *
  7912. * @private
  7913. */
  7914. this.deferred = undefined;
  7915. /**
  7916. * Whether the request was explicitly cancelled.
  7917. *
  7918. * @type {Boolean}
  7919. *
  7920. * @private
  7921. */
  7922. this.cancelled = false;
  7923. }
  7924. /**
  7925. * Mark the request as cancelled.
  7926. *
  7927. * @private
  7928. */
  7929. Request.prototype.cancel = function () {
  7930. this.cancelled = true;
  7931. };
  7932. /**
  7933. * Duplicates a Request instance.
  7934. *
  7935. * @param {Request} [result] The object onto which to store the result.
  7936. *
  7937. * @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
  7938. */
  7939. Request.prototype.clone = function (result) {
  7940. if (!defaultValue.defined(result)) {
  7941. return new Request(this);
  7942. }
  7943. result.url = this.url;
  7944. result.requestFunction = this.requestFunction;
  7945. result.cancelFunction = this.cancelFunction;
  7946. result.priorityFunction = this.priorityFunction;
  7947. result.priority = this.priority;
  7948. result.throttle = this.throttle;
  7949. result.throttleByServer = this.throttleByServer;
  7950. result.type = this.type;
  7951. result.serverKey = this.serverKey;
  7952. // These get defaulted because the cloned request hasn't been issued
  7953. result.state = this.RequestState.UNISSUED;
  7954. result.deferred = undefined;
  7955. result.cancelled = false;
  7956. return result;
  7957. };
  7958. /**
  7959. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  7960. * a dictionary.
  7961. *
  7962. * @function parseResponseHeaders
  7963. *
  7964. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  7965. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  7966. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  7967. * is that header's value.
  7968. *
  7969. * @private
  7970. */
  7971. function parseResponseHeaders(headerString) {
  7972. const headers = {};
  7973. if (!headerString) {
  7974. return headers;
  7975. }
  7976. const headerPairs = headerString.split("\u000d\u000a");
  7977. for (let i = 0; i < headerPairs.length; ++i) {
  7978. const headerPair = headerPairs[i];
  7979. // Can't use split() here because it does the wrong thing
  7980. // if the header value has the string ": " in it.
  7981. const index = headerPair.indexOf("\u003a\u0020");
  7982. if (index > 0) {
  7983. const key = headerPair.substring(0, index);
  7984. const val = headerPair.substring(index + 2);
  7985. headers[key] = val;
  7986. }
  7987. }
  7988. return headers;
  7989. }
  7990. /**
  7991. * An event that is raised when a request encounters an error.
  7992. *
  7993. * @constructor
  7994. * @alias RequestErrorEvent
  7995. *
  7996. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  7997. * @param {Object} [response] The response included along with the error.
  7998. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  7999. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  8000. */
  8001. function RequestErrorEvent(statusCode, response, responseHeaders) {
  8002. /**
  8003. * The HTTP error status code, such as 404. If the error does not have a particular
  8004. * HTTP code, this property will be undefined.
  8005. *
  8006. * @type {Number}
  8007. */
  8008. this.statusCode = statusCode;
  8009. /**
  8010. * The response included along with the error. If the error does not include a response,
  8011. * this property will be undefined.
  8012. *
  8013. * @type {Object}
  8014. */
  8015. this.response = response;
  8016. /**
  8017. * The headers included in the response, represented as an object literal of key/value pairs.
  8018. * If the error does not include any headers, this property will be undefined.
  8019. *
  8020. * @type {Object}
  8021. */
  8022. this.responseHeaders = responseHeaders;
  8023. if (typeof this.responseHeaders === "string") {
  8024. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  8025. }
  8026. }
  8027. /**
  8028. * Creates a string representing this RequestErrorEvent.
  8029. * @memberof RequestErrorEvent
  8030. *
  8031. * @returns {String} A string representing the provided RequestErrorEvent.
  8032. */
  8033. RequestErrorEvent.prototype.toString = function () {
  8034. let str = "Request has failed.";
  8035. if (defaultValue.defined(this.statusCode)) {
  8036. str += ` Status Code: ${this.statusCode}`;
  8037. }
  8038. return str;
  8039. };
  8040. /**
  8041. * A generic utility class for managing subscribers for a particular event.
  8042. * This class is usually instantiated inside of a container class and
  8043. * exposed as a property for others to subscribe to.
  8044. *
  8045. * @alias Event
  8046. * @template Listener extends (...args: any[]) => void = (...args: any[]) => void
  8047. * @constructor
  8048. * @example
  8049. * MyObject.prototype.myListener = function(arg1, arg2) {
  8050. * this.myArg1Copy = arg1;
  8051. * this.myArg2Copy = arg2;
  8052. * }
  8053. *
  8054. * const myObjectInstance = new MyObject();
  8055. * const evt = new Cesium.Event();
  8056. * evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
  8057. * evt.raiseEvent('1', '2');
  8058. * evt.removeEventListener(MyObject.prototype.myListener);
  8059. */
  8060. function Event() {
  8061. this._listeners = [];
  8062. this._scopes = [];
  8063. this._toRemove = [];
  8064. this._insideRaiseEvent = false;
  8065. }
  8066. Object.defineProperties(Event.prototype, {
  8067. /**
  8068. * The number of listeners currently subscribed to the event.
  8069. * @memberof Event.prototype
  8070. * @type {Number}
  8071. * @readonly
  8072. */
  8073. numberOfListeners: {
  8074. get: function () {
  8075. return this._listeners.length - this._toRemove.length;
  8076. },
  8077. },
  8078. });
  8079. /**
  8080. * Registers a callback function to be executed whenever the event is raised.
  8081. * An optional scope can be provided to serve as the <code>this</code> pointer
  8082. * in which the function will execute.
  8083. *
  8084. * @param {Listener} listener The function to be executed when the event is raised.
  8085. * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
  8086. * pointer in which the listener function will execute.
  8087. * @returns {Event.RemoveCallback} A function that will remove this event listener when invoked.
  8088. *
  8089. * @see Event#raiseEvent
  8090. * @see Event#removeEventListener
  8091. */
  8092. Event.prototype.addEventListener = function (listener, scope) {
  8093. //>>includeStart('debug', pragmas.debug);
  8094. RuntimeError.Check.typeOf.func("listener", listener);
  8095. //>>includeEnd('debug');
  8096. this._listeners.push(listener);
  8097. this._scopes.push(scope);
  8098. const event = this;
  8099. return function () {
  8100. event.removeEventListener(listener, scope);
  8101. };
  8102. };
  8103. /**
  8104. * Unregisters a previously registered callback.
  8105. *
  8106. * @param {Listener} listener The function to be unregistered.
  8107. * @param {Object} [scope] The scope that was originally passed to addEventListener.
  8108. * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> if the listener and scope are not registered with the event.
  8109. *
  8110. * @see Event#addEventListener
  8111. * @see Event#raiseEvent
  8112. */
  8113. Event.prototype.removeEventListener = function (listener, scope) {
  8114. //>>includeStart('debug', pragmas.debug);
  8115. RuntimeError.Check.typeOf.func("listener", listener);
  8116. //>>includeEnd('debug');
  8117. const listeners = this._listeners;
  8118. const scopes = this._scopes;
  8119. let index = -1;
  8120. for (let i = 0; i < listeners.length; i++) {
  8121. if (listeners[i] === listener && scopes[i] === scope) {
  8122. index = i;
  8123. break;
  8124. }
  8125. }
  8126. if (index !== -1) {
  8127. if (this._insideRaiseEvent) {
  8128. //In order to allow removing an event subscription from within
  8129. //a callback, we don't actually remove the items here. Instead
  8130. //remember the index they are at and undefined their value.
  8131. this._toRemove.push(index);
  8132. listeners[index] = undefined;
  8133. scopes[index] = undefined;
  8134. } else {
  8135. listeners.splice(index, 1);
  8136. scopes.splice(index, 1);
  8137. }
  8138. return true;
  8139. }
  8140. return false;
  8141. };
  8142. function compareNumber(a, b) {
  8143. return b - a;
  8144. }
  8145. /**
  8146. * Raises the event by calling each registered listener with all supplied arguments.
  8147. *
  8148. * @param {...Parameters<Listener>} arguments This method takes any number of parameters and passes them through to the listener functions.
  8149. *
  8150. * @see Event#addEventListener
  8151. * @see Event#removeEventListener
  8152. */
  8153. Event.prototype.raiseEvent = function () {
  8154. this._insideRaiseEvent = true;
  8155. let i;
  8156. const listeners = this._listeners;
  8157. const scopes = this._scopes;
  8158. let length = listeners.length;
  8159. for (i = 0; i < length; i++) {
  8160. const listener = listeners[i];
  8161. if (defaultValue.defined(listener)) {
  8162. listeners[i].apply(scopes[i], arguments);
  8163. }
  8164. }
  8165. //Actually remove items removed in removeEventListener.
  8166. const toRemove = this._toRemove;
  8167. length = toRemove.length;
  8168. if (length > 0) {
  8169. toRemove.sort(compareNumber);
  8170. for (i = 0; i < length; i++) {
  8171. const index = toRemove[i];
  8172. listeners.splice(index, 1);
  8173. scopes.splice(index, 1);
  8174. }
  8175. toRemove.length = 0;
  8176. }
  8177. this._insideRaiseEvent = false;
  8178. };
  8179. /**
  8180. * Array implementation of a heap.
  8181. *
  8182. * @alias Heap
  8183. * @constructor
  8184. * @private
  8185. *
  8186. * @param {Object} options Object with the following properties:
  8187. * @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.
  8188. */
  8189. function Heap(options) {
  8190. //>>includeStart('debug', pragmas.debug);
  8191. RuntimeError.Check.typeOf.object("options", options);
  8192. RuntimeError.Check.defined("options.comparator", options.comparator);
  8193. //>>includeEnd('debug');
  8194. this._comparator = options.comparator;
  8195. this._array = [];
  8196. this._length = 0;
  8197. this._maximumLength = undefined;
  8198. }
  8199. Object.defineProperties(Heap.prototype, {
  8200. /**
  8201. * Gets the length of the heap.
  8202. *
  8203. * @memberof Heap.prototype
  8204. *
  8205. * @type {Number}
  8206. * @readonly
  8207. */
  8208. length: {
  8209. get: function () {
  8210. return this._length;
  8211. },
  8212. },
  8213. /**
  8214. * Gets the internal array.
  8215. *
  8216. * @memberof Heap.prototype
  8217. *
  8218. * @type {Array}
  8219. * @readonly
  8220. */
  8221. internalArray: {
  8222. get: function () {
  8223. return this._array;
  8224. },
  8225. },
  8226. /**
  8227. * Gets and sets the maximum length of the heap.
  8228. *
  8229. * @memberof Heap.prototype
  8230. *
  8231. * @type {Number}
  8232. */
  8233. maximumLength: {
  8234. get: function () {
  8235. return this._maximumLength;
  8236. },
  8237. set: function (value) {
  8238. //>>includeStart('debug', pragmas.debug);
  8239. RuntimeError.Check.typeOf.number.greaterThanOrEquals("maximumLength", value, 0);
  8240. //>>includeEnd('debug');
  8241. const originalLength = this._length;
  8242. if (value < originalLength) {
  8243. const array = this._array;
  8244. // Remove trailing references
  8245. for (let i = value; i < originalLength; ++i) {
  8246. array[i] = undefined;
  8247. }
  8248. this._length = value;
  8249. array.length = value;
  8250. }
  8251. this._maximumLength = value;
  8252. },
  8253. },
  8254. /**
  8255. * 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.
  8256. *
  8257. * @memberof Heap.prototype
  8258. *
  8259. * @type {Heap.ComparatorCallback}
  8260. */
  8261. comparator: {
  8262. get: function () {
  8263. return this._comparator;
  8264. },
  8265. },
  8266. });
  8267. function swap(array, a, b) {
  8268. const temp = array[a];
  8269. array[a] = array[b];
  8270. array[b] = temp;
  8271. }
  8272. /**
  8273. * Resizes the internal array of the heap.
  8274. *
  8275. * @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
  8276. */
  8277. Heap.prototype.reserve = function (length) {
  8278. length = defaultValue.defaultValue(length, this._length);
  8279. this._array.length = length;
  8280. };
  8281. /**
  8282. * Update the heap so that index and all descendants satisfy the heap property.
  8283. *
  8284. * @param {Number} [index=0] The starting index to heapify from.
  8285. */
  8286. Heap.prototype.heapify = function (index) {
  8287. index = defaultValue.defaultValue(index, 0);
  8288. const length = this._length;
  8289. const comparator = this._comparator;
  8290. const array = this._array;
  8291. let candidate = -1;
  8292. let inserting = true;
  8293. while (inserting) {
  8294. const right = 2 * (index + 1);
  8295. const left = right - 1;
  8296. if (left < length && comparator(array[left], array[index]) < 0) {
  8297. candidate = left;
  8298. } else {
  8299. candidate = index;
  8300. }
  8301. if (right < length && comparator(array[right], array[candidate]) < 0) {
  8302. candidate = right;
  8303. }
  8304. if (candidate !== index) {
  8305. swap(array, candidate, index);
  8306. index = candidate;
  8307. } else {
  8308. inserting = false;
  8309. }
  8310. }
  8311. };
  8312. /**
  8313. * Resort the heap.
  8314. */
  8315. Heap.prototype.resort = function () {
  8316. const length = this._length;
  8317. for (let i = Math.ceil(length / 2); i >= 0; --i) {
  8318. this.heapify(i);
  8319. }
  8320. };
  8321. /**
  8322. * Insert an element into the heap. If the length would grow greater than maximumLength
  8323. * of the heap, extra elements are removed.
  8324. *
  8325. * @param {*} element The element to insert
  8326. *
  8327. * @return {*} The element that was removed from the heap if the heap is at full capacity.
  8328. */
  8329. Heap.prototype.insert = function (element) {
  8330. //>>includeStart('debug', pragmas.debug);
  8331. RuntimeError.Check.defined("element", element);
  8332. //>>includeEnd('debug');
  8333. const array = this._array;
  8334. const comparator = this._comparator;
  8335. const maximumLength = this._maximumLength;
  8336. let index = this._length++;
  8337. if (index < array.length) {
  8338. array[index] = element;
  8339. } else {
  8340. array.push(element);
  8341. }
  8342. while (index !== 0) {
  8343. const parent = Math.floor((index - 1) / 2);
  8344. if (comparator(array[index], array[parent]) < 0) {
  8345. swap(array, index, parent);
  8346. index = parent;
  8347. } else {
  8348. break;
  8349. }
  8350. }
  8351. let removedElement;
  8352. if (defaultValue.defined(maximumLength) && this._length > maximumLength) {
  8353. removedElement = array[maximumLength];
  8354. this._length = maximumLength;
  8355. }
  8356. return removedElement;
  8357. };
  8358. /**
  8359. * Remove the element specified by index from the heap and return it.
  8360. *
  8361. * @param {Number} [index=0] The index to remove.
  8362. * @returns {*} The specified element of the heap.
  8363. */
  8364. Heap.prototype.pop = function (index) {
  8365. index = defaultValue.defaultValue(index, 0);
  8366. if (this._length === 0) {
  8367. return undefined;
  8368. }
  8369. //>>includeStart('debug', pragmas.debug);
  8370. RuntimeError.Check.typeOf.number.lessThan("index", index, this._length);
  8371. //>>includeEnd('debug');
  8372. const array = this._array;
  8373. const root = array[index];
  8374. swap(array, index, --this._length);
  8375. this.heapify(index);
  8376. array[this._length] = undefined; // Remove trailing reference
  8377. return root;
  8378. };
  8379. function sortRequests(a, b) {
  8380. return a.priority - b.priority;
  8381. }
  8382. const statistics = {
  8383. numberOfAttemptedRequests: 0,
  8384. numberOfActiveRequests: 0,
  8385. numberOfCancelledRequests: 0,
  8386. numberOfCancelledActiveRequests: 0,
  8387. numberOfFailedRequests: 0,
  8388. numberOfActiveRequestsEver: 0,
  8389. lastNumberOfActiveRequests: 0,
  8390. };
  8391. let priorityHeapLength = 20;
  8392. const requestHeap = new Heap({
  8393. comparator: sortRequests,
  8394. });
  8395. requestHeap.maximumLength = priorityHeapLength;
  8396. requestHeap.reserve(priorityHeapLength);
  8397. const activeRequests = [];
  8398. let numberOfActiveRequestsByServer = {};
  8399. const pageUri =
  8400. typeof document !== "undefined" ? new URI(document.location.href) : new URI();
  8401. const requestCompletedEvent = new Event();
  8402. /**
  8403. * The request scheduler is used to track and constrain the number of active requests in order to prioritize incoming requests. The ability
  8404. * to retain control over the number of requests in CesiumJS is important because due to events such as changes in the camera position,
  8405. * a lot of new requests may be generated and a lot of in-flight requests may become redundant. The request scheduler manually constrains the
  8406. * 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.
  8407. *
  8408. * @namespace RequestScheduler
  8409. *
  8410. */
  8411. function RequestScheduler() {}
  8412. /**
  8413. * The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
  8414. * @type {Number}
  8415. * @default 50
  8416. */
  8417. RequestScheduler.maximumRequests = 50;
  8418. /**
  8419. * The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
  8420. * listed in {@link requestsByServer} do not observe this limit.
  8421. * @type {Number}
  8422. * @default 6
  8423. */
  8424. RequestScheduler.maximumRequestsPerServer = 6;
  8425. /**
  8426. * A per server key list of overrides to use for throttling instead of <code>maximumRequestsPerServer</code>
  8427. * @type {Object}
  8428. *
  8429. * @example
  8430. * RequestScheduler.requestsByServer = {
  8431. * 'api.cesium.com:443': 18,
  8432. * 'assets.cesium.com:443': 18
  8433. * };
  8434. */
  8435. RequestScheduler.requestsByServer = {
  8436. "api.cesium.com:443": 18,
  8437. "assets.cesium.com:443": 18,
  8438. };
  8439. /**
  8440. * Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
  8441. * @type {Boolean}
  8442. * @default true
  8443. */
  8444. RequestScheduler.throttleRequests = true;
  8445. /**
  8446. * When true, log statistics to the console every frame
  8447. * @type {Boolean}
  8448. * @default false
  8449. * @private
  8450. */
  8451. RequestScheduler.debugShowStatistics = false;
  8452. /**
  8453. * An event that's raised when a request is completed. Event handlers are passed
  8454. * the error object if the request fails.
  8455. *
  8456. * @type {Event}
  8457. * @default Event()
  8458. * @private
  8459. */
  8460. RequestScheduler.requestCompletedEvent = requestCompletedEvent;
  8461. Object.defineProperties(RequestScheduler, {
  8462. /**
  8463. * Returns the statistics used by the request scheduler.
  8464. *
  8465. * @memberof RequestScheduler
  8466. *
  8467. * @type Object
  8468. * @readonly
  8469. * @private
  8470. */
  8471. statistics: {
  8472. get: function () {
  8473. return statistics;
  8474. },
  8475. },
  8476. /**
  8477. * 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.
  8478. *
  8479. * @memberof RequestScheduler
  8480. *
  8481. * @type {Number}
  8482. * @default 20
  8483. * @private
  8484. */
  8485. priorityHeapLength: {
  8486. get: function () {
  8487. return priorityHeapLength;
  8488. },
  8489. set: function (value) {
  8490. // If the new length shrinks the heap, need to cancel some of the requests.
  8491. // Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
  8492. if (value < priorityHeapLength) {
  8493. while (requestHeap.length > value) {
  8494. const request = requestHeap.pop();
  8495. cancelRequest(request);
  8496. }
  8497. }
  8498. priorityHeapLength = value;
  8499. requestHeap.maximumLength = value;
  8500. requestHeap.reserve(value);
  8501. },
  8502. },
  8503. });
  8504. function updatePriority(request) {
  8505. if (defaultValue.defined(request.priorityFunction)) {
  8506. request.priority = request.priorityFunction();
  8507. }
  8508. }
  8509. /**
  8510. * 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.
  8511. * @param {String} serverKey The server key returned by {@link RequestScheduler.getServerKey}.
  8512. * @param {Number} [desiredRequests=1] How many requests the caller plans to request
  8513. * @return {Boolean} True if there are enough open slots for <code>desiredRequests</code> more requests.
  8514. * @private
  8515. */
  8516. RequestScheduler.serverHasOpenSlots = function (serverKey, desiredRequests) {
  8517. desiredRequests = defaultValue.defaultValue(desiredRequests, 1);
  8518. const maxRequests = defaultValue.defaultValue(
  8519. RequestScheduler.requestsByServer[serverKey],
  8520. RequestScheduler.maximumRequestsPerServer
  8521. );
  8522. const hasOpenSlotsServer =
  8523. numberOfActiveRequestsByServer[serverKey] + desiredRequests <= maxRequests;
  8524. return hasOpenSlotsServer;
  8525. };
  8526. /**
  8527. * Check if the priority heap has open slots, regardless of which server they
  8528. * are from. This is used in {@link Multiple3DTileContent} for determining when
  8529. * all requests can be scheduled
  8530. * @param {Number} desiredRequests The number of requests the caller intends to make
  8531. * @return {Boolean} <code>true</code> if the heap has enough available slots to meet the desiredRequests. <code>false</code> otherwise.
  8532. *
  8533. * @private
  8534. */
  8535. RequestScheduler.heapHasOpenSlots = function (desiredRequests) {
  8536. const hasOpenSlotsHeap =
  8537. requestHeap.length + desiredRequests <= priorityHeapLength;
  8538. return hasOpenSlotsHeap;
  8539. };
  8540. function issueRequest(request) {
  8541. if (request.state === RequestState$1.UNISSUED) {
  8542. request.state = RequestState$1.ISSUED;
  8543. request.deferred = defer();
  8544. }
  8545. return request.deferred.promise;
  8546. }
  8547. function getRequestReceivedFunction(request) {
  8548. return function (results) {
  8549. if (request.state === RequestState$1.CANCELLED) {
  8550. // If the data request comes back but the request is cancelled, ignore it.
  8551. return;
  8552. }
  8553. // explicitly set to undefined to ensure GC of request response data. See #8843
  8554. const deferred = request.deferred;
  8555. --statistics.numberOfActiveRequests;
  8556. --numberOfActiveRequestsByServer[request.serverKey];
  8557. requestCompletedEvent.raiseEvent();
  8558. request.state = RequestState$1.RECEIVED;
  8559. request.deferred = undefined;
  8560. deferred.resolve(results);
  8561. };
  8562. }
  8563. function getRequestFailedFunction(request) {
  8564. return function (error) {
  8565. if (request.state === RequestState$1.CANCELLED) {
  8566. // If the data request comes back but the request is cancelled, ignore it.
  8567. return;
  8568. }
  8569. ++statistics.numberOfFailedRequests;
  8570. --statistics.numberOfActiveRequests;
  8571. --numberOfActiveRequestsByServer[request.serverKey];
  8572. requestCompletedEvent.raiseEvent(error);
  8573. request.state = RequestState$1.FAILED;
  8574. request.deferred.reject(error);
  8575. };
  8576. }
  8577. function startRequest(request) {
  8578. const promise = issueRequest(request);
  8579. request.state = RequestState$1.ACTIVE;
  8580. activeRequests.push(request);
  8581. ++statistics.numberOfActiveRequests;
  8582. ++statistics.numberOfActiveRequestsEver;
  8583. ++numberOfActiveRequestsByServer[request.serverKey];
  8584. request
  8585. .requestFunction()
  8586. .then(getRequestReceivedFunction(request))
  8587. .catch(getRequestFailedFunction(request));
  8588. return promise;
  8589. }
  8590. function cancelRequest(request) {
  8591. const active = request.state === RequestState$1.ACTIVE;
  8592. request.state = RequestState$1.CANCELLED;
  8593. ++statistics.numberOfCancelledRequests;
  8594. // check that deferred has not been cleared since cancelRequest can be called
  8595. // on a finished request, e.g. by clearForSpecs during tests
  8596. if (defaultValue.defined(request.deferred)) {
  8597. const deferred = request.deferred;
  8598. request.deferred = undefined;
  8599. deferred.reject();
  8600. }
  8601. if (active) {
  8602. --statistics.numberOfActiveRequests;
  8603. --numberOfActiveRequestsByServer[request.serverKey];
  8604. ++statistics.numberOfCancelledActiveRequests;
  8605. }
  8606. if (defaultValue.defined(request.cancelFunction)) {
  8607. request.cancelFunction();
  8608. }
  8609. }
  8610. /**
  8611. * Sort requests by priority and start requests.
  8612. * @private
  8613. */
  8614. RequestScheduler.update = function () {
  8615. let i;
  8616. let request;
  8617. // Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
  8618. let removeCount = 0;
  8619. const activeLength = activeRequests.length;
  8620. for (i = 0; i < activeLength; ++i) {
  8621. request = activeRequests[i];
  8622. if (request.cancelled) {
  8623. // Request was explicitly cancelled
  8624. cancelRequest(request);
  8625. }
  8626. if (request.state !== RequestState$1.ACTIVE) {
  8627. // Request is no longer active, remove from array
  8628. ++removeCount;
  8629. continue;
  8630. }
  8631. if (removeCount > 0) {
  8632. // Shift back to fill in vacated slots from completed requests
  8633. activeRequests[i - removeCount] = request;
  8634. }
  8635. }
  8636. activeRequests.length -= removeCount;
  8637. // Update priority of issued requests and resort the heap
  8638. const issuedRequests = requestHeap.internalArray;
  8639. const issuedLength = requestHeap.length;
  8640. for (i = 0; i < issuedLength; ++i) {
  8641. updatePriority(issuedRequests[i]);
  8642. }
  8643. requestHeap.resort();
  8644. // Get the number of open slots and fill with the highest priority requests.
  8645. // Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
  8646. const openSlots = Math.max(
  8647. RequestScheduler.maximumRequests - activeRequests.length,
  8648. 0
  8649. );
  8650. let filledSlots = 0;
  8651. while (filledSlots < openSlots && requestHeap.length > 0) {
  8652. // Loop until all open slots are filled or the heap becomes empty
  8653. request = requestHeap.pop();
  8654. if (request.cancelled) {
  8655. // Request was explicitly cancelled
  8656. cancelRequest(request);
  8657. continue;
  8658. }
  8659. if (
  8660. request.throttleByServer &&
  8661. !RequestScheduler.serverHasOpenSlots(request.serverKey)
  8662. ) {
  8663. // Open slots are available, but the request is throttled by its server. Cancel and try again later.
  8664. cancelRequest(request);
  8665. continue;
  8666. }
  8667. startRequest(request);
  8668. ++filledSlots;
  8669. }
  8670. updateStatistics();
  8671. };
  8672. /**
  8673. * Get the server key from a given url.
  8674. *
  8675. * @param {String} url The url.
  8676. * @returns {String} The server key.
  8677. * @private
  8678. */
  8679. RequestScheduler.getServerKey = function (url) {
  8680. //>>includeStart('debug', pragmas.debug);
  8681. RuntimeError.Check.typeOf.string("url", url);
  8682. //>>includeEnd('debug');
  8683. let uri = new URI(url);
  8684. if (uri.scheme() === "") {
  8685. uri = new URI(url).absoluteTo(pageUri);
  8686. uri.normalize();
  8687. }
  8688. let serverKey = uri.authority();
  8689. if (!/:/.test(serverKey)) {
  8690. // If the authority does not contain a port number, add port 443 for https or port 80 for http
  8691. serverKey = `${serverKey}:${uri.scheme() === "https" ? "443" : "80"}`;
  8692. }
  8693. const length = numberOfActiveRequestsByServer[serverKey];
  8694. if (!defaultValue.defined(length)) {
  8695. numberOfActiveRequestsByServer[serverKey] = 0;
  8696. }
  8697. return serverKey;
  8698. };
  8699. /**
  8700. * Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
  8701. * queued and sorted by priority before being sent.
  8702. *
  8703. * @param {Request} request The request object.
  8704. *
  8705. * @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
  8706. *
  8707. * @private
  8708. */
  8709. RequestScheduler.request = function (request) {
  8710. //>>includeStart('debug', pragmas.debug);
  8711. RuntimeError.Check.typeOf.object("request", request);
  8712. RuntimeError.Check.typeOf.string("request.url", request.url);
  8713. RuntimeError.Check.typeOf.func("request.requestFunction", request.requestFunction);
  8714. //>>includeEnd('debug');
  8715. if (isDataUri(request.url) || isBlobUri(request.url)) {
  8716. requestCompletedEvent.raiseEvent();
  8717. request.state = RequestState$1.RECEIVED;
  8718. return request.requestFunction();
  8719. }
  8720. ++statistics.numberOfAttemptedRequests;
  8721. if (!defaultValue.defined(request.serverKey)) {
  8722. request.serverKey = RequestScheduler.getServerKey(request.url);
  8723. }
  8724. if (
  8725. RequestScheduler.throttleRequests &&
  8726. request.throttleByServer &&
  8727. !RequestScheduler.serverHasOpenSlots(request.serverKey)
  8728. ) {
  8729. // Server is saturated. Try again later.
  8730. return undefined;
  8731. }
  8732. if (!RequestScheduler.throttleRequests || !request.throttle) {
  8733. return startRequest(request);
  8734. }
  8735. if (activeRequests.length >= RequestScheduler.maximumRequests) {
  8736. // Active requests are saturated. Try again later.
  8737. return undefined;
  8738. }
  8739. // Insert into the priority heap and see if a request was bumped off. If this request is the lowest
  8740. // priority it will be returned.
  8741. updatePriority(request);
  8742. const removedRequest = requestHeap.insert(request);
  8743. if (defaultValue.defined(removedRequest)) {
  8744. if (removedRequest === request) {
  8745. // Request does not have high enough priority to be issued
  8746. return undefined;
  8747. }
  8748. // A previously issued request has been bumped off the priority heap, so cancel it
  8749. cancelRequest(removedRequest);
  8750. }
  8751. return issueRequest(request);
  8752. };
  8753. function updateStatistics() {
  8754. if (!RequestScheduler.debugShowStatistics) {
  8755. return;
  8756. }
  8757. if (
  8758. statistics.numberOfActiveRequests === 0 &&
  8759. statistics.lastNumberOfActiveRequests > 0
  8760. ) {
  8761. if (statistics.numberOfAttemptedRequests > 0) {
  8762. console.log(
  8763. `Number of attempted requests: ${statistics.numberOfAttemptedRequests}`
  8764. );
  8765. statistics.numberOfAttemptedRequests = 0;
  8766. }
  8767. if (statistics.numberOfCancelledRequests > 0) {
  8768. console.log(
  8769. `Number of cancelled requests: ${statistics.numberOfCancelledRequests}`
  8770. );
  8771. statistics.numberOfCancelledRequests = 0;
  8772. }
  8773. if (statistics.numberOfCancelledActiveRequests > 0) {
  8774. console.log(
  8775. `Number of cancelled active requests: ${statistics.numberOfCancelledActiveRequests}`
  8776. );
  8777. statistics.numberOfCancelledActiveRequests = 0;
  8778. }
  8779. if (statistics.numberOfFailedRequests > 0) {
  8780. console.log(
  8781. `Number of failed requests: ${statistics.numberOfFailedRequests}`
  8782. );
  8783. statistics.numberOfFailedRequests = 0;
  8784. }
  8785. }
  8786. statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
  8787. }
  8788. /**
  8789. * For testing only. Clears any requests that may not have completed from previous tests.
  8790. *
  8791. * @private
  8792. */
  8793. RequestScheduler.clearForSpecs = function () {
  8794. while (requestHeap.length > 0) {
  8795. const request = requestHeap.pop();
  8796. cancelRequest(request);
  8797. }
  8798. const length = activeRequests.length;
  8799. for (let i = 0; i < length; ++i) {
  8800. cancelRequest(activeRequests[i]);
  8801. }
  8802. activeRequests.length = 0;
  8803. numberOfActiveRequestsByServer = {};
  8804. // Clear stats
  8805. statistics.numberOfAttemptedRequests = 0;
  8806. statistics.numberOfActiveRequests = 0;
  8807. statistics.numberOfCancelledRequests = 0;
  8808. statistics.numberOfCancelledActiveRequests = 0;
  8809. statistics.numberOfFailedRequests = 0;
  8810. statistics.numberOfActiveRequestsEver = 0;
  8811. statistics.lastNumberOfActiveRequests = 0;
  8812. };
  8813. /**
  8814. * For testing only.
  8815. *
  8816. * @private
  8817. */
  8818. RequestScheduler.numberOfActiveRequestsByServer = function (serverKey) {
  8819. return numberOfActiveRequestsByServer[serverKey];
  8820. };
  8821. /**
  8822. * For testing only.
  8823. *
  8824. * @private
  8825. */
  8826. RequestScheduler.requestHeap = requestHeap;
  8827. /**
  8828. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  8829. * any requests to these servers.
  8830. *
  8831. * @namespace TrustedServers
  8832. *
  8833. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  8834. */
  8835. const TrustedServers = {};
  8836. let _servers = {};
  8837. /**
  8838. * Adds a trusted server to the registry
  8839. *
  8840. * @param {String} host The host to be added.
  8841. * @param {Number} port The port used to access the host.
  8842. *
  8843. * @example
  8844. * // Add a trusted server
  8845. * TrustedServers.add('my.server.com', 80);
  8846. */
  8847. TrustedServers.add = function (host, port) {
  8848. //>>includeStart('debug', pragmas.debug);
  8849. if (!defaultValue.defined(host)) {
  8850. throw new RuntimeError.DeveloperError("host is required.");
  8851. }
  8852. if (!defaultValue.defined(port) || port <= 0) {
  8853. throw new RuntimeError.DeveloperError("port is required to be greater than 0.");
  8854. }
  8855. //>>includeEnd('debug');
  8856. const authority = `${host.toLowerCase()}:${port}`;
  8857. if (!defaultValue.defined(_servers[authority])) {
  8858. _servers[authority] = true;
  8859. }
  8860. };
  8861. /**
  8862. * Removes a trusted server from the registry
  8863. *
  8864. * @param {String} host The host to be removed.
  8865. * @param {Number} port The port used to access the host.
  8866. *
  8867. * @example
  8868. * // Remove a trusted server
  8869. * TrustedServers.remove('my.server.com', 80);
  8870. */
  8871. TrustedServers.remove = function (host, port) {
  8872. //>>includeStart('debug', pragmas.debug);
  8873. if (!defaultValue.defined(host)) {
  8874. throw new RuntimeError.DeveloperError("host is required.");
  8875. }
  8876. if (!defaultValue.defined(port) || port <= 0) {
  8877. throw new RuntimeError.DeveloperError("port is required to be greater than 0.");
  8878. }
  8879. //>>includeEnd('debug');
  8880. const authority = `${host.toLowerCase()}:${port}`;
  8881. if (defaultValue.defined(_servers[authority])) {
  8882. delete _servers[authority];
  8883. }
  8884. };
  8885. function getAuthority(url) {
  8886. const uri = new URI(url);
  8887. uri.normalize();
  8888. // Removes username:password@ so we just have host[:port]
  8889. let authority = uri.authority();
  8890. if (authority.length === 0) {
  8891. return undefined; // Relative URL
  8892. }
  8893. uri.authority(authority);
  8894. if (authority.indexOf("@") !== -1) {
  8895. const parts = authority.split("@");
  8896. authority = parts[1];
  8897. }
  8898. // If the port is missing add one based on the scheme
  8899. if (authority.indexOf(":") === -1) {
  8900. let scheme = uri.scheme();
  8901. if (scheme.length === 0) {
  8902. scheme = window.location.protocol;
  8903. scheme = scheme.substring(0, scheme.length - 1);
  8904. }
  8905. if (scheme === "http") {
  8906. authority += ":80";
  8907. } else if (scheme === "https") {
  8908. authority += ":443";
  8909. } else {
  8910. return undefined;
  8911. }
  8912. }
  8913. return authority;
  8914. }
  8915. /**
  8916. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  8917. *
  8918. * @param {String} url The url to be tested against the trusted list
  8919. *
  8920. * @returns {boolean} Returns true if url is trusted, false otherwise.
  8921. *
  8922. * @example
  8923. * // Add server
  8924. * TrustedServers.add('my.server.com', 81);
  8925. *
  8926. * // Check if server is trusted
  8927. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  8928. * // my.server.com:81 is trusted
  8929. * }
  8930. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  8931. * // my.server.com isn't trusted
  8932. * }
  8933. */
  8934. TrustedServers.contains = function (url) {
  8935. //>>includeStart('debug', pragmas.debug);
  8936. if (!defaultValue.defined(url)) {
  8937. throw new RuntimeError.DeveloperError("url is required.");
  8938. }
  8939. //>>includeEnd('debug');
  8940. const authority = getAuthority(url);
  8941. if (defaultValue.defined(authority) && defaultValue.defined(_servers[authority])) {
  8942. return true;
  8943. }
  8944. return false;
  8945. };
  8946. /**
  8947. * Clears the registry
  8948. *
  8949. * @example
  8950. * // Remove a trusted server
  8951. * TrustedServers.clear();
  8952. */
  8953. TrustedServers.clear = function () {
  8954. _servers = {};
  8955. };
  8956. const xhrBlobSupported = (function () {
  8957. try {
  8958. const xhr = new XMLHttpRequest();
  8959. xhr.open("GET", "#", true);
  8960. xhr.responseType = "blob";
  8961. return xhr.responseType === "blob";
  8962. } catch (e) {
  8963. return false;
  8964. }
  8965. })();
  8966. /**
  8967. * Parses a query string and returns the object equivalent.
  8968. *
  8969. * @param {Uri} uri The Uri with a query object.
  8970. * @param {Resource} resource The Resource that will be assigned queryParameters.
  8971. * @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
  8972. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
  8973. *
  8974. * @private
  8975. */
  8976. function parseQuery(uri, resource, merge, preserveQueryParameters) {
  8977. const queryString = uri.query();
  8978. if (queryString.length === 0) {
  8979. return {};
  8980. }
  8981. let query;
  8982. // Special case we run into where the querystring is just a string, not key/value pairs
  8983. if (queryString.indexOf("=") === -1) {
  8984. const result = {};
  8985. result[queryString] = undefined;
  8986. query = result;
  8987. } else {
  8988. query = queryToObject(queryString);
  8989. }
  8990. if (merge) {
  8991. resource._queryParameters = combineQueryParameters(
  8992. query,
  8993. resource._queryParameters,
  8994. preserveQueryParameters
  8995. );
  8996. } else {
  8997. resource._queryParameters = query;
  8998. }
  8999. uri.search("");
  9000. }
  9001. /**
  9002. * Converts a query object into a string.
  9003. *
  9004. * @param {Uri} uri The Uri object that will have the query object set.
  9005. * @param {Resource} resource The resource that has queryParameters
  9006. *
  9007. * @private
  9008. */
  9009. function stringifyQuery(uri, resource) {
  9010. const queryObject = resource._queryParameters;
  9011. const keys = Object.keys(queryObject);
  9012. // We have 1 key with an undefined value, so this is just a string, not key/value pairs
  9013. if (keys.length === 1 && !defaultValue.defined(queryObject[keys[0]])) {
  9014. uri.search(keys[0]);
  9015. } else {
  9016. uri.search(objectToQuery(queryObject));
  9017. }
  9018. }
  9019. /**
  9020. * Clones a value if it is defined, otherwise returns the default value
  9021. *
  9022. * @param {*} [val] The value to clone.
  9023. * @param {*} [defaultVal] The default value.
  9024. *
  9025. * @returns {*} A clone of val or the defaultVal.
  9026. *
  9027. * @private
  9028. */
  9029. function defaultClone(val, defaultVal) {
  9030. if (!defaultValue.defined(val)) {
  9031. return defaultVal;
  9032. }
  9033. return defaultValue.defined(val.clone) ? val.clone() : clone(val);
  9034. }
  9035. /**
  9036. * Checks to make sure the Resource isn't already being requested.
  9037. *
  9038. * @param {Request} request The request to check.
  9039. *
  9040. * @private
  9041. */
  9042. function checkAndResetRequest(request) {
  9043. if (
  9044. request.state === RequestState$1.ISSUED ||
  9045. request.state === RequestState$1.ACTIVE
  9046. ) {
  9047. throw new RuntimeError.RuntimeError("The Resource is already being fetched.");
  9048. }
  9049. request.state = RequestState$1.UNISSUED;
  9050. request.deferred = undefined;
  9051. }
  9052. /**
  9053. * This combines a map of query parameters.
  9054. *
  9055. * @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
  9056. * @param {Object} q2 The second map of query parameters.
  9057. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
  9058. *
  9059. * @returns {Object} The combined map of query parameters.
  9060. *
  9061. * @example
  9062. * const q1 = {
  9063. * a: 1,
  9064. * b: 2
  9065. * };
  9066. * const q2 = {
  9067. * a: 3,
  9068. * c: 4
  9069. * };
  9070. * const q3 = {
  9071. * b: [5, 6],
  9072. * d: 7
  9073. * }
  9074. *
  9075. * // Returns
  9076. * // {
  9077. * // a: [1, 3],
  9078. * // b: 2,
  9079. * // c: 4
  9080. * // };
  9081. * combineQueryParameters(q1, q2, true);
  9082. *
  9083. * // Returns
  9084. * // {
  9085. * // a: 1,
  9086. * // b: 2,
  9087. * // c: 4
  9088. * // };
  9089. * combineQueryParameters(q1, q2, false);
  9090. *
  9091. * // Returns
  9092. * // {
  9093. * // a: 1,
  9094. * // b: [2, 5, 6],
  9095. * // d: 7
  9096. * // };
  9097. * combineQueryParameters(q1, q3, true);
  9098. *
  9099. * // Returns
  9100. * // {
  9101. * // a: 1,
  9102. * // b: 2,
  9103. * // d: 7
  9104. * // };
  9105. * combineQueryParameters(q1, q3, false);
  9106. *
  9107. * @private
  9108. */
  9109. function combineQueryParameters(q1, q2, preserveQueryParameters) {
  9110. if (!preserveQueryParameters) {
  9111. return combine.combine(q1, q2);
  9112. }
  9113. const result = clone(q1, true);
  9114. for (const param in q2) {
  9115. if (q2.hasOwnProperty(param)) {
  9116. let value = result[param];
  9117. const q2Value = q2[param];
  9118. if (defaultValue.defined(value)) {
  9119. if (!Array.isArray(value)) {
  9120. value = result[param] = [value];
  9121. }
  9122. result[param] = value.concat(q2Value);
  9123. } else {
  9124. result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
  9125. }
  9126. }
  9127. }
  9128. return result;
  9129. }
  9130. /**
  9131. * @typedef {Object} Resource.ConstructorOptions
  9132. *
  9133. * Initialization options for the Resource constructor
  9134. *
  9135. * @property {String} url The url of the resource.
  9136. * @property {Object} [queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9137. * @property {Object} [templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9138. * @property {Object} [headers={}] Additional HTTP headers that will be sent.
  9139. * @property {Proxy} [proxy] A proxy to be used when loading the resource.
  9140. * @property {Resource.RetryCallback} [retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  9141. * @property {Number} [retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9142. * @property {Request} [request] A Request object that will be used. Intended for internal use only.
  9143. */
  9144. /**
  9145. * 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.
  9146. *
  9147. * @alias Resource
  9148. * @constructor
  9149. *
  9150. * @param {String|Resource.ConstructorOptions} options A url or an object describing initialization options
  9151. *
  9152. * @example
  9153. * function refreshTokenRetryCallback(resource, error) {
  9154. * if (error.statusCode === 403) {
  9155. * // 403 status code means a new token should be generated
  9156. * return getNewAccessToken()
  9157. * .then(function(token) {
  9158. * resource.queryParameters.access_token = token;
  9159. * return true;
  9160. * })
  9161. * .catch(function() {
  9162. * return false;
  9163. * });
  9164. * }
  9165. *
  9166. * return false;
  9167. * }
  9168. *
  9169. * const resource = new Resource({
  9170. * url: 'http://server.com/path/to/resource.json',
  9171. * proxy: new DefaultProxy('/proxy/'),
  9172. * headers: {
  9173. * 'X-My-Header': 'valueOfHeader'
  9174. * },
  9175. * queryParameters: {
  9176. * 'access_token': '123-435-456-000'
  9177. * },
  9178. * retryCallback: refreshTokenRetryCallback,
  9179. * retryAttempts: 1
  9180. * });
  9181. */
  9182. function Resource(options) {
  9183. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  9184. if (typeof options === "string") {
  9185. options = {
  9186. url: options,
  9187. };
  9188. }
  9189. //>>includeStart('debug', pragmas.debug);
  9190. RuntimeError.Check.typeOf.string("options.url", options.url);
  9191. //>>includeEnd('debug');
  9192. this._url = undefined;
  9193. this._templateValues = defaultClone(options.templateValues, {});
  9194. this._queryParameters = defaultClone(options.queryParameters, {});
  9195. /**
  9196. * Additional HTTP headers that will be sent with the request.
  9197. *
  9198. * @type {Object}
  9199. */
  9200. this.headers = defaultClone(options.headers, {});
  9201. /**
  9202. * A Request object that will be used. Intended for internal use only.
  9203. *
  9204. * @type {Request}
  9205. */
  9206. this.request = defaultValue.defaultValue(options.request, new Request());
  9207. /**
  9208. * A proxy to be used when loading the resource.
  9209. *
  9210. * @type {Proxy}
  9211. */
  9212. this.proxy = options.proxy;
  9213. /**
  9214. * 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.
  9215. *
  9216. * @type {Function}
  9217. */
  9218. this.retryCallback = options.retryCallback;
  9219. /**
  9220. * The number of times the retryCallback should be called before giving up.
  9221. *
  9222. * @type {Number}
  9223. */
  9224. this.retryAttempts = defaultValue.defaultValue(options.retryAttempts, 0);
  9225. this._retryCount = 0;
  9226. const uri = new URI(options.url);
  9227. parseQuery(uri, this, true, true);
  9228. // Remove the fragment as it's not sent with a request
  9229. uri.fragment("");
  9230. this._url = uri.toString();
  9231. }
  9232. /**
  9233. * A helper function to create a resource depending on whether we have a String or a Resource
  9234. *
  9235. * @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
  9236. *
  9237. * @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
  9238. *
  9239. * @private
  9240. */
  9241. Resource.createIfNeeded = function (resource) {
  9242. if (resource instanceof Resource) {
  9243. // Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
  9244. // be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
  9245. // 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
  9246. // in the underlying tiling code the requests for this resource will use it.
  9247. return resource.getDerivedResource({
  9248. request: resource.request,
  9249. });
  9250. }
  9251. if (typeof resource !== "string") {
  9252. return resource;
  9253. }
  9254. return new Resource({
  9255. url: resource,
  9256. });
  9257. };
  9258. let supportsImageBitmapOptionsPromise;
  9259. /**
  9260. * A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
  9261. *
  9262. * @returns {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
  9263. *
  9264. * @private
  9265. */
  9266. Resource.supportsImageBitmapOptions = function () {
  9267. // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
  9268. // know if this browser supports passing options to the createImageBitmap function.
  9269. // https://github.com/whatwg/html/pull/4248
  9270. //
  9271. // We also need to check whether the colorSpaceConversion option is supported.
  9272. // We do this by loading a PNG with an embedded color profile, first with
  9273. // colorSpaceConversion: "none" and then with colorSpaceConversion: "default".
  9274. // If the pixel color is different then we know the option is working.
  9275. // As of Webkit 17612.3.6.1.6 the createImageBitmap promise resolves but the
  9276. // option is not actually supported.
  9277. if (defaultValue.defined(supportsImageBitmapOptionsPromise)) {
  9278. return supportsImageBitmapOptionsPromise;
  9279. }
  9280. if (typeof createImageBitmap !== "function") {
  9281. supportsImageBitmapOptionsPromise = Promise.resolve(false);
  9282. return supportsImageBitmapOptionsPromise;
  9283. }
  9284. const imageDataUri =
  9285. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGdBTUEAAE4g3rEiDgAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAADElEQVQI12Ng6GAAAAEUAIngE3ZiAAAAAElFTkSuQmCC";
  9286. supportsImageBitmapOptionsPromise = Resource.fetchBlob({
  9287. url: imageDataUri,
  9288. })
  9289. .then(function (blob) {
  9290. const imageBitmapOptions = {
  9291. imageOrientation: "flipY", // default is "none"
  9292. premultiplyAlpha: "none", // default is "default"
  9293. colorSpaceConversion: "none", // default is "default"
  9294. };
  9295. return Promise.all([
  9296. createImageBitmap(blob, imageBitmapOptions),
  9297. createImageBitmap(blob),
  9298. ]);
  9299. })
  9300. .then(function (imageBitmaps) {
  9301. // Check whether the colorSpaceConversion option had any effect on the green channel
  9302. const colorWithOptions = getImagePixels(imageBitmaps[0]);
  9303. const colorWithDefaults = getImagePixels(imageBitmaps[1]);
  9304. return colorWithOptions[1] !== colorWithDefaults[1];
  9305. })
  9306. .catch(function () {
  9307. return false;
  9308. });
  9309. return supportsImageBitmapOptionsPromise;
  9310. };
  9311. Object.defineProperties(Resource, {
  9312. /**
  9313. * Returns true if blobs are supported.
  9314. *
  9315. * @memberof Resource
  9316. * @type {Boolean}
  9317. *
  9318. * @readonly
  9319. */
  9320. isBlobSupported: {
  9321. get: function () {
  9322. return xhrBlobSupported;
  9323. },
  9324. },
  9325. });
  9326. Object.defineProperties(Resource.prototype, {
  9327. /**
  9328. * Query parameters appended to the url.
  9329. *
  9330. * @memberof Resource.prototype
  9331. * @type {Object}
  9332. *
  9333. * @readonly
  9334. */
  9335. queryParameters: {
  9336. get: function () {
  9337. return this._queryParameters;
  9338. },
  9339. },
  9340. /**
  9341. * The key/value pairs used to replace template parameters in the url.
  9342. *
  9343. * @memberof Resource.prototype
  9344. * @type {Object}
  9345. *
  9346. * @readonly
  9347. */
  9348. templateValues: {
  9349. get: function () {
  9350. return this._templateValues;
  9351. },
  9352. },
  9353. /**
  9354. * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
  9355. *
  9356. * @memberof Resource.prototype
  9357. * @type {String}
  9358. */
  9359. url: {
  9360. get: function () {
  9361. return this.getUrlComponent(true, true);
  9362. },
  9363. set: function (value) {
  9364. const uri = new URI(value);
  9365. parseQuery(uri, this, false);
  9366. // Remove the fragment as it's not sent with a request
  9367. uri.fragment("");
  9368. this._url = uri.toString();
  9369. },
  9370. },
  9371. /**
  9372. * The file extension of the resource.
  9373. *
  9374. * @memberof Resource.prototype
  9375. * @type {String}
  9376. *
  9377. * @readonly
  9378. */
  9379. extension: {
  9380. get: function () {
  9381. return getExtensionFromUri(this._url);
  9382. },
  9383. },
  9384. /**
  9385. * True if the Resource refers to a data URI.
  9386. *
  9387. * @memberof Resource.prototype
  9388. * @type {Boolean}
  9389. */
  9390. isDataUri: {
  9391. get: function () {
  9392. return isDataUri(this._url);
  9393. },
  9394. },
  9395. /**
  9396. * True if the Resource refers to a blob URI.
  9397. *
  9398. * @memberof Resource.prototype
  9399. * @type {Boolean}
  9400. */
  9401. isBlobUri: {
  9402. get: function () {
  9403. return isBlobUri(this._url);
  9404. },
  9405. },
  9406. /**
  9407. * True if the Resource refers to a cross origin URL.
  9408. *
  9409. * @memberof Resource.prototype
  9410. * @type {Boolean}
  9411. */
  9412. isCrossOriginUrl: {
  9413. get: function () {
  9414. return isCrossOriginUrl(this._url);
  9415. },
  9416. },
  9417. /**
  9418. * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
  9419. *
  9420. * @memberof Resource.prototype
  9421. * @type {Boolean}
  9422. */
  9423. hasHeaders: {
  9424. get: function () {
  9425. return Object.keys(this.headers).length > 0;
  9426. },
  9427. },
  9428. });
  9429. /**
  9430. * Override Object#toString so that implicit string conversion gives the
  9431. * complete URL represented by this Resource.
  9432. *
  9433. * @returns {String} The URL represented by this Resource
  9434. */
  9435. Resource.prototype.toString = function () {
  9436. return this.getUrlComponent(true, true);
  9437. };
  9438. /**
  9439. * Returns the url, optional with the query string and processed by a proxy.
  9440. *
  9441. * @param {Boolean} [query=false] If true, the query string is included.
  9442. * @param {Boolean} [proxy=false] If true, the url is processed by the proxy object, if defined.
  9443. *
  9444. * @returns {String} The url with all the requested components.
  9445. */
  9446. Resource.prototype.getUrlComponent = function (query, proxy) {
  9447. if (this.isDataUri) {
  9448. return this._url;
  9449. }
  9450. const uri = new URI(this._url);
  9451. if (query) {
  9452. stringifyQuery(uri, this);
  9453. }
  9454. // objectToQuery escapes the placeholders. Undo that.
  9455. let url = uri.toString().replace(/%7B/g, "{").replace(/%7D/g, "}");
  9456. const templateValues = this._templateValues;
  9457. url = url.replace(/{(.*?)}/g, function (match, key) {
  9458. const replacement = templateValues[key];
  9459. if (defaultValue.defined(replacement)) {
  9460. // use the replacement value from templateValues if there is one...
  9461. return encodeURIComponent(replacement);
  9462. }
  9463. // otherwise leave it unchanged
  9464. return match;
  9465. });
  9466. if (proxy && defaultValue.defined(this.proxy)) {
  9467. url = this.proxy.getURL(url);
  9468. }
  9469. return url;
  9470. };
  9471. /**
  9472. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  9473. * 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.
  9474. *
  9475. * @param {Object} params The query parameters
  9476. * @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.
  9477. */
  9478. Resource.prototype.setQueryParameters = function (params, useAsDefault) {
  9479. if (useAsDefault) {
  9480. this._queryParameters = combineQueryParameters(
  9481. this._queryParameters,
  9482. params,
  9483. false
  9484. );
  9485. } else {
  9486. this._queryParameters = combineQueryParameters(
  9487. params,
  9488. this._queryParameters,
  9489. false
  9490. );
  9491. }
  9492. };
  9493. /**
  9494. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  9495. * as opposed to adding them one at a time to the queryParameters property.
  9496. *
  9497. * @param {Object} params The query parameters
  9498. */
  9499. Resource.prototype.appendQueryParameters = function (params) {
  9500. this._queryParameters = combineQueryParameters(
  9501. params,
  9502. this._queryParameters,
  9503. true
  9504. );
  9505. };
  9506. /**
  9507. * Combines the specified object and the existing template values. This allows you to add many values at once,
  9508. * 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.
  9509. *
  9510. * @param {Object} template The template values
  9511. * @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.
  9512. */
  9513. Resource.prototype.setTemplateValues = function (template, useAsDefault) {
  9514. if (useAsDefault) {
  9515. this._templateValues = combine.combine(this._templateValues, template);
  9516. } else {
  9517. this._templateValues = combine.combine(template, this._templateValues);
  9518. }
  9519. };
  9520. /**
  9521. * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
  9522. *
  9523. * @param {Object} options An object with the following properties
  9524. * @param {String} [options.url] The url that will be resolved relative to the url of the current instance.
  9525. * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
  9526. * @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.
  9527. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9528. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9529. * @param {Resource.RetryCallback} [options.retryCallback] The function to call when loading the resource fails.
  9530. * @param {Number} [options.retryAttempts] The number of times the retryCallback should be called before giving up.
  9531. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9532. * @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.
  9533. *
  9534. * @returns {Resource} The resource derived from the current one.
  9535. */
  9536. Resource.prototype.getDerivedResource = function (options) {
  9537. const resource = this.clone();
  9538. resource._retryCount = 0;
  9539. if (defaultValue.defined(options.url)) {
  9540. const uri = new URI(options.url);
  9541. const preserveQueryParameters = defaultValue.defaultValue(
  9542. options.preserveQueryParameters,
  9543. false
  9544. );
  9545. parseQuery(uri, resource, true, preserveQueryParameters);
  9546. // Remove the fragment as it's not sent with a request
  9547. uri.fragment("");
  9548. if (uri.scheme() !== "") {
  9549. resource._url = uri.toString();
  9550. } else {
  9551. resource._url = uri
  9552. .absoluteTo(new URI(getAbsoluteUri(this._url)))
  9553. .toString();
  9554. }
  9555. }
  9556. if (defaultValue.defined(options.queryParameters)) {
  9557. resource._queryParameters = combine.combine(
  9558. options.queryParameters,
  9559. resource._queryParameters
  9560. );
  9561. }
  9562. if (defaultValue.defined(options.templateValues)) {
  9563. resource._templateValues = combine.combine(
  9564. options.templateValues,
  9565. resource.templateValues
  9566. );
  9567. }
  9568. if (defaultValue.defined(options.headers)) {
  9569. resource.headers = combine.combine(options.headers, resource.headers);
  9570. }
  9571. if (defaultValue.defined(options.proxy)) {
  9572. resource.proxy = options.proxy;
  9573. }
  9574. if (defaultValue.defined(options.request)) {
  9575. resource.request = options.request;
  9576. }
  9577. if (defaultValue.defined(options.retryCallback)) {
  9578. resource.retryCallback = options.retryCallback;
  9579. }
  9580. if (defaultValue.defined(options.retryAttempts)) {
  9581. resource.retryAttempts = options.retryAttempts;
  9582. }
  9583. return resource;
  9584. };
  9585. /**
  9586. * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
  9587. *
  9588. * @param {Error} [error] The error that was encountered.
  9589. *
  9590. * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
  9591. *
  9592. * @private
  9593. */
  9594. Resource.prototype.retryOnError = function (error) {
  9595. const retryCallback = this.retryCallback;
  9596. if (
  9597. typeof retryCallback !== "function" ||
  9598. this._retryCount >= this.retryAttempts
  9599. ) {
  9600. return Promise.resolve(false);
  9601. }
  9602. const that = this;
  9603. return Promise.resolve(retryCallback(this, error)).then(function (result) {
  9604. ++that._retryCount;
  9605. return result;
  9606. });
  9607. };
  9608. /**
  9609. * Duplicates a Resource instance.
  9610. *
  9611. * @param {Resource} [result] The object onto which to store the result.
  9612. *
  9613. * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
  9614. */
  9615. Resource.prototype.clone = function (result) {
  9616. if (!defaultValue.defined(result)) {
  9617. result = new Resource({
  9618. url: this._url,
  9619. });
  9620. }
  9621. result._url = this._url;
  9622. result._queryParameters = clone(this._queryParameters);
  9623. result._templateValues = clone(this._templateValues);
  9624. result.headers = clone(this.headers);
  9625. result.proxy = this.proxy;
  9626. result.retryCallback = this.retryCallback;
  9627. result.retryAttempts = this.retryAttempts;
  9628. result._retryCount = 0;
  9629. result.request = this.request.clone();
  9630. return result;
  9631. };
  9632. /**
  9633. * Returns the base path of the Resource.
  9634. *
  9635. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  9636. *
  9637. * @returns {String} The base URI of the resource
  9638. */
  9639. Resource.prototype.getBaseUri = function (includeQuery) {
  9640. return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  9641. };
  9642. /**
  9643. * Appends a forward slash to the URL.
  9644. */
  9645. Resource.prototype.appendForwardSlash = function () {
  9646. this._url = appendForwardSlash(this._url);
  9647. };
  9648. /**
  9649. * Asynchronously loads the resource as raw binary data. Returns a promise that will resolve to
  9650. * an ArrayBuffer once loaded, or reject if the resource failed to load. The data is loaded
  9651. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9652. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  9653. *
  9654. * @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.
  9655. *
  9656. * @example
  9657. * // load a single URL asynchronously
  9658. * resource.fetchArrayBuffer().then(function(arrayBuffer) {
  9659. * // use the data
  9660. * }).catch(function(error) {
  9661. * // an error occurred
  9662. * });
  9663. *
  9664. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9665. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9666. */
  9667. Resource.prototype.fetchArrayBuffer = function () {
  9668. return this.fetch({
  9669. responseType: "arraybuffer",
  9670. });
  9671. };
  9672. /**
  9673. * Creates a Resource and calls fetchArrayBuffer() on it.
  9674. *
  9675. * @param {String|Object} options A url or an object with the following properties
  9676. * @param {String} options.url The url of the resource.
  9677. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9678. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9679. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9680. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9681. * @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.
  9682. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9683. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9684. * @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.
  9685. */
  9686. Resource.fetchArrayBuffer = function (options) {
  9687. const resource = new Resource(options);
  9688. return resource.fetchArrayBuffer();
  9689. };
  9690. /**
  9691. * Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
  9692. * a Blob once loaded, or reject if the resource failed to load. The data is loaded
  9693. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9694. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  9695. *
  9696. * @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.
  9697. *
  9698. * @example
  9699. * // load a single URL asynchronously
  9700. * resource.fetchBlob().then(function(blob) {
  9701. * // use the data
  9702. * }).catch(function(error) {
  9703. * // an error occurred
  9704. * });
  9705. *
  9706. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9707. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9708. */
  9709. Resource.prototype.fetchBlob = function () {
  9710. return this.fetch({
  9711. responseType: "blob",
  9712. });
  9713. };
  9714. /**
  9715. * Creates a Resource and calls fetchBlob() on it.
  9716. *
  9717. * @param {String|Object} options A url or an object with the following properties
  9718. * @param {String} options.url The url of the resource.
  9719. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9720. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9721. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9722. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9723. * @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.
  9724. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9725. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9726. * @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.
  9727. */
  9728. Resource.fetchBlob = function (options) {
  9729. const resource = new Resource(options);
  9730. return resource.fetchBlob();
  9731. };
  9732. /**
  9733. * Asynchronously loads the given image resource. Returns a promise that will resolve to
  9734. * 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
  9735. * {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
  9736. *
  9737. * @param {Object} [options] An object with the following properties.
  9738. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  9739. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  9740. * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  9741. * @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>.
  9742. * @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.
  9743. *
  9744. *
  9745. * @example
  9746. * // load a single image asynchronously
  9747. * resource.fetchImage().then(function(image) {
  9748. * // use the loaded image
  9749. * }).catch(function(error) {
  9750. * // an error occurred
  9751. * });
  9752. *
  9753. * // load several images in parallel
  9754. * Promise.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
  9755. * // images is an array containing all the loaded images
  9756. * });
  9757. *
  9758. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9759. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9760. */
  9761. Resource.prototype.fetchImage = function (options) {
  9762. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  9763. const preferImageBitmap = defaultValue.defaultValue(options.preferImageBitmap, false);
  9764. const preferBlob = defaultValue.defaultValue(options.preferBlob, false);
  9765. const flipY = defaultValue.defaultValue(options.flipY, false);
  9766. const skipColorSpaceConversion = defaultValue.defaultValue(
  9767. options.skipColorSpaceConversion,
  9768. false
  9769. );
  9770. checkAndResetRequest(this.request);
  9771. // We try to load the image normally if
  9772. // 1. Blobs aren't supported
  9773. // 2. It's a data URI
  9774. // 3. It's a blob URI
  9775. // 4. It doesn't have request headers and we preferBlob is false
  9776. if (
  9777. !xhrBlobSupported ||
  9778. this.isDataUri ||
  9779. this.isBlobUri ||
  9780. (!this.hasHeaders && !preferBlob)
  9781. ) {
  9782. return fetchImage({
  9783. resource: this,
  9784. flipY: flipY,
  9785. skipColorSpaceConversion: skipColorSpaceConversion,
  9786. preferImageBitmap: preferImageBitmap,
  9787. });
  9788. }
  9789. const blobPromise = this.fetchBlob();
  9790. if (!defaultValue.defined(blobPromise)) {
  9791. return;
  9792. }
  9793. let supportsImageBitmap;
  9794. let useImageBitmap;
  9795. let generatedBlobResource;
  9796. let generatedBlob;
  9797. return Resource.supportsImageBitmapOptions()
  9798. .then(function (result) {
  9799. supportsImageBitmap = result;
  9800. useImageBitmap = supportsImageBitmap && preferImageBitmap;
  9801. return blobPromise;
  9802. })
  9803. .then(function (blob) {
  9804. if (!defaultValue.defined(blob)) {
  9805. return;
  9806. }
  9807. generatedBlob = blob;
  9808. if (useImageBitmap) {
  9809. return Resource.createImageBitmapFromBlob(blob, {
  9810. flipY: flipY,
  9811. premultiplyAlpha: false,
  9812. skipColorSpaceConversion: skipColorSpaceConversion,
  9813. });
  9814. }
  9815. const blobUrl = window.URL.createObjectURL(blob);
  9816. generatedBlobResource = new Resource({
  9817. url: blobUrl,
  9818. });
  9819. return fetchImage({
  9820. resource: generatedBlobResource,
  9821. flipY: flipY,
  9822. skipColorSpaceConversion: skipColorSpaceConversion,
  9823. preferImageBitmap: false,
  9824. });
  9825. })
  9826. .then(function (image) {
  9827. if (!defaultValue.defined(image)) {
  9828. return;
  9829. }
  9830. // The blob object may be needed for use by a TileDiscardPolicy,
  9831. // so attach it to the image.
  9832. image.blob = generatedBlob;
  9833. if (useImageBitmap) {
  9834. return image;
  9835. }
  9836. window.URL.revokeObjectURL(generatedBlobResource.url);
  9837. return image;
  9838. })
  9839. .catch(function (error) {
  9840. if (defaultValue.defined(generatedBlobResource)) {
  9841. window.URL.revokeObjectURL(generatedBlobResource.url);
  9842. }
  9843. // If the blob load succeeded but the image decode failed, attach the blob
  9844. // to the error object for use by a TileDiscardPolicy.
  9845. // In particular, BingMapsImageryProvider uses this to detect the
  9846. // zero-length response that is returned when a tile is not available.
  9847. error.blob = generatedBlob;
  9848. return Promise.reject(error);
  9849. });
  9850. };
  9851. /**
  9852. * Fetches an image and returns a promise to it.
  9853. *
  9854. * @param {Object} [options] An object with the following properties.
  9855. * @param {Resource} [options.resource] Resource object that points to an image to fetch.
  9856. * @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  9857. * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  9858. * @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>.
  9859. * @private
  9860. */
  9861. function fetchImage(options) {
  9862. const resource = options.resource;
  9863. const flipY = options.flipY;
  9864. const skipColorSpaceConversion = options.skipColorSpaceConversion;
  9865. const preferImageBitmap = options.preferImageBitmap;
  9866. const request = resource.request;
  9867. request.url = resource.url;
  9868. request.requestFunction = function () {
  9869. let crossOrigin = false;
  9870. // data URIs can't have crossorigin set.
  9871. if (!resource.isDataUri && !resource.isBlobUri) {
  9872. crossOrigin = resource.isCrossOriginUrl;
  9873. }
  9874. const deferred = defer();
  9875. Resource._Implementations.createImage(
  9876. request,
  9877. crossOrigin,
  9878. deferred,
  9879. flipY,
  9880. skipColorSpaceConversion,
  9881. preferImageBitmap
  9882. );
  9883. return deferred.promise;
  9884. };
  9885. const promise = RequestScheduler.request(request);
  9886. if (!defaultValue.defined(promise)) {
  9887. return;
  9888. }
  9889. return promise.catch(function (e) {
  9890. // Don't retry cancelled or otherwise aborted requests
  9891. if (request.state !== RequestState$1.FAILED) {
  9892. return Promise.reject(e);
  9893. }
  9894. return resource.retryOnError(e).then(function (retry) {
  9895. if (retry) {
  9896. // Reset request so it can try again
  9897. request.state = RequestState$1.UNISSUED;
  9898. request.deferred = undefined;
  9899. return fetchImage({
  9900. resource: resource,
  9901. flipY: flipY,
  9902. skipColorSpaceConversion: skipColorSpaceConversion,
  9903. preferImageBitmap: preferImageBitmap,
  9904. });
  9905. }
  9906. return Promise.reject(e);
  9907. });
  9908. });
  9909. }
  9910. /**
  9911. * Creates a Resource and calls fetchImage() on it.
  9912. *
  9913. * @param {String|Object} options A url or an object with the following properties
  9914. * @param {String} options.url The url of the resource.
  9915. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9916. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9917. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9918. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9919. * @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>.
  9920. * @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.
  9921. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9922. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9923. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  9924. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  9925. * @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>.
  9926. * @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.
  9927. */
  9928. Resource.fetchImage = function (options) {
  9929. const resource = new Resource(options);
  9930. return resource.fetchImage({
  9931. flipY: options.flipY,
  9932. skipColorSpaceConversion: options.skipColorSpaceConversion,
  9933. preferBlob: options.preferBlob,
  9934. preferImageBitmap: options.preferImageBitmap,
  9935. });
  9936. };
  9937. /**
  9938. * Asynchronously loads the given resource as text. Returns a promise that will resolve to
  9939. * a String once loaded, or reject if the resource failed to load. The data is loaded
  9940. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9941. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  9942. *
  9943. * @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.
  9944. *
  9945. * @example
  9946. * // load text from a URL, setting a custom header
  9947. * const resource = new Resource({
  9948. * url: 'http://someUrl.com/someJson.txt',
  9949. * headers: {
  9950. * 'X-Custom-Header' : 'some value'
  9951. * }
  9952. * });
  9953. * resource.fetchText().then(function(text) {
  9954. * // Do something with the text
  9955. * }).catch(function(error) {
  9956. * // an error occurred
  9957. * });
  9958. *
  9959. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  9960. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  9961. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  9962. */
  9963. Resource.prototype.fetchText = function () {
  9964. return this.fetch({
  9965. responseType: "text",
  9966. });
  9967. };
  9968. /**
  9969. * Creates a Resource and calls fetchText() on it.
  9970. *
  9971. * @param {String|Object} options A url or an object with the following properties
  9972. * @param {String} options.url The url of the resource.
  9973. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  9974. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  9975. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  9976. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  9977. * @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.
  9978. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  9979. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  9980. * @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.
  9981. */
  9982. Resource.fetchText = function (options) {
  9983. const resource = new Resource(options);
  9984. return resource.fetchText();
  9985. };
  9986. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  9987. /**
  9988. * Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
  9989. * a JSON object once loaded, or reject if the resource failed to load. The data is loaded
  9990. * using XMLHttpRequest, which means that in order to make requests to another origin,
  9991. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  9992. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  9993. * already specified.
  9994. *
  9995. * @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.
  9996. *
  9997. *
  9998. * @example
  9999. * resource.fetchJson().then(function(jsonData) {
  10000. * // Do something with the JSON object
  10001. * }).catch(function(error) {
  10002. * // an error occurred
  10003. * });
  10004. *
  10005. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10006. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10007. */
  10008. Resource.prototype.fetchJson = function () {
  10009. const promise = this.fetch({
  10010. responseType: "text",
  10011. headers: {
  10012. Accept: "application/json,*/*;q=0.01",
  10013. },
  10014. });
  10015. if (!defaultValue.defined(promise)) {
  10016. return undefined;
  10017. }
  10018. return promise.then(function (value) {
  10019. if (!defaultValue.defined(value)) {
  10020. return;
  10021. }
  10022. return JSON.parse(value);
  10023. });
  10024. };
  10025. /**
  10026. * Creates a Resource and calls fetchJson() on it.
  10027. *
  10028. * @param {String|Object} options A url or an object with the following properties
  10029. * @param {String} options.url The url of the resource.
  10030. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10031. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10032. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10033. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10034. * @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.
  10035. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10036. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10037. * @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.
  10038. */
  10039. Resource.fetchJson = function (options) {
  10040. const resource = new Resource(options);
  10041. return resource.fetchJson();
  10042. };
  10043. /**
  10044. * Asynchronously loads the given resource as XML. Returns a promise that will resolve to
  10045. * an XML Document once loaded, or reject if the resource failed to load. The data is loaded
  10046. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10047. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10048. *
  10049. * @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.
  10050. *
  10051. *
  10052. * @example
  10053. * // load XML from a URL, setting a custom header
  10054. * Cesium.loadXML('http://someUrl.com/someXML.xml', {
  10055. * 'X-Custom-Header' : 'some value'
  10056. * }).then(function(document) {
  10057. * // Do something with the document
  10058. * }).catch(function(error) {
  10059. * // an error occurred
  10060. * });
  10061. *
  10062. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  10063. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10064. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10065. */
  10066. Resource.prototype.fetchXML = function () {
  10067. return this.fetch({
  10068. responseType: "document",
  10069. overrideMimeType: "text/xml",
  10070. });
  10071. };
  10072. /**
  10073. * Creates a Resource and calls fetchXML() on it.
  10074. *
  10075. * @param {String|Object} options A url or an object with the following properties
  10076. * @param {String} options.url The url of the resource.
  10077. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10078. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10079. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10080. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10081. * @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.
  10082. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10083. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10084. * @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.
  10085. */
  10086. Resource.fetchXML = function (options) {
  10087. const resource = new Resource(options);
  10088. return resource.fetchXML();
  10089. };
  10090. /**
  10091. * Requests a resource using JSONP.
  10092. *
  10093. * @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
  10094. * @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.
  10095. *
  10096. *
  10097. * @example
  10098. * // load a data asynchronously
  10099. * resource.fetchJsonp().then(function(data) {
  10100. * // use the loaded data
  10101. * }).catch(function(error) {
  10102. * // an error occurred
  10103. * });
  10104. *
  10105. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10106. */
  10107. Resource.prototype.fetchJsonp = function (callbackParameterName) {
  10108. callbackParameterName = defaultValue.defaultValue(callbackParameterName, "callback");
  10109. checkAndResetRequest(this.request);
  10110. //generate a unique function name
  10111. let functionName;
  10112. do {
  10113. functionName = `loadJsonp${ComponentDatatype.CesiumMath.nextRandomNumber()
  10114. .toString()
  10115. .substring(2, 8)}`;
  10116. } while (defaultValue.defined(window[functionName]));
  10117. return fetchJsonp(this, callbackParameterName, functionName);
  10118. };
  10119. function fetchJsonp(resource, callbackParameterName, functionName) {
  10120. const callbackQuery = {};
  10121. callbackQuery[callbackParameterName] = functionName;
  10122. resource.setQueryParameters(callbackQuery);
  10123. const request = resource.request;
  10124. request.url = resource.url;
  10125. request.requestFunction = function () {
  10126. const deferred = defer();
  10127. //assign a function with that name in the global scope
  10128. window[functionName] = function (data) {
  10129. deferred.resolve(data);
  10130. try {
  10131. delete window[functionName];
  10132. } catch (e) {
  10133. window[functionName] = undefined;
  10134. }
  10135. };
  10136. Resource._Implementations.loadAndExecuteScript(
  10137. resource.url,
  10138. functionName,
  10139. deferred
  10140. );
  10141. return deferred.promise;
  10142. };
  10143. const promise = RequestScheduler.request(request);
  10144. if (!defaultValue.defined(promise)) {
  10145. return;
  10146. }
  10147. return promise.catch(function (e) {
  10148. if (request.state !== RequestState$1.FAILED) {
  10149. return Promise.reject(e);
  10150. }
  10151. return resource.retryOnError(e).then(function (retry) {
  10152. if (retry) {
  10153. // Reset request so it can try again
  10154. request.state = RequestState$1.UNISSUED;
  10155. request.deferred = undefined;
  10156. return fetchJsonp(resource, callbackParameterName, functionName);
  10157. }
  10158. return Promise.reject(e);
  10159. });
  10160. });
  10161. }
  10162. /**
  10163. * Creates a Resource from a URL and calls fetchJsonp() on it.
  10164. *
  10165. * @param {String|Object} options A url or an object with the following properties
  10166. * @param {String} options.url The url of the resource.
  10167. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10168. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10169. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10170. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10171. * @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.
  10172. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10173. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10174. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
  10175. * @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.
  10176. */
  10177. Resource.fetchJsonp = function (options) {
  10178. const resource = new Resource(options);
  10179. return resource.fetchJsonp(options.callbackParameterName);
  10180. };
  10181. /**
  10182. * @private
  10183. */
  10184. Resource.prototype._makeRequest = function (options) {
  10185. const resource = this;
  10186. checkAndResetRequest(resource.request);
  10187. const request = resource.request;
  10188. request.url = resource.url;
  10189. request.requestFunction = function () {
  10190. const responseType = options.responseType;
  10191. const headers = combine.combine(options.headers, resource.headers);
  10192. const overrideMimeType = options.overrideMimeType;
  10193. const method = options.method;
  10194. const data = options.data;
  10195. const deferred = defer();
  10196. const xhr = Resource._Implementations.loadWithXhr(
  10197. resource.url,
  10198. responseType,
  10199. method,
  10200. data,
  10201. headers,
  10202. deferred,
  10203. overrideMimeType
  10204. );
  10205. if (defaultValue.defined(xhr) && defaultValue.defined(xhr.abort)) {
  10206. request.cancelFunction = function () {
  10207. xhr.abort();
  10208. };
  10209. }
  10210. return deferred.promise;
  10211. };
  10212. const promise = RequestScheduler.request(request);
  10213. if (!defaultValue.defined(promise)) {
  10214. return;
  10215. }
  10216. return promise
  10217. .then(function (data) {
  10218. // explicitly set to undefined to ensure GC of request response data. See #8843
  10219. request.cancelFunction = undefined;
  10220. return data;
  10221. })
  10222. .catch(function (e) {
  10223. request.cancelFunction = undefined;
  10224. if (request.state !== RequestState$1.FAILED) {
  10225. return Promise.reject(e);
  10226. }
  10227. return resource.retryOnError(e).then(function (retry) {
  10228. if (retry) {
  10229. // Reset request so it can try again
  10230. request.state = RequestState$1.UNISSUED;
  10231. request.deferred = undefined;
  10232. return resource.fetch(options);
  10233. }
  10234. return Promise.reject(e);
  10235. });
  10236. });
  10237. };
  10238. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  10239. function decodeDataUriText(isBase64, data) {
  10240. const result = decodeURIComponent(data);
  10241. if (isBase64) {
  10242. return atob(result);
  10243. }
  10244. return result;
  10245. }
  10246. function decodeDataUriArrayBuffer(isBase64, data) {
  10247. const byteString = decodeDataUriText(isBase64, data);
  10248. const buffer = new ArrayBuffer(byteString.length);
  10249. const view = new Uint8Array(buffer);
  10250. for (let i = 0; i < byteString.length; i++) {
  10251. view[i] = byteString.charCodeAt(i);
  10252. }
  10253. return buffer;
  10254. }
  10255. function decodeDataUri(dataUriRegexResult, responseType) {
  10256. responseType = defaultValue.defaultValue(responseType, "");
  10257. const mimeType = dataUriRegexResult[1];
  10258. const isBase64 = !!dataUriRegexResult[2];
  10259. const data = dataUriRegexResult[3];
  10260. let buffer;
  10261. let parser;
  10262. switch (responseType) {
  10263. case "":
  10264. case "text":
  10265. return decodeDataUriText(isBase64, data);
  10266. case "arraybuffer":
  10267. return decodeDataUriArrayBuffer(isBase64, data);
  10268. case "blob":
  10269. buffer = decodeDataUriArrayBuffer(isBase64, data);
  10270. return new Blob([buffer], {
  10271. type: mimeType,
  10272. });
  10273. case "document":
  10274. parser = new DOMParser();
  10275. return parser.parseFromString(
  10276. decodeDataUriText(isBase64, data),
  10277. mimeType
  10278. );
  10279. case "json":
  10280. return JSON.parse(decodeDataUriText(isBase64, data));
  10281. default:
  10282. //>>includeStart('debug', pragmas.debug);
  10283. throw new RuntimeError.DeveloperError(`Unhandled responseType: ${responseType}`);
  10284. //>>includeEnd('debug');
  10285. }
  10286. }
  10287. /**
  10288. * Asynchronously loads the given resource. Returns a promise that will resolve to
  10289. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10290. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10291. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
  10292. * the more specific functions eg. fetchJson, fetchBlob, etc.
  10293. *
  10294. * @param {Object} [options] Object with the following properties:
  10295. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10296. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10297. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10298. * @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.
  10299. *
  10300. *
  10301. * @example
  10302. * resource.fetch()
  10303. * .then(function(body) {
  10304. * // use the data
  10305. * }).catch(function(error) {
  10306. * // an error occurred
  10307. * });
  10308. *
  10309. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10310. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10311. */
  10312. Resource.prototype.fetch = function (options) {
  10313. options = defaultClone(options, {});
  10314. options.method = "GET";
  10315. return this._makeRequest(options);
  10316. };
  10317. /**
  10318. * Creates a Resource from a URL and calls fetch() on it.
  10319. *
  10320. * @param {String|Object} options A url or an object with the following properties
  10321. * @param {String} options.url The url of the resource.
  10322. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10323. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10324. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10325. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10326. * @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.
  10327. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10328. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10329. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10330. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10331. * @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.
  10332. */
  10333. Resource.fetch = function (options) {
  10334. const resource = new Resource(options);
  10335. return resource.fetch({
  10336. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10337. responseType: options.responseType,
  10338. overrideMimeType: options.overrideMimeType,
  10339. });
  10340. };
  10341. /**
  10342. * Asynchronously deletes the given resource. Returns a promise that will resolve to
  10343. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10344. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10345. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10346. *
  10347. * @param {Object} [options] Object with the following properties:
  10348. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10349. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10350. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10351. * @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.
  10352. *
  10353. *
  10354. * @example
  10355. * resource.delete()
  10356. * .then(function(body) {
  10357. * // use the data
  10358. * }).catch(function(error) {
  10359. * // an error occurred
  10360. * });
  10361. *
  10362. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10363. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10364. */
  10365. Resource.prototype.delete = function (options) {
  10366. options = defaultClone(options, {});
  10367. options.method = "DELETE";
  10368. return this._makeRequest(options);
  10369. };
  10370. /**
  10371. * Creates a Resource from a URL and calls delete() on it.
  10372. *
  10373. * @param {String|Object} options A url or an object with the following properties
  10374. * @param {String} options.url The url of the resource.
  10375. * @param {Object} [options.data] Data that is posted with the resource.
  10376. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10377. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10378. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10379. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10380. * @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.
  10381. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10382. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10383. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10384. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10385. * @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.
  10386. */
  10387. Resource.delete = function (options) {
  10388. const resource = new Resource(options);
  10389. return resource.delete({
  10390. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10391. responseType: options.responseType,
  10392. overrideMimeType: options.overrideMimeType,
  10393. data: options.data,
  10394. });
  10395. };
  10396. /**
  10397. * Asynchronously gets headers the given resource. Returns a promise that will resolve to
  10398. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10399. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10400. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10401. *
  10402. * @param {Object} [options] Object with the following properties:
  10403. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10404. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10405. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10406. * @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.
  10407. *
  10408. *
  10409. * @example
  10410. * resource.head()
  10411. * .then(function(headers) {
  10412. * // use the data
  10413. * }).catch(function(error) {
  10414. * // an error occurred
  10415. * });
  10416. *
  10417. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10418. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10419. */
  10420. Resource.prototype.head = function (options) {
  10421. options = defaultClone(options, {});
  10422. options.method = "HEAD";
  10423. return this._makeRequest(options);
  10424. };
  10425. /**
  10426. * Creates a Resource from a URL and calls head() on it.
  10427. *
  10428. * @param {String|Object} options A url or an object with the following properties
  10429. * @param {String} options.url The url of the resource.
  10430. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10431. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10432. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10433. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10434. * @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.
  10435. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10436. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10437. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10438. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10439. * @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.
  10440. */
  10441. Resource.head = function (options) {
  10442. const resource = new Resource(options);
  10443. return resource.head({
  10444. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10445. responseType: options.responseType,
  10446. overrideMimeType: options.overrideMimeType,
  10447. });
  10448. };
  10449. /**
  10450. * Asynchronously gets options the given resource. Returns a promise that will resolve to
  10451. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10452. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10453. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10454. *
  10455. * @param {Object} [options] Object with the following properties:
  10456. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10457. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10458. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10459. * @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.
  10460. *
  10461. *
  10462. * @example
  10463. * resource.options()
  10464. * .then(function(headers) {
  10465. * // use the data
  10466. * }).catch(function(error) {
  10467. * // an error occurred
  10468. * });
  10469. *
  10470. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10471. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10472. */
  10473. Resource.prototype.options = function (options) {
  10474. options = defaultClone(options, {});
  10475. options.method = "OPTIONS";
  10476. return this._makeRequest(options);
  10477. };
  10478. /**
  10479. * Creates a Resource from a URL and calls options() on it.
  10480. *
  10481. * @param {String|Object} options A url or an object with the following properties
  10482. * @param {String} options.url The url of the resource.
  10483. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10484. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10485. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10486. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10487. * @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.
  10488. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10489. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10490. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10491. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10492. * @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.
  10493. */
  10494. Resource.options = function (options) {
  10495. const resource = new Resource(options);
  10496. return resource.options({
  10497. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  10498. responseType: options.responseType,
  10499. overrideMimeType: options.overrideMimeType,
  10500. });
  10501. };
  10502. /**
  10503. * Asynchronously posts data to the given resource. Returns a promise that will resolve to
  10504. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10505. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10506. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10507. *
  10508. * @param {Object} data Data that is posted with the resource.
  10509. * @param {Object} [options] Object with the following properties:
  10510. * @param {Object} [options.data] Data that is posted with the resource.
  10511. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10512. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10513. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10514. * @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.
  10515. *
  10516. *
  10517. * @example
  10518. * resource.post(data)
  10519. * .then(function(result) {
  10520. * // use the result
  10521. * }).catch(function(error) {
  10522. * // an error occurred
  10523. * });
  10524. *
  10525. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10526. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10527. */
  10528. Resource.prototype.post = function (data, options) {
  10529. RuntimeError.Check.defined("data", data);
  10530. options = defaultClone(options, {});
  10531. options.method = "POST";
  10532. options.data = data;
  10533. return this._makeRequest(options);
  10534. };
  10535. /**
  10536. * Creates a Resource from a URL and calls post() on it.
  10537. *
  10538. * @param {Object} options A url or an object with the following properties
  10539. * @param {String} options.url The url of the resource.
  10540. * @param {Object} options.data Data that is posted with the resource.
  10541. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10542. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10543. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10544. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10545. * @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.
  10546. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10547. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10548. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10549. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10550. * @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.
  10551. */
  10552. Resource.post = function (options) {
  10553. const resource = new Resource(options);
  10554. return resource.post(options.data, {
  10555. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  10556. responseType: options.responseType,
  10557. overrideMimeType: options.overrideMimeType,
  10558. });
  10559. };
  10560. /**
  10561. * Asynchronously puts data to the given resource. Returns a promise that will resolve to
  10562. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10563. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10564. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10565. *
  10566. * @param {Object} data Data that is posted with the resource.
  10567. * @param {Object} [options] Object with the following properties:
  10568. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10569. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10570. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10571. * @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.
  10572. *
  10573. *
  10574. * @example
  10575. * resource.put(data)
  10576. * .then(function(result) {
  10577. * // use the result
  10578. * }).catch(function(error) {
  10579. * // an error occurred
  10580. * });
  10581. *
  10582. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10583. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10584. */
  10585. Resource.prototype.put = function (data, options) {
  10586. RuntimeError.Check.defined("data", data);
  10587. options = defaultClone(options, {});
  10588. options.method = "PUT";
  10589. options.data = data;
  10590. return this._makeRequest(options);
  10591. };
  10592. /**
  10593. * Creates a Resource from a URL and calls put() on it.
  10594. *
  10595. * @param {Object} options A url or an object with the following properties
  10596. * @param {String} options.url The url of the resource.
  10597. * @param {Object} options.data Data that is posted with the resource.
  10598. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10599. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10600. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10601. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10602. * @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.
  10603. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10604. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10605. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10606. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10607. * @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.
  10608. */
  10609. Resource.put = function (options) {
  10610. const resource = new Resource(options);
  10611. return resource.put(options.data, {
  10612. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  10613. responseType: options.responseType,
  10614. overrideMimeType: options.overrideMimeType,
  10615. });
  10616. };
  10617. /**
  10618. * Asynchronously patches data to the given resource. Returns a promise that will resolve to
  10619. * the result once loaded, or reject if the resource failed to load. The data is loaded
  10620. * using XMLHttpRequest, which means that in order to make requests to another origin,
  10621. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  10622. *
  10623. * @param {Object} data Data that is posted with the resource.
  10624. * @param {Object} [options] Object with the following properties:
  10625. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10626. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  10627. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10628. * @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.
  10629. *
  10630. *
  10631. * @example
  10632. * resource.patch(data)
  10633. * .then(function(result) {
  10634. * // use the result
  10635. * }).catch(function(error) {
  10636. * // an error occurred
  10637. * });
  10638. *
  10639. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10640. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  10641. */
  10642. Resource.prototype.patch = function (data, options) {
  10643. RuntimeError.Check.defined("data", data);
  10644. options = defaultClone(options, {});
  10645. options.method = "PATCH";
  10646. options.data = data;
  10647. return this._makeRequest(options);
  10648. };
  10649. /**
  10650. * Creates a Resource from a URL and calls patch() on it.
  10651. *
  10652. * @param {Object} options A url or an object with the following properties
  10653. * @param {String} options.url The url of the resource.
  10654. * @param {Object} options.data Data that is posted with the resource.
  10655. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10656. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10657. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10658. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  10659. * @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.
  10660. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10661. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10662. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  10663. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  10664. * @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.
  10665. */
  10666. Resource.patch = function (options) {
  10667. const resource = new Resource(options);
  10668. return resource.patch(options.data, {
  10669. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  10670. responseType: options.responseType,
  10671. overrideMimeType: options.overrideMimeType,
  10672. });
  10673. };
  10674. /**
  10675. * Contains implementations of functions that can be replaced for testing
  10676. *
  10677. * @private
  10678. */
  10679. Resource._Implementations = {};
  10680. Resource._Implementations.loadImageElement = function (
  10681. url,
  10682. crossOrigin,
  10683. deferred
  10684. ) {
  10685. const image = new Image();
  10686. image.onload = function () {
  10687. // work-around a known issue with Firefox and dimensionless SVG, see:
  10688. // - https://github.com/whatwg/html/issues/3510
  10689. // - https://bugzilla.mozilla.org/show_bug.cgi?id=700533
  10690. if (
  10691. image.naturalWidth === 0 &&
  10692. image.naturalHeight === 0 &&
  10693. image.width === 0 &&
  10694. image.height === 0
  10695. ) {
  10696. // these values affect rasterization and will likely mar the content
  10697. // until Firefox takes a stance on the issue, marred content is better than no content
  10698. // Chromium uses a more refined heuristic about its choice given nil viewBox, and a better stance and solution is
  10699. // proposed later in the original issue thread:
  10700. // - Chromium behavior: https://github.com/CesiumGS/cesium/issues/9188#issuecomment-704400825
  10701. // - Cesium's stance/solve: https://github.com/CesiumGS/cesium/issues/9188#issuecomment-720645777
  10702. image.width = 300;
  10703. image.height = 150;
  10704. }
  10705. deferred.resolve(image);
  10706. };
  10707. image.onerror = function (e) {
  10708. deferred.reject(e);
  10709. };
  10710. if (crossOrigin) {
  10711. if (TrustedServers.contains(url)) {
  10712. image.crossOrigin = "use-credentials";
  10713. } else {
  10714. image.crossOrigin = "";
  10715. }
  10716. }
  10717. image.src = url;
  10718. };
  10719. Resource._Implementations.createImage = function (
  10720. request,
  10721. crossOrigin,
  10722. deferred,
  10723. flipY,
  10724. skipColorSpaceConversion,
  10725. preferImageBitmap
  10726. ) {
  10727. const url = request.url;
  10728. // Passing an Image to createImageBitmap will force it to run on the main thread
  10729. // since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
  10730. // See:
  10731. // https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
  10732. // https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
  10733. Resource.supportsImageBitmapOptions()
  10734. .then(function (supportsImageBitmap) {
  10735. // We can only use ImageBitmap if we can flip on decode.
  10736. // See: https://github.com/CesiumGS/cesium/pull/7579#issuecomment-466146898
  10737. if (!(supportsImageBitmap && preferImageBitmap)) {
  10738. Resource._Implementations.loadImageElement(url, crossOrigin, deferred);
  10739. return;
  10740. }
  10741. const responseType = "blob";
  10742. const method = "GET";
  10743. const xhrDeferred = defer();
  10744. const xhr = Resource._Implementations.loadWithXhr(
  10745. url,
  10746. responseType,
  10747. method,
  10748. undefined,
  10749. undefined,
  10750. xhrDeferred,
  10751. undefined,
  10752. undefined,
  10753. undefined
  10754. );
  10755. if (defaultValue.defined(xhr) && defaultValue.defined(xhr.abort)) {
  10756. request.cancelFunction = function () {
  10757. xhr.abort();
  10758. };
  10759. }
  10760. return xhrDeferred.promise
  10761. .then(function (blob) {
  10762. if (!defaultValue.defined(blob)) {
  10763. deferred.reject(
  10764. new RuntimeError.RuntimeError(
  10765. `Successfully retrieved ${url} but it contained no content.`
  10766. )
  10767. );
  10768. return;
  10769. }
  10770. return Resource.createImageBitmapFromBlob(blob, {
  10771. flipY: flipY,
  10772. premultiplyAlpha: false,
  10773. skipColorSpaceConversion: skipColorSpaceConversion,
  10774. });
  10775. })
  10776. .then(function (image) {
  10777. deferred.resolve(image);
  10778. });
  10779. })
  10780. .catch(function (e) {
  10781. deferred.reject(e);
  10782. });
  10783. };
  10784. /**
  10785. * Wrapper for createImageBitmap
  10786. *
  10787. * @private
  10788. */
  10789. Resource.createImageBitmapFromBlob = function (blob, options) {
  10790. RuntimeError.Check.defined("options", options);
  10791. RuntimeError.Check.typeOf.bool("options.flipY", options.flipY);
  10792. RuntimeError.Check.typeOf.bool("options.premultiplyAlpha", options.premultiplyAlpha);
  10793. RuntimeError.Check.typeOf.bool(
  10794. "options.skipColorSpaceConversion",
  10795. options.skipColorSpaceConversion
  10796. );
  10797. return createImageBitmap(blob, {
  10798. imageOrientation: options.flipY ? "flipY" : "none",
  10799. premultiplyAlpha: options.premultiplyAlpha ? "premultiply" : "none",
  10800. colorSpaceConversion: options.skipColorSpaceConversion ? "none" : "default",
  10801. });
  10802. };
  10803. function decodeResponse(loadWithHttpResponse, responseType) {
  10804. switch (responseType) {
  10805. case "text":
  10806. return loadWithHttpResponse.toString("utf8");
  10807. case "json":
  10808. return JSON.parse(loadWithHttpResponse.toString("utf8"));
  10809. default:
  10810. return new Uint8Array(loadWithHttpResponse).buffer;
  10811. }
  10812. }
  10813. function loadWithHttpRequest(
  10814. url,
  10815. responseType,
  10816. method,
  10817. data,
  10818. headers,
  10819. deferred,
  10820. overrideMimeType
  10821. ) {
  10822. // Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
  10823. /* eslint-disable no-undef */
  10824. const URL = require("url").parse(url);
  10825. const http = URL.protocol === "https:" ? require("https") : require("http");
  10826. const zlib = require("zlib");
  10827. /* eslint-enable no-undef */
  10828. const options = {
  10829. protocol: URL.protocol,
  10830. hostname: URL.hostname,
  10831. port: URL.port,
  10832. path: URL.path,
  10833. query: URL.query,
  10834. method: method,
  10835. headers: headers,
  10836. };
  10837. http
  10838. .request(options)
  10839. .on("response", function (res) {
  10840. if (res.statusCode < 200 || res.statusCode >= 300) {
  10841. deferred.reject(
  10842. new RequestErrorEvent(res.statusCode, res, res.headers)
  10843. );
  10844. return;
  10845. }
  10846. const chunkArray = [];
  10847. res.on("data", function (chunk) {
  10848. chunkArray.push(chunk);
  10849. });
  10850. res.on("end", function () {
  10851. // eslint-disable-next-line no-undef
  10852. const result = Buffer.concat(chunkArray);
  10853. if (res.headers["content-encoding"] === "gzip") {
  10854. zlib.gunzip(result, function (error, resultUnzipped) {
  10855. if (error) {
  10856. deferred.reject(
  10857. new RuntimeError.RuntimeError("Error decompressing response.")
  10858. );
  10859. } else {
  10860. deferred.resolve(decodeResponse(resultUnzipped, responseType));
  10861. }
  10862. });
  10863. } else {
  10864. deferred.resolve(decodeResponse(result, responseType));
  10865. }
  10866. });
  10867. })
  10868. .on("error", function (e) {
  10869. deferred.reject(new RequestErrorEvent());
  10870. })
  10871. .end();
  10872. }
  10873. const noXMLHttpRequest = typeof XMLHttpRequest === "undefined";
  10874. Resource._Implementations.loadWithXhr = function (
  10875. url,
  10876. responseType,
  10877. method,
  10878. data,
  10879. headers,
  10880. deferred,
  10881. overrideMimeType
  10882. ) {
  10883. const dataUriRegexResult = dataUriRegex.exec(url);
  10884. if (dataUriRegexResult !== null) {
  10885. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  10886. return;
  10887. }
  10888. if (noXMLHttpRequest) {
  10889. loadWithHttpRequest(
  10890. url,
  10891. responseType,
  10892. method,
  10893. data,
  10894. headers,
  10895. deferred);
  10896. return;
  10897. }
  10898. const xhr = new XMLHttpRequest();
  10899. if (TrustedServers.contains(url)) {
  10900. xhr.withCredentials = true;
  10901. }
  10902. xhr.open(method, url, true);
  10903. if (defaultValue.defined(overrideMimeType) && defaultValue.defined(xhr.overrideMimeType)) {
  10904. xhr.overrideMimeType(overrideMimeType);
  10905. }
  10906. if (defaultValue.defined(headers)) {
  10907. for (const key in headers) {
  10908. if (headers.hasOwnProperty(key)) {
  10909. xhr.setRequestHeader(key, headers[key]);
  10910. }
  10911. }
  10912. }
  10913. if (defaultValue.defined(responseType)) {
  10914. xhr.responseType = responseType;
  10915. }
  10916. // While non-standard, file protocol always returns a status of 0 on success
  10917. let localFile = false;
  10918. if (typeof url === "string") {
  10919. localFile =
  10920. url.indexOf("file://") === 0 ||
  10921. (typeof window !== "undefined" && window.location.origin === "file://");
  10922. }
  10923. xhr.onload = function () {
  10924. if (
  10925. (xhr.status < 200 || xhr.status >= 300) &&
  10926. !(localFile && xhr.status === 0)
  10927. ) {
  10928. deferred.reject(
  10929. new RequestErrorEvent(
  10930. xhr.status,
  10931. xhr.response,
  10932. xhr.getAllResponseHeaders()
  10933. )
  10934. );
  10935. return;
  10936. }
  10937. const response = xhr.response;
  10938. const browserResponseType = xhr.responseType;
  10939. if (method === "HEAD" || method === "OPTIONS") {
  10940. const responseHeaderString = xhr.getAllResponseHeaders();
  10941. const splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
  10942. const responseHeaders = {};
  10943. splitHeaders.forEach(function (line) {
  10944. const parts = line.split(": ");
  10945. const header = parts.shift();
  10946. responseHeaders[header] = parts.join(": ");
  10947. });
  10948. deferred.resolve(responseHeaders);
  10949. return;
  10950. }
  10951. //All modern browsers will go into either the first or second if block or last else block.
  10952. //Other code paths support older browsers that either do not support the supplied responseType
  10953. //or do not support the xhr.response property.
  10954. if (xhr.status === 204) {
  10955. // accept no content
  10956. deferred.resolve();
  10957. } else if (
  10958. defaultValue.defined(response) &&
  10959. (!defaultValue.defined(responseType) || browserResponseType === responseType)
  10960. ) {
  10961. deferred.resolve(response);
  10962. } else if (responseType === "json" && typeof response === "string") {
  10963. try {
  10964. deferred.resolve(JSON.parse(response));
  10965. } catch (e) {
  10966. deferred.reject(e);
  10967. }
  10968. } else if (
  10969. (browserResponseType === "" || browserResponseType === "document") &&
  10970. defaultValue.defined(xhr.responseXML) &&
  10971. xhr.responseXML.hasChildNodes()
  10972. ) {
  10973. deferred.resolve(xhr.responseXML);
  10974. } else if (
  10975. (browserResponseType === "" || browserResponseType === "text") &&
  10976. defaultValue.defined(xhr.responseText)
  10977. ) {
  10978. deferred.resolve(xhr.responseText);
  10979. } else {
  10980. deferred.reject(
  10981. new RuntimeError.RuntimeError("Invalid XMLHttpRequest response type.")
  10982. );
  10983. }
  10984. };
  10985. xhr.onerror = function (e) {
  10986. deferred.reject(new RequestErrorEvent());
  10987. };
  10988. xhr.send(data);
  10989. return xhr;
  10990. };
  10991. Resource._Implementations.loadAndExecuteScript = function (
  10992. url,
  10993. functionName,
  10994. deferred
  10995. ) {
  10996. return loadAndExecuteScript(url).catch(function (e) {
  10997. deferred.reject(e);
  10998. });
  10999. };
  11000. /**
  11001. * The default implementations
  11002. *
  11003. * @private
  11004. */
  11005. Resource._DefaultImplementations = {};
  11006. Resource._DefaultImplementations.createImage =
  11007. Resource._Implementations.createImage;
  11008. Resource._DefaultImplementations.loadWithXhr =
  11009. Resource._Implementations.loadWithXhr;
  11010. Resource._DefaultImplementations.loadAndExecuteScript =
  11011. Resource._Implementations.loadAndExecuteScript;
  11012. /**
  11013. * A resource instance initialized to the current browser location
  11014. *
  11015. * @type {Resource}
  11016. * @constant
  11017. */
  11018. Resource.DEFAULT = Object.freeze(
  11019. new Resource({
  11020. url:
  11021. typeof document === "undefined"
  11022. ? ""
  11023. : document.location.href.split("?")[0],
  11024. })
  11025. );
  11026. /**
  11027. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  11028. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  11029. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  11030. * Reference Frame (ITRF).
  11031. *
  11032. * @alias EarthOrientationParameters
  11033. * @constructor
  11034. *
  11035. * @param {Object} [options] Object with the following properties:
  11036. * @param {Resource|String} [options.url] The URL from which to obtain EOP data. If neither this
  11037. * parameter nor options.data is specified, all EOP values are assumed
  11038. * to be 0.0. If options.data is specified, this parameter is
  11039. * ignored.
  11040. * @param {Object} [options.data] The actual EOP data. If neither this
  11041. * parameter nor options.data is specified, all EOP values are assumed
  11042. * to be 0.0.
  11043. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  11044. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  11045. * should be added to {@link JulianDate.leapSeconds}. False if
  11046. * new leap seconds should be handled correctly in the context
  11047. * of the EOP data but otherwise ignored.
  11048. *
  11049. * @example
  11050. * // An example EOP data file, EOP.json:
  11051. * {
  11052. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  11053. * "samples" : [
  11054. * "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,
  11055. * "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,
  11056. * "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
  11057. * ]
  11058. * }
  11059. *
  11060. * @example
  11061. * // Loading the EOP data
  11062. * const eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  11063. * Cesium.Transforms.earthOrientationParameters = eop;
  11064. *
  11065. * @private
  11066. */
  11067. function EarthOrientationParameters(options) {
  11068. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  11069. this._dates = undefined;
  11070. this._samples = undefined;
  11071. this._dateColumn = -1;
  11072. this._xPoleWanderRadiansColumn = -1;
  11073. this._yPoleWanderRadiansColumn = -1;
  11074. this._ut1MinusUtcSecondsColumn = -1;
  11075. this._xCelestialPoleOffsetRadiansColumn = -1;
  11076. this._yCelestialPoleOffsetRadiansColumn = -1;
  11077. this._taiMinusUtcSecondsColumn = -1;
  11078. this._columnCount = 0;
  11079. this._lastIndex = -1;
  11080. this._downloadPromise = undefined;
  11081. this._dataError = undefined;
  11082. this._addNewLeapSeconds = defaultValue.defaultValue(options.addNewLeapSeconds, true);
  11083. if (defaultValue.defined(options.data)) {
  11084. // Use supplied EOP data.
  11085. onDataReady(this, options.data);
  11086. } else if (defaultValue.defined(options.url)) {
  11087. const resource = Resource.createIfNeeded(options.url);
  11088. // Download EOP data.
  11089. const that = this;
  11090. this._downloadPromise = resource
  11091. .fetchJson()
  11092. .then(function (eopData) {
  11093. onDataReady(that, eopData);
  11094. })
  11095. .catch(function () {
  11096. that._dataError = `An error occurred while retrieving the EOP data from the URL ${resource.url}.`;
  11097. });
  11098. } else {
  11099. // Use all zeros for EOP data.
  11100. onDataReady(this, {
  11101. columnNames: [
  11102. "dateIso8601",
  11103. "modifiedJulianDateUtc",
  11104. "xPoleWanderRadians",
  11105. "yPoleWanderRadians",
  11106. "ut1MinusUtcSeconds",
  11107. "lengthOfDayCorrectionSeconds",
  11108. "xCelestialPoleOffsetRadians",
  11109. "yCelestialPoleOffsetRadians",
  11110. "taiMinusUtcSeconds",
  11111. ],
  11112. samples: [],
  11113. });
  11114. }
  11115. }
  11116. /**
  11117. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  11118. */
  11119. EarthOrientationParameters.NONE = Object.freeze({
  11120. getPromiseToLoad: function () {
  11121. return Promise.resolve();
  11122. },
  11123. compute: function (date, result) {
  11124. if (!defaultValue.defined(result)) {
  11125. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  11126. } else {
  11127. result.xPoleWander = 0.0;
  11128. result.yPoleWander = 0.0;
  11129. result.xPoleOffset = 0.0;
  11130. result.yPoleOffset = 0.0;
  11131. result.ut1MinusUtc = 0.0;
  11132. }
  11133. return result;
  11134. },
  11135. });
  11136. /**
  11137. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  11138. * ready to use.
  11139. *
  11140. * @returns {Promise<void>} The promise.
  11141. */
  11142. EarthOrientationParameters.prototype.getPromiseToLoad = function () {
  11143. return Promise.resolve(this._downloadPromise);
  11144. };
  11145. /**
  11146. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  11147. * If the EOP data has not yet been download, this method returns undefined.
  11148. *
  11149. * @param {JulianDate} date The date for each to evaluate the EOP.
  11150. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  11151. * If this parameter is undefined, a new instance is created and returned.
  11152. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  11153. * undefined if the data necessary to evaluate EOP at the date has not yet been
  11154. * downloaded.
  11155. *
  11156. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  11157. *
  11158. * @see EarthOrientationParameters#getPromiseToLoad
  11159. */
  11160. EarthOrientationParameters.prototype.compute = function (date, result) {
  11161. // We cannot compute until the samples are available.
  11162. if (!defaultValue.defined(this._samples)) {
  11163. if (defaultValue.defined(this._dataError)) {
  11164. throw new RuntimeError.RuntimeError(this._dataError);
  11165. }
  11166. return undefined;
  11167. }
  11168. if (!defaultValue.defined(result)) {
  11169. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  11170. }
  11171. if (this._samples.length === 0) {
  11172. result.xPoleWander = 0.0;
  11173. result.yPoleWander = 0.0;
  11174. result.xPoleOffset = 0.0;
  11175. result.yPoleOffset = 0.0;
  11176. result.ut1MinusUtc = 0.0;
  11177. return result;
  11178. }
  11179. const dates = this._dates;
  11180. const lastIndex = this._lastIndex;
  11181. let before = 0;
  11182. let after = 0;
  11183. if (defaultValue.defined(lastIndex)) {
  11184. const previousIndexDate = dates[lastIndex];
  11185. const nextIndexDate = dates[lastIndex + 1];
  11186. const isAfterPrevious = JulianDate.lessThanOrEquals(
  11187. previousIndexDate,
  11188. date
  11189. );
  11190. const isAfterLastSample = !defaultValue.defined(nextIndexDate);
  11191. const isBeforeNext =
  11192. isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  11193. if (isAfterPrevious && isBeforeNext) {
  11194. before = lastIndex;
  11195. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  11196. ++before;
  11197. }
  11198. after = before + 1;
  11199. interpolate(this, dates, this._samples, date, before, after, result);
  11200. return result;
  11201. }
  11202. }
  11203. let index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  11204. if (index >= 0) {
  11205. // If the next entry is the same date, use the later entry. This way, if two entries
  11206. // describe the same moment, one before a leap second and the other after, then we will use
  11207. // the post-leap second data.
  11208. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  11209. ++index;
  11210. }
  11211. before = index;
  11212. after = index;
  11213. } else {
  11214. after = ~index;
  11215. before = after - 1;
  11216. // Use the first entry if the date requested is before the beginning of the data.
  11217. if (before < 0) {
  11218. before = 0;
  11219. }
  11220. }
  11221. this._lastIndex = before;
  11222. interpolate(this, dates, this._samples, date, before, after, result);
  11223. return result;
  11224. };
  11225. function compareLeapSecondDates(leapSecond, dateToFind) {
  11226. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  11227. }
  11228. function onDataReady(eop, eopData) {
  11229. if (!defaultValue.defined(eopData.columnNames)) {
  11230. eop._dataError =
  11231. "Error in loaded EOP data: The columnNames property is required.";
  11232. return;
  11233. }
  11234. if (!defaultValue.defined(eopData.samples)) {
  11235. eop._dataError =
  11236. "Error in loaded EOP data: The samples property is required.";
  11237. return;
  11238. }
  11239. const dateColumn = eopData.columnNames.indexOf("modifiedJulianDateUtc");
  11240. const xPoleWanderRadiansColumn = eopData.columnNames.indexOf(
  11241. "xPoleWanderRadians"
  11242. );
  11243. const yPoleWanderRadiansColumn = eopData.columnNames.indexOf(
  11244. "yPoleWanderRadians"
  11245. );
  11246. const ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf(
  11247. "ut1MinusUtcSeconds"
  11248. );
  11249. const xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
  11250. "xCelestialPoleOffsetRadians"
  11251. );
  11252. const yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
  11253. "yCelestialPoleOffsetRadians"
  11254. );
  11255. const taiMinusUtcSecondsColumn = eopData.columnNames.indexOf(
  11256. "taiMinusUtcSeconds"
  11257. );
  11258. if (
  11259. dateColumn < 0 ||
  11260. xPoleWanderRadiansColumn < 0 ||
  11261. yPoleWanderRadiansColumn < 0 ||
  11262. ut1MinusUtcSecondsColumn < 0 ||
  11263. xCelestialPoleOffsetRadiansColumn < 0 ||
  11264. yCelestialPoleOffsetRadiansColumn < 0 ||
  11265. taiMinusUtcSecondsColumn < 0
  11266. ) {
  11267. eop._dataError =
  11268. "Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns";
  11269. return;
  11270. }
  11271. const samples = (eop._samples = eopData.samples);
  11272. const dates = (eop._dates = []);
  11273. eop._dateColumn = dateColumn;
  11274. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  11275. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  11276. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  11277. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  11278. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  11279. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  11280. eop._columnCount = eopData.columnNames.length;
  11281. eop._lastIndex = undefined;
  11282. let lastTaiMinusUtc;
  11283. const addNewLeapSeconds = eop._addNewLeapSeconds;
  11284. // Convert the ISO8601 dates to JulianDates.
  11285. for (let i = 0, len = samples.length; i < len; i += eop._columnCount) {
  11286. const mjd = samples[i + dateColumn];
  11287. const taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  11288. const day = mjd + TimeConstants$1.MODIFIED_JULIAN_DATE_DIFFERENCE;
  11289. const date = new JulianDate(day, taiMinusUtc, TimeStandard$1.TAI);
  11290. dates.push(date);
  11291. if (addNewLeapSeconds) {
  11292. if (taiMinusUtc !== lastTaiMinusUtc && defaultValue.defined(lastTaiMinusUtc)) {
  11293. // We crossed a leap second boundary, so add the leap second
  11294. // if it does not already exist.
  11295. const leapSeconds = JulianDate.leapSeconds;
  11296. const leapSecondIndex = binarySearch(
  11297. leapSeconds,
  11298. date,
  11299. compareLeapSecondDates
  11300. );
  11301. if (leapSecondIndex < 0) {
  11302. const leapSecond = new LeapSecond(date, taiMinusUtc);
  11303. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  11304. }
  11305. }
  11306. lastTaiMinusUtc = taiMinusUtc;
  11307. }
  11308. }
  11309. }
  11310. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  11311. const start = index * columnCount;
  11312. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  11313. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  11314. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  11315. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  11316. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  11317. }
  11318. function linearInterp(dx, y1, y2) {
  11319. return y1 + dx * (y2 - y1);
  11320. }
  11321. function interpolate(eop, dates, samples, date, before, after, result) {
  11322. const columnCount = eop._columnCount;
  11323. // First check the bounds on the EOP data
  11324. // If we are after the bounds of the data, return zeros.
  11325. // The 'before' index should never be less than zero.
  11326. if (after > dates.length - 1) {
  11327. result.xPoleWander = 0;
  11328. result.yPoleWander = 0;
  11329. result.xPoleOffset = 0;
  11330. result.yPoleOffset = 0;
  11331. result.ut1MinusUtc = 0;
  11332. return result;
  11333. }
  11334. const beforeDate = dates[before];
  11335. const afterDate = dates[after];
  11336. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  11337. fillResultFromIndex(eop, samples, before, columnCount, result);
  11338. return result;
  11339. } else if (date.equals(afterDate)) {
  11340. fillResultFromIndex(eop, samples, after, columnCount, result);
  11341. return result;
  11342. }
  11343. const factor =
  11344. JulianDate.secondsDifference(date, beforeDate) /
  11345. JulianDate.secondsDifference(afterDate, beforeDate);
  11346. const startBefore = before * columnCount;
  11347. const startAfter = after * columnCount;
  11348. // Handle UT1 leap second edge case
  11349. let beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  11350. let afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  11351. const offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  11352. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  11353. // The absolute difference between the values is more than 0.5, so we may have
  11354. // crossed a leap second. Check if this is the case and, if so, adjust the
  11355. // afterValue to account for the leap second. This way, our interpolation will
  11356. // produce reasonable results.
  11357. const beforeTaiMinusUtc =
  11358. samples[startBefore + eop._taiMinusUtcSecondsColumn];
  11359. const afterTaiMinusUtc =
  11360. samples[startAfter + eop._taiMinusUtcSecondsColumn];
  11361. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  11362. if (afterDate.equals(date)) {
  11363. // If we are at the end of the leap second interval, take the second value
  11364. // Otherwise, the interpolation below will yield the wrong side of the
  11365. // discontinuity
  11366. // At the end of the leap second, we need to start accounting for the jump
  11367. beforeUt1MinusUtc = afterUt1MinusUtc;
  11368. } else {
  11369. // Otherwise, remove the leap second so that the interpolation is correct
  11370. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  11371. }
  11372. }
  11373. }
  11374. result.xPoleWander = linearInterp(
  11375. factor,
  11376. samples[startBefore + eop._xPoleWanderRadiansColumn],
  11377. samples[startAfter + eop._xPoleWanderRadiansColumn]
  11378. );
  11379. result.yPoleWander = linearInterp(
  11380. factor,
  11381. samples[startBefore + eop._yPoleWanderRadiansColumn],
  11382. samples[startAfter + eop._yPoleWanderRadiansColumn]
  11383. );
  11384. result.xPoleOffset = linearInterp(
  11385. factor,
  11386. samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn],
  11387. samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]
  11388. );
  11389. result.yPoleOffset = linearInterp(
  11390. factor,
  11391. samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn],
  11392. samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]
  11393. );
  11394. result.ut1MinusUtc = linearInterp(
  11395. factor,
  11396. beforeUt1MinusUtc,
  11397. afterUt1MinusUtc
  11398. );
  11399. return result;
  11400. }
  11401. /**
  11402. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  11403. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  11404. * the positive x axis.
  11405. * @alias HeadingPitchRoll
  11406. * @constructor
  11407. *
  11408. * @param {Number} [heading=0.0] The heading component in radians.
  11409. * @param {Number} [pitch=0.0] The pitch component in radians.
  11410. * @param {Number} [roll=0.0] The roll component in radians.
  11411. */
  11412. function HeadingPitchRoll(heading, pitch, roll) {
  11413. /**
  11414. * Gets or sets the heading.
  11415. * @type {Number}
  11416. * @default 0.0
  11417. */
  11418. this.heading = defaultValue.defaultValue(heading, 0.0);
  11419. /**
  11420. * Gets or sets the pitch.
  11421. * @type {Number}
  11422. * @default 0.0
  11423. */
  11424. this.pitch = defaultValue.defaultValue(pitch, 0.0);
  11425. /**
  11426. * Gets or sets the roll.
  11427. * @type {Number}
  11428. * @default 0.0
  11429. */
  11430. this.roll = defaultValue.defaultValue(roll, 0.0);
  11431. }
  11432. /**
  11433. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  11434. *
  11435. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  11436. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  11437. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  11438. */
  11439. HeadingPitchRoll.fromQuaternion = function (quaternion, result) {
  11440. //>>includeStart('debug', pragmas.debug);
  11441. if (!defaultValue.defined(quaternion)) {
  11442. throw new RuntimeError.DeveloperError("quaternion is required");
  11443. }
  11444. //>>includeEnd('debug');
  11445. if (!defaultValue.defined(result)) {
  11446. result = new HeadingPitchRoll();
  11447. }
  11448. const test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  11449. const denominatorRoll =
  11450. 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  11451. const numeratorRoll =
  11452. 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  11453. const denominatorHeading =
  11454. 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  11455. const numeratorHeading =
  11456. 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  11457. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  11458. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  11459. result.pitch = -ComponentDatatype.CesiumMath.asinClamped(test);
  11460. return result;
  11461. };
  11462. /**
  11463. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  11464. *
  11465. * @param {Number} heading the heading in degrees
  11466. * @param {Number} pitch the pitch in degrees
  11467. * @param {Number} roll the heading in degrees
  11468. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  11469. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  11470. */
  11471. HeadingPitchRoll.fromDegrees = function (heading, pitch, roll, result) {
  11472. //>>includeStart('debug', pragmas.debug);
  11473. if (!defaultValue.defined(heading)) {
  11474. throw new RuntimeError.DeveloperError("heading is required");
  11475. }
  11476. if (!defaultValue.defined(pitch)) {
  11477. throw new RuntimeError.DeveloperError("pitch is required");
  11478. }
  11479. if (!defaultValue.defined(roll)) {
  11480. throw new RuntimeError.DeveloperError("roll is required");
  11481. }
  11482. //>>includeEnd('debug');
  11483. if (!defaultValue.defined(result)) {
  11484. result = new HeadingPitchRoll();
  11485. }
  11486. result.heading = heading * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE;
  11487. result.pitch = pitch * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE;
  11488. result.roll = roll * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE;
  11489. return result;
  11490. };
  11491. /**
  11492. * Duplicates a HeadingPitchRoll instance.
  11493. *
  11494. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  11495. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  11496. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  11497. */
  11498. HeadingPitchRoll.clone = function (headingPitchRoll, result) {
  11499. if (!defaultValue.defined(headingPitchRoll)) {
  11500. return undefined;
  11501. }
  11502. if (!defaultValue.defined(result)) {
  11503. return new HeadingPitchRoll(
  11504. headingPitchRoll.heading,
  11505. headingPitchRoll.pitch,
  11506. headingPitchRoll.roll
  11507. );
  11508. }
  11509. result.heading = headingPitchRoll.heading;
  11510. result.pitch = headingPitchRoll.pitch;
  11511. result.roll = headingPitchRoll.roll;
  11512. return result;
  11513. };
  11514. /**
  11515. * Compares the provided HeadingPitchRolls componentwise and returns
  11516. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11517. *
  11518. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  11519. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  11520. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  11521. */
  11522. HeadingPitchRoll.equals = function (left, right) {
  11523. return (
  11524. left === right ||
  11525. (defaultValue.defined(left) &&
  11526. defaultValue.defined(right) &&
  11527. left.heading === right.heading &&
  11528. left.pitch === right.pitch &&
  11529. left.roll === right.roll)
  11530. );
  11531. };
  11532. /**
  11533. * Compares the provided HeadingPitchRolls componentwise and returns
  11534. * <code>true</code> if they pass an absolute or relative tolerance test,
  11535. * <code>false</code> otherwise.
  11536. *
  11537. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  11538. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  11539. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  11540. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  11541. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  11542. */
  11543. HeadingPitchRoll.equalsEpsilon = function (
  11544. left,
  11545. right,
  11546. relativeEpsilon,
  11547. absoluteEpsilon
  11548. ) {
  11549. return (
  11550. left === right ||
  11551. (defaultValue.defined(left) &&
  11552. defaultValue.defined(right) &&
  11553. ComponentDatatype.CesiumMath.equalsEpsilon(
  11554. left.heading,
  11555. right.heading,
  11556. relativeEpsilon,
  11557. absoluteEpsilon
  11558. ) &&
  11559. ComponentDatatype.CesiumMath.equalsEpsilon(
  11560. left.pitch,
  11561. right.pitch,
  11562. relativeEpsilon,
  11563. absoluteEpsilon
  11564. ) &&
  11565. ComponentDatatype.CesiumMath.equalsEpsilon(
  11566. left.roll,
  11567. right.roll,
  11568. relativeEpsilon,
  11569. absoluteEpsilon
  11570. ))
  11571. );
  11572. };
  11573. /**
  11574. * Duplicates this HeadingPitchRoll instance.
  11575. *
  11576. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  11577. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  11578. */
  11579. HeadingPitchRoll.prototype.clone = function (result) {
  11580. return HeadingPitchRoll.clone(this, result);
  11581. };
  11582. /**
  11583. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  11584. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11585. *
  11586. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  11587. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  11588. */
  11589. HeadingPitchRoll.prototype.equals = function (right) {
  11590. return HeadingPitchRoll.equals(this, right);
  11591. };
  11592. /**
  11593. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  11594. * <code>true</code> if they pass an absolute or relative tolerance test,
  11595. * <code>false</code> otherwise.
  11596. *
  11597. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  11598. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  11599. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  11600. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  11601. */
  11602. HeadingPitchRoll.prototype.equalsEpsilon = function (
  11603. right,
  11604. relativeEpsilon,
  11605. absoluteEpsilon
  11606. ) {
  11607. return HeadingPitchRoll.equalsEpsilon(
  11608. this,
  11609. right,
  11610. relativeEpsilon,
  11611. absoluteEpsilon
  11612. );
  11613. };
  11614. /**
  11615. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  11616. *
  11617. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  11618. */
  11619. HeadingPitchRoll.prototype.toString = function () {
  11620. return `(${this.heading}, ${this.pitch}, ${this.roll})`;
  11621. };
  11622. /*global CESIUM_BASE_URL,define,require*/
  11623. const cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js(?:\?|\#|$)/;
  11624. function getBaseUrlFromCesiumScript() {
  11625. const scripts = document.getElementsByTagName("script");
  11626. for (let i = 0, len = scripts.length; i < len; ++i) {
  11627. const src = scripts[i].getAttribute("src");
  11628. const result = cesiumScriptRegex.exec(src);
  11629. if (result !== null) {
  11630. return result[1];
  11631. }
  11632. }
  11633. return undefined;
  11634. }
  11635. let a;
  11636. function tryMakeAbsolute(url) {
  11637. if (typeof document === "undefined") {
  11638. //Node.js and Web Workers. In both cases, the URL will already be absolute.
  11639. return url;
  11640. }
  11641. if (!defaultValue.defined(a)) {
  11642. a = document.createElement("a");
  11643. }
  11644. a.href = url;
  11645. // IE only absolutizes href on get, not set
  11646. // eslint-disable-next-line no-self-assign
  11647. a.href = a.href;
  11648. return a.href;
  11649. }
  11650. let baseResource;
  11651. function getCesiumBaseUrl() {
  11652. if (defaultValue.defined(baseResource)) {
  11653. return baseResource;
  11654. }
  11655. let baseUrlString;
  11656. if (typeof CESIUM_BASE_URL !== "undefined") {
  11657. baseUrlString = CESIUM_BASE_URL;
  11658. } else if (
  11659. typeof define === "object" &&
  11660. defaultValue.defined(define.amd) &&
  11661. !define.amd.toUrlUndefined &&
  11662. defaultValue.defined(require.toUrl)
  11663. ) {
  11664. baseUrlString = getAbsoluteUri(
  11665. "..",
  11666. buildModuleUrl("Core/buildModuleUrl.js")
  11667. );
  11668. } else {
  11669. baseUrlString = getBaseUrlFromCesiumScript();
  11670. }
  11671. //>>includeStart('debug', pragmas.debug);
  11672. if (!defaultValue.defined(baseUrlString)) {
  11673. throw new RuntimeError.DeveloperError(
  11674. "Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL."
  11675. );
  11676. }
  11677. //>>includeEnd('debug');
  11678. baseResource = new Resource({
  11679. url: tryMakeAbsolute(baseUrlString),
  11680. });
  11681. baseResource.appendForwardSlash();
  11682. return baseResource;
  11683. }
  11684. function buildModuleUrlFromRequireToUrl(moduleID) {
  11685. //moduleID will be non-relative, so require it relative to this module, in Core.
  11686. return tryMakeAbsolute(require.toUrl(`../${moduleID}`));
  11687. }
  11688. function buildModuleUrlFromBaseUrl(moduleID) {
  11689. const resource = getCesiumBaseUrl().getDerivedResource({
  11690. url: moduleID,
  11691. });
  11692. return resource.url;
  11693. }
  11694. let implementation;
  11695. /**
  11696. * Given a relative URL under the Cesium base URL, returns an absolute URL.
  11697. * @function
  11698. *
  11699. * @param {String} relativeUrl The relative path.
  11700. * @returns {String} The absolutely URL representation of the provided path.
  11701. *
  11702. * @example
  11703. * const viewer = new Cesium.Viewer("cesiumContainer", {
  11704. * imageryProvider: new Cesium.TileMapServiceImageryProvider({
  11705. * url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
  11706. * }),
  11707. * baseLayerPicker: false,
  11708. * });
  11709. */
  11710. function buildModuleUrl(relativeUrl) {
  11711. if (!defaultValue.defined(implementation)) {
  11712. //select implementation
  11713. if (
  11714. typeof define === "object" &&
  11715. defaultValue.defined(define.amd) &&
  11716. !define.amd.toUrlUndefined &&
  11717. defaultValue.defined(require.toUrl)
  11718. ) {
  11719. implementation = buildModuleUrlFromRequireToUrl;
  11720. } else {
  11721. implementation = buildModuleUrlFromBaseUrl;
  11722. }
  11723. }
  11724. const url = implementation(relativeUrl);
  11725. return url;
  11726. }
  11727. // exposed for testing
  11728. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  11729. buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
  11730. buildModuleUrl._clearBaseResource = function () {
  11731. baseResource = undefined;
  11732. };
  11733. /**
  11734. * Sets the base URL for resolving modules.
  11735. * @param {String} value The new base URL.
  11736. */
  11737. buildModuleUrl.setBaseUrl = function (value) {
  11738. baseResource = Resource.DEFAULT.getDerivedResource({
  11739. url: value,
  11740. });
  11741. };
  11742. /**
  11743. * Gets the base URL for resolving modules.
  11744. *
  11745. * @function
  11746. * @returns {String} The configured base URL
  11747. */
  11748. buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
  11749. /**
  11750. * An IAU 2006 XYS value sampled at a particular time.
  11751. *
  11752. * @alias Iau2006XysSample
  11753. * @constructor
  11754. *
  11755. * @param {Number} x The X value.
  11756. * @param {Number} y The Y value.
  11757. * @param {Number} s The S value.
  11758. *
  11759. * @private
  11760. */
  11761. function Iau2006XysSample(x, y, s) {
  11762. /**
  11763. * The X value.
  11764. * @type {Number}
  11765. */
  11766. this.x = x;
  11767. /**
  11768. * The Y value.
  11769. * @type {Number}
  11770. */
  11771. this.y = y;
  11772. /**
  11773. * The S value.
  11774. * @type {Number}
  11775. */
  11776. this.s = s;
  11777. }
  11778. /**
  11779. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  11780. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  11781. *
  11782. * @alias Iau2006XysData
  11783. * @constructor
  11784. *
  11785. * @param {Object} [options] Object with the following properties:
  11786. * @param {Resource|String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  11787. * `{0}` will be replaced with the file index.
  11788. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  11789. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  11790. * first XYS sample.
  11791. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  11792. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  11793. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  11794. *
  11795. * @private
  11796. */
  11797. function Iau2006XysData(options) {
  11798. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  11799. this._xysFileUrlTemplate = Resource.createIfNeeded(
  11800. options.xysFileUrlTemplate
  11801. );
  11802. this._interpolationOrder = defaultValue.defaultValue(options.interpolationOrder, 9);
  11803. this._sampleZeroJulianEphemerisDate = defaultValue.defaultValue(
  11804. options.sampleZeroJulianEphemerisDate,
  11805. 2442396.5
  11806. );
  11807. this._sampleZeroDateTT = new JulianDate(
  11808. this._sampleZeroJulianEphemerisDate,
  11809. 0.0,
  11810. TimeStandard$1.TAI
  11811. );
  11812. this._stepSizeDays = defaultValue.defaultValue(options.stepSizeDays, 1.0);
  11813. this._samplesPerXysFile = defaultValue.defaultValue(options.samplesPerXysFile, 1000);
  11814. this._totalSamples = defaultValue.defaultValue(options.totalSamples, 27426);
  11815. this._samples = new Array(this._totalSamples * 3);
  11816. this._chunkDownloadsInProgress = [];
  11817. const order = this._interpolationOrder;
  11818. // Compute denominators and X values for interpolation.
  11819. const denom = (this._denominators = new Array(order + 1));
  11820. const xTable = (this._xTable = new Array(order + 1));
  11821. const stepN = Math.pow(this._stepSizeDays, order);
  11822. for (let i = 0; i <= order; ++i) {
  11823. denom[i] = stepN;
  11824. xTable[i] = i * this._stepSizeDays;
  11825. for (let j = 0; j <= order; ++j) {
  11826. if (j !== i) {
  11827. denom[i] *= i - j;
  11828. }
  11829. }
  11830. denom[i] = 1.0 / denom[i];
  11831. }
  11832. // Allocate scratch arrays for interpolation.
  11833. this._work = new Array(order + 1);
  11834. this._coef = new Array(order + 1);
  11835. }
  11836. const julianDateScratch = new JulianDate(0, 0.0, TimeStandard$1.TAI);
  11837. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  11838. const dateTT = julianDateScratch;
  11839. dateTT.dayNumber = dayTT;
  11840. dateTT.secondsOfDay = secondTT;
  11841. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  11842. }
  11843. /**
  11844. * Preloads XYS data for a specified date range.
  11845. *
  11846. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  11847. * the Terrestrial Time (TT) time standard.
  11848. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  11849. * the Terrestrial Time (TT) time standard.
  11850. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  11851. * the Terrestrial Time (TT) time standard.
  11852. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  11853. * the Terrestrial Time (TT) time standard.
  11854. * @returns {Promise<void>} A promise that, when resolved, indicates that the requested interval has been
  11855. * preloaded.
  11856. */
  11857. Iau2006XysData.prototype.preload = function (
  11858. startDayTT,
  11859. startSecondTT,
  11860. stopDayTT,
  11861. stopSecondTT
  11862. ) {
  11863. const startDaysSinceEpoch = getDaysSinceEpoch(
  11864. this,
  11865. startDayTT,
  11866. startSecondTT
  11867. );
  11868. const stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  11869. let startIndex =
  11870. (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
  11871. 0;
  11872. if (startIndex < 0) {
  11873. startIndex = 0;
  11874. }
  11875. let stopIndex =
  11876. (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
  11877. (0 + this._interpolationOrder);
  11878. if (stopIndex >= this._totalSamples) {
  11879. stopIndex = this._totalSamples - 1;
  11880. }
  11881. const startChunk = (startIndex / this._samplesPerXysFile) | 0;
  11882. const stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  11883. const promises = [];
  11884. for (let i = startChunk; i <= stopChunk; ++i) {
  11885. promises.push(requestXysChunk(this, i));
  11886. }
  11887. return Promise.all(promises);
  11888. };
  11889. /**
  11890. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  11891. * this method will return undefined.
  11892. *
  11893. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  11894. * the Terrestrial Time (TT) time standard.
  11895. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  11896. * the Terrestrial Time (TT) time standard.
  11897. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  11898. * is undefined, a new instance is allocated and returned.
  11899. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  11900. * computation has not yet been downloaded.
  11901. *
  11902. * @see Iau2006XysData#preload
  11903. */
  11904. Iau2006XysData.prototype.computeXysRadians = function (
  11905. dayTT,
  11906. secondTT,
  11907. result
  11908. ) {
  11909. const daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  11910. if (daysSinceEpoch < 0.0) {
  11911. // Can't evaluate prior to the epoch of the data.
  11912. return undefined;
  11913. }
  11914. const centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  11915. if (centerIndex >= this._totalSamples) {
  11916. // Can't evaluate after the last sample in the data.
  11917. return undefined;
  11918. }
  11919. const degree = this._interpolationOrder;
  11920. let firstIndex = centerIndex - ((degree / 2) | 0);
  11921. if (firstIndex < 0) {
  11922. firstIndex = 0;
  11923. }
  11924. let lastIndex = firstIndex + degree;
  11925. if (lastIndex >= this._totalSamples) {
  11926. lastIndex = this._totalSamples - 1;
  11927. firstIndex = lastIndex - degree;
  11928. if (firstIndex < 0) {
  11929. firstIndex = 0;
  11930. }
  11931. }
  11932. // Are all the samples we need present?
  11933. // We can assume so if the first and last are present
  11934. let isDataMissing = false;
  11935. const samples = this._samples;
  11936. if (!defaultValue.defined(samples[firstIndex * 3])) {
  11937. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  11938. isDataMissing = true;
  11939. }
  11940. if (!defaultValue.defined(samples[lastIndex * 3])) {
  11941. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  11942. isDataMissing = true;
  11943. }
  11944. if (isDataMissing) {
  11945. return undefined;
  11946. }
  11947. if (!defaultValue.defined(result)) {
  11948. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  11949. } else {
  11950. result.x = 0.0;
  11951. result.y = 0.0;
  11952. result.s = 0.0;
  11953. }
  11954. const x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  11955. const work = this._work;
  11956. const denom = this._denominators;
  11957. const coef = this._coef;
  11958. const xTable = this._xTable;
  11959. let i, j;
  11960. for (i = 0; i <= degree; ++i) {
  11961. work[i] = x - xTable[i];
  11962. }
  11963. for (i = 0; i <= degree; ++i) {
  11964. coef[i] = 1.0;
  11965. for (j = 0; j <= degree; ++j) {
  11966. if (j !== i) {
  11967. coef[i] *= work[j];
  11968. }
  11969. }
  11970. coef[i] *= denom[i];
  11971. let sampleIndex = (firstIndex + i) * 3;
  11972. result.x += coef[i] * samples[sampleIndex++];
  11973. result.y += coef[i] * samples[sampleIndex++];
  11974. result.s += coef[i] * samples[sampleIndex];
  11975. }
  11976. return result;
  11977. };
  11978. function requestXysChunk(xysData, chunkIndex) {
  11979. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  11980. // Chunk has already been requested.
  11981. return xysData._chunkDownloadsInProgress[chunkIndex];
  11982. }
  11983. const deferred = defer();
  11984. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  11985. let chunkUrl;
  11986. const xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  11987. if (defaultValue.defined(xysFileUrlTemplate)) {
  11988. chunkUrl = xysFileUrlTemplate.getDerivedResource({
  11989. templateValues: {
  11990. 0: chunkIndex,
  11991. },
  11992. });
  11993. } else {
  11994. chunkUrl = new Resource({
  11995. url: buildModuleUrl(`Assets/IAU2006_XYS/IAU2006_XYS_${chunkIndex}.json`),
  11996. });
  11997. }
  11998. chunkUrl.fetchJson().then(function (chunk) {
  11999. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  12000. const samples = xysData._samples;
  12001. const newSamples = chunk.samples;
  12002. const startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  12003. for (let i = 0, len = newSamples.length; i < len; ++i) {
  12004. samples[startIndex + i] = newSamples[i];
  12005. }
  12006. deferred.resolve();
  12007. });
  12008. return deferred.promise;
  12009. }
  12010. /**
  12011. * Contains functions for transforming positions to various reference frames.
  12012. *
  12013. * @namespace Transforms
  12014. */
  12015. const Transforms = {};
  12016. const vectorProductLocalFrame = {
  12017. up: {
  12018. south: "east",
  12019. north: "west",
  12020. west: "south",
  12021. east: "north",
  12022. },
  12023. down: {
  12024. south: "west",
  12025. north: "east",
  12026. west: "north",
  12027. east: "south",
  12028. },
  12029. south: {
  12030. up: "west",
  12031. down: "east",
  12032. west: "down",
  12033. east: "up",
  12034. },
  12035. north: {
  12036. up: "east",
  12037. down: "west",
  12038. west: "up",
  12039. east: "down",
  12040. },
  12041. west: {
  12042. up: "north",
  12043. down: "south",
  12044. north: "down",
  12045. south: "up",
  12046. },
  12047. east: {
  12048. up: "south",
  12049. down: "north",
  12050. north: "up",
  12051. south: "down",
  12052. },
  12053. };
  12054. const degeneratePositionLocalFrame = {
  12055. north: [-1, 0, 0],
  12056. east: [0, 1, 0],
  12057. up: [0, 0, 1],
  12058. south: [1, 0, 0],
  12059. west: [0, -1, 0],
  12060. down: [0, 0, -1],
  12061. };
  12062. const localFrameToFixedFrameCache = {};
  12063. const scratchCalculateCartesian = {
  12064. east: new Matrix2.Cartesian3(),
  12065. north: new Matrix2.Cartesian3(),
  12066. up: new Matrix2.Cartesian3(),
  12067. west: new Matrix2.Cartesian3(),
  12068. south: new Matrix2.Cartesian3(),
  12069. down: new Matrix2.Cartesian3(),
  12070. };
  12071. let scratchFirstCartesian = new Matrix2.Cartesian3();
  12072. let scratchSecondCartesian = new Matrix2.Cartesian3();
  12073. let scratchThirdCartesian = new Matrix2.Cartesian3();
  12074. /**
  12075. * Generates a function that computes a 4x4 transformation matrix from a reference frame
  12076. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12077. * @param {String} firstAxis name of the first axis of the local reference frame. Must be
  12078. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  12079. * @param {String} secondAxis name of the second axis of the local reference frame. Must be
  12080. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  12081. * @return {Transforms.LocalFrameToFixedFrame} The function that will computes a
  12082. * 4x4 transformation matrix from a reference frame, with first axis and second axis compliant with the parameters,
  12083. */
  12084. Transforms.localFrameToFixedFrameGenerator = function (firstAxis, secondAxis) {
  12085. if (
  12086. !vectorProductLocalFrame.hasOwnProperty(firstAxis) ||
  12087. !vectorProductLocalFrame[firstAxis].hasOwnProperty(secondAxis)
  12088. ) {
  12089. throw new RuntimeError.DeveloperError(
  12090. "firstAxis and secondAxis must be east, north, up, west, south or down."
  12091. );
  12092. }
  12093. const thirdAxis = vectorProductLocalFrame[firstAxis][secondAxis];
  12094. /**
  12095. * Computes a 4x4 transformation matrix from a reference frame
  12096. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12097. * @callback Transforms.LocalFrameToFixedFrame
  12098. * @param {Cartesian3} origin The center point of the local reference frame.
  12099. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12100. * @param {Matrix4} [result] The object onto which to store the result.
  12101. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12102. */
  12103. let resultat;
  12104. const hashAxis = firstAxis + secondAxis;
  12105. if (defaultValue.defined(localFrameToFixedFrameCache[hashAxis])) {
  12106. resultat = localFrameToFixedFrameCache[hashAxis];
  12107. } else {
  12108. resultat = function (origin, ellipsoid, result) {
  12109. //>>includeStart('debug', pragmas.debug);
  12110. if (!defaultValue.defined(origin)) {
  12111. throw new RuntimeError.DeveloperError("origin is required.");
  12112. }
  12113. //>>includeEnd('debug');
  12114. if (!defaultValue.defined(result)) {
  12115. result = new Matrix2.Matrix4();
  12116. }
  12117. if (
  12118. Matrix2.Cartesian3.equalsEpsilon(origin, Matrix2.Cartesian3.ZERO, ComponentDatatype.CesiumMath.EPSILON14)
  12119. ) {
  12120. // If x, y, and z are zero, use the degenerate local frame, which is a special case
  12121. Matrix2.Cartesian3.unpack(
  12122. degeneratePositionLocalFrame[firstAxis],
  12123. 0,
  12124. scratchFirstCartesian
  12125. );
  12126. Matrix2.Cartesian3.unpack(
  12127. degeneratePositionLocalFrame[secondAxis],
  12128. 0,
  12129. scratchSecondCartesian
  12130. );
  12131. Matrix2.Cartesian3.unpack(
  12132. degeneratePositionLocalFrame[thirdAxis],
  12133. 0,
  12134. scratchThirdCartesian
  12135. );
  12136. } else if (
  12137. ComponentDatatype.CesiumMath.equalsEpsilon(origin.x, 0.0, ComponentDatatype.CesiumMath.EPSILON14) &&
  12138. ComponentDatatype.CesiumMath.equalsEpsilon(origin.y, 0.0, ComponentDatatype.CesiumMath.EPSILON14)
  12139. ) {
  12140. // If x and y are zero, assume origin is at a pole, which is a special case.
  12141. const sign = ComponentDatatype.CesiumMath.sign(origin.z);
  12142. Matrix2.Cartesian3.unpack(
  12143. degeneratePositionLocalFrame[firstAxis],
  12144. 0,
  12145. scratchFirstCartesian
  12146. );
  12147. if (firstAxis !== "east" && firstAxis !== "west") {
  12148. Matrix2.Cartesian3.multiplyByScalar(
  12149. scratchFirstCartesian,
  12150. sign,
  12151. scratchFirstCartesian
  12152. );
  12153. }
  12154. Matrix2.Cartesian3.unpack(
  12155. degeneratePositionLocalFrame[secondAxis],
  12156. 0,
  12157. scratchSecondCartesian
  12158. );
  12159. if (secondAxis !== "east" && secondAxis !== "west") {
  12160. Matrix2.Cartesian3.multiplyByScalar(
  12161. scratchSecondCartesian,
  12162. sign,
  12163. scratchSecondCartesian
  12164. );
  12165. }
  12166. Matrix2.Cartesian3.unpack(
  12167. degeneratePositionLocalFrame[thirdAxis],
  12168. 0,
  12169. scratchThirdCartesian
  12170. );
  12171. if (thirdAxis !== "east" && thirdAxis !== "west") {
  12172. Matrix2.Cartesian3.multiplyByScalar(
  12173. scratchThirdCartesian,
  12174. sign,
  12175. scratchThirdCartesian
  12176. );
  12177. }
  12178. } else {
  12179. ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  12180. ellipsoid.geodeticSurfaceNormal(origin, scratchCalculateCartesian.up);
  12181. const up = scratchCalculateCartesian.up;
  12182. const east = scratchCalculateCartesian.east;
  12183. east.x = -origin.y;
  12184. east.y = origin.x;
  12185. east.z = 0.0;
  12186. Matrix2.Cartesian3.normalize(east, scratchCalculateCartesian.east);
  12187. Matrix2.Cartesian3.cross(up, east, scratchCalculateCartesian.north);
  12188. Matrix2.Cartesian3.multiplyByScalar(
  12189. scratchCalculateCartesian.up,
  12190. -1,
  12191. scratchCalculateCartesian.down
  12192. );
  12193. Matrix2.Cartesian3.multiplyByScalar(
  12194. scratchCalculateCartesian.east,
  12195. -1,
  12196. scratchCalculateCartesian.west
  12197. );
  12198. Matrix2.Cartesian3.multiplyByScalar(
  12199. scratchCalculateCartesian.north,
  12200. -1,
  12201. scratchCalculateCartesian.south
  12202. );
  12203. scratchFirstCartesian = scratchCalculateCartesian[firstAxis];
  12204. scratchSecondCartesian = scratchCalculateCartesian[secondAxis];
  12205. scratchThirdCartesian = scratchCalculateCartesian[thirdAxis];
  12206. }
  12207. result[0] = scratchFirstCartesian.x;
  12208. result[1] = scratchFirstCartesian.y;
  12209. result[2] = scratchFirstCartesian.z;
  12210. result[3] = 0.0;
  12211. result[4] = scratchSecondCartesian.x;
  12212. result[5] = scratchSecondCartesian.y;
  12213. result[6] = scratchSecondCartesian.z;
  12214. result[7] = 0.0;
  12215. result[8] = scratchThirdCartesian.x;
  12216. result[9] = scratchThirdCartesian.y;
  12217. result[10] = scratchThirdCartesian.z;
  12218. result[11] = 0.0;
  12219. result[12] = origin.x;
  12220. result[13] = origin.y;
  12221. result[14] = origin.z;
  12222. result[15] = 1.0;
  12223. return result;
  12224. };
  12225. localFrameToFixedFrameCache[hashAxis] = resultat;
  12226. }
  12227. return resultat;
  12228. };
  12229. /**
  12230. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  12231. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12232. * The local axes are defined as:
  12233. * <ul>
  12234. * <li>The <code>x</code> axis points in the local east direction.</li>
  12235. * <li>The <code>y</code> axis points in the local north direction.</li>
  12236. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  12237. * </ul>
  12238. *
  12239. * @function
  12240. * @param {Cartesian3} origin The center point of the local reference frame.
  12241. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12242. * @param {Matrix4} [result] The object onto which to store the result.
  12243. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12244. *
  12245. * @example
  12246. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  12247. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12248. * const transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  12249. */
  12250. Transforms.eastNorthUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12251. "east",
  12252. "north"
  12253. );
  12254. /**
  12255. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  12256. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12257. * The local axes are defined as:
  12258. * <ul>
  12259. * <li>The <code>x</code> axis points in the local north direction.</li>
  12260. * <li>The <code>y</code> axis points in the local east direction.</li>
  12261. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  12262. * </ul>
  12263. *
  12264. * @function
  12265. * @param {Cartesian3} origin The center point of the local reference frame.
  12266. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12267. * @param {Matrix4} [result] The object onto which to store the result.
  12268. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12269. *
  12270. * @example
  12271. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  12272. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12273. * const transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  12274. */
  12275. Transforms.northEastDownToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12276. "north",
  12277. "east"
  12278. );
  12279. /**
  12280. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  12281. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12282. * The local axes are defined as:
  12283. * <ul>
  12284. * <li>The <code>x</code> axis points in the local north direction.</li>
  12285. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  12286. * <li>The <code>z</code> axis points in the local east direction.</li>
  12287. * </ul>
  12288. *
  12289. * @function
  12290. * @param {Cartesian3} origin The center point of the local reference frame.
  12291. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12292. * @param {Matrix4} [result] The object onto which to store the result.
  12293. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12294. *
  12295. * @example
  12296. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  12297. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12298. * const transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  12299. */
  12300. Transforms.northUpEastToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12301. "north",
  12302. "up"
  12303. );
  12304. /**
  12305. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  12306. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  12307. * The local axes are defined as:
  12308. * <ul>
  12309. * <li>The <code>x</code> axis points in the local north direction.</li>
  12310. * <li>The <code>y</code> axis points in the local west direction.</li>
  12311. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  12312. * </ul>
  12313. *
  12314. * @function
  12315. * @param {Cartesian3} origin The center point of the local reference frame.
  12316. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12317. * @param {Matrix4} [result] The object onto which to store the result.
  12318. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12319. *
  12320. * @example
  12321. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  12322. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12323. * const transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  12324. */
  12325. Transforms.northWestUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  12326. "north",
  12327. "west"
  12328. );
  12329. const scratchHPRQuaternion = new Quaternion();
  12330. const scratchScale = new Matrix2.Cartesian3(1.0, 1.0, 1.0);
  12331. const scratchHPRMatrix4 = new Matrix2.Matrix4();
  12332. /**
  12333. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  12334. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  12335. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  12336. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  12337. *
  12338. * @param {Cartesian3} origin The center point of the local reference frame.
  12339. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  12340. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12341. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  12342. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  12343. * @param {Matrix4} [result] The object onto which to store the result.
  12344. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  12345. *
  12346. * @example
  12347. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  12348. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12349. * const heading = -Cesium.Math.PI_OVER_TWO;
  12350. * const pitch = Cesium.Math.PI_OVER_FOUR;
  12351. * const roll = 0.0;
  12352. * const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  12353. * const transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  12354. */
  12355. Transforms.headingPitchRollToFixedFrame = function (
  12356. origin,
  12357. headingPitchRoll,
  12358. ellipsoid,
  12359. fixedFrameTransform,
  12360. result
  12361. ) {
  12362. //>>includeStart('debug', pragmas.debug);
  12363. RuntimeError.Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
  12364. //>>includeEnd('debug');
  12365. fixedFrameTransform = defaultValue.defaultValue(
  12366. fixedFrameTransform,
  12367. Transforms.eastNorthUpToFixedFrame
  12368. );
  12369. const hprQuaternion = Quaternion.fromHeadingPitchRoll(
  12370. headingPitchRoll,
  12371. scratchHPRQuaternion
  12372. );
  12373. const hprMatrix = Matrix2.Matrix4.fromTranslationQuaternionRotationScale(
  12374. Matrix2.Cartesian3.ZERO,
  12375. hprQuaternion,
  12376. scratchScale,
  12377. scratchHPRMatrix4
  12378. );
  12379. result = fixedFrameTransform(origin, ellipsoid, result);
  12380. return Matrix2.Matrix4.multiply(result, hprMatrix, result);
  12381. };
  12382. const scratchENUMatrix4 = new Matrix2.Matrix4();
  12383. const scratchHPRMatrix3 = new Matrix2.Matrix3();
  12384. /**
  12385. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  12386. * centered at the provided origin. Heading is the rotation from the local north
  12387. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  12388. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  12389. *
  12390. * @param {Cartesian3} origin The center point of the local reference frame.
  12391. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  12392. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12393. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  12394. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  12395. * @param {Quaternion} [result] The object onto which to store the result.
  12396. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  12397. *
  12398. * @example
  12399. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  12400. * const center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12401. * const heading = -Cesium.Math.PI_OVER_TWO;
  12402. * const pitch = Cesium.Math.PI_OVER_FOUR;
  12403. * const roll = 0.0;
  12404. * const hpr = new HeadingPitchRoll(heading, pitch, roll);
  12405. * const quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  12406. */
  12407. Transforms.headingPitchRollQuaternion = function (
  12408. origin,
  12409. headingPitchRoll,
  12410. ellipsoid,
  12411. fixedFrameTransform,
  12412. result
  12413. ) {
  12414. //>>includeStart('debug', pragmas.debug);
  12415. RuntimeError.Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
  12416. //>>includeEnd('debug');
  12417. const transform = Transforms.headingPitchRollToFixedFrame(
  12418. origin,
  12419. headingPitchRoll,
  12420. ellipsoid,
  12421. fixedFrameTransform,
  12422. scratchENUMatrix4
  12423. );
  12424. const rotation = Matrix2.Matrix4.getMatrix3(transform, scratchHPRMatrix3);
  12425. return Quaternion.fromRotationMatrix(rotation, result);
  12426. };
  12427. const noScale = new Matrix2.Cartesian3(1.0, 1.0, 1.0);
  12428. const hprCenterScratch = new Matrix2.Cartesian3();
  12429. const ffScratch = new Matrix2.Matrix4();
  12430. const hprTransformScratch = new Matrix2.Matrix4();
  12431. const hprRotationScratch = new Matrix2.Matrix3();
  12432. const hprQuaternionScratch = new Quaternion();
  12433. /**
  12434. * Computes heading-pitch-roll angles from a transform in a particular reference frame. Heading is the rotation from the local north
  12435. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  12436. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  12437. *
  12438. * @param {Matrix4} transform The transform
  12439. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12440. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  12441. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  12442. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  12443. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if none was provided.
  12444. */
  12445. Transforms.fixedFrameToHeadingPitchRoll = function (
  12446. transform,
  12447. ellipsoid,
  12448. fixedFrameTransform,
  12449. result
  12450. ) {
  12451. //>>includeStart('debug', pragmas.debug);
  12452. RuntimeError.Check.defined("transform", transform);
  12453. //>>includeEnd('debug');
  12454. ellipsoid = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
  12455. fixedFrameTransform = defaultValue.defaultValue(
  12456. fixedFrameTransform,
  12457. Transforms.eastNorthUpToFixedFrame
  12458. );
  12459. if (!defaultValue.defined(result)) {
  12460. result = new HeadingPitchRoll();
  12461. }
  12462. const center = Matrix2.Matrix4.getTranslation(transform, hprCenterScratch);
  12463. if (Matrix2.Cartesian3.equals(center, Matrix2.Cartesian3.ZERO)) {
  12464. result.heading = 0;
  12465. result.pitch = 0;
  12466. result.roll = 0;
  12467. return result;
  12468. }
  12469. let toFixedFrame = Matrix2.Matrix4.inverseTransformation(
  12470. fixedFrameTransform(center, ellipsoid, ffScratch),
  12471. ffScratch
  12472. );
  12473. let transformCopy = Matrix2.Matrix4.setScale(transform, noScale, hprTransformScratch);
  12474. transformCopy = Matrix2.Matrix4.setTranslation(
  12475. transformCopy,
  12476. Matrix2.Cartesian3.ZERO,
  12477. transformCopy
  12478. );
  12479. toFixedFrame = Matrix2.Matrix4.multiply(toFixedFrame, transformCopy, toFixedFrame);
  12480. let quaternionRotation = Quaternion.fromRotationMatrix(
  12481. Matrix2.Matrix4.getMatrix3(toFixedFrame, hprRotationScratch),
  12482. hprQuaternionScratch
  12483. );
  12484. quaternionRotation = Quaternion.normalize(
  12485. quaternionRotation,
  12486. quaternionRotation
  12487. );
  12488. return HeadingPitchRoll.fromQuaternion(quaternionRotation, result);
  12489. };
  12490. const gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  12491. const gmstConstant1 = 8640184.812866;
  12492. const gmstConstant2 = 0.093104;
  12493. const gmstConstant3 = -6.2e-6;
  12494. const rateCoef = 1.1772758384668e-19;
  12495. const wgs84WRPrecessing = 7.2921158553e-5;
  12496. const twoPiOverSecondsInDay = ComponentDatatype.CesiumMath.TWO_PI / 86400.0;
  12497. let dateInUtc = new JulianDate();
  12498. /**
  12499. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  12500. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  12501. *
  12502. * @param {JulianDate} date The time at which to compute the rotation matrix.
  12503. * @param {Matrix3} [result] The object onto which to store the result.
  12504. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  12505. *
  12506. * @example
  12507. * //Set the view to the inertial frame.
  12508. * scene.postUpdate.addEventListener(function(scene, time) {
  12509. * const now = Cesium.JulianDate.now();
  12510. * const offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  12511. * const transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  12512. * const inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  12513. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  12514. * camera.lookAtTransform(transform, offset);
  12515. * });
  12516. */
  12517. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  12518. //>>includeStart('debug', pragmas.debug);
  12519. if (!defaultValue.defined(date)) {
  12520. throw new RuntimeError.DeveloperError("date is required.");
  12521. }
  12522. //>>includeEnd('debug');
  12523. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  12524. // We do not want to use the function like convertTaiToUtc in JulianDate because
  12525. // we explicitly do not want to fail when inside the leap second.
  12526. dateInUtc = JulianDate.addSeconds(
  12527. date,
  12528. -JulianDate.computeTaiMinusUtc(date),
  12529. dateInUtc
  12530. );
  12531. const utcDayNumber = dateInUtc.dayNumber;
  12532. const utcSecondsIntoDay = dateInUtc.secondsOfDay;
  12533. let t;
  12534. const diffDays = utcDayNumber - 2451545;
  12535. if (utcSecondsIntoDay >= 43200.0) {
  12536. t = (diffDays + 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  12537. } else {
  12538. t = (diffDays - 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  12539. }
  12540. const gmst0 =
  12541. gmstConstant0 +
  12542. t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  12543. const angle = (gmst0 * twoPiOverSecondsInDay) % ComponentDatatype.CesiumMath.TWO_PI;
  12544. const ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  12545. const secondsSinceMidnight =
  12546. (utcSecondsIntoDay + TimeConstants$1.SECONDS_PER_DAY * 0.5) %
  12547. TimeConstants$1.SECONDS_PER_DAY;
  12548. const gha = angle + ratio * secondsSinceMidnight;
  12549. const cosGha = Math.cos(gha);
  12550. const sinGha = Math.sin(gha);
  12551. if (!defaultValue.defined(result)) {
  12552. return new Matrix2.Matrix3(
  12553. cosGha,
  12554. sinGha,
  12555. 0.0,
  12556. -sinGha,
  12557. cosGha,
  12558. 0.0,
  12559. 0.0,
  12560. 0.0,
  12561. 1.0
  12562. );
  12563. }
  12564. result[0] = cosGha;
  12565. result[1] = -sinGha;
  12566. result[2] = 0.0;
  12567. result[3] = sinGha;
  12568. result[4] = cosGha;
  12569. result[5] = 0.0;
  12570. result[6] = 0.0;
  12571. result[7] = 0.0;
  12572. result[8] = 1.0;
  12573. return result;
  12574. };
  12575. /**
  12576. * The source of IAU 2006 XYS data, used for computing the transformation between the
  12577. * Fixed and ICRF axes.
  12578. * @type {Iau2006XysData}
  12579. *
  12580. * @see Transforms.computeIcrfToFixedMatrix
  12581. * @see Transforms.computeFixedToIcrfMatrix
  12582. *
  12583. * @private
  12584. */
  12585. Transforms.iau2006XysData = new Iau2006XysData();
  12586. /**
  12587. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  12588. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  12589. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  12590. * @type {EarthOrientationParameters}
  12591. *
  12592. * @see Transforms.computeIcrfToFixedMatrix
  12593. * @see Transforms.computeFixedToIcrfMatrix
  12594. *
  12595. * @private
  12596. */
  12597. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  12598. const ttMinusTai = 32.184;
  12599. const j2000ttDays = 2451545.0;
  12600. /**
  12601. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  12602. * direction, over a given interval. This function returns a promise that, when resolved,
  12603. * indicates that the preload has completed.
  12604. *
  12605. * @param {TimeInterval} timeInterval The interval to preload.
  12606. * @returns {Promise<void>} A promise that, when resolved, indicates that the preload has completed
  12607. * and evaluation of the transformation between the fixed and ICRF axes will
  12608. * no longer return undefined for a time inside the interval.
  12609. *
  12610. *
  12611. * @example
  12612. * const interval = new Cesium.TimeInterval(...);
  12613. * Promise.resolve(Cesium.Transforms.preloadIcrfFixed(interval)).then(function() {
  12614. * // the data is now loaded
  12615. * });
  12616. *
  12617. * @see Transforms.computeIcrfToFixedMatrix
  12618. * @see Transforms.computeFixedToIcrfMatrix
  12619. */
  12620. Transforms.preloadIcrfFixed = function (timeInterval) {
  12621. const startDayTT = timeInterval.start.dayNumber;
  12622. const startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  12623. const stopDayTT = timeInterval.stop.dayNumber;
  12624. const stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  12625. const xysPromise = Transforms.iau2006XysData.preload(
  12626. startDayTT,
  12627. startSecondTT,
  12628. stopDayTT,
  12629. stopSecondTT
  12630. );
  12631. const eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  12632. return Promise.all([xysPromise, eopPromise]);
  12633. };
  12634. /**
  12635. * Computes a rotation matrix to transform a point or vector from the International Celestial
  12636. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  12637. * at a given time. This function may return undefined if the data necessary to
  12638. * do the transformation is not yet loaded.
  12639. *
  12640. * @param {JulianDate} date The time at which to compute the rotation matrix.
  12641. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  12642. * not specified, a new instance is created and returned.
  12643. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  12644. * transformation is not yet loaded.
  12645. *
  12646. *
  12647. * @example
  12648. * scene.postUpdate.addEventListener(function(scene, time) {
  12649. * // View in ICRF.
  12650. * const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  12651. * if (Cesium.defined(icrfToFixed)) {
  12652. * const offset = Cesium.Cartesian3.clone(camera.position);
  12653. * const transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
  12654. * camera.lookAtTransform(transform, offset);
  12655. * }
  12656. * });
  12657. *
  12658. * @see Transforms.preloadIcrfFixed
  12659. */
  12660. Transforms.computeIcrfToFixedMatrix = function (date, result) {
  12661. //>>includeStart('debug', pragmas.debug);
  12662. if (!defaultValue.defined(date)) {
  12663. throw new RuntimeError.DeveloperError("date is required.");
  12664. }
  12665. //>>includeEnd('debug');
  12666. if (!defaultValue.defined(result)) {
  12667. result = new Matrix2.Matrix3();
  12668. }
  12669. const fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  12670. if (!defaultValue.defined(fixedToIcrfMtx)) {
  12671. return undefined;
  12672. }
  12673. return Matrix2.Matrix3.transpose(fixedToIcrfMtx, result);
  12674. };
  12675. const xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  12676. const eopScratch = new EarthOrientationParametersSample(
  12677. 0.0,
  12678. 0.0,
  12679. 0.0,
  12680. 0.0,
  12681. 0.0);
  12682. const rotation1Scratch = new Matrix2.Matrix3();
  12683. const rotation2Scratch = new Matrix2.Matrix3();
  12684. /**
  12685. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  12686. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  12687. * at a given time. This function may return undefined if the data necessary to
  12688. * do the transformation is not yet loaded.
  12689. *
  12690. * @param {JulianDate} date The time at which to compute the rotation matrix.
  12691. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  12692. * not specified, a new instance is created and returned.
  12693. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  12694. * transformation is not yet loaded.
  12695. *
  12696. *
  12697. * @example
  12698. * // Transform a point from the ICRF axes to the Fixed axes.
  12699. * const now = Cesium.JulianDate.now();
  12700. * const pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  12701. * const fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  12702. * let pointInInertial = new Cesium.Cartesian3();
  12703. * if (Cesium.defined(fixedToIcrf)) {
  12704. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  12705. * }
  12706. *
  12707. * @see Transforms.preloadIcrfFixed
  12708. */
  12709. Transforms.computeFixedToIcrfMatrix = function (date, result) {
  12710. //>>includeStart('debug', pragmas.debug);
  12711. if (!defaultValue.defined(date)) {
  12712. throw new RuntimeError.DeveloperError("date is required.");
  12713. }
  12714. //>>includeEnd('debug');
  12715. if (!defaultValue.defined(result)) {
  12716. result = new Matrix2.Matrix3();
  12717. }
  12718. // Compute pole wander
  12719. const eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  12720. if (!defaultValue.defined(eop)) {
  12721. return undefined;
  12722. }
  12723. // There is no external conversion to Terrestrial Time (TT).
  12724. // So use International Atomic Time (TAI) and convert using offsets.
  12725. // Here we are assuming that dayTT and secondTT are positive
  12726. const dayTT = date.dayNumber;
  12727. // It's possible here that secondTT could roll over 86400
  12728. // This does not seem to affect the precision (unit tests check for this)
  12729. const secondTT = date.secondsOfDay + ttMinusTai;
  12730. const xys = Transforms.iau2006XysData.computeXysRadians(
  12731. dayTT,
  12732. secondTT,
  12733. xysScratch
  12734. );
  12735. if (!defaultValue.defined(xys)) {
  12736. return undefined;
  12737. }
  12738. const x = xys.x + eop.xPoleOffset;
  12739. const y = xys.y + eop.yPoleOffset;
  12740. // Compute XYS rotation
  12741. const a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  12742. const rotation1 = rotation1Scratch;
  12743. rotation1[0] = 1.0 - a * x * x;
  12744. rotation1[3] = -a * x * y;
  12745. rotation1[6] = x;
  12746. rotation1[1] = -a * x * y;
  12747. rotation1[4] = 1 - a * y * y;
  12748. rotation1[7] = y;
  12749. rotation1[2] = -x;
  12750. rotation1[5] = -y;
  12751. rotation1[8] = 1 - a * (x * x + y * y);
  12752. const rotation2 = Matrix2.Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  12753. const matrixQ = Matrix2.Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  12754. // Similar to TT conversions above
  12755. // It's possible here that secondTT could roll over 86400
  12756. // This does not seem to affect the precision (unit tests check for this)
  12757. const dateUt1day = date.dayNumber;
  12758. const dateUt1sec =
  12759. date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  12760. // Compute Earth rotation angle
  12761. // The IERS standard for era is
  12762. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  12763. // where
  12764. // Tu = JulianDateInUt1 - 2451545.0
  12765. // However, you get much more precision if you make the following simplification
  12766. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  12767. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  12768. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  12769. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  12770. const daysSinceJ2000 = dateUt1day - 2451545;
  12771. const fractionOfDay = dateUt1sec / TimeConstants$1.SECONDS_PER_DAY;
  12772. let era =
  12773. 0.779057273264 +
  12774. fractionOfDay +
  12775. 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  12776. era = (era % 1.0) * ComponentDatatype.CesiumMath.TWO_PI;
  12777. const earthRotation = Matrix2.Matrix3.fromRotationZ(era, rotation2Scratch);
  12778. // pseudoFixed to ICRF
  12779. const pfToIcrf = Matrix2.Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  12780. // Compute pole wander matrix
  12781. const cosxp = Math.cos(eop.xPoleWander);
  12782. const cosyp = Math.cos(eop.yPoleWander);
  12783. const sinxp = Math.sin(eop.xPoleWander);
  12784. const sinyp = Math.sin(eop.yPoleWander);
  12785. let ttt = dayTT - j2000ttDays + secondTT / TimeConstants$1.SECONDS_PER_DAY;
  12786. ttt /= 36525.0;
  12787. // approximate sp value in rad
  12788. const sp = (-47.0e-6 * ttt * ComponentDatatype.CesiumMath.RADIANS_PER_DEGREE) / 3600.0;
  12789. const cossp = Math.cos(sp);
  12790. const sinsp = Math.sin(sp);
  12791. const fToPfMtx = rotation2Scratch;
  12792. fToPfMtx[0] = cosxp * cossp;
  12793. fToPfMtx[1] = cosxp * sinsp;
  12794. fToPfMtx[2] = sinxp;
  12795. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  12796. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  12797. fToPfMtx[5] = -sinyp * cosxp;
  12798. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  12799. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  12800. fToPfMtx[8] = cosyp * cosxp;
  12801. return Matrix2.Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  12802. };
  12803. const pointToWindowCoordinatesTemp = new Matrix2.Cartesian4();
  12804. /**
  12805. * Transform a point from model coordinates to window coordinates.
  12806. *
  12807. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  12808. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  12809. * @param {Cartesian3} point The point to transform.
  12810. * @param {Cartesian2} [result] The object onto which to store the result.
  12811. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  12812. */
  12813. Transforms.pointToWindowCoordinates = function (
  12814. modelViewProjectionMatrix,
  12815. viewportTransformation,
  12816. point,
  12817. result
  12818. ) {
  12819. result = Transforms.pointToGLWindowCoordinates(
  12820. modelViewProjectionMatrix,
  12821. viewportTransformation,
  12822. point,
  12823. result
  12824. );
  12825. result.y = 2.0 * viewportTransformation[5] - result.y;
  12826. return result;
  12827. };
  12828. /**
  12829. * @private
  12830. */
  12831. Transforms.pointToGLWindowCoordinates = function (
  12832. modelViewProjectionMatrix,
  12833. viewportTransformation,
  12834. point,
  12835. result
  12836. ) {
  12837. //>>includeStart('debug', pragmas.debug);
  12838. if (!defaultValue.defined(modelViewProjectionMatrix)) {
  12839. throw new RuntimeError.DeveloperError("modelViewProjectionMatrix is required.");
  12840. }
  12841. if (!defaultValue.defined(viewportTransformation)) {
  12842. throw new RuntimeError.DeveloperError("viewportTransformation is required.");
  12843. }
  12844. if (!defaultValue.defined(point)) {
  12845. throw new RuntimeError.DeveloperError("point is required.");
  12846. }
  12847. //>>includeEnd('debug');
  12848. if (!defaultValue.defined(result)) {
  12849. result = new Matrix2.Cartesian2();
  12850. }
  12851. const tmp = pointToWindowCoordinatesTemp;
  12852. Matrix2.Matrix4.multiplyByVector(
  12853. modelViewProjectionMatrix,
  12854. Matrix2.Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp),
  12855. tmp
  12856. );
  12857. Matrix2.Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  12858. Matrix2.Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  12859. return Matrix2.Cartesian2.fromCartesian4(tmp, result);
  12860. };
  12861. const normalScratch = new Matrix2.Cartesian3();
  12862. const rightScratch = new Matrix2.Cartesian3();
  12863. const upScratch = new Matrix2.Cartesian3();
  12864. /**
  12865. * Transform a position and velocity to a rotation matrix.
  12866. *
  12867. * @param {Cartesian3} position The position to transform.
  12868. * @param {Cartesian3} velocity The velocity vector to transform.
  12869. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  12870. * @param {Matrix3} [result] The object onto which to store the result.
  12871. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  12872. */
  12873. Transforms.rotationMatrixFromPositionVelocity = function (
  12874. position,
  12875. velocity,
  12876. ellipsoid,
  12877. result
  12878. ) {
  12879. //>>includeStart('debug', pragmas.debug);
  12880. if (!defaultValue.defined(position)) {
  12881. throw new RuntimeError.DeveloperError("position is required.");
  12882. }
  12883. if (!defaultValue.defined(velocity)) {
  12884. throw new RuntimeError.DeveloperError("velocity is required.");
  12885. }
  12886. //>>includeEnd('debug');
  12887. const normal = defaultValue.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84).geodeticSurfaceNormal(
  12888. position,
  12889. normalScratch
  12890. );
  12891. let right = Matrix2.Cartesian3.cross(velocity, normal, rightScratch);
  12892. if (Matrix2.Cartesian3.equalsEpsilon(right, Matrix2.Cartesian3.ZERO, ComponentDatatype.CesiumMath.EPSILON6)) {
  12893. right = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, right);
  12894. }
  12895. const up = Matrix2.Cartesian3.cross(right, velocity, upScratch);
  12896. Matrix2.Cartesian3.normalize(up, up);
  12897. Matrix2.Cartesian3.cross(velocity, up, right);
  12898. Matrix2.Cartesian3.negate(right, right);
  12899. Matrix2.Cartesian3.normalize(right, right);
  12900. if (!defaultValue.defined(result)) {
  12901. result = new Matrix2.Matrix3();
  12902. }
  12903. result[0] = velocity.x;
  12904. result[1] = velocity.y;
  12905. result[2] = velocity.z;
  12906. result[3] = right.x;
  12907. result[4] = right.y;
  12908. result[5] = right.z;
  12909. result[6] = up.x;
  12910. result[7] = up.y;
  12911. result[8] = up.z;
  12912. return result;
  12913. };
  12914. const swizzleMatrix = new Matrix2.Matrix4(
  12915. 0.0,
  12916. 0.0,
  12917. 1.0,
  12918. 0.0,
  12919. 1.0,
  12920. 0.0,
  12921. 0.0,
  12922. 0.0,
  12923. 0.0,
  12924. 1.0,
  12925. 0.0,
  12926. 0.0,
  12927. 0.0,
  12928. 0.0,
  12929. 0.0,
  12930. 1.0
  12931. );
  12932. const scratchCartographic = new Matrix2.Cartographic();
  12933. const scratchCartesian3Projection = new Matrix2.Cartesian3();
  12934. const scratchCenter = new Matrix2.Cartesian3();
  12935. const scratchRotation = new Matrix2.Matrix3();
  12936. const scratchFromENU = new Matrix2.Matrix4();
  12937. const scratchToENU = new Matrix2.Matrix4();
  12938. /**
  12939. * @private
  12940. */
  12941. Transforms.basisTo2D = function (projection, matrix, result) {
  12942. //>>includeStart('debug', pragmas.debug);
  12943. if (!defaultValue.defined(projection)) {
  12944. throw new RuntimeError.DeveloperError("projection is required.");
  12945. }
  12946. if (!defaultValue.defined(matrix)) {
  12947. throw new RuntimeError.DeveloperError("matrix is required.");
  12948. }
  12949. if (!defaultValue.defined(result)) {
  12950. throw new RuntimeError.DeveloperError("result is required.");
  12951. }
  12952. //>>includeEnd('debug');
  12953. const rtcCenter = Matrix2.Matrix4.getTranslation(matrix, scratchCenter);
  12954. const ellipsoid = projection.ellipsoid;
  12955. // Get the 2D Center
  12956. const cartographic = ellipsoid.cartesianToCartographic(
  12957. rtcCenter,
  12958. scratchCartographic
  12959. );
  12960. const projectedPosition = projection.project(
  12961. cartographic,
  12962. scratchCartesian3Projection
  12963. );
  12964. Matrix2.Cartesian3.fromElements(
  12965. projectedPosition.z,
  12966. projectedPosition.x,
  12967. projectedPosition.y,
  12968. projectedPosition
  12969. );
  12970. // Assuming the instance are positioned in WGS84, invert the WGS84 transform to get the local transform and then convert to 2D
  12971. const fromENU = Transforms.eastNorthUpToFixedFrame(
  12972. rtcCenter,
  12973. ellipsoid,
  12974. scratchFromENU
  12975. );
  12976. const toENU = Matrix2.Matrix4.inverseTransformation(fromENU, scratchToENU);
  12977. const rotation = Matrix2.Matrix4.getMatrix3(matrix, scratchRotation);
  12978. const local = Matrix2.Matrix4.multiplyByMatrix3(toENU, rotation, result);
  12979. Matrix2.Matrix4.multiply(swizzleMatrix, local, result); // Swap x, y, z for 2D
  12980. Matrix2.Matrix4.setTranslation(result, projectedPosition, result); // Use the projected center
  12981. return result;
  12982. };
  12983. /**
  12984. * @private
  12985. */
  12986. Transforms.wgs84To2DModelMatrix = function (projection, center, result) {
  12987. //>>includeStart('debug', pragmas.debug);
  12988. if (!defaultValue.defined(projection)) {
  12989. throw new RuntimeError.DeveloperError("projection is required.");
  12990. }
  12991. if (!defaultValue.defined(center)) {
  12992. throw new RuntimeError.DeveloperError("center is required.");
  12993. }
  12994. if (!defaultValue.defined(result)) {
  12995. throw new RuntimeError.DeveloperError("result is required.");
  12996. }
  12997. //>>includeEnd('debug');
  12998. const ellipsoid = projection.ellipsoid;
  12999. const fromENU = Transforms.eastNorthUpToFixedFrame(
  13000. center,
  13001. ellipsoid,
  13002. scratchFromENU
  13003. );
  13004. const toENU = Matrix2.Matrix4.inverseTransformation(fromENU, scratchToENU);
  13005. const cartographic = ellipsoid.cartesianToCartographic(
  13006. center,
  13007. scratchCartographic
  13008. );
  13009. const projectedPosition = projection.project(
  13010. cartographic,
  13011. scratchCartesian3Projection
  13012. );
  13013. Matrix2.Cartesian3.fromElements(
  13014. projectedPosition.z,
  13015. projectedPosition.x,
  13016. projectedPosition.y,
  13017. projectedPosition
  13018. );
  13019. const translation = Matrix2.Matrix4.fromTranslation(
  13020. projectedPosition,
  13021. scratchFromENU
  13022. );
  13023. Matrix2.Matrix4.multiply(swizzleMatrix, toENU, result);
  13024. Matrix2.Matrix4.multiply(translation, result, result);
  13025. return result;
  13026. };
  13027. exports.BoundingSphere = BoundingSphere;
  13028. exports.FeatureDetection = FeatureDetection;
  13029. exports.GeographicProjection = GeographicProjection;
  13030. exports.Intersect = Intersect$1;
  13031. exports.Interval = Interval;
  13032. exports.Quaternion = Quaternion;
  13033. exports.Resource = Resource;
  13034. exports.Transforms = Transforms;
  13035. exports.buildModuleUrl = buildModuleUrl;
  13036. }));