Transforms-81680c41.js 569 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160
  1. /* This file is automatically rebuilt by the Cesium build process. */
  2. define(['exports', './when-e6985d2a', './Check-24cae389', './Math-392d0035', './Cartesian2-a5d6dde9', './RuntimeError-61701d3e'], function (exports, when, Check, _Math, Cartesian2, RuntimeError) { '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 = when.defaultValue(ellipsoid, Cartesian2.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. var semimajorAxis = this._semimajorAxis;
  51. var x = cartographic.longitude * semimajorAxis;
  52. var y = cartographic.latitude * semimajorAxis;
  53. var z = cartographic.height;
  54. if (!when.defined(result)) {
  55. return new Cartesian2.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 (!when.defined(cartesian)) {
  77. throw new Check.DeveloperError("cartesian is required");
  78. }
  79. //>>includeEnd('debug');
  80. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  81. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  82. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  83. var height = cartesian.z;
  84. if (!when.defined(result)) {
  85. return new Cartesian2.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. var 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 = when.defaultValue(start, 0.0);
  139. /**
  140. * The end of the interval.
  141. * @type {Number}
  142. * @default 0.0
  143. */
  144. this.stop = when.defaultValue(stop, 0.0);
  145. }
  146. /**
  147. * A 3x3 matrix, indexable as a column-major order array.
  148. * Constructor parameters are in row-major order for code readability.
  149. * @alias Matrix3
  150. * @constructor
  151. * @implements {ArrayLike<number>}
  152. *
  153. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  154. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  155. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  156. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  157. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  158. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  159. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  160. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  161. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  162. *
  163. * @see Matrix3.fromColumnMajorArray
  164. * @see Matrix3.fromRowMajorArray
  165. * @see Matrix3.fromQuaternion
  166. * @see Matrix3.fromScale
  167. * @see Matrix3.fromUniformScale
  168. * @see Matrix2
  169. * @see Matrix4
  170. */
  171. function Matrix3(
  172. column0Row0,
  173. column1Row0,
  174. column2Row0,
  175. column0Row1,
  176. column1Row1,
  177. column2Row1,
  178. column0Row2,
  179. column1Row2,
  180. column2Row2
  181. ) {
  182. this[0] = when.defaultValue(column0Row0, 0.0);
  183. this[1] = when.defaultValue(column0Row1, 0.0);
  184. this[2] = when.defaultValue(column0Row2, 0.0);
  185. this[3] = when.defaultValue(column1Row0, 0.0);
  186. this[4] = when.defaultValue(column1Row1, 0.0);
  187. this[5] = when.defaultValue(column1Row2, 0.0);
  188. this[6] = when.defaultValue(column2Row0, 0.0);
  189. this[7] = when.defaultValue(column2Row1, 0.0);
  190. this[8] = when.defaultValue(column2Row2, 0.0);
  191. }
  192. /**
  193. * The number of elements used to pack the object into an array.
  194. * @type {Number}
  195. */
  196. Matrix3.packedLength = 9;
  197. /**
  198. * Stores the provided instance into the provided array.
  199. *
  200. * @param {Matrix3} value The value to pack.
  201. * @param {Number[]} array The array to pack into.
  202. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  203. *
  204. * @returns {Number[]} The array that was packed into
  205. */
  206. Matrix3.pack = function (value, array, startingIndex) {
  207. //>>includeStart('debug', pragmas.debug);
  208. Check.Check.typeOf.object("value", value);
  209. Check.Check.defined("array", array);
  210. //>>includeEnd('debug');
  211. startingIndex = when.defaultValue(startingIndex, 0);
  212. array[startingIndex++] = value[0];
  213. array[startingIndex++] = value[1];
  214. array[startingIndex++] = value[2];
  215. array[startingIndex++] = value[3];
  216. array[startingIndex++] = value[4];
  217. array[startingIndex++] = value[5];
  218. array[startingIndex++] = value[6];
  219. array[startingIndex++] = value[7];
  220. array[startingIndex++] = value[8];
  221. return array;
  222. };
  223. /**
  224. * Retrieves an instance from a packed array.
  225. *
  226. * @param {Number[]} array The packed array.
  227. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  228. * @param {Matrix3} [result] The object into which to store the result.
  229. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  230. */
  231. Matrix3.unpack = function (array, startingIndex, result) {
  232. //>>includeStart('debug', pragmas.debug);
  233. Check.Check.defined("array", array);
  234. //>>includeEnd('debug');
  235. startingIndex = when.defaultValue(startingIndex, 0);
  236. if (!when.defined(result)) {
  237. result = new Matrix3();
  238. }
  239. result[0] = array[startingIndex++];
  240. result[1] = array[startingIndex++];
  241. result[2] = array[startingIndex++];
  242. result[3] = array[startingIndex++];
  243. result[4] = array[startingIndex++];
  244. result[5] = array[startingIndex++];
  245. result[6] = array[startingIndex++];
  246. result[7] = array[startingIndex++];
  247. result[8] = array[startingIndex++];
  248. return result;
  249. };
  250. /**
  251. * Duplicates a Matrix3 instance.
  252. *
  253. * @param {Matrix3} matrix The matrix to duplicate.
  254. * @param {Matrix3} [result] The object onto which to store the result.
  255. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  256. */
  257. Matrix3.clone = function (matrix, result) {
  258. if (!when.defined(matrix)) {
  259. return undefined;
  260. }
  261. if (!when.defined(result)) {
  262. return new Matrix3(
  263. matrix[0],
  264. matrix[3],
  265. matrix[6],
  266. matrix[1],
  267. matrix[4],
  268. matrix[7],
  269. matrix[2],
  270. matrix[5],
  271. matrix[8]
  272. );
  273. }
  274. result[0] = matrix[0];
  275. result[1] = matrix[1];
  276. result[2] = matrix[2];
  277. result[3] = matrix[3];
  278. result[4] = matrix[4];
  279. result[5] = matrix[5];
  280. result[6] = matrix[6];
  281. result[7] = matrix[7];
  282. result[8] = matrix[8];
  283. return result;
  284. };
  285. /**
  286. * Creates a Matrix3 from 9 consecutive elements in an array.
  287. *
  288. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  289. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  290. * @param {Matrix3} [result] The object onto which to store the result.
  291. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  292. *
  293. * @example
  294. * // Create the Matrix3:
  295. * // [1.0, 2.0, 3.0]
  296. * // [1.0, 2.0, 3.0]
  297. * // [1.0, 2.0, 3.0]
  298. *
  299. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  300. * var m = Cesium.Matrix3.fromArray(v);
  301. *
  302. * // Create same Matrix3 with using an offset into an array
  303. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  304. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  305. */
  306. Matrix3.fromArray = function (array, startingIndex, result) {
  307. //>>includeStart('debug', pragmas.debug);
  308. Check.Check.defined("array", array);
  309. //>>includeEnd('debug');
  310. startingIndex = when.defaultValue(startingIndex, 0);
  311. if (!when.defined(result)) {
  312. result = new Matrix3();
  313. }
  314. result[0] = array[startingIndex];
  315. result[1] = array[startingIndex + 1];
  316. result[2] = array[startingIndex + 2];
  317. result[3] = array[startingIndex + 3];
  318. result[4] = array[startingIndex + 4];
  319. result[5] = array[startingIndex + 5];
  320. result[6] = array[startingIndex + 6];
  321. result[7] = array[startingIndex + 7];
  322. result[8] = array[startingIndex + 8];
  323. return result;
  324. };
  325. /**
  326. * Creates a Matrix3 instance from a column-major order array.
  327. *
  328. * @param {Number[]} values The column-major order array.
  329. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  330. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  331. */
  332. Matrix3.fromColumnMajorArray = function (values, result) {
  333. //>>includeStart('debug', pragmas.debug);
  334. Check.Check.defined("values", values);
  335. //>>includeEnd('debug');
  336. return Matrix3.clone(values, result);
  337. };
  338. /**
  339. * Creates a Matrix3 instance from a row-major order array.
  340. * The resulting matrix will be in column-major order.
  341. *
  342. * @param {Number[]} values The row-major order array.
  343. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  344. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  345. */
  346. Matrix3.fromRowMajorArray = function (values, result) {
  347. //>>includeStart('debug', pragmas.debug);
  348. Check.Check.defined("values", values);
  349. //>>includeEnd('debug');
  350. if (!when.defined(result)) {
  351. return new Matrix3(
  352. values[0],
  353. values[1],
  354. values[2],
  355. values[3],
  356. values[4],
  357. values[5],
  358. values[6],
  359. values[7],
  360. values[8]
  361. );
  362. }
  363. result[0] = values[0];
  364. result[1] = values[3];
  365. result[2] = values[6];
  366. result[3] = values[1];
  367. result[4] = values[4];
  368. result[5] = values[7];
  369. result[6] = values[2];
  370. result[7] = values[5];
  371. result[8] = values[8];
  372. return result;
  373. };
  374. /**
  375. * Computes a 3x3 rotation matrix from the provided quaternion.
  376. *
  377. * @param {Quaternion} quaternion the quaternion to use.
  378. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  379. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  380. */
  381. Matrix3.fromQuaternion = function (quaternion, result) {
  382. //>>includeStart('debug', pragmas.debug);
  383. Check.Check.typeOf.object("quaternion", quaternion);
  384. //>>includeEnd('debug');
  385. var x2 = quaternion.x * quaternion.x;
  386. var xy = quaternion.x * quaternion.y;
  387. var xz = quaternion.x * quaternion.z;
  388. var xw = quaternion.x * quaternion.w;
  389. var y2 = quaternion.y * quaternion.y;
  390. var yz = quaternion.y * quaternion.z;
  391. var yw = quaternion.y * quaternion.w;
  392. var z2 = quaternion.z * quaternion.z;
  393. var zw = quaternion.z * quaternion.w;
  394. var w2 = quaternion.w * quaternion.w;
  395. var m00 = x2 - y2 - z2 + w2;
  396. var m01 = 2.0 * (xy - zw);
  397. var m02 = 2.0 * (xz + yw);
  398. var m10 = 2.0 * (xy + zw);
  399. var m11 = -x2 + y2 - z2 + w2;
  400. var m12 = 2.0 * (yz - xw);
  401. var m20 = 2.0 * (xz - yw);
  402. var m21 = 2.0 * (yz + xw);
  403. var m22 = -x2 - y2 + z2 + w2;
  404. if (!when.defined(result)) {
  405. return new Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
  406. }
  407. result[0] = m00;
  408. result[1] = m10;
  409. result[2] = m20;
  410. result[3] = m01;
  411. result[4] = m11;
  412. result[5] = m21;
  413. result[6] = m02;
  414. result[7] = m12;
  415. result[8] = m22;
  416. return result;
  417. };
  418. /**
  419. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  420. *
  421. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  422. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  423. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  424. */
  425. Matrix3.fromHeadingPitchRoll = function (headingPitchRoll, result) {
  426. //>>includeStart('debug', pragmas.debug);
  427. Check.Check.typeOf.object("headingPitchRoll", headingPitchRoll);
  428. //>>includeEnd('debug');
  429. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  430. var cosPsi = Math.cos(-headingPitchRoll.heading);
  431. var cosPhi = Math.cos(headingPitchRoll.roll);
  432. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  433. var sinPsi = Math.sin(-headingPitchRoll.heading);
  434. var sinPhi = Math.sin(headingPitchRoll.roll);
  435. var m00 = cosTheta * cosPsi;
  436. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  437. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  438. var m10 = cosTheta * sinPsi;
  439. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  440. var m12 = -sinPhi * cosPsi + cosPhi * sinTheta * sinPsi;
  441. var m20 = -sinTheta;
  442. var m21 = sinPhi * cosTheta;
  443. var m22 = cosPhi * cosTheta;
  444. if (!when.defined(result)) {
  445. return new Matrix3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
  446. }
  447. result[0] = m00;
  448. result[1] = m10;
  449. result[2] = m20;
  450. result[3] = m01;
  451. result[4] = m11;
  452. result[5] = m21;
  453. result[6] = m02;
  454. result[7] = m12;
  455. result[8] = m22;
  456. return result;
  457. };
  458. /**
  459. * Computes a Matrix3 instance representing a non-uniform scale.
  460. *
  461. * @param {Cartesian3} scale The x, y, and z scale factors.
  462. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  463. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  464. *
  465. * @example
  466. * // Creates
  467. * // [7.0, 0.0, 0.0]
  468. * // [0.0, 8.0, 0.0]
  469. * // [0.0, 0.0, 9.0]
  470. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  471. */
  472. Matrix3.fromScale = function (scale, result) {
  473. //>>includeStart('debug', pragmas.debug);
  474. Check.Check.typeOf.object("scale", scale);
  475. //>>includeEnd('debug');
  476. if (!when.defined(result)) {
  477. return new Matrix3(scale.x, 0.0, 0.0, 0.0, scale.y, 0.0, 0.0, 0.0, scale.z);
  478. }
  479. result[0] = scale.x;
  480. result[1] = 0.0;
  481. result[2] = 0.0;
  482. result[3] = 0.0;
  483. result[4] = scale.y;
  484. result[5] = 0.0;
  485. result[6] = 0.0;
  486. result[7] = 0.0;
  487. result[8] = scale.z;
  488. return result;
  489. };
  490. /**
  491. * Computes a Matrix3 instance representing a uniform scale.
  492. *
  493. * @param {Number} scale The uniform scale factor.
  494. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  495. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  496. *
  497. * @example
  498. * // Creates
  499. * // [2.0, 0.0, 0.0]
  500. * // [0.0, 2.0, 0.0]
  501. * // [0.0, 0.0, 2.0]
  502. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  503. */
  504. Matrix3.fromUniformScale = function (scale, result) {
  505. //>>includeStart('debug', pragmas.debug);
  506. Check.Check.typeOf.number("scale", scale);
  507. //>>includeEnd('debug');
  508. if (!when.defined(result)) {
  509. return new Matrix3(scale, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, scale);
  510. }
  511. result[0] = scale;
  512. result[1] = 0.0;
  513. result[2] = 0.0;
  514. result[3] = 0.0;
  515. result[4] = scale;
  516. result[5] = 0.0;
  517. result[6] = 0.0;
  518. result[7] = 0.0;
  519. result[8] = scale;
  520. return result;
  521. };
  522. /**
  523. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  524. *
  525. * @param {Cartesian3} vector the vector on the left hand side of the cross product operation.
  526. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  527. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  528. *
  529. * @example
  530. * // Creates
  531. * // [0.0, -9.0, 8.0]
  532. * // [9.0, 0.0, -7.0]
  533. * // [-8.0, 7.0, 0.0]
  534. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  535. */
  536. Matrix3.fromCrossProduct = function (vector, result) {
  537. //>>includeStart('debug', pragmas.debug);
  538. Check.Check.typeOf.object("vector", vector);
  539. //>>includeEnd('debug');
  540. if (!when.defined(result)) {
  541. return new Matrix3(
  542. 0.0,
  543. -vector.z,
  544. vector.y,
  545. vector.z,
  546. 0.0,
  547. -vector.x,
  548. -vector.y,
  549. vector.x,
  550. 0.0
  551. );
  552. }
  553. result[0] = 0.0;
  554. result[1] = vector.z;
  555. result[2] = -vector.y;
  556. result[3] = -vector.z;
  557. result[4] = 0.0;
  558. result[5] = vector.x;
  559. result[6] = vector.y;
  560. result[7] = -vector.x;
  561. result[8] = 0.0;
  562. return result;
  563. };
  564. /**
  565. * Creates a rotation matrix around the x-axis.
  566. *
  567. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  568. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  569. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  570. *
  571. * @example
  572. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  573. * var p = new Cesium.Cartesian3(5, 6, 7);
  574. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  575. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  576. */
  577. Matrix3.fromRotationX = function (angle, result) {
  578. //>>includeStart('debug', pragmas.debug);
  579. Check.Check.typeOf.number("angle", angle);
  580. //>>includeEnd('debug');
  581. var cosAngle = Math.cos(angle);
  582. var sinAngle = Math.sin(angle);
  583. if (!when.defined(result)) {
  584. return new Matrix3(
  585. 1.0,
  586. 0.0,
  587. 0.0,
  588. 0.0,
  589. cosAngle,
  590. -sinAngle,
  591. 0.0,
  592. sinAngle,
  593. cosAngle
  594. );
  595. }
  596. result[0] = 1.0;
  597. result[1] = 0.0;
  598. result[2] = 0.0;
  599. result[3] = 0.0;
  600. result[4] = cosAngle;
  601. result[5] = sinAngle;
  602. result[6] = 0.0;
  603. result[7] = -sinAngle;
  604. result[8] = cosAngle;
  605. return result;
  606. };
  607. /**
  608. * Creates a rotation matrix around the y-axis.
  609. *
  610. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  611. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  612. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  613. *
  614. * @example
  615. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  616. * var p = new Cesium.Cartesian3(5, 6, 7);
  617. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  618. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  619. */
  620. Matrix3.fromRotationY = function (angle, result) {
  621. //>>includeStart('debug', pragmas.debug);
  622. Check.Check.typeOf.number("angle", angle);
  623. //>>includeEnd('debug');
  624. var cosAngle = Math.cos(angle);
  625. var sinAngle = Math.sin(angle);
  626. if (!when.defined(result)) {
  627. return new Matrix3(
  628. cosAngle,
  629. 0.0,
  630. sinAngle,
  631. 0.0,
  632. 1.0,
  633. 0.0,
  634. -sinAngle,
  635. 0.0,
  636. cosAngle
  637. );
  638. }
  639. result[0] = cosAngle;
  640. result[1] = 0.0;
  641. result[2] = -sinAngle;
  642. result[3] = 0.0;
  643. result[4] = 1.0;
  644. result[5] = 0.0;
  645. result[6] = sinAngle;
  646. result[7] = 0.0;
  647. result[8] = cosAngle;
  648. return result;
  649. };
  650. /**
  651. * Creates a rotation matrix around the z-axis.
  652. *
  653. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  654. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  655. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  656. *
  657. * @example
  658. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  659. * var p = new Cesium.Cartesian3(5, 6, 7);
  660. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  661. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  662. */
  663. Matrix3.fromRotationZ = function (angle, result) {
  664. //>>includeStart('debug', pragmas.debug);
  665. Check.Check.typeOf.number("angle", angle);
  666. //>>includeEnd('debug');
  667. var cosAngle = Math.cos(angle);
  668. var sinAngle = Math.sin(angle);
  669. if (!when.defined(result)) {
  670. return new Matrix3(
  671. cosAngle,
  672. -sinAngle,
  673. 0.0,
  674. sinAngle,
  675. cosAngle,
  676. 0.0,
  677. 0.0,
  678. 0.0,
  679. 1.0
  680. );
  681. }
  682. result[0] = cosAngle;
  683. result[1] = sinAngle;
  684. result[2] = 0.0;
  685. result[3] = -sinAngle;
  686. result[4] = cosAngle;
  687. result[5] = 0.0;
  688. result[6] = 0.0;
  689. result[7] = 0.0;
  690. result[8] = 1.0;
  691. return result;
  692. };
  693. /**
  694. * Creates an Array from the provided Matrix3 instance.
  695. * The array will be in column-major order.
  696. *
  697. * @param {Matrix3} matrix The matrix to use..
  698. * @param {Number[]} [result] The Array onto which to store the result.
  699. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  700. */
  701. Matrix3.toArray = function (matrix, result) {
  702. //>>includeStart('debug', pragmas.debug);
  703. Check.Check.typeOf.object("matrix", matrix);
  704. //>>includeEnd('debug');
  705. if (!when.defined(result)) {
  706. return [
  707. matrix[0],
  708. matrix[1],
  709. matrix[2],
  710. matrix[3],
  711. matrix[4],
  712. matrix[5],
  713. matrix[6],
  714. matrix[7],
  715. matrix[8],
  716. ];
  717. }
  718. result[0] = matrix[0];
  719. result[1] = matrix[1];
  720. result[2] = matrix[2];
  721. result[3] = matrix[3];
  722. result[4] = matrix[4];
  723. result[5] = matrix[5];
  724. result[6] = matrix[6];
  725. result[7] = matrix[7];
  726. result[8] = matrix[8];
  727. return result;
  728. };
  729. /**
  730. * Computes the array index of the element at the provided row and column.
  731. *
  732. * @param {Number} row The zero-based index of the row.
  733. * @param {Number} column The zero-based index of the column.
  734. * @returns {Number} The index of the element at the provided row and column.
  735. *
  736. * @exception {DeveloperError} row must be 0, 1, or 2.
  737. * @exception {DeveloperError} column must be 0, 1, or 2.
  738. *
  739. * @example
  740. * var myMatrix = new Cesium.Matrix3();
  741. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  742. * var column1Row0 = myMatrix[column1Row0Index]
  743. * myMatrix[column1Row0Index] = 10.0;
  744. */
  745. Matrix3.getElementIndex = function (column, row) {
  746. //>>includeStart('debug', pragmas.debug);
  747. Check.Check.typeOf.number.greaterThanOrEquals("row", row, 0);
  748. Check.Check.typeOf.number.lessThanOrEquals("row", row, 2);
  749. Check.Check.typeOf.number.greaterThanOrEquals("column", column, 0);
  750. Check.Check.typeOf.number.lessThanOrEquals("column", column, 2);
  751. //>>includeEnd('debug');
  752. return column * 3 + row;
  753. };
  754. /**
  755. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  756. *
  757. * @param {Matrix3} matrix The matrix to use.
  758. * @param {Number} index The zero-based index of the column to retrieve.
  759. * @param {Cartesian3} result The object onto which to store the result.
  760. * @returns {Cartesian3} The modified result parameter.
  761. *
  762. * @exception {DeveloperError} index must be 0, 1, or 2.
  763. */
  764. Matrix3.getColumn = function (matrix, index, result) {
  765. //>>includeStart('debug', pragmas.debug);
  766. Check.Check.typeOf.object("matrix", matrix);
  767. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  768. Check.Check.typeOf.number.lessThanOrEquals("index", index, 2);
  769. Check.Check.typeOf.object("result", result);
  770. //>>includeEnd('debug');
  771. var startIndex = index * 3;
  772. var x = matrix[startIndex];
  773. var y = matrix[startIndex + 1];
  774. var z = matrix[startIndex + 2];
  775. result.x = x;
  776. result.y = y;
  777. result.z = z;
  778. return result;
  779. };
  780. /**
  781. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  782. *
  783. * @param {Matrix3} matrix The matrix to use.
  784. * @param {Number} index The zero-based index of the column to set.
  785. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  786. * @param {Matrix3} result The object onto which to store the result.
  787. * @returns {Matrix3} The modified result parameter.
  788. *
  789. * @exception {DeveloperError} index must be 0, 1, or 2.
  790. */
  791. Matrix3.setColumn = function (matrix, index, cartesian, result) {
  792. //>>includeStart('debug', pragmas.debug);
  793. Check.Check.typeOf.object("matrix", matrix);
  794. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  795. Check.Check.typeOf.number.lessThanOrEquals("index", index, 2);
  796. Check.Check.typeOf.object("cartesian", cartesian);
  797. Check.Check.typeOf.object("result", result);
  798. //>>includeEnd('debug');
  799. result = Matrix3.clone(matrix, result);
  800. var startIndex = index * 3;
  801. result[startIndex] = cartesian.x;
  802. result[startIndex + 1] = cartesian.y;
  803. result[startIndex + 2] = cartesian.z;
  804. return result;
  805. };
  806. /**
  807. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  808. *
  809. * @param {Matrix3} matrix The matrix to use.
  810. * @param {Number} index The zero-based index of the row to retrieve.
  811. * @param {Cartesian3} result The object onto which to store the result.
  812. * @returns {Cartesian3} The modified result parameter.
  813. *
  814. * @exception {DeveloperError} index must be 0, 1, or 2.
  815. */
  816. Matrix3.getRow = function (matrix, index, result) {
  817. //>>includeStart('debug', pragmas.debug);
  818. Check.Check.typeOf.object("matrix", matrix);
  819. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  820. Check.Check.typeOf.number.lessThanOrEquals("index", index, 2);
  821. Check.Check.typeOf.object("result", result);
  822. //>>includeEnd('debug');
  823. var x = matrix[index];
  824. var y = matrix[index + 3];
  825. var z = matrix[index + 6];
  826. result.x = x;
  827. result.y = y;
  828. result.z = z;
  829. return result;
  830. };
  831. /**
  832. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  833. *
  834. * @param {Matrix3} matrix The matrix to use.
  835. * @param {Number} index The zero-based index of the row to set.
  836. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  837. * @param {Matrix3} result The object onto which to store the result.
  838. * @returns {Matrix3} The modified result parameter.
  839. *
  840. * @exception {DeveloperError} index must be 0, 1, or 2.
  841. */
  842. Matrix3.setRow = function (matrix, index, cartesian, result) {
  843. //>>includeStart('debug', pragmas.debug);
  844. Check.Check.typeOf.object("matrix", matrix);
  845. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  846. Check.Check.typeOf.number.lessThanOrEquals("index", index, 2);
  847. Check.Check.typeOf.object("cartesian", cartesian);
  848. Check.Check.typeOf.object("result", result);
  849. //>>includeEnd('debug');
  850. result = Matrix3.clone(matrix, result);
  851. result[index] = cartesian.x;
  852. result[index + 3] = cartesian.y;
  853. result[index + 6] = cartesian.z;
  854. return result;
  855. };
  856. var scratchColumn = new Cartesian2.Cartesian3();
  857. /**
  858. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  859. *
  860. * @param {Matrix3} matrix The matrix.
  861. * @param {Cartesian3} result The object onto which to store the result.
  862. * @returns {Cartesian3} The modified result parameter.
  863. */
  864. Matrix3.getScale = function (matrix, result) {
  865. //>>includeStart('debug', pragmas.debug);
  866. Check.Check.typeOf.object("matrix", matrix);
  867. Check.Check.typeOf.object("result", result);
  868. //>>includeEnd('debug');
  869. result.x = Cartesian2.Cartesian3.magnitude(
  870. Cartesian2.Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn)
  871. );
  872. result.y = Cartesian2.Cartesian3.magnitude(
  873. Cartesian2.Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn)
  874. );
  875. result.z = Cartesian2.Cartesian3.magnitude(
  876. Cartesian2.Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn)
  877. );
  878. return result;
  879. };
  880. var scratchScale = new Cartesian2.Cartesian3();
  881. /**
  882. * Computes the maximum scale assuming the matrix is an affine transformation.
  883. * The maximum scale is the maximum length of the column vectors.
  884. *
  885. * @param {Matrix3} matrix The matrix.
  886. * @returns {Number} The maximum scale.
  887. */
  888. Matrix3.getMaximumScale = function (matrix) {
  889. Matrix3.getScale(matrix, scratchScale);
  890. return Cartesian2.Cartesian3.maximumComponent(scratchScale);
  891. };
  892. /**
  893. * Computes the product of two matrices.
  894. *
  895. * @param {Matrix3} left The first matrix.
  896. * @param {Matrix3} right The second matrix.
  897. * @param {Matrix3} result The object onto which to store the result.
  898. * @returns {Matrix3} The modified result parameter.
  899. */
  900. Matrix3.multiply = function (left, right, result) {
  901. //>>includeStart('debug', pragmas.debug);
  902. Check.Check.typeOf.object("left", left);
  903. Check.Check.typeOf.object("right", right);
  904. Check.Check.typeOf.object("result", result);
  905. //>>includeEnd('debug');
  906. var column0Row0 =
  907. left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  908. var column0Row1 =
  909. left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  910. var column0Row2 =
  911. left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  912. var column1Row0 =
  913. left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  914. var column1Row1 =
  915. left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  916. var column1Row2 =
  917. left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  918. var column2Row0 =
  919. left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  920. var column2Row1 =
  921. left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  922. var column2Row2 =
  923. left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  924. result[0] = column0Row0;
  925. result[1] = column0Row1;
  926. result[2] = column0Row2;
  927. result[3] = column1Row0;
  928. result[4] = column1Row1;
  929. result[5] = column1Row2;
  930. result[6] = column2Row0;
  931. result[7] = column2Row1;
  932. result[8] = column2Row2;
  933. return result;
  934. };
  935. /**
  936. * Computes the sum of two matrices.
  937. *
  938. * @param {Matrix3} left The first matrix.
  939. * @param {Matrix3} right The second matrix.
  940. * @param {Matrix3} result The object onto which to store the result.
  941. * @returns {Matrix3} The modified result parameter.
  942. */
  943. Matrix3.add = function (left, right, result) {
  944. //>>includeStart('debug', pragmas.debug);
  945. Check.Check.typeOf.object("left", left);
  946. Check.Check.typeOf.object("right", right);
  947. Check.Check.typeOf.object("result", result);
  948. //>>includeEnd('debug');
  949. result[0] = left[0] + right[0];
  950. result[1] = left[1] + right[1];
  951. result[2] = left[2] + right[2];
  952. result[3] = left[3] + right[3];
  953. result[4] = left[4] + right[4];
  954. result[5] = left[5] + right[5];
  955. result[6] = left[6] + right[6];
  956. result[7] = left[7] + right[7];
  957. result[8] = left[8] + right[8];
  958. return result;
  959. };
  960. /**
  961. * Computes the difference of two matrices.
  962. *
  963. * @param {Matrix3} left The first matrix.
  964. * @param {Matrix3} right The second matrix.
  965. * @param {Matrix3} result The object onto which to store the result.
  966. * @returns {Matrix3} The modified result parameter.
  967. */
  968. Matrix3.subtract = function (left, right, result) {
  969. //>>includeStart('debug', pragmas.debug);
  970. Check.Check.typeOf.object("left", left);
  971. Check.Check.typeOf.object("right", right);
  972. Check.Check.typeOf.object("result", result);
  973. //>>includeEnd('debug');
  974. result[0] = left[0] - right[0];
  975. result[1] = left[1] - right[1];
  976. result[2] = left[2] - right[2];
  977. result[3] = left[3] - right[3];
  978. result[4] = left[4] - right[4];
  979. result[5] = left[5] - right[5];
  980. result[6] = left[6] - right[6];
  981. result[7] = left[7] - right[7];
  982. result[8] = left[8] - right[8];
  983. return result;
  984. };
  985. /**
  986. * Computes the product of a matrix and a column vector.
  987. *
  988. * @param {Matrix3} matrix The matrix.
  989. * @param {Cartesian3} cartesian The column.
  990. * @param {Cartesian3} result The object onto which to store the result.
  991. * @returns {Cartesian3} The modified result parameter.
  992. */
  993. Matrix3.multiplyByVector = function (matrix, cartesian, result) {
  994. //>>includeStart('debug', pragmas.debug);
  995. Check.Check.typeOf.object("matrix", matrix);
  996. Check.Check.typeOf.object("cartesian", cartesian);
  997. Check.Check.typeOf.object("result", result);
  998. //>>includeEnd('debug');
  999. var vX = cartesian.x;
  1000. var vY = cartesian.y;
  1001. var vZ = cartesian.z;
  1002. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  1003. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  1004. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  1005. result.x = x;
  1006. result.y = y;
  1007. result.z = z;
  1008. return result;
  1009. };
  1010. /**
  1011. * Computes the product of a matrix and a scalar.
  1012. *
  1013. * @param {Matrix3} matrix The matrix.
  1014. * @param {Number} scalar The number to multiply by.
  1015. * @param {Matrix3} result The object onto which to store the result.
  1016. * @returns {Matrix3} The modified result parameter.
  1017. */
  1018. Matrix3.multiplyByScalar = function (matrix, scalar, result) {
  1019. //>>includeStart('debug', pragmas.debug);
  1020. Check.Check.typeOf.object("matrix", matrix);
  1021. Check.Check.typeOf.number("scalar", scalar);
  1022. Check.Check.typeOf.object("result", result);
  1023. //>>includeEnd('debug');
  1024. result[0] = matrix[0] * scalar;
  1025. result[1] = matrix[1] * scalar;
  1026. result[2] = matrix[2] * scalar;
  1027. result[3] = matrix[3] * scalar;
  1028. result[4] = matrix[4] * scalar;
  1029. result[5] = matrix[5] * scalar;
  1030. result[6] = matrix[6] * scalar;
  1031. result[7] = matrix[7] * scalar;
  1032. result[8] = matrix[8] * scalar;
  1033. return result;
  1034. };
  1035. /**
  1036. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  1037. *
  1038. * @param {Matrix3} matrix The matrix on the left-hand side.
  1039. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  1040. * @param {Matrix3} result The object onto which to store the result.
  1041. * @returns {Matrix3} The modified result parameter.
  1042. *
  1043. *
  1044. * @example
  1045. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  1046. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  1047. *
  1048. * @see Matrix3.fromScale
  1049. * @see Matrix3.multiplyByUniformScale
  1050. */
  1051. Matrix3.multiplyByScale = function (matrix, scale, result) {
  1052. //>>includeStart('debug', pragmas.debug);
  1053. Check.Check.typeOf.object("matrix", matrix);
  1054. Check.Check.typeOf.object("scale", scale);
  1055. Check.Check.typeOf.object("result", result);
  1056. //>>includeEnd('debug');
  1057. result[0] = matrix[0] * scale.x;
  1058. result[1] = matrix[1] * scale.x;
  1059. result[2] = matrix[2] * scale.x;
  1060. result[3] = matrix[3] * scale.y;
  1061. result[4] = matrix[4] * scale.y;
  1062. result[5] = matrix[5] * scale.y;
  1063. result[6] = matrix[6] * scale.z;
  1064. result[7] = matrix[7] * scale.z;
  1065. result[8] = matrix[8] * scale.z;
  1066. return result;
  1067. };
  1068. /**
  1069. * Creates a negated copy of the provided matrix.
  1070. *
  1071. * @param {Matrix3} matrix The matrix to negate.
  1072. * @param {Matrix3} result The object onto which to store the result.
  1073. * @returns {Matrix3} The modified result parameter.
  1074. */
  1075. Matrix3.negate = function (matrix, result) {
  1076. //>>includeStart('debug', pragmas.debug);
  1077. Check.Check.typeOf.object("matrix", matrix);
  1078. Check.Check.typeOf.object("result", result);
  1079. //>>includeEnd('debug');
  1080. result[0] = -matrix[0];
  1081. result[1] = -matrix[1];
  1082. result[2] = -matrix[2];
  1083. result[3] = -matrix[3];
  1084. result[4] = -matrix[4];
  1085. result[5] = -matrix[5];
  1086. result[6] = -matrix[6];
  1087. result[7] = -matrix[7];
  1088. result[8] = -matrix[8];
  1089. return result;
  1090. };
  1091. /**
  1092. * Computes the transpose of the provided matrix.
  1093. *
  1094. * @param {Matrix3} matrix The matrix to transpose.
  1095. * @param {Matrix3} result The object onto which to store the result.
  1096. * @returns {Matrix3} The modified result parameter.
  1097. */
  1098. Matrix3.transpose = function (matrix, result) {
  1099. //>>includeStart('debug', pragmas.debug);
  1100. Check.Check.typeOf.object("matrix", matrix);
  1101. Check.Check.typeOf.object("result", result);
  1102. //>>includeEnd('debug');
  1103. var column0Row0 = matrix[0];
  1104. var column0Row1 = matrix[3];
  1105. var column0Row2 = matrix[6];
  1106. var column1Row0 = matrix[1];
  1107. var column1Row1 = matrix[4];
  1108. var column1Row2 = matrix[7];
  1109. var column2Row0 = matrix[2];
  1110. var column2Row1 = matrix[5];
  1111. var column2Row2 = matrix[8];
  1112. result[0] = column0Row0;
  1113. result[1] = column0Row1;
  1114. result[2] = column0Row2;
  1115. result[3] = column1Row0;
  1116. result[4] = column1Row1;
  1117. result[5] = column1Row2;
  1118. result[6] = column2Row0;
  1119. result[7] = column2Row1;
  1120. result[8] = column2Row2;
  1121. return result;
  1122. };
  1123. var UNIT = new Cartesian2.Cartesian3(1, 1, 1);
  1124. /**
  1125. * Extracts the rotation assuming the matrix is an affine transformation.
  1126. *
  1127. * @param {Matrix3} matrix The matrix.
  1128. * @param {Matrix3} result The object onto which to store the result.
  1129. * @returns {Matrix3} The modified result parameter
  1130. */
  1131. Matrix3.getRotation = function (matrix, result) {
  1132. //>>includeStart('debug', pragmas.debug);
  1133. Check.Check.typeOf.object("matrix", matrix);
  1134. Check.Check.typeOf.object("result", result);
  1135. //>>includeEnd('debug');
  1136. var inverseScale = Cartesian2.Cartesian3.divideComponents(
  1137. UNIT,
  1138. Matrix3.getScale(matrix, scratchScale),
  1139. scratchScale
  1140. );
  1141. result = Matrix3.multiplyByScale(matrix, inverseScale, result);
  1142. return result;
  1143. };
  1144. function computeFrobeniusNorm(matrix) {
  1145. var norm = 0.0;
  1146. for (var i = 0; i < 9; ++i) {
  1147. var temp = matrix[i];
  1148. norm += temp * temp;
  1149. }
  1150. return Math.sqrt(norm);
  1151. }
  1152. var rowVal = [1, 0, 0];
  1153. var colVal = [2, 2, 1];
  1154. function offDiagonalFrobeniusNorm(matrix) {
  1155. // Computes the "off-diagonal" Frobenius norm.
  1156. // Assumes matrix is symmetric.
  1157. var norm = 0.0;
  1158. for (var i = 0; i < 3; ++i) {
  1159. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  1160. norm += 2.0 * temp * temp;
  1161. }
  1162. return Math.sqrt(norm);
  1163. }
  1164. function shurDecomposition(matrix, result) {
  1165. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  1166. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  1167. //
  1168. // The routine takes a matrix, which is assumed to be symmetric, and
  1169. // finds the largest off-diagonal term, and then creates
  1170. // a matrix (result) which can be used to help reduce it
  1171. var tolerance = _Math.CesiumMath.EPSILON15;
  1172. var maxDiagonal = 0.0;
  1173. var rotAxis = 1;
  1174. // find pivot (rotAxis) based on max diagonal of matrix
  1175. for (var i = 0; i < 3; ++i) {
  1176. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  1177. if (temp > maxDiagonal) {
  1178. rotAxis = i;
  1179. maxDiagonal = temp;
  1180. }
  1181. }
  1182. var c = 1.0;
  1183. var s = 0.0;
  1184. var p = rowVal[rotAxis];
  1185. var q = colVal[rotAxis];
  1186. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  1187. var qq = matrix[Matrix3.getElementIndex(q, q)];
  1188. var pp = matrix[Matrix3.getElementIndex(p, p)];
  1189. var qp = matrix[Matrix3.getElementIndex(q, p)];
  1190. var tau = (qq - pp) / 2.0 / qp;
  1191. var t;
  1192. if (tau < 0.0) {
  1193. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  1194. } else {
  1195. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  1196. }
  1197. c = 1.0 / Math.sqrt(1.0 + t * t);
  1198. s = t * c;
  1199. }
  1200. result = Matrix3.clone(Matrix3.IDENTITY, result);
  1201. result[Matrix3.getElementIndex(p, p)] = result[
  1202. Matrix3.getElementIndex(q, q)
  1203. ] = c;
  1204. result[Matrix3.getElementIndex(q, p)] = s;
  1205. result[Matrix3.getElementIndex(p, q)] = -s;
  1206. return result;
  1207. }
  1208. var jMatrix = new Matrix3();
  1209. var jMatrixTranspose = new Matrix3();
  1210. /**
  1211. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  1212. * <p>
  1213. * Returns a diagonal matrix and unitary matrix such that:
  1214. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  1215. * </p>
  1216. * <p>
  1217. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  1218. * of the unitary matrix are the corresponding eigenvectors.
  1219. * </p>
  1220. *
  1221. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  1222. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  1223. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  1224. *
  1225. * @example
  1226. * var a = //... symetric matrix
  1227. * var result = {
  1228. * unitary : new Cesium.Matrix3(),
  1229. * diagonal : new Cesium.Matrix3()
  1230. * };
  1231. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  1232. *
  1233. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  1234. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  1235. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  1236. *
  1237. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  1238. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  1239. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  1240. */
  1241. Matrix3.computeEigenDecomposition = function (matrix, result) {
  1242. //>>includeStart('debug', pragmas.debug);
  1243. Check.Check.typeOf.object("matrix", matrix);
  1244. //>>includeEnd('debug');
  1245. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  1246. // section 8.4.3 The Classical Jacobi Algorithm
  1247. var tolerance = _Math.CesiumMath.EPSILON20;
  1248. var maxSweeps = 10;
  1249. var count = 0;
  1250. var sweep = 0;
  1251. if (!when.defined(result)) {
  1252. result = {};
  1253. }
  1254. var unitaryMatrix = (result.unitary = Matrix3.clone(
  1255. Matrix3.IDENTITY,
  1256. result.unitary
  1257. ));
  1258. var diagMatrix = (result.diagonal = Matrix3.clone(matrix, result.diagonal));
  1259. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  1260. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  1261. shurDecomposition(diagMatrix, jMatrix);
  1262. Matrix3.transpose(jMatrix, jMatrixTranspose);
  1263. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  1264. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  1265. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  1266. if (++count > 2) {
  1267. ++sweep;
  1268. count = 0;
  1269. }
  1270. }
  1271. return result;
  1272. };
  1273. /**
  1274. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  1275. *
  1276. * @param {Matrix3} matrix The matrix with signed elements.
  1277. * @param {Matrix3} result The object onto which to store the result.
  1278. * @returns {Matrix3} The modified result parameter.
  1279. */
  1280. Matrix3.abs = function (matrix, result) {
  1281. //>>includeStart('debug', pragmas.debug);
  1282. Check.Check.typeOf.object("matrix", matrix);
  1283. Check.Check.typeOf.object("result", result);
  1284. //>>includeEnd('debug');
  1285. result[0] = Math.abs(matrix[0]);
  1286. result[1] = Math.abs(matrix[1]);
  1287. result[2] = Math.abs(matrix[2]);
  1288. result[3] = Math.abs(matrix[3]);
  1289. result[4] = Math.abs(matrix[4]);
  1290. result[5] = Math.abs(matrix[5]);
  1291. result[6] = Math.abs(matrix[6]);
  1292. result[7] = Math.abs(matrix[7]);
  1293. result[8] = Math.abs(matrix[8]);
  1294. return result;
  1295. };
  1296. /**
  1297. * Computes the determinant of the provided matrix.
  1298. *
  1299. * @param {Matrix3} matrix The matrix to use.
  1300. * @returns {Number} The value of the determinant of the matrix.
  1301. */
  1302. Matrix3.determinant = function (matrix) {
  1303. //>>includeStart('debug', pragmas.debug);
  1304. Check.Check.typeOf.object("matrix", matrix);
  1305. //>>includeEnd('debug');
  1306. var m11 = matrix[0];
  1307. var m21 = matrix[3];
  1308. var m31 = matrix[6];
  1309. var m12 = matrix[1];
  1310. var m22 = matrix[4];
  1311. var m32 = matrix[7];
  1312. var m13 = matrix[2];
  1313. var m23 = matrix[5];
  1314. var m33 = matrix[8];
  1315. return (
  1316. m11 * (m22 * m33 - m23 * m32) +
  1317. m12 * (m23 * m31 - m21 * m33) +
  1318. m13 * (m21 * m32 - m22 * m31)
  1319. );
  1320. };
  1321. /**
  1322. * Computes the inverse of the provided matrix.
  1323. *
  1324. * @param {Matrix3} matrix The matrix to invert.
  1325. * @param {Matrix3} result The object onto which to store the result.
  1326. * @returns {Matrix3} The modified result parameter.
  1327. *
  1328. * @exception {DeveloperError} matrix is not invertible.
  1329. */
  1330. Matrix3.inverse = function (matrix, result) {
  1331. //>>includeStart('debug', pragmas.debug);
  1332. Check.Check.typeOf.object("matrix", matrix);
  1333. Check.Check.typeOf.object("result", result);
  1334. //>>includeEnd('debug');
  1335. var m11 = matrix[0];
  1336. var m21 = matrix[1];
  1337. var m31 = matrix[2];
  1338. var m12 = matrix[3];
  1339. var m22 = matrix[4];
  1340. var m32 = matrix[5];
  1341. var m13 = matrix[6];
  1342. var m23 = matrix[7];
  1343. var m33 = matrix[8];
  1344. var determinant = Matrix3.determinant(matrix);
  1345. //>>includeStart('debug', pragmas.debug);
  1346. if (Math.abs(determinant) <= _Math.CesiumMath.EPSILON15) {
  1347. throw new Check.DeveloperError("matrix is not invertible");
  1348. }
  1349. //>>includeEnd('debug');
  1350. result[0] = m22 * m33 - m23 * m32;
  1351. result[1] = m23 * m31 - m21 * m33;
  1352. result[2] = m21 * m32 - m22 * m31;
  1353. result[3] = m13 * m32 - m12 * m33;
  1354. result[4] = m11 * m33 - m13 * m31;
  1355. result[5] = m12 * m31 - m11 * m32;
  1356. result[6] = m12 * m23 - m13 * m22;
  1357. result[7] = m13 * m21 - m11 * m23;
  1358. result[8] = m11 * m22 - m12 * m21;
  1359. var scale = 1.0 / determinant;
  1360. return Matrix3.multiplyByScalar(result, scale, result);
  1361. };
  1362. /**
  1363. * Compares the provided matrices componentwise and returns
  1364. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1365. *
  1366. * @param {Matrix3} [left] The first matrix.
  1367. * @param {Matrix3} [right] The second matrix.
  1368. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1369. */
  1370. Matrix3.equals = function (left, right) {
  1371. return (
  1372. left === right ||
  1373. (when.defined(left) &&
  1374. when.defined(right) &&
  1375. left[0] === right[0] &&
  1376. left[1] === right[1] &&
  1377. left[2] === right[2] &&
  1378. left[3] === right[3] &&
  1379. left[4] === right[4] &&
  1380. left[5] === right[5] &&
  1381. left[6] === right[6] &&
  1382. left[7] === right[7] &&
  1383. left[8] === right[8])
  1384. );
  1385. };
  1386. /**
  1387. * Compares the provided matrices componentwise and returns
  1388. * <code>true</code> if they are within the provided epsilon,
  1389. * <code>false</code> otherwise.
  1390. *
  1391. * @param {Matrix3} [left] The first matrix.
  1392. * @param {Matrix3} [right] The second matrix.
  1393. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  1394. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  1395. */
  1396. Matrix3.equalsEpsilon = function (left, right, epsilon) {
  1397. epsilon = when.defaultValue(epsilon, 0);
  1398. return (
  1399. left === right ||
  1400. (when.defined(left) &&
  1401. when.defined(right) &&
  1402. Math.abs(left[0] - right[0]) <= epsilon &&
  1403. Math.abs(left[1] - right[1]) <= epsilon &&
  1404. Math.abs(left[2] - right[2]) <= epsilon &&
  1405. Math.abs(left[3] - right[3]) <= epsilon &&
  1406. Math.abs(left[4] - right[4]) <= epsilon &&
  1407. Math.abs(left[5] - right[5]) <= epsilon &&
  1408. Math.abs(left[6] - right[6]) <= epsilon &&
  1409. Math.abs(left[7] - right[7]) <= epsilon &&
  1410. Math.abs(left[8] - right[8]) <= epsilon)
  1411. );
  1412. };
  1413. /**
  1414. * An immutable Matrix3 instance initialized to the identity matrix.
  1415. *
  1416. * @type {Matrix3}
  1417. * @constant
  1418. */
  1419. Matrix3.IDENTITY = Object.freeze(
  1420. new Matrix3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
  1421. );
  1422. /**
  1423. * An immutable Matrix3 instance initialized to the zero matrix.
  1424. *
  1425. * @type {Matrix3}
  1426. * @constant
  1427. */
  1428. Matrix3.ZERO = Object.freeze(
  1429. new Matrix3(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
  1430. );
  1431. /**
  1432. * The index into Matrix3 for column 0, row 0.
  1433. *
  1434. * @type {Number}
  1435. * @constant
  1436. */
  1437. Matrix3.COLUMN0ROW0 = 0;
  1438. /**
  1439. * The index into Matrix3 for column 0, row 1.
  1440. *
  1441. * @type {Number}
  1442. * @constant
  1443. */
  1444. Matrix3.COLUMN0ROW1 = 1;
  1445. /**
  1446. * The index into Matrix3 for column 0, row 2.
  1447. *
  1448. * @type {Number}
  1449. * @constant
  1450. */
  1451. Matrix3.COLUMN0ROW2 = 2;
  1452. /**
  1453. * The index into Matrix3 for column 1, row 0.
  1454. *
  1455. * @type {Number}
  1456. * @constant
  1457. */
  1458. Matrix3.COLUMN1ROW0 = 3;
  1459. /**
  1460. * The index into Matrix3 for column 1, row 1.
  1461. *
  1462. * @type {Number}
  1463. * @constant
  1464. */
  1465. Matrix3.COLUMN1ROW1 = 4;
  1466. /**
  1467. * The index into Matrix3 for column 1, row 2.
  1468. *
  1469. * @type {Number}
  1470. * @constant
  1471. */
  1472. Matrix3.COLUMN1ROW2 = 5;
  1473. /**
  1474. * The index into Matrix3 for column 2, row 0.
  1475. *
  1476. * @type {Number}
  1477. * @constant
  1478. */
  1479. Matrix3.COLUMN2ROW0 = 6;
  1480. /**
  1481. * The index into Matrix3 for column 2, row 1.
  1482. *
  1483. * @type {Number}
  1484. * @constant
  1485. */
  1486. Matrix3.COLUMN2ROW1 = 7;
  1487. /**
  1488. * The index into Matrix3 for column 2, row 2.
  1489. *
  1490. * @type {Number}
  1491. * @constant
  1492. */
  1493. Matrix3.COLUMN2ROW2 = 8;
  1494. Object.defineProperties(Matrix3.prototype, {
  1495. /**
  1496. * Gets the number of items in the collection.
  1497. * @memberof Matrix3.prototype
  1498. *
  1499. * @type {Number}
  1500. */
  1501. length: {
  1502. get: function () {
  1503. return Matrix3.packedLength;
  1504. },
  1505. },
  1506. });
  1507. /**
  1508. * Duplicates the provided Matrix3 instance.
  1509. *
  1510. * @param {Matrix3} [result] The object onto which to store the result.
  1511. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  1512. */
  1513. Matrix3.prototype.clone = function (result) {
  1514. return Matrix3.clone(this, result);
  1515. };
  1516. /**
  1517. * Compares this matrix to the provided matrix componentwise and returns
  1518. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1519. *
  1520. * @param {Matrix3} [right] The right hand side matrix.
  1521. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  1522. */
  1523. Matrix3.prototype.equals = function (right) {
  1524. return Matrix3.equals(this, right);
  1525. };
  1526. /**
  1527. * @private
  1528. */
  1529. Matrix3.equalsArray = function (matrix, array, offset) {
  1530. return (
  1531. matrix[0] === array[offset] &&
  1532. matrix[1] === array[offset + 1] &&
  1533. matrix[2] === array[offset + 2] &&
  1534. matrix[3] === array[offset + 3] &&
  1535. matrix[4] === array[offset + 4] &&
  1536. matrix[5] === array[offset + 5] &&
  1537. matrix[6] === array[offset + 6] &&
  1538. matrix[7] === array[offset + 7] &&
  1539. matrix[8] === array[offset + 8]
  1540. );
  1541. };
  1542. /**
  1543. * Compares this matrix to the provided matrix componentwise and returns
  1544. * <code>true</code> if they are within the provided epsilon,
  1545. * <code>false</code> otherwise.
  1546. *
  1547. * @param {Matrix3} [right] The right hand side matrix.
  1548. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  1549. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  1550. */
  1551. Matrix3.prototype.equalsEpsilon = function (right, epsilon) {
  1552. return Matrix3.equalsEpsilon(this, right, epsilon);
  1553. };
  1554. /**
  1555. * Creates a string representing this Matrix with each row being
  1556. * on a separate line and in the format '(column0, column1, column2)'.
  1557. *
  1558. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  1559. */
  1560. Matrix3.prototype.toString = function () {
  1561. return (
  1562. "(" +
  1563. this[0] +
  1564. ", " +
  1565. this[3] +
  1566. ", " +
  1567. this[6] +
  1568. ")\n" +
  1569. "(" +
  1570. this[1] +
  1571. ", " +
  1572. this[4] +
  1573. ", " +
  1574. this[7] +
  1575. ")\n" +
  1576. "(" +
  1577. this[2] +
  1578. ", " +
  1579. this[5] +
  1580. ", " +
  1581. this[8] +
  1582. ")"
  1583. );
  1584. };
  1585. /**
  1586. * A 4D Cartesian point.
  1587. * @alias Cartesian4
  1588. * @constructor
  1589. *
  1590. * @param {Number} [x=0.0] The X component.
  1591. * @param {Number} [y=0.0] The Y component.
  1592. * @param {Number} [z=0.0] The Z component.
  1593. * @param {Number} [w=0.0] The W component.
  1594. *
  1595. * @see Cartesian2
  1596. * @see Cartesian3
  1597. * @see Packable
  1598. */
  1599. function Cartesian4(x, y, z, w) {
  1600. /**
  1601. * The X component.
  1602. * @type {Number}
  1603. * @default 0.0
  1604. */
  1605. this.x = when.defaultValue(x, 0.0);
  1606. /**
  1607. * The Y component.
  1608. * @type {Number}
  1609. * @default 0.0
  1610. */
  1611. this.y = when.defaultValue(y, 0.0);
  1612. /**
  1613. * The Z component.
  1614. * @type {Number}
  1615. * @default 0.0
  1616. */
  1617. this.z = when.defaultValue(z, 0.0);
  1618. /**
  1619. * The W component.
  1620. * @type {Number}
  1621. * @default 0.0
  1622. */
  1623. this.w = when.defaultValue(w, 0.0);
  1624. }
  1625. /**
  1626. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  1627. *
  1628. * @param {Number} x The x coordinate.
  1629. * @param {Number} y The y coordinate.
  1630. * @param {Number} z The z coordinate.
  1631. * @param {Number} w The w coordinate.
  1632. * @param {Cartesian4} [result] The object onto which to store the result.
  1633. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1634. */
  1635. Cartesian4.fromElements = function (x, y, z, w, result) {
  1636. if (!when.defined(result)) {
  1637. return new Cartesian4(x, y, z, w);
  1638. }
  1639. result.x = x;
  1640. result.y = y;
  1641. result.z = z;
  1642. result.w = w;
  1643. return result;
  1644. };
  1645. /**
  1646. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  1647. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  1648. *
  1649. * @param {Color} color The source color.
  1650. * @param {Cartesian4} [result] The object onto which to store the result.
  1651. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1652. */
  1653. Cartesian4.fromColor = function (color, result) {
  1654. //>>includeStart('debug', pragmas.debug);
  1655. Check.Check.typeOf.object("color", color);
  1656. //>>includeEnd('debug');
  1657. if (!when.defined(result)) {
  1658. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  1659. }
  1660. result.x = color.red;
  1661. result.y = color.green;
  1662. result.z = color.blue;
  1663. result.w = color.alpha;
  1664. return result;
  1665. };
  1666. /**
  1667. * Duplicates a Cartesian4 instance.
  1668. *
  1669. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  1670. * @param {Cartesian4} [result] The object onto which to store the result.
  1671. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  1672. */
  1673. Cartesian4.clone = function (cartesian, result) {
  1674. if (!when.defined(cartesian)) {
  1675. return undefined;
  1676. }
  1677. if (!when.defined(result)) {
  1678. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  1679. }
  1680. result.x = cartesian.x;
  1681. result.y = cartesian.y;
  1682. result.z = cartesian.z;
  1683. result.w = cartesian.w;
  1684. return result;
  1685. };
  1686. /**
  1687. * The number of elements used to pack the object into an array.
  1688. * @type {Number}
  1689. */
  1690. Cartesian4.packedLength = 4;
  1691. /**
  1692. * Stores the provided instance into the provided array.
  1693. *
  1694. * @param {Cartesian4} value The value to pack.
  1695. * @param {Number[]} array The array to pack into.
  1696. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  1697. *
  1698. * @returns {Number[]} The array that was packed into
  1699. */
  1700. Cartesian4.pack = function (value, array, startingIndex) {
  1701. //>>includeStart('debug', pragmas.debug);
  1702. Check.Check.typeOf.object("value", value);
  1703. Check.Check.defined("array", array);
  1704. //>>includeEnd('debug');
  1705. startingIndex = when.defaultValue(startingIndex, 0);
  1706. array[startingIndex++] = value.x;
  1707. array[startingIndex++] = value.y;
  1708. array[startingIndex++] = value.z;
  1709. array[startingIndex] = value.w;
  1710. return array;
  1711. };
  1712. /**
  1713. * Retrieves an instance from a packed array.
  1714. *
  1715. * @param {Number[]} array The packed array.
  1716. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  1717. * @param {Cartesian4} [result] The object into which to store the result.
  1718. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1719. */
  1720. Cartesian4.unpack = function (array, startingIndex, result) {
  1721. //>>includeStart('debug', pragmas.debug);
  1722. Check.Check.defined("array", array);
  1723. //>>includeEnd('debug');
  1724. startingIndex = when.defaultValue(startingIndex, 0);
  1725. if (!when.defined(result)) {
  1726. result = new Cartesian4();
  1727. }
  1728. result.x = array[startingIndex++];
  1729. result.y = array[startingIndex++];
  1730. result.z = array[startingIndex++];
  1731. result.w = array[startingIndex];
  1732. return result;
  1733. };
  1734. /**
  1735. * Flattens an array of Cartesian4s into and array of components.
  1736. *
  1737. * @param {Cartesian4[]} array The array of cartesians to pack.
  1738. * @param {Number[]} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 4 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 4) elements.
  1739. * @returns {Number[]} The packed array.
  1740. */
  1741. Cartesian4.packArray = function (array, result) {
  1742. //>>includeStart('debug', pragmas.debug);
  1743. Check.Check.defined("array", array);
  1744. //>>includeEnd('debug');
  1745. var length = array.length;
  1746. var resultLength = length * 4;
  1747. if (!when.defined(result)) {
  1748. result = new Array(resultLength);
  1749. } else if (!Array.isArray(result) && result.length !== resultLength) {
  1750. throw new Check.DeveloperError(
  1751. "If result is a typed array, it must have exactly array.length * 4 elements"
  1752. );
  1753. } else if (result.length !== resultLength) {
  1754. result.length = resultLength;
  1755. }
  1756. for (var i = 0; i < length; ++i) {
  1757. Cartesian4.pack(array[i], result, i * 4);
  1758. }
  1759. return result;
  1760. };
  1761. /**
  1762. * Unpacks an array of cartesian components into and array of Cartesian4s.
  1763. *
  1764. * @param {Number[]} array The array of components to unpack.
  1765. * @param {Cartesian4[]} [result] The array onto which to store the result.
  1766. * @returns {Cartesian4[]} The unpacked array.
  1767. */
  1768. Cartesian4.unpackArray = function (array, result) {
  1769. //>>includeStart('debug', pragmas.debug);
  1770. Check.Check.defined("array", array);
  1771. Check.Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 4);
  1772. if (array.length % 4 !== 0) {
  1773. throw new Check.DeveloperError("array length must be a multiple of 4.");
  1774. }
  1775. //>>includeEnd('debug');
  1776. var length = array.length;
  1777. if (!when.defined(result)) {
  1778. result = new Array(length / 4);
  1779. } else {
  1780. result.length = length / 4;
  1781. }
  1782. for (var i = 0; i < length; i += 4) {
  1783. var index = i / 4;
  1784. result[index] = Cartesian4.unpack(array, i, result[index]);
  1785. }
  1786. return result;
  1787. };
  1788. /**
  1789. * Creates a Cartesian4 from four consecutive elements in an array.
  1790. * @function
  1791. *
  1792. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  1793. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  1794. * @param {Cartesian4} [result] The object onto which to store the result.
  1795. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1796. *
  1797. * @example
  1798. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  1799. * var v = [1.0, 2.0, 3.0, 4.0];
  1800. * var p = Cesium.Cartesian4.fromArray(v);
  1801. *
  1802. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  1803. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  1804. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  1805. */
  1806. Cartesian4.fromArray = Cartesian4.unpack;
  1807. /**
  1808. * Computes the value of the maximum component for the supplied Cartesian.
  1809. *
  1810. * @param {Cartesian4} cartesian The cartesian to use.
  1811. * @returns {Number} The value of the maximum component.
  1812. */
  1813. Cartesian4.maximumComponent = function (cartesian) {
  1814. //>>includeStart('debug', pragmas.debug);
  1815. Check.Check.typeOf.object("cartesian", cartesian);
  1816. //>>includeEnd('debug');
  1817. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  1818. };
  1819. /**
  1820. * Computes the value of the minimum component for the supplied Cartesian.
  1821. *
  1822. * @param {Cartesian4} cartesian The cartesian to use.
  1823. * @returns {Number} The value of the minimum component.
  1824. */
  1825. Cartesian4.minimumComponent = function (cartesian) {
  1826. //>>includeStart('debug', pragmas.debug);
  1827. Check.Check.typeOf.object("cartesian", cartesian);
  1828. //>>includeEnd('debug');
  1829. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  1830. };
  1831. /**
  1832. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  1833. *
  1834. * @param {Cartesian4} first A cartesian to compare.
  1835. * @param {Cartesian4} second A cartesian to compare.
  1836. * @param {Cartesian4} result The object into which to store the result.
  1837. * @returns {Cartesian4} A cartesian with the minimum components.
  1838. */
  1839. Cartesian4.minimumByComponent = function (first, second, result) {
  1840. //>>includeStart('debug', pragmas.debug);
  1841. Check.Check.typeOf.object("first", first);
  1842. Check.Check.typeOf.object("second", second);
  1843. Check.Check.typeOf.object("result", result);
  1844. //>>includeEnd('debug');
  1845. result.x = Math.min(first.x, second.x);
  1846. result.y = Math.min(first.y, second.y);
  1847. result.z = Math.min(first.z, second.z);
  1848. result.w = Math.min(first.w, second.w);
  1849. return result;
  1850. };
  1851. /**
  1852. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  1853. *
  1854. * @param {Cartesian4} first A cartesian to compare.
  1855. * @param {Cartesian4} second A cartesian to compare.
  1856. * @param {Cartesian4} result The object into which to store the result.
  1857. * @returns {Cartesian4} A cartesian with the maximum components.
  1858. */
  1859. Cartesian4.maximumByComponent = function (first, second, result) {
  1860. //>>includeStart('debug', pragmas.debug);
  1861. Check.Check.typeOf.object("first", first);
  1862. Check.Check.typeOf.object("second", second);
  1863. Check.Check.typeOf.object("result", result);
  1864. //>>includeEnd('debug');
  1865. result.x = Math.max(first.x, second.x);
  1866. result.y = Math.max(first.y, second.y);
  1867. result.z = Math.max(first.z, second.z);
  1868. result.w = Math.max(first.w, second.w);
  1869. return result;
  1870. };
  1871. /**
  1872. * Computes the provided Cartesian's squared magnitude.
  1873. *
  1874. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  1875. * @returns {Number} The squared magnitude.
  1876. */
  1877. Cartesian4.magnitudeSquared = function (cartesian) {
  1878. //>>includeStart('debug', pragmas.debug);
  1879. Check.Check.typeOf.object("cartesian", cartesian);
  1880. //>>includeEnd('debug');
  1881. return (
  1882. cartesian.x * cartesian.x +
  1883. cartesian.y * cartesian.y +
  1884. cartesian.z * cartesian.z +
  1885. cartesian.w * cartesian.w
  1886. );
  1887. };
  1888. /**
  1889. * Computes the Cartesian's magnitude (length).
  1890. *
  1891. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  1892. * @returns {Number} The magnitude.
  1893. */
  1894. Cartesian4.magnitude = function (cartesian) {
  1895. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  1896. };
  1897. var distanceScratch = new Cartesian4();
  1898. /**
  1899. * Computes the 4-space distance between two points.
  1900. *
  1901. * @param {Cartesian4} left The first point to compute the distance from.
  1902. * @param {Cartesian4} right The second point to compute the distance to.
  1903. * @returns {Number} The distance between two points.
  1904. *
  1905. * @example
  1906. * // Returns 1.0
  1907. * var d = Cesium.Cartesian4.distance(
  1908. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  1909. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  1910. */
  1911. Cartesian4.distance = function (left, right) {
  1912. //>>includeStart('debug', pragmas.debug);
  1913. Check.Check.typeOf.object("left", left);
  1914. Check.Check.typeOf.object("right", right);
  1915. //>>includeEnd('debug');
  1916. Cartesian4.subtract(left, right, distanceScratch);
  1917. return Cartesian4.magnitude(distanceScratch);
  1918. };
  1919. /**
  1920. * Computes the squared distance between two points. Comparing squared distances
  1921. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  1922. *
  1923. * @param {Cartesian4} left The first point to compute the distance from.
  1924. * @param {Cartesian4} right The second point to compute the distance to.
  1925. * @returns {Number} The distance between two points.
  1926. *
  1927. * @example
  1928. * // Returns 4.0, not 2.0
  1929. * var d = Cesium.Cartesian4.distance(
  1930. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  1931. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  1932. */
  1933. Cartesian4.distanceSquared = function (left, right) {
  1934. //>>includeStart('debug', pragmas.debug);
  1935. Check.Check.typeOf.object("left", left);
  1936. Check.Check.typeOf.object("right", right);
  1937. //>>includeEnd('debug');
  1938. Cartesian4.subtract(left, right, distanceScratch);
  1939. return Cartesian4.magnitudeSquared(distanceScratch);
  1940. };
  1941. /**
  1942. * Computes the normalized form of the supplied Cartesian.
  1943. *
  1944. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  1945. * @param {Cartesian4} result The object onto which to store the result.
  1946. * @returns {Cartesian4} The modified result parameter.
  1947. */
  1948. Cartesian4.normalize = function (cartesian, result) {
  1949. //>>includeStart('debug', pragmas.debug);
  1950. Check.Check.typeOf.object("cartesian", cartesian);
  1951. Check.Check.typeOf.object("result", result);
  1952. //>>includeEnd('debug');
  1953. var magnitude = Cartesian4.magnitude(cartesian);
  1954. result.x = cartesian.x / magnitude;
  1955. result.y = cartesian.y / magnitude;
  1956. result.z = cartesian.z / magnitude;
  1957. result.w = cartesian.w / magnitude;
  1958. //>>includeStart('debug', pragmas.debug);
  1959. if (
  1960. isNaN(result.x) ||
  1961. isNaN(result.y) ||
  1962. isNaN(result.z) ||
  1963. isNaN(result.w)
  1964. ) {
  1965. throw new Check.DeveloperError("normalized result is not a number");
  1966. }
  1967. //>>includeEnd('debug');
  1968. return result;
  1969. };
  1970. /**
  1971. * Computes the dot (scalar) product of two Cartesians.
  1972. *
  1973. * @param {Cartesian4} left The first Cartesian.
  1974. * @param {Cartesian4} right The second Cartesian.
  1975. * @returns {Number} The dot product.
  1976. */
  1977. Cartesian4.dot = function (left, right) {
  1978. //>>includeStart('debug', pragmas.debug);
  1979. Check.Check.typeOf.object("left", left);
  1980. Check.Check.typeOf.object("right", right);
  1981. //>>includeEnd('debug');
  1982. return (
  1983. left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
  1984. );
  1985. };
  1986. /**
  1987. * Computes the componentwise product of two Cartesians.
  1988. *
  1989. * @param {Cartesian4} left The first Cartesian.
  1990. * @param {Cartesian4} right The second Cartesian.
  1991. * @param {Cartesian4} result The object onto which to store the result.
  1992. * @returns {Cartesian4} The modified result parameter.
  1993. */
  1994. Cartesian4.multiplyComponents = function (left, right, result) {
  1995. //>>includeStart('debug', pragmas.debug);
  1996. Check.Check.typeOf.object("left", left);
  1997. Check.Check.typeOf.object("right", right);
  1998. Check.Check.typeOf.object("result", result);
  1999. //>>includeEnd('debug');
  2000. result.x = left.x * right.x;
  2001. result.y = left.y * right.y;
  2002. result.z = left.z * right.z;
  2003. result.w = left.w * right.w;
  2004. return result;
  2005. };
  2006. /**
  2007. * Computes the componentwise quotient of two Cartesians.
  2008. *
  2009. * @param {Cartesian4} left The first Cartesian.
  2010. * @param {Cartesian4} right The second Cartesian.
  2011. * @param {Cartesian4} result The object onto which to store the result.
  2012. * @returns {Cartesian4} The modified result parameter.
  2013. */
  2014. Cartesian4.divideComponents = function (left, right, result) {
  2015. //>>includeStart('debug', pragmas.debug);
  2016. Check.Check.typeOf.object("left", left);
  2017. Check.Check.typeOf.object("right", right);
  2018. Check.Check.typeOf.object("result", result);
  2019. //>>includeEnd('debug');
  2020. result.x = left.x / right.x;
  2021. result.y = left.y / right.y;
  2022. result.z = left.z / right.z;
  2023. result.w = left.w / right.w;
  2024. return result;
  2025. };
  2026. /**
  2027. * Computes the componentwise sum of two Cartesians.
  2028. *
  2029. * @param {Cartesian4} left The first Cartesian.
  2030. * @param {Cartesian4} right The second Cartesian.
  2031. * @param {Cartesian4} result The object onto which to store the result.
  2032. * @returns {Cartesian4} The modified result parameter.
  2033. */
  2034. Cartesian4.add = function (left, right, result) {
  2035. //>>includeStart('debug', pragmas.debug);
  2036. Check.Check.typeOf.object("left", left);
  2037. Check.Check.typeOf.object("right", right);
  2038. Check.Check.typeOf.object("result", result);
  2039. //>>includeEnd('debug');
  2040. result.x = left.x + right.x;
  2041. result.y = left.y + right.y;
  2042. result.z = left.z + right.z;
  2043. result.w = left.w + right.w;
  2044. return result;
  2045. };
  2046. /**
  2047. * Computes the componentwise difference of two Cartesians.
  2048. *
  2049. * @param {Cartesian4} left The first Cartesian.
  2050. * @param {Cartesian4} right The second Cartesian.
  2051. * @param {Cartesian4} result The object onto which to store the result.
  2052. * @returns {Cartesian4} The modified result parameter.
  2053. */
  2054. Cartesian4.subtract = function (left, right, result) {
  2055. //>>includeStart('debug', pragmas.debug);
  2056. Check.Check.typeOf.object("left", left);
  2057. Check.Check.typeOf.object("right", right);
  2058. Check.Check.typeOf.object("result", result);
  2059. //>>includeEnd('debug');
  2060. result.x = left.x - right.x;
  2061. result.y = left.y - right.y;
  2062. result.z = left.z - right.z;
  2063. result.w = left.w - right.w;
  2064. return result;
  2065. };
  2066. /**
  2067. * Multiplies the provided Cartesian componentwise by the provided scalar.
  2068. *
  2069. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  2070. * @param {Number} scalar The scalar to multiply with.
  2071. * @param {Cartesian4} result The object onto which to store the result.
  2072. * @returns {Cartesian4} The modified result parameter.
  2073. */
  2074. Cartesian4.multiplyByScalar = function (cartesian, scalar, result) {
  2075. //>>includeStart('debug', pragmas.debug);
  2076. Check.Check.typeOf.object("cartesian", cartesian);
  2077. Check.Check.typeOf.number("scalar", scalar);
  2078. Check.Check.typeOf.object("result", result);
  2079. //>>includeEnd('debug');
  2080. result.x = cartesian.x * scalar;
  2081. result.y = cartesian.y * scalar;
  2082. result.z = cartesian.z * scalar;
  2083. result.w = cartesian.w * scalar;
  2084. return result;
  2085. };
  2086. /**
  2087. * Divides the provided Cartesian componentwise by the provided scalar.
  2088. *
  2089. * @param {Cartesian4} cartesian The Cartesian to be divided.
  2090. * @param {Number} scalar The scalar to divide by.
  2091. * @param {Cartesian4} result The object onto which to store the result.
  2092. * @returns {Cartesian4} The modified result parameter.
  2093. */
  2094. Cartesian4.divideByScalar = function (cartesian, scalar, result) {
  2095. //>>includeStart('debug', pragmas.debug);
  2096. Check.Check.typeOf.object("cartesian", cartesian);
  2097. Check.Check.typeOf.number("scalar", scalar);
  2098. Check.Check.typeOf.object("result", result);
  2099. //>>includeEnd('debug');
  2100. result.x = cartesian.x / scalar;
  2101. result.y = cartesian.y / scalar;
  2102. result.z = cartesian.z / scalar;
  2103. result.w = cartesian.w / scalar;
  2104. return result;
  2105. };
  2106. /**
  2107. * Negates the provided Cartesian.
  2108. *
  2109. * @param {Cartesian4} cartesian The Cartesian to be negated.
  2110. * @param {Cartesian4} result The object onto which to store the result.
  2111. * @returns {Cartesian4} The modified result parameter.
  2112. */
  2113. Cartesian4.negate = function (cartesian, result) {
  2114. //>>includeStart('debug', pragmas.debug);
  2115. Check.Check.typeOf.object("cartesian", cartesian);
  2116. Check.Check.typeOf.object("result", result);
  2117. //>>includeEnd('debug');
  2118. result.x = -cartesian.x;
  2119. result.y = -cartesian.y;
  2120. result.z = -cartesian.z;
  2121. result.w = -cartesian.w;
  2122. return result;
  2123. };
  2124. /**
  2125. * Computes the absolute value of the provided Cartesian.
  2126. *
  2127. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  2128. * @param {Cartesian4} result The object onto which to store the result.
  2129. * @returns {Cartesian4} The modified result parameter.
  2130. */
  2131. Cartesian4.abs = function (cartesian, result) {
  2132. //>>includeStart('debug', pragmas.debug);
  2133. Check.Check.typeOf.object("cartesian", cartesian);
  2134. Check.Check.typeOf.object("result", result);
  2135. //>>includeEnd('debug');
  2136. result.x = Math.abs(cartesian.x);
  2137. result.y = Math.abs(cartesian.y);
  2138. result.z = Math.abs(cartesian.z);
  2139. result.w = Math.abs(cartesian.w);
  2140. return result;
  2141. };
  2142. var lerpScratch = new Cartesian4();
  2143. /**
  2144. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  2145. *
  2146. * @param {Cartesian4} start The value corresponding to t at 0.0.
  2147. * @param {Cartesian4}end The value corresponding to t at 1.0.
  2148. * @param {Number} t The point along t at which to interpolate.
  2149. * @param {Cartesian4} result The object onto which to store the result.
  2150. * @returns {Cartesian4} The modified result parameter.
  2151. */
  2152. Cartesian4.lerp = function (start, end, t, result) {
  2153. //>>includeStart('debug', pragmas.debug);
  2154. Check.Check.typeOf.object("start", start);
  2155. Check.Check.typeOf.object("end", end);
  2156. Check.Check.typeOf.number("t", t);
  2157. Check.Check.typeOf.object("result", result);
  2158. //>>includeEnd('debug');
  2159. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  2160. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  2161. return Cartesian4.add(lerpScratch, result, result);
  2162. };
  2163. var mostOrthogonalAxisScratch = new Cartesian4();
  2164. /**
  2165. * Returns the axis that is most orthogonal to the provided Cartesian.
  2166. *
  2167. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  2168. * @param {Cartesian4} result The object onto which to store the result.
  2169. * @returns {Cartesian4} The most orthogonal axis.
  2170. */
  2171. Cartesian4.mostOrthogonalAxis = function (cartesian, result) {
  2172. //>>includeStart('debug', pragmas.debug);
  2173. Check.Check.typeOf.object("cartesian", cartesian);
  2174. Check.Check.typeOf.object("result", result);
  2175. //>>includeEnd('debug');
  2176. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  2177. Cartesian4.abs(f, f);
  2178. if (f.x <= f.y) {
  2179. if (f.x <= f.z) {
  2180. if (f.x <= f.w) {
  2181. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  2182. } else {
  2183. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2184. }
  2185. } else if (f.z <= f.w) {
  2186. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  2187. } else {
  2188. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2189. }
  2190. } else if (f.y <= f.z) {
  2191. if (f.y <= f.w) {
  2192. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  2193. } else {
  2194. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2195. }
  2196. } else if (f.z <= f.w) {
  2197. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  2198. } else {
  2199. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2200. }
  2201. return result;
  2202. };
  2203. /**
  2204. * Compares the provided Cartesians componentwise and returns
  2205. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2206. *
  2207. * @param {Cartesian4} [left] The first Cartesian.
  2208. * @param {Cartesian4} [right] The second Cartesian.
  2209. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2210. */
  2211. Cartesian4.equals = function (left, right) {
  2212. return (
  2213. left === right ||
  2214. (when.defined(left) &&
  2215. when.defined(right) &&
  2216. left.x === right.x &&
  2217. left.y === right.y &&
  2218. left.z === right.z &&
  2219. left.w === right.w)
  2220. );
  2221. };
  2222. /**
  2223. * @private
  2224. */
  2225. Cartesian4.equalsArray = function (cartesian, array, offset) {
  2226. return (
  2227. cartesian.x === array[offset] &&
  2228. cartesian.y === array[offset + 1] &&
  2229. cartesian.z === array[offset + 2] &&
  2230. cartesian.w === array[offset + 3]
  2231. );
  2232. };
  2233. /**
  2234. * Compares the provided Cartesians componentwise and returns
  2235. * <code>true</code> if they pass an absolute or relative tolerance test,
  2236. * <code>false</code> otherwise.
  2237. *
  2238. * @param {Cartesian4} [left] The first Cartesian.
  2239. * @param {Cartesian4} [right] The second Cartesian.
  2240. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  2241. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2242. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2243. */
  2244. Cartesian4.equalsEpsilon = function (
  2245. left,
  2246. right,
  2247. relativeEpsilon,
  2248. absoluteEpsilon
  2249. ) {
  2250. return (
  2251. left === right ||
  2252. (when.defined(left) &&
  2253. when.defined(right) &&
  2254. _Math.CesiumMath.equalsEpsilon(
  2255. left.x,
  2256. right.x,
  2257. relativeEpsilon,
  2258. absoluteEpsilon
  2259. ) &&
  2260. _Math.CesiumMath.equalsEpsilon(
  2261. left.y,
  2262. right.y,
  2263. relativeEpsilon,
  2264. absoluteEpsilon
  2265. ) &&
  2266. _Math.CesiumMath.equalsEpsilon(
  2267. left.z,
  2268. right.z,
  2269. relativeEpsilon,
  2270. absoluteEpsilon
  2271. ) &&
  2272. _Math.CesiumMath.equalsEpsilon(
  2273. left.w,
  2274. right.w,
  2275. relativeEpsilon,
  2276. absoluteEpsilon
  2277. ))
  2278. );
  2279. };
  2280. /**
  2281. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  2282. *
  2283. * @type {Cartesian4}
  2284. * @constant
  2285. */
  2286. Cartesian4.ZERO = Object.freeze(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  2287. /**
  2288. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  2289. *
  2290. * @type {Cartesian4}
  2291. * @constant
  2292. */
  2293. Cartesian4.UNIT_X = Object.freeze(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  2294. /**
  2295. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  2296. *
  2297. * @type {Cartesian4}
  2298. * @constant
  2299. */
  2300. Cartesian4.UNIT_Y = Object.freeze(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  2301. /**
  2302. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  2303. *
  2304. * @type {Cartesian4}
  2305. * @constant
  2306. */
  2307. Cartesian4.UNIT_Z = Object.freeze(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  2308. /**
  2309. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  2310. *
  2311. * @type {Cartesian4}
  2312. * @constant
  2313. */
  2314. Cartesian4.UNIT_W = Object.freeze(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  2315. /**
  2316. * Duplicates this Cartesian4 instance.
  2317. *
  2318. * @param {Cartesian4} [result] The object onto which to store the result.
  2319. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  2320. */
  2321. Cartesian4.prototype.clone = function (result) {
  2322. return Cartesian4.clone(this, result);
  2323. };
  2324. /**
  2325. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2326. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2327. *
  2328. * @param {Cartesian4} [right] The right hand side Cartesian.
  2329. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  2330. */
  2331. Cartesian4.prototype.equals = function (right) {
  2332. return Cartesian4.equals(this, right);
  2333. };
  2334. /**
  2335. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2336. * <code>true</code> if they pass an absolute or relative tolerance test,
  2337. * <code>false</code> otherwise.
  2338. *
  2339. * @param {Cartesian4} [right] The right hand side Cartesian.
  2340. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  2341. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2342. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  2343. */
  2344. Cartesian4.prototype.equalsEpsilon = function (
  2345. right,
  2346. relativeEpsilon,
  2347. absoluteEpsilon
  2348. ) {
  2349. return Cartesian4.equalsEpsilon(
  2350. this,
  2351. right,
  2352. relativeEpsilon,
  2353. absoluteEpsilon
  2354. );
  2355. };
  2356. /**
  2357. * Creates a string representing this Cartesian in the format '(x, y, z, w)'.
  2358. *
  2359. * @returns {String} A string representing the provided Cartesian in the format '(x, y, z, w)'.
  2360. */
  2361. Cartesian4.prototype.toString = function () {
  2362. return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")";
  2363. };
  2364. var scratchFloatArray = new Float32Array(1);
  2365. var SHIFT_LEFT_8 = 256.0;
  2366. var SHIFT_LEFT_16 = 65536.0;
  2367. var SHIFT_LEFT_24 = 16777216.0;
  2368. var SHIFT_RIGHT_8 = 1.0 / SHIFT_LEFT_8;
  2369. var SHIFT_RIGHT_16 = 1.0 / SHIFT_LEFT_16;
  2370. var SHIFT_RIGHT_24 = 1.0 / SHIFT_LEFT_24;
  2371. var BIAS = 38.0;
  2372. /**
  2373. * Packs an arbitrary floating point value to 4 values representable using uint8.
  2374. *
  2375. * @param {Number} value A floating point number
  2376. * @param {Cartesian4} [result] The Cartesian4 that will contain the packed float.
  2377. * @returns {Cartesian4} A Cartesian4 representing the float packed to values in x, y, z, and w.
  2378. */
  2379. Cartesian4.packFloat = function (value, result) {
  2380. //>>includeStart('debug', pragmas.debug);
  2381. Check.Check.typeOf.number("value", value);
  2382. //>>includeEnd('debug');
  2383. if (!when.defined(result)) {
  2384. result = new Cartesian4();
  2385. }
  2386. // Force the value to 32 bit precision
  2387. scratchFloatArray[0] = value;
  2388. value = scratchFloatArray[0];
  2389. if (value === 0.0) {
  2390. return Cartesian4.clone(Cartesian4.ZERO, result);
  2391. }
  2392. var sign = value < 0.0 ? 1.0 : 0.0;
  2393. var exponent;
  2394. if (!isFinite(value)) {
  2395. value = 0.1;
  2396. exponent = BIAS;
  2397. } else {
  2398. value = Math.abs(value);
  2399. exponent = Math.floor(_Math.CesiumMath.logBase(value, 10)) + 1.0;
  2400. value = value / Math.pow(10.0, exponent);
  2401. }
  2402. var temp = value * SHIFT_LEFT_8;
  2403. result.x = Math.floor(temp);
  2404. temp = (temp - result.x) * SHIFT_LEFT_8;
  2405. result.y = Math.floor(temp);
  2406. temp = (temp - result.y) * SHIFT_LEFT_8;
  2407. result.z = Math.floor(temp);
  2408. result.w = (exponent + BIAS) * 2.0 + sign;
  2409. return result;
  2410. };
  2411. /**
  2412. * Unpacks a float packed using Cartesian4.packFloat.
  2413. *
  2414. * @param {Cartesian4} packedFloat A Cartesian4 containing a float packed to 4 values representable using uint8.
  2415. * @returns {Number} The unpacked float.
  2416. * @private
  2417. */
  2418. Cartesian4.unpackFloat = function (packedFloat) {
  2419. //>>includeStart('debug', pragmas.debug);
  2420. Check.Check.typeOf.object("packedFloat", packedFloat);
  2421. //>>includeEnd('debug');
  2422. var temp = packedFloat.w / 2.0;
  2423. var exponent = Math.floor(temp);
  2424. var sign = (temp - exponent) * 2.0;
  2425. exponent = exponent - BIAS;
  2426. sign = sign * 2.0 - 1.0;
  2427. sign = -sign;
  2428. if (exponent >= BIAS) {
  2429. return sign < 0.0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
  2430. }
  2431. var unpacked = sign * packedFloat.x * SHIFT_RIGHT_8;
  2432. unpacked += sign * packedFloat.y * SHIFT_RIGHT_16;
  2433. unpacked += sign * packedFloat.z * SHIFT_RIGHT_24;
  2434. return unpacked * Math.pow(10.0, exponent);
  2435. };
  2436. /**
  2437. * A 4x4 matrix, indexable as a column-major order array.
  2438. * Constructor parameters are in row-major order for code readability.
  2439. * @alias Matrix4
  2440. * @constructor
  2441. * @implements {ArrayLike<number>}
  2442. *
  2443. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  2444. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  2445. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  2446. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  2447. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  2448. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  2449. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  2450. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  2451. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  2452. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  2453. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  2454. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  2455. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  2456. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  2457. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  2458. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  2459. *
  2460. * @see Matrix4.fromColumnMajorArray
  2461. * @see Matrix4.fromRowMajorArray
  2462. * @see Matrix4.fromRotationTranslation
  2463. * @see Matrix4.fromTranslationRotationScale
  2464. * @see Matrix4.fromTranslationQuaternionRotationScale
  2465. * @see Matrix4.fromTranslation
  2466. * @see Matrix4.fromScale
  2467. * @see Matrix4.fromUniformScale
  2468. * @see Matrix4.fromCamera
  2469. * @see Matrix4.computePerspectiveFieldOfView
  2470. * @see Matrix4.computeOrthographicOffCenter
  2471. * @see Matrix4.computePerspectiveOffCenter
  2472. * @see Matrix4.computeInfinitePerspectiveOffCenter
  2473. * @see Matrix4.computeViewportTransformation
  2474. * @see Matrix4.computeView
  2475. * @see Matrix2
  2476. * @see Matrix3
  2477. * @see Packable
  2478. */
  2479. function Matrix4(
  2480. column0Row0,
  2481. column1Row0,
  2482. column2Row0,
  2483. column3Row0,
  2484. column0Row1,
  2485. column1Row1,
  2486. column2Row1,
  2487. column3Row1,
  2488. column0Row2,
  2489. column1Row2,
  2490. column2Row2,
  2491. column3Row2,
  2492. column0Row3,
  2493. column1Row3,
  2494. column2Row3,
  2495. column3Row3
  2496. ) {
  2497. this[0] = when.defaultValue(column0Row0, 0.0);
  2498. this[1] = when.defaultValue(column0Row1, 0.0);
  2499. this[2] = when.defaultValue(column0Row2, 0.0);
  2500. this[3] = when.defaultValue(column0Row3, 0.0);
  2501. this[4] = when.defaultValue(column1Row0, 0.0);
  2502. this[5] = when.defaultValue(column1Row1, 0.0);
  2503. this[6] = when.defaultValue(column1Row2, 0.0);
  2504. this[7] = when.defaultValue(column1Row3, 0.0);
  2505. this[8] = when.defaultValue(column2Row0, 0.0);
  2506. this[9] = when.defaultValue(column2Row1, 0.0);
  2507. this[10] = when.defaultValue(column2Row2, 0.0);
  2508. this[11] = when.defaultValue(column2Row3, 0.0);
  2509. this[12] = when.defaultValue(column3Row0, 0.0);
  2510. this[13] = when.defaultValue(column3Row1, 0.0);
  2511. this[14] = when.defaultValue(column3Row2, 0.0);
  2512. this[15] = when.defaultValue(column3Row3, 0.0);
  2513. }
  2514. /**
  2515. * The number of elements used to pack the object into an array.
  2516. * @type {Number}
  2517. */
  2518. Matrix4.packedLength = 16;
  2519. /**
  2520. * Stores the provided instance into the provided array.
  2521. *
  2522. * @param {Matrix4} value The value to pack.
  2523. * @param {Number[]} array The array to pack into.
  2524. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2525. *
  2526. * @returns {Number[]} The array that was packed into
  2527. */
  2528. Matrix4.pack = function (value, array, startingIndex) {
  2529. //>>includeStart('debug', pragmas.debug);
  2530. Check.Check.typeOf.object("value", value);
  2531. Check.Check.defined("array", array);
  2532. //>>includeEnd('debug');
  2533. startingIndex = when.defaultValue(startingIndex, 0);
  2534. array[startingIndex++] = value[0];
  2535. array[startingIndex++] = value[1];
  2536. array[startingIndex++] = value[2];
  2537. array[startingIndex++] = value[3];
  2538. array[startingIndex++] = value[4];
  2539. array[startingIndex++] = value[5];
  2540. array[startingIndex++] = value[6];
  2541. array[startingIndex++] = value[7];
  2542. array[startingIndex++] = value[8];
  2543. array[startingIndex++] = value[9];
  2544. array[startingIndex++] = value[10];
  2545. array[startingIndex++] = value[11];
  2546. array[startingIndex++] = value[12];
  2547. array[startingIndex++] = value[13];
  2548. array[startingIndex++] = value[14];
  2549. array[startingIndex] = value[15];
  2550. return array;
  2551. };
  2552. /**
  2553. * Retrieves an instance from a packed array.
  2554. *
  2555. * @param {Number[]} array The packed array.
  2556. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2557. * @param {Matrix4} [result] The object into which to store the result.
  2558. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  2559. */
  2560. Matrix4.unpack = function (array, startingIndex, result) {
  2561. //>>includeStart('debug', pragmas.debug);
  2562. Check.Check.defined("array", array);
  2563. //>>includeEnd('debug');
  2564. startingIndex = when.defaultValue(startingIndex, 0);
  2565. if (!when.defined(result)) {
  2566. result = new Matrix4();
  2567. }
  2568. result[0] = array[startingIndex++];
  2569. result[1] = array[startingIndex++];
  2570. result[2] = array[startingIndex++];
  2571. result[3] = array[startingIndex++];
  2572. result[4] = array[startingIndex++];
  2573. result[5] = array[startingIndex++];
  2574. result[6] = array[startingIndex++];
  2575. result[7] = array[startingIndex++];
  2576. result[8] = array[startingIndex++];
  2577. result[9] = array[startingIndex++];
  2578. result[10] = array[startingIndex++];
  2579. result[11] = array[startingIndex++];
  2580. result[12] = array[startingIndex++];
  2581. result[13] = array[startingIndex++];
  2582. result[14] = array[startingIndex++];
  2583. result[15] = array[startingIndex];
  2584. return result;
  2585. };
  2586. /**
  2587. * Duplicates a Matrix4 instance.
  2588. *
  2589. * @param {Matrix4} matrix The matrix to duplicate.
  2590. * @param {Matrix4} [result] The object onto which to store the result.
  2591. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  2592. */
  2593. Matrix4.clone = function (matrix, result) {
  2594. if (!when.defined(matrix)) {
  2595. return undefined;
  2596. }
  2597. if (!when.defined(result)) {
  2598. return new Matrix4(
  2599. matrix[0],
  2600. matrix[4],
  2601. matrix[8],
  2602. matrix[12],
  2603. matrix[1],
  2604. matrix[5],
  2605. matrix[9],
  2606. matrix[13],
  2607. matrix[2],
  2608. matrix[6],
  2609. matrix[10],
  2610. matrix[14],
  2611. matrix[3],
  2612. matrix[7],
  2613. matrix[11],
  2614. matrix[15]
  2615. );
  2616. }
  2617. result[0] = matrix[0];
  2618. result[1] = matrix[1];
  2619. result[2] = matrix[2];
  2620. result[3] = matrix[3];
  2621. result[4] = matrix[4];
  2622. result[5] = matrix[5];
  2623. result[6] = matrix[6];
  2624. result[7] = matrix[7];
  2625. result[8] = matrix[8];
  2626. result[9] = matrix[9];
  2627. result[10] = matrix[10];
  2628. result[11] = matrix[11];
  2629. result[12] = matrix[12];
  2630. result[13] = matrix[13];
  2631. result[14] = matrix[14];
  2632. result[15] = matrix[15];
  2633. return result;
  2634. };
  2635. /**
  2636. * Creates a Matrix4 from 16 consecutive elements in an array.
  2637. * @function
  2638. *
  2639. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  2640. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  2641. * @param {Matrix4} [result] The object onto which to store the result.
  2642. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  2643. *
  2644. * @example
  2645. * // Create the Matrix4:
  2646. * // [1.0, 2.0, 3.0, 4.0]
  2647. * // [1.0, 2.0, 3.0, 4.0]
  2648. * // [1.0, 2.0, 3.0, 4.0]
  2649. * // [1.0, 2.0, 3.0, 4.0]
  2650. *
  2651. * var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
  2652. * var m = Cesium.Matrix4.fromArray(v);
  2653. *
  2654. * // Create same Matrix4 with using an offset into an array
  2655. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
  2656. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  2657. */
  2658. Matrix4.fromArray = Matrix4.unpack;
  2659. /**
  2660. * Computes a Matrix4 instance from a column-major order array.
  2661. *
  2662. * @param {Number[]} values The column-major order array.
  2663. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2664. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2665. */
  2666. Matrix4.fromColumnMajorArray = function (values, result) {
  2667. //>>includeStart('debug', pragmas.debug);
  2668. Check.Check.defined("values", values);
  2669. //>>includeEnd('debug');
  2670. return Matrix4.clone(values, result);
  2671. };
  2672. /**
  2673. * Computes a Matrix4 instance from a row-major order array.
  2674. * The resulting matrix will be in column-major order.
  2675. *
  2676. * @param {Number[]} values The row-major order array.
  2677. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2678. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2679. */
  2680. Matrix4.fromRowMajorArray = function (values, result) {
  2681. //>>includeStart('debug', pragmas.debug);
  2682. Check.Check.defined("values", values);
  2683. //>>includeEnd('debug');
  2684. if (!when.defined(result)) {
  2685. return new Matrix4(
  2686. values[0],
  2687. values[1],
  2688. values[2],
  2689. values[3],
  2690. values[4],
  2691. values[5],
  2692. values[6],
  2693. values[7],
  2694. values[8],
  2695. values[9],
  2696. values[10],
  2697. values[11],
  2698. values[12],
  2699. values[13],
  2700. values[14],
  2701. values[15]
  2702. );
  2703. }
  2704. result[0] = values[0];
  2705. result[1] = values[4];
  2706. result[2] = values[8];
  2707. result[3] = values[12];
  2708. result[4] = values[1];
  2709. result[5] = values[5];
  2710. result[6] = values[9];
  2711. result[7] = values[13];
  2712. result[8] = values[2];
  2713. result[9] = values[6];
  2714. result[10] = values[10];
  2715. result[11] = values[14];
  2716. result[12] = values[3];
  2717. result[13] = values[7];
  2718. result[14] = values[11];
  2719. result[15] = values[15];
  2720. return result;
  2721. };
  2722. /**
  2723. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  2724. * and a Cartesian3 representing the translation.
  2725. *
  2726. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  2727. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  2728. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2729. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2730. */
  2731. Matrix4.fromRotationTranslation = function (rotation, translation, result) {
  2732. //>>includeStart('debug', pragmas.debug);
  2733. Check.Check.typeOf.object("rotation", rotation);
  2734. //>>includeEnd('debug');
  2735. translation = when.defaultValue(translation, Cartesian2.Cartesian3.ZERO);
  2736. if (!when.defined(result)) {
  2737. return new Matrix4(
  2738. rotation[0],
  2739. rotation[3],
  2740. rotation[6],
  2741. translation.x,
  2742. rotation[1],
  2743. rotation[4],
  2744. rotation[7],
  2745. translation.y,
  2746. rotation[2],
  2747. rotation[5],
  2748. rotation[8],
  2749. translation.z,
  2750. 0.0,
  2751. 0.0,
  2752. 0.0,
  2753. 1.0
  2754. );
  2755. }
  2756. result[0] = rotation[0];
  2757. result[1] = rotation[1];
  2758. result[2] = rotation[2];
  2759. result[3] = 0.0;
  2760. result[4] = rotation[3];
  2761. result[5] = rotation[4];
  2762. result[6] = rotation[5];
  2763. result[7] = 0.0;
  2764. result[8] = rotation[6];
  2765. result[9] = rotation[7];
  2766. result[10] = rotation[8];
  2767. result[11] = 0.0;
  2768. result[12] = translation.x;
  2769. result[13] = translation.y;
  2770. result[14] = translation.z;
  2771. result[15] = 1.0;
  2772. return result;
  2773. };
  2774. /**
  2775. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  2776. * representation with the rotation represented as a quaternion.
  2777. *
  2778. * @param {Cartesian3} translation The translation transformation.
  2779. * @param {Quaternion} rotation The rotation transformation.
  2780. * @param {Cartesian3} scale The non-uniform scale transformation.
  2781. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2782. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2783. *
  2784. * @example
  2785. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  2786. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  2787. * Cesium.Quaternion.IDENTITY, // rotation
  2788. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  2789. * result);
  2790. */
  2791. Matrix4.fromTranslationQuaternionRotationScale = function (
  2792. translation,
  2793. rotation,
  2794. scale,
  2795. result
  2796. ) {
  2797. //>>includeStart('debug', pragmas.debug);
  2798. Check.Check.typeOf.object("translation", translation);
  2799. Check.Check.typeOf.object("rotation", rotation);
  2800. Check.Check.typeOf.object("scale", scale);
  2801. //>>includeEnd('debug');
  2802. if (!when.defined(result)) {
  2803. result = new Matrix4();
  2804. }
  2805. var scaleX = scale.x;
  2806. var scaleY = scale.y;
  2807. var scaleZ = scale.z;
  2808. var x2 = rotation.x * rotation.x;
  2809. var xy = rotation.x * rotation.y;
  2810. var xz = rotation.x * rotation.z;
  2811. var xw = rotation.x * rotation.w;
  2812. var y2 = rotation.y * rotation.y;
  2813. var yz = rotation.y * rotation.z;
  2814. var yw = rotation.y * rotation.w;
  2815. var z2 = rotation.z * rotation.z;
  2816. var zw = rotation.z * rotation.w;
  2817. var w2 = rotation.w * rotation.w;
  2818. var m00 = x2 - y2 - z2 + w2;
  2819. var m01 = 2.0 * (xy - zw);
  2820. var m02 = 2.0 * (xz + yw);
  2821. var m10 = 2.0 * (xy + zw);
  2822. var m11 = -x2 + y2 - z2 + w2;
  2823. var m12 = 2.0 * (yz - xw);
  2824. var m20 = 2.0 * (xz - yw);
  2825. var m21 = 2.0 * (yz + xw);
  2826. var m22 = -x2 - y2 + z2 + w2;
  2827. result[0] = m00 * scaleX;
  2828. result[1] = m10 * scaleX;
  2829. result[2] = m20 * scaleX;
  2830. result[3] = 0.0;
  2831. result[4] = m01 * scaleY;
  2832. result[5] = m11 * scaleY;
  2833. result[6] = m21 * scaleY;
  2834. result[7] = 0.0;
  2835. result[8] = m02 * scaleZ;
  2836. result[9] = m12 * scaleZ;
  2837. result[10] = m22 * scaleZ;
  2838. result[11] = 0.0;
  2839. result[12] = translation.x;
  2840. result[13] = translation.y;
  2841. result[14] = translation.z;
  2842. result[15] = 1.0;
  2843. return result;
  2844. };
  2845. /**
  2846. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  2847. *
  2848. * @param {TranslationRotationScale} translationRotationScale The instance.
  2849. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2850. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2851. */
  2852. Matrix4.fromTranslationRotationScale = function (
  2853. translationRotationScale,
  2854. result
  2855. ) {
  2856. //>>includeStart('debug', pragmas.debug);
  2857. Check.Check.typeOf.object("translationRotationScale", translationRotationScale);
  2858. //>>includeEnd('debug');
  2859. return Matrix4.fromTranslationQuaternionRotationScale(
  2860. translationRotationScale.translation,
  2861. translationRotationScale.rotation,
  2862. translationRotationScale.scale,
  2863. result
  2864. );
  2865. };
  2866. /**
  2867. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  2868. *
  2869. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  2870. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2871. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2872. *
  2873. * @see Matrix4.multiplyByTranslation
  2874. */
  2875. Matrix4.fromTranslation = function (translation, result) {
  2876. //>>includeStart('debug', pragmas.debug);
  2877. Check.Check.typeOf.object("translation", translation);
  2878. //>>includeEnd('debug');
  2879. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  2880. };
  2881. /**
  2882. * Computes a Matrix4 instance representing a non-uniform scale.
  2883. *
  2884. * @param {Cartesian3} scale The x, y, and z scale factors.
  2885. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2886. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2887. *
  2888. * @example
  2889. * // Creates
  2890. * // [7.0, 0.0, 0.0, 0.0]
  2891. * // [0.0, 8.0, 0.0, 0.0]
  2892. * // [0.0, 0.0, 9.0, 0.0]
  2893. * // [0.0, 0.0, 0.0, 1.0]
  2894. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  2895. */
  2896. Matrix4.fromScale = function (scale, result) {
  2897. //>>includeStart('debug', pragmas.debug);
  2898. Check.Check.typeOf.object("scale", scale);
  2899. //>>includeEnd('debug');
  2900. if (!when.defined(result)) {
  2901. return new Matrix4(
  2902. scale.x,
  2903. 0.0,
  2904. 0.0,
  2905. 0.0,
  2906. 0.0,
  2907. scale.y,
  2908. 0.0,
  2909. 0.0,
  2910. 0.0,
  2911. 0.0,
  2912. scale.z,
  2913. 0.0,
  2914. 0.0,
  2915. 0.0,
  2916. 0.0,
  2917. 1.0
  2918. );
  2919. }
  2920. result[0] = scale.x;
  2921. result[1] = 0.0;
  2922. result[2] = 0.0;
  2923. result[3] = 0.0;
  2924. result[4] = 0.0;
  2925. result[5] = scale.y;
  2926. result[6] = 0.0;
  2927. result[7] = 0.0;
  2928. result[8] = 0.0;
  2929. result[9] = 0.0;
  2930. result[10] = scale.z;
  2931. result[11] = 0.0;
  2932. result[12] = 0.0;
  2933. result[13] = 0.0;
  2934. result[14] = 0.0;
  2935. result[15] = 1.0;
  2936. return result;
  2937. };
  2938. /**
  2939. * Computes a Matrix4 instance representing a uniform scale.
  2940. *
  2941. * @param {Number} scale The uniform scale factor.
  2942. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2943. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2944. *
  2945. * @example
  2946. * // Creates
  2947. * // [2.0, 0.0, 0.0, 0.0]
  2948. * // [0.0, 2.0, 0.0, 0.0]
  2949. * // [0.0, 0.0, 2.0, 0.0]
  2950. * // [0.0, 0.0, 0.0, 1.0]
  2951. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  2952. */
  2953. Matrix4.fromUniformScale = function (scale, result) {
  2954. //>>includeStart('debug', pragmas.debug);
  2955. Check.Check.typeOf.number("scale", scale);
  2956. //>>includeEnd('debug');
  2957. if (!when.defined(result)) {
  2958. return new Matrix4(
  2959. scale,
  2960. 0.0,
  2961. 0.0,
  2962. 0.0,
  2963. 0.0,
  2964. scale,
  2965. 0.0,
  2966. 0.0,
  2967. 0.0,
  2968. 0.0,
  2969. scale,
  2970. 0.0,
  2971. 0.0,
  2972. 0.0,
  2973. 0.0,
  2974. 1.0
  2975. );
  2976. }
  2977. result[0] = scale;
  2978. result[1] = 0.0;
  2979. result[2] = 0.0;
  2980. result[3] = 0.0;
  2981. result[4] = 0.0;
  2982. result[5] = scale;
  2983. result[6] = 0.0;
  2984. result[7] = 0.0;
  2985. result[8] = 0.0;
  2986. result[9] = 0.0;
  2987. result[10] = scale;
  2988. result[11] = 0.0;
  2989. result[12] = 0.0;
  2990. result[13] = 0.0;
  2991. result[14] = 0.0;
  2992. result[15] = 1.0;
  2993. return result;
  2994. };
  2995. var fromCameraF = new Cartesian2.Cartesian3();
  2996. var fromCameraR = new Cartesian2.Cartesian3();
  2997. var fromCameraU = new Cartesian2.Cartesian3();
  2998. /**
  2999. * Computes a Matrix4 instance from a Camera.
  3000. *
  3001. * @param {Camera} camera The camera to use.
  3002. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3003. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  3004. */
  3005. Matrix4.fromCamera = function (camera, result) {
  3006. //>>includeStart('debug', pragmas.debug);
  3007. Check.Check.typeOf.object("camera", camera);
  3008. //>>includeEnd('debug');
  3009. var position = camera.position;
  3010. var direction = camera.direction;
  3011. var up = camera.up;
  3012. //>>includeStart('debug', pragmas.debug);
  3013. Check.Check.typeOf.object("camera.position", position);
  3014. Check.Check.typeOf.object("camera.direction", direction);
  3015. Check.Check.typeOf.object("camera.up", up);
  3016. //>>includeEnd('debug');
  3017. Cartesian2.Cartesian3.normalize(direction, fromCameraF);
  3018. Cartesian2.Cartesian3.normalize(
  3019. Cartesian2.Cartesian3.cross(fromCameraF, up, fromCameraR),
  3020. fromCameraR
  3021. );
  3022. Cartesian2.Cartesian3.normalize(
  3023. Cartesian2.Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU),
  3024. fromCameraU
  3025. );
  3026. var sX = fromCameraR.x;
  3027. var sY = fromCameraR.y;
  3028. var sZ = fromCameraR.z;
  3029. var fX = fromCameraF.x;
  3030. var fY = fromCameraF.y;
  3031. var fZ = fromCameraF.z;
  3032. var uX = fromCameraU.x;
  3033. var uY = fromCameraU.y;
  3034. var uZ = fromCameraU.z;
  3035. var positionX = position.x;
  3036. var positionY = position.y;
  3037. var positionZ = position.z;
  3038. var t0 = sX * -positionX + sY * -positionY + sZ * -positionZ;
  3039. var t1 = uX * -positionX + uY * -positionY + uZ * -positionZ;
  3040. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  3041. // The code below this comment is an optimized
  3042. // version of the commented lines.
  3043. // Rather that create two matrices and then multiply,
  3044. // we just bake in the multiplcation as part of creation.
  3045. // var rotation = new Matrix4(
  3046. // sX, sY, sZ, 0.0,
  3047. // uX, uY, uZ, 0.0,
  3048. // -fX, -fY, -fZ, 0.0,
  3049. // 0.0, 0.0, 0.0, 1.0);
  3050. // var translation = new Matrix4(
  3051. // 1.0, 0.0, 0.0, -position.x,
  3052. // 0.0, 1.0, 0.0, -position.y,
  3053. // 0.0, 0.0, 1.0, -position.z,
  3054. // 0.0, 0.0, 0.0, 1.0);
  3055. // return rotation.multiply(translation);
  3056. if (!when.defined(result)) {
  3057. return new Matrix4(
  3058. sX,
  3059. sY,
  3060. sZ,
  3061. t0,
  3062. uX,
  3063. uY,
  3064. uZ,
  3065. t1,
  3066. -fX,
  3067. -fY,
  3068. -fZ,
  3069. t2,
  3070. 0.0,
  3071. 0.0,
  3072. 0.0,
  3073. 1.0
  3074. );
  3075. }
  3076. result[0] = sX;
  3077. result[1] = uX;
  3078. result[2] = -fX;
  3079. result[3] = 0.0;
  3080. result[4] = sY;
  3081. result[5] = uY;
  3082. result[6] = -fY;
  3083. result[7] = 0.0;
  3084. result[8] = sZ;
  3085. result[9] = uZ;
  3086. result[10] = -fZ;
  3087. result[11] = 0.0;
  3088. result[12] = t0;
  3089. result[13] = t1;
  3090. result[14] = t2;
  3091. result[15] = 1.0;
  3092. return result;
  3093. };
  3094. /**
  3095. * Computes a Matrix4 instance representing a perspective transformation matrix.
  3096. *
  3097. * @param {Number} fovY The field of view along the Y axis in radians.
  3098. * @param {Number} aspectRatio The aspect ratio.
  3099. * @param {Number} near The distance to the near plane in meters.
  3100. * @param {Number} far The distance to the far plane in meters.
  3101. * @param {Matrix4} result The object in which the result will be stored.
  3102. * @returns {Matrix4} The modified result parameter.
  3103. *
  3104. * @exception {DeveloperError} fovY must be in (0, PI].
  3105. * @exception {DeveloperError} aspectRatio must be greater than zero.
  3106. * @exception {DeveloperError} near must be greater than zero.
  3107. * @exception {DeveloperError} far must be greater than zero.
  3108. */
  3109. Matrix4.computePerspectiveFieldOfView = function (
  3110. fovY,
  3111. aspectRatio,
  3112. near,
  3113. far,
  3114. result
  3115. ) {
  3116. //>>includeStart('debug', pragmas.debug);
  3117. Check.Check.typeOf.number.greaterThan("fovY", fovY, 0.0);
  3118. Check.Check.typeOf.number.lessThan("fovY", fovY, Math.PI);
  3119. Check.Check.typeOf.number.greaterThan("near", near, 0.0);
  3120. Check.Check.typeOf.number.greaterThan("far", far, 0.0);
  3121. Check.Check.typeOf.object("result", result);
  3122. //>>includeEnd('debug');
  3123. var bottom = Math.tan(fovY * 0.5);
  3124. var column1Row1 = 1.0 / bottom;
  3125. var column0Row0 = column1Row1 / aspectRatio;
  3126. var column2Row2 = (far + near) / (near - far);
  3127. var column3Row2 = (2.0 * far * near) / (near - far);
  3128. result[0] = column0Row0;
  3129. result[1] = 0.0;
  3130. result[2] = 0.0;
  3131. result[3] = 0.0;
  3132. result[4] = 0.0;
  3133. result[5] = column1Row1;
  3134. result[6] = 0.0;
  3135. result[7] = 0.0;
  3136. result[8] = 0.0;
  3137. result[9] = 0.0;
  3138. result[10] = column2Row2;
  3139. result[11] = -1.0;
  3140. result[12] = 0.0;
  3141. result[13] = 0.0;
  3142. result[14] = column3Row2;
  3143. result[15] = 0.0;
  3144. return result;
  3145. };
  3146. /**
  3147. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  3148. *
  3149. * @param {Number} left The number of meters to the left of the camera that will be in view.
  3150. * @param {Number} right The number of meters to the right of the camera that will be in view.
  3151. * @param {Number} bottom The number of meters below of the camera that will be in view.
  3152. * @param {Number} top The number of meters above of the camera that will be in view.
  3153. * @param {Number} near The distance to the near plane in meters.
  3154. * @param {Number} far The distance to the far plane in meters.
  3155. * @param {Matrix4} result The object in which the result will be stored.
  3156. * @returns {Matrix4} The modified result parameter.
  3157. */
  3158. Matrix4.computeOrthographicOffCenter = function (
  3159. left,
  3160. right,
  3161. bottom,
  3162. top,
  3163. near,
  3164. far,
  3165. result
  3166. ) {
  3167. //>>includeStart('debug', pragmas.debug);
  3168. Check.Check.typeOf.number("left", left);
  3169. Check.Check.typeOf.number("right", right);
  3170. Check.Check.typeOf.number("bottom", bottom);
  3171. Check.Check.typeOf.number("top", top);
  3172. Check.Check.typeOf.number("near", near);
  3173. Check.Check.typeOf.number("far", far);
  3174. Check.Check.typeOf.object("result", result);
  3175. //>>includeEnd('debug');
  3176. var a = 1.0 / (right - left);
  3177. var b = 1.0 / (top - bottom);
  3178. var c = 1.0 / (far - near);
  3179. var tx = -(right + left) * a;
  3180. var ty = -(top + bottom) * b;
  3181. var tz = -(far + near) * c;
  3182. a *= 2.0;
  3183. b *= 2.0;
  3184. c *= -2.0;
  3185. result[0] = a;
  3186. result[1] = 0.0;
  3187. result[2] = 0.0;
  3188. result[3] = 0.0;
  3189. result[4] = 0.0;
  3190. result[5] = b;
  3191. result[6] = 0.0;
  3192. result[7] = 0.0;
  3193. result[8] = 0.0;
  3194. result[9] = 0.0;
  3195. result[10] = c;
  3196. result[11] = 0.0;
  3197. result[12] = tx;
  3198. result[13] = ty;
  3199. result[14] = tz;
  3200. result[15] = 1.0;
  3201. return result;
  3202. };
  3203. /**
  3204. * Computes a Matrix4 instance representing an off center perspective transformation.
  3205. *
  3206. * @param {Number} left The number of meters to the left of the camera that will be in view.
  3207. * @param {Number} right The number of meters to the right of the camera that will be in view.
  3208. * @param {Number} bottom The number of meters below of the camera that will be in view.
  3209. * @param {Number} top The number of meters above of the camera that will be in view.
  3210. * @param {Number} near The distance to the near plane in meters.
  3211. * @param {Number} far The distance to the far plane in meters.
  3212. * @param {Matrix4} result The object in which the result will be stored.
  3213. * @returns {Matrix4} The modified result parameter.
  3214. */
  3215. Matrix4.computePerspectiveOffCenter = function (
  3216. left,
  3217. right,
  3218. bottom,
  3219. top,
  3220. near,
  3221. far,
  3222. result
  3223. ) {
  3224. //>>includeStart('debug', pragmas.debug);
  3225. Check.Check.typeOf.number("left", left);
  3226. Check.Check.typeOf.number("right", right);
  3227. Check.Check.typeOf.number("bottom", bottom);
  3228. Check.Check.typeOf.number("top", top);
  3229. Check.Check.typeOf.number("near", near);
  3230. Check.Check.typeOf.number("far", far);
  3231. Check.Check.typeOf.object("result", result);
  3232. //>>includeEnd('debug');
  3233. var column0Row0 = (2.0 * near) / (right - left);
  3234. var column1Row1 = (2.0 * near) / (top - bottom);
  3235. var column2Row0 = (right + left) / (right - left);
  3236. var column2Row1 = (top + bottom) / (top - bottom);
  3237. var column2Row2 = -(far + near) / (far - near);
  3238. var column2Row3 = -1.0;
  3239. var column3Row2 = (-2.0 * far * near) / (far - near);
  3240. result[0] = column0Row0;
  3241. result[1] = 0.0;
  3242. result[2] = 0.0;
  3243. result[3] = 0.0;
  3244. result[4] = 0.0;
  3245. result[5] = column1Row1;
  3246. result[6] = 0.0;
  3247. result[7] = 0.0;
  3248. result[8] = column2Row0;
  3249. result[9] = column2Row1;
  3250. result[10] = column2Row2;
  3251. result[11] = column2Row3;
  3252. result[12] = 0.0;
  3253. result[13] = 0.0;
  3254. result[14] = column3Row2;
  3255. result[15] = 0.0;
  3256. return result;
  3257. };
  3258. /**
  3259. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  3260. *
  3261. * @param {Number} left The number of meters to the left of the camera that will be in view.
  3262. * @param {Number} right The number of meters to the right of the camera that will be in view.
  3263. * @param {Number} bottom The number of meters below of the camera that will be in view.
  3264. * @param {Number} top The number of meters above of the camera that will be in view.
  3265. * @param {Number} near The distance to the near plane in meters.
  3266. * @param {Matrix4} result The object in which the result will be stored.
  3267. * @returns {Matrix4} The modified result parameter.
  3268. */
  3269. Matrix4.computeInfinitePerspectiveOffCenter = function (
  3270. left,
  3271. right,
  3272. bottom,
  3273. top,
  3274. near,
  3275. result
  3276. ) {
  3277. //>>includeStart('debug', pragmas.debug);
  3278. Check.Check.typeOf.number("left", left);
  3279. Check.Check.typeOf.number("right", right);
  3280. Check.Check.typeOf.number("bottom", bottom);
  3281. Check.Check.typeOf.number("top", top);
  3282. Check.Check.typeOf.number("near", near);
  3283. Check.Check.typeOf.object("result", result);
  3284. //>>includeEnd('debug');
  3285. var column0Row0 = (2.0 * near) / (right - left);
  3286. var column1Row1 = (2.0 * near) / (top - bottom);
  3287. var column2Row0 = (right + left) / (right - left);
  3288. var column2Row1 = (top + bottom) / (top - bottom);
  3289. var column2Row2 = -1.0;
  3290. var column2Row3 = -1.0;
  3291. var column3Row2 = -2.0 * near;
  3292. result[0] = column0Row0;
  3293. result[1] = 0.0;
  3294. result[2] = 0.0;
  3295. result[3] = 0.0;
  3296. result[4] = 0.0;
  3297. result[5] = column1Row1;
  3298. result[6] = 0.0;
  3299. result[7] = 0.0;
  3300. result[8] = column2Row0;
  3301. result[9] = column2Row1;
  3302. result[10] = column2Row2;
  3303. result[11] = column2Row3;
  3304. result[12] = 0.0;
  3305. result[13] = 0.0;
  3306. result[14] = column3Row2;
  3307. result[15] = 0.0;
  3308. return result;
  3309. };
  3310. /**
  3311. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  3312. *
  3313. * @param {Object} [viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  3314. * @param {Number} [nearDepthRange=0.0] The near plane distance in window coordinates.
  3315. * @param {Number} [farDepthRange=1.0] The far plane distance in window coordinates.
  3316. * @param {Matrix4} [result] The object in which the result will be stored.
  3317. * @returns {Matrix4} The modified result parameter.
  3318. *
  3319. * @example
  3320. * // Create viewport transformation using an explicit viewport and depth range.
  3321. * var m = Cesium.Matrix4.computeViewportTransformation({
  3322. * x : 0.0,
  3323. * y : 0.0,
  3324. * width : 1024.0,
  3325. * height : 768.0
  3326. * }, 0.0, 1.0, new Cesium.Matrix4());
  3327. */
  3328. Matrix4.computeViewportTransformation = function (
  3329. viewport,
  3330. nearDepthRange,
  3331. farDepthRange,
  3332. result
  3333. ) {
  3334. if (!when.defined(result)) {
  3335. result = new Matrix4();
  3336. }
  3337. viewport = when.defaultValue(viewport, when.defaultValue.EMPTY_OBJECT);
  3338. var x = when.defaultValue(viewport.x, 0.0);
  3339. var y = when.defaultValue(viewport.y, 0.0);
  3340. var width = when.defaultValue(viewport.width, 0.0);
  3341. var height = when.defaultValue(viewport.height, 0.0);
  3342. nearDepthRange = when.defaultValue(nearDepthRange, 0.0);
  3343. farDepthRange = when.defaultValue(farDepthRange, 1.0);
  3344. var halfWidth = width * 0.5;
  3345. var halfHeight = height * 0.5;
  3346. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  3347. var column0Row0 = halfWidth;
  3348. var column1Row1 = halfHeight;
  3349. var column2Row2 = halfDepth;
  3350. var column3Row0 = x + halfWidth;
  3351. var column3Row1 = y + halfHeight;
  3352. var column3Row2 = nearDepthRange + halfDepth;
  3353. var column3Row3 = 1.0;
  3354. result[0] = column0Row0;
  3355. result[1] = 0.0;
  3356. result[2] = 0.0;
  3357. result[3] = 0.0;
  3358. result[4] = 0.0;
  3359. result[5] = column1Row1;
  3360. result[6] = 0.0;
  3361. result[7] = 0.0;
  3362. result[8] = 0.0;
  3363. result[9] = 0.0;
  3364. result[10] = column2Row2;
  3365. result[11] = 0.0;
  3366. result[12] = column3Row0;
  3367. result[13] = column3Row1;
  3368. result[14] = column3Row2;
  3369. result[15] = column3Row3;
  3370. return result;
  3371. };
  3372. /**
  3373. * Computes a Matrix4 instance that transforms from world space to view space.
  3374. *
  3375. * @param {Cartesian3} position The position of the camera.
  3376. * @param {Cartesian3} direction The forward direction.
  3377. * @param {Cartesian3} up The up direction.
  3378. * @param {Cartesian3} right The right direction.
  3379. * @param {Matrix4} result The object in which the result will be stored.
  3380. * @returns {Matrix4} The modified result parameter.
  3381. */
  3382. Matrix4.computeView = function (position, direction, up, right, result) {
  3383. //>>includeStart('debug', pragmas.debug);
  3384. Check.Check.typeOf.object("position", position);
  3385. Check.Check.typeOf.object("direction", direction);
  3386. Check.Check.typeOf.object("up", up);
  3387. Check.Check.typeOf.object("right", right);
  3388. Check.Check.typeOf.object("result", result);
  3389. //>>includeEnd('debug');
  3390. result[0] = right.x;
  3391. result[1] = up.x;
  3392. result[2] = -direction.x;
  3393. result[3] = 0.0;
  3394. result[4] = right.y;
  3395. result[5] = up.y;
  3396. result[6] = -direction.y;
  3397. result[7] = 0.0;
  3398. result[8] = right.z;
  3399. result[9] = up.z;
  3400. result[10] = -direction.z;
  3401. result[11] = 0.0;
  3402. result[12] = -Cartesian2.Cartesian3.dot(right, position);
  3403. result[13] = -Cartesian2.Cartesian3.dot(up, position);
  3404. result[14] = Cartesian2.Cartesian3.dot(direction, position);
  3405. result[15] = 1.0;
  3406. return result;
  3407. };
  3408. /**
  3409. * Computes an Array from the provided Matrix4 instance.
  3410. * The array will be in column-major order.
  3411. *
  3412. * @param {Matrix4} matrix The matrix to use..
  3413. * @param {Number[]} [result] The Array onto which to store the result.
  3414. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  3415. *
  3416. * @example
  3417. * //create an array from an instance of Matrix4
  3418. * // m = [10.0, 14.0, 18.0, 22.0]
  3419. * // [11.0, 15.0, 19.0, 23.0]
  3420. * // [12.0, 16.0, 20.0, 24.0]
  3421. * // [13.0, 17.0, 21.0, 25.0]
  3422. * var a = Cesium.Matrix4.toArray(m);
  3423. *
  3424. * // m remains the same
  3425. * //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
  3426. */
  3427. Matrix4.toArray = function (matrix, result) {
  3428. //>>includeStart('debug', pragmas.debug);
  3429. Check.Check.typeOf.object("matrix", matrix);
  3430. //>>includeEnd('debug');
  3431. if (!when.defined(result)) {
  3432. return [
  3433. matrix[0],
  3434. matrix[1],
  3435. matrix[2],
  3436. matrix[3],
  3437. matrix[4],
  3438. matrix[5],
  3439. matrix[6],
  3440. matrix[7],
  3441. matrix[8],
  3442. matrix[9],
  3443. matrix[10],
  3444. matrix[11],
  3445. matrix[12],
  3446. matrix[13],
  3447. matrix[14],
  3448. matrix[15],
  3449. ];
  3450. }
  3451. result[0] = matrix[0];
  3452. result[1] = matrix[1];
  3453. result[2] = matrix[2];
  3454. result[3] = matrix[3];
  3455. result[4] = matrix[4];
  3456. result[5] = matrix[5];
  3457. result[6] = matrix[6];
  3458. result[7] = matrix[7];
  3459. result[8] = matrix[8];
  3460. result[9] = matrix[9];
  3461. result[10] = matrix[10];
  3462. result[11] = matrix[11];
  3463. result[12] = matrix[12];
  3464. result[13] = matrix[13];
  3465. result[14] = matrix[14];
  3466. result[15] = matrix[15];
  3467. return result;
  3468. };
  3469. /**
  3470. * Computes the array index of the element at the provided row and column.
  3471. *
  3472. * @param {Number} row The zero-based index of the row.
  3473. * @param {Number} column The zero-based index of the column.
  3474. * @returns {Number} The index of the element at the provided row and column.
  3475. *
  3476. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  3477. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  3478. *
  3479. * @example
  3480. * var myMatrix = new Cesium.Matrix4();
  3481. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  3482. * var column1Row0 = myMatrix[column1Row0Index];
  3483. * myMatrix[column1Row0Index] = 10.0;
  3484. */
  3485. Matrix4.getElementIndex = function (column, row) {
  3486. //>>includeStart('debug', pragmas.debug);
  3487. Check.Check.typeOf.number.greaterThanOrEquals("row", row, 0);
  3488. Check.Check.typeOf.number.lessThanOrEquals("row", row, 3);
  3489. Check.Check.typeOf.number.greaterThanOrEquals("column", column, 0);
  3490. Check.Check.typeOf.number.lessThanOrEquals("column", column, 3);
  3491. //>>includeEnd('debug');
  3492. return column * 4 + row;
  3493. };
  3494. /**
  3495. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  3496. *
  3497. * @param {Matrix4} matrix The matrix to use.
  3498. * @param {Number} index The zero-based index of the column to retrieve.
  3499. * @param {Cartesian4} result The object onto which to store the result.
  3500. * @returns {Cartesian4} The modified result parameter.
  3501. *
  3502. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3503. *
  3504. * @example
  3505. * //returns a Cartesian4 instance with values from the specified column
  3506. * // m = [10.0, 11.0, 12.0, 13.0]
  3507. * // [14.0, 15.0, 16.0, 17.0]
  3508. * // [18.0, 19.0, 20.0, 21.0]
  3509. * // [22.0, 23.0, 24.0, 25.0]
  3510. *
  3511. * //Example 1: Creates an instance of Cartesian
  3512. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  3513. *
  3514. * @example
  3515. * //Example 2: Sets values for Cartesian instance
  3516. * var a = new Cesium.Cartesian4();
  3517. * Cesium.Matrix4.getColumn(m, 2, a);
  3518. *
  3519. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  3520. */
  3521. Matrix4.getColumn = function (matrix, index, result) {
  3522. //>>includeStart('debug', pragmas.debug);
  3523. Check.Check.typeOf.object("matrix", matrix);
  3524. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  3525. Check.Check.typeOf.number.lessThanOrEquals("index", index, 3);
  3526. Check.Check.typeOf.object("result", result);
  3527. //>>includeEnd('debug');
  3528. var startIndex = index * 4;
  3529. var x = matrix[startIndex];
  3530. var y = matrix[startIndex + 1];
  3531. var z = matrix[startIndex + 2];
  3532. var w = matrix[startIndex + 3];
  3533. result.x = x;
  3534. result.y = y;
  3535. result.z = z;
  3536. result.w = w;
  3537. return result;
  3538. };
  3539. /**
  3540. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  3541. *
  3542. * @param {Matrix4} matrix The matrix to use.
  3543. * @param {Number} index The zero-based index of the column to set.
  3544. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  3545. * @param {Matrix4} result The object onto which to store the result.
  3546. * @returns {Matrix4} The modified result parameter.
  3547. *
  3548. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3549. *
  3550. * @example
  3551. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  3552. * // m = [10.0, 11.0, 12.0, 13.0]
  3553. * // [14.0, 15.0, 16.0, 17.0]
  3554. * // [18.0, 19.0, 20.0, 21.0]
  3555. * // [22.0, 23.0, 24.0, 25.0]
  3556. *
  3557. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  3558. *
  3559. * // m remains the same
  3560. * // a = [10.0, 11.0, 99.0, 13.0]
  3561. * // [14.0, 15.0, 98.0, 17.0]
  3562. * // [18.0, 19.0, 97.0, 21.0]
  3563. * // [22.0, 23.0, 96.0, 25.0]
  3564. */
  3565. Matrix4.setColumn = function (matrix, index, cartesian, result) {
  3566. //>>includeStart('debug', pragmas.debug);
  3567. Check.Check.typeOf.object("matrix", matrix);
  3568. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  3569. Check.Check.typeOf.number.lessThanOrEquals("index", index, 3);
  3570. Check.Check.typeOf.object("cartesian", cartesian);
  3571. Check.Check.typeOf.object("result", result);
  3572. //>>includeEnd('debug');
  3573. result = Matrix4.clone(matrix, result);
  3574. var startIndex = index * 4;
  3575. result[startIndex] = cartesian.x;
  3576. result[startIndex + 1] = cartesian.y;
  3577. result[startIndex + 2] = cartesian.z;
  3578. result[startIndex + 3] = cartesian.w;
  3579. return result;
  3580. };
  3581. /**
  3582. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  3583. * matrix with the provided translation. This assumes the matrix is an affine transformation
  3584. *
  3585. * @param {Matrix4} matrix The matrix to use.
  3586. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  3587. * @param {Matrix4} result The object onto which to store the result.
  3588. * @returns {Matrix4} The modified result parameter.
  3589. */
  3590. Matrix4.setTranslation = function (matrix, translation, result) {
  3591. //>>includeStart('debug', pragmas.debug);
  3592. Check.Check.typeOf.object("matrix", matrix);
  3593. Check.Check.typeOf.object("translation", translation);
  3594. Check.Check.typeOf.object("result", result);
  3595. //>>includeEnd('debug');
  3596. result[0] = matrix[0];
  3597. result[1] = matrix[1];
  3598. result[2] = matrix[2];
  3599. result[3] = matrix[3];
  3600. result[4] = matrix[4];
  3601. result[5] = matrix[5];
  3602. result[6] = matrix[6];
  3603. result[7] = matrix[7];
  3604. result[8] = matrix[8];
  3605. result[9] = matrix[9];
  3606. result[10] = matrix[10];
  3607. result[11] = matrix[11];
  3608. result[12] = translation.x;
  3609. result[13] = translation.y;
  3610. result[14] = translation.z;
  3611. result[15] = matrix[15];
  3612. return result;
  3613. };
  3614. var scaleScratch = new Cartesian2.Cartesian3();
  3615. /**
  3616. * Computes a new matrix that replaces the scale with the provided scale. This assumes the matrix is an affine transformation
  3617. *
  3618. * @param {Matrix4} matrix The matrix to use.
  3619. * @param {Cartesian3} scale The scale that replaces the scale of the provided matrix.
  3620. * @param {Matrix4} result The object onto which to store the result.
  3621. * @returns {Matrix4} The modified result parameter.
  3622. */
  3623. Matrix4.setScale = function (matrix, scale, result) {
  3624. //>>includeStart('debug', pragmas.debug);
  3625. Check.Check.typeOf.object("matrix", matrix);
  3626. Check.Check.typeOf.object("scale", scale);
  3627. Check.Check.typeOf.object("result", result);
  3628. //>>includeEnd('debug');
  3629. var existingScale = Matrix4.getScale(matrix, scaleScratch);
  3630. var newScale = Cartesian2.Cartesian3.divideComponents(
  3631. scale,
  3632. existingScale,
  3633. scaleScratch
  3634. );
  3635. return Matrix4.multiplyByScale(matrix, newScale, result);
  3636. };
  3637. /**
  3638. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  3639. *
  3640. * @param {Matrix4} matrix The matrix to use.
  3641. * @param {Number} index The zero-based index of the row to retrieve.
  3642. * @param {Cartesian4} result The object onto which to store the result.
  3643. * @returns {Cartesian4} The modified result parameter.
  3644. *
  3645. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3646. *
  3647. * @example
  3648. * //returns a Cartesian4 instance with values from the specified column
  3649. * // m = [10.0, 11.0, 12.0, 13.0]
  3650. * // [14.0, 15.0, 16.0, 17.0]
  3651. * // [18.0, 19.0, 20.0, 21.0]
  3652. * // [22.0, 23.0, 24.0, 25.0]
  3653. *
  3654. * //Example 1: Returns an instance of Cartesian
  3655. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  3656. *
  3657. * @example
  3658. * //Example 2: Sets values for a Cartesian instance
  3659. * var a = new Cesium.Cartesian4();
  3660. * Cesium.Matrix4.getRow(m, 2, a);
  3661. *
  3662. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  3663. */
  3664. Matrix4.getRow = function (matrix, index, result) {
  3665. //>>includeStart('debug', pragmas.debug);
  3666. Check.Check.typeOf.object("matrix", matrix);
  3667. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  3668. Check.Check.typeOf.number.lessThanOrEquals("index", index, 3);
  3669. Check.Check.typeOf.object("result", result);
  3670. //>>includeEnd('debug');
  3671. var x = matrix[index];
  3672. var y = matrix[index + 4];
  3673. var z = matrix[index + 8];
  3674. var w = matrix[index + 12];
  3675. result.x = x;
  3676. result.y = y;
  3677. result.z = z;
  3678. result.w = w;
  3679. return result;
  3680. };
  3681. /**
  3682. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  3683. *
  3684. * @param {Matrix4} matrix The matrix to use.
  3685. * @param {Number} index The zero-based index of the row to set.
  3686. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  3687. * @param {Matrix4} result The object onto which to store the result.
  3688. * @returns {Matrix4} The modified result parameter.
  3689. *
  3690. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3691. *
  3692. * @example
  3693. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  3694. * // m = [10.0, 11.0, 12.0, 13.0]
  3695. * // [14.0, 15.0, 16.0, 17.0]
  3696. * // [18.0, 19.0, 20.0, 21.0]
  3697. * // [22.0, 23.0, 24.0, 25.0]
  3698. *
  3699. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  3700. *
  3701. * // m remains the same
  3702. * // a = [10.0, 11.0, 12.0, 13.0]
  3703. * // [14.0, 15.0, 16.0, 17.0]
  3704. * // [99.0, 98.0, 97.0, 96.0]
  3705. * // [22.0, 23.0, 24.0, 25.0]
  3706. */
  3707. Matrix4.setRow = function (matrix, index, cartesian, result) {
  3708. //>>includeStart('debug', pragmas.debug);
  3709. Check.Check.typeOf.object("matrix", matrix);
  3710. Check.Check.typeOf.number.greaterThanOrEquals("index", index, 0);
  3711. Check.Check.typeOf.number.lessThanOrEquals("index", index, 3);
  3712. Check.Check.typeOf.object("cartesian", cartesian);
  3713. Check.Check.typeOf.object("result", result);
  3714. //>>includeEnd('debug');
  3715. result = Matrix4.clone(matrix, result);
  3716. result[index] = cartesian.x;
  3717. result[index + 4] = cartesian.y;
  3718. result[index + 8] = cartesian.z;
  3719. result[index + 12] = cartesian.w;
  3720. return result;
  3721. };
  3722. var scratchColumn$1 = new Cartesian2.Cartesian3();
  3723. /**
  3724. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  3725. *
  3726. * @param {Matrix4} matrix The matrix.
  3727. * @param {Cartesian3} result The object onto which to store the result.
  3728. * @returns {Cartesian3} The modified result parameter
  3729. */
  3730. Matrix4.getScale = function (matrix, result) {
  3731. //>>includeStart('debug', pragmas.debug);
  3732. Check.Check.typeOf.object("matrix", matrix);
  3733. Check.Check.typeOf.object("result", result);
  3734. //>>includeEnd('debug');
  3735. result.x = Cartesian2.Cartesian3.magnitude(
  3736. Cartesian2.Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn$1)
  3737. );
  3738. result.y = Cartesian2.Cartesian3.magnitude(
  3739. Cartesian2.Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn$1)
  3740. );
  3741. result.z = Cartesian2.Cartesian3.magnitude(
  3742. Cartesian2.Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn$1)
  3743. );
  3744. return result;
  3745. };
  3746. var scratchScale$1 = new Cartesian2.Cartesian3();
  3747. /**
  3748. * Computes the maximum scale assuming the matrix is an affine transformation.
  3749. * The maximum scale is the maximum length of the column vectors in the upper-left
  3750. * 3x3 matrix.
  3751. *
  3752. * @param {Matrix4} matrix The matrix.
  3753. * @returns {Number} The maximum scale.
  3754. */
  3755. Matrix4.getMaximumScale = function (matrix) {
  3756. Matrix4.getScale(matrix, scratchScale$1);
  3757. return Cartesian2.Cartesian3.maximumComponent(scratchScale$1);
  3758. };
  3759. /**
  3760. * Computes the product of two matrices.
  3761. *
  3762. * @param {Matrix4} left The first matrix.
  3763. * @param {Matrix4} right The second matrix.
  3764. * @param {Matrix4} result The object onto which to store the result.
  3765. * @returns {Matrix4} The modified result parameter.
  3766. */
  3767. Matrix4.multiply = function (left, right, result) {
  3768. //>>includeStart('debug', pragmas.debug);
  3769. Check.Check.typeOf.object("left", left);
  3770. Check.Check.typeOf.object("right", right);
  3771. Check.Check.typeOf.object("result", result);
  3772. //>>includeEnd('debug');
  3773. var left0 = left[0];
  3774. var left1 = left[1];
  3775. var left2 = left[2];
  3776. var left3 = left[3];
  3777. var left4 = left[4];
  3778. var left5 = left[5];
  3779. var left6 = left[6];
  3780. var left7 = left[7];
  3781. var left8 = left[8];
  3782. var left9 = left[9];
  3783. var left10 = left[10];
  3784. var left11 = left[11];
  3785. var left12 = left[12];
  3786. var left13 = left[13];
  3787. var left14 = left[14];
  3788. var left15 = left[15];
  3789. var right0 = right[0];
  3790. var right1 = right[1];
  3791. var right2 = right[2];
  3792. var right3 = right[3];
  3793. var right4 = right[4];
  3794. var right5 = right[5];
  3795. var right6 = right[6];
  3796. var right7 = right[7];
  3797. var right8 = right[8];
  3798. var right9 = right[9];
  3799. var right10 = right[10];
  3800. var right11 = right[11];
  3801. var right12 = right[12];
  3802. var right13 = right[13];
  3803. var right14 = right[14];
  3804. var right15 = right[15];
  3805. var column0Row0 =
  3806. left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  3807. var column0Row1 =
  3808. left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  3809. var column0Row2 =
  3810. left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  3811. var column0Row3 =
  3812. left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  3813. var column1Row0 =
  3814. left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  3815. var column1Row1 =
  3816. left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  3817. var column1Row2 =
  3818. left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  3819. var column1Row3 =
  3820. left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  3821. var column2Row0 =
  3822. left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  3823. var column2Row1 =
  3824. left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  3825. var column2Row2 =
  3826. left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  3827. var column2Row3 =
  3828. left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  3829. var column3Row0 =
  3830. left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  3831. var column3Row1 =
  3832. left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  3833. var column3Row2 =
  3834. left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  3835. var column3Row3 =
  3836. left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  3837. result[0] = column0Row0;
  3838. result[1] = column0Row1;
  3839. result[2] = column0Row2;
  3840. result[3] = column0Row3;
  3841. result[4] = column1Row0;
  3842. result[5] = column1Row1;
  3843. result[6] = column1Row2;
  3844. result[7] = column1Row3;
  3845. result[8] = column2Row0;
  3846. result[9] = column2Row1;
  3847. result[10] = column2Row2;
  3848. result[11] = column2Row3;
  3849. result[12] = column3Row0;
  3850. result[13] = column3Row1;
  3851. result[14] = column3Row2;
  3852. result[15] = column3Row3;
  3853. return result;
  3854. };
  3855. /**
  3856. * Computes the sum of two matrices.
  3857. *
  3858. * @param {Matrix4} left The first matrix.
  3859. * @param {Matrix4} right The second matrix.
  3860. * @param {Matrix4} result The object onto which to store the result.
  3861. * @returns {Matrix4} The modified result parameter.
  3862. */
  3863. Matrix4.add = function (left, right, result) {
  3864. //>>includeStart('debug', pragmas.debug);
  3865. Check.Check.typeOf.object("left", left);
  3866. Check.Check.typeOf.object("right", right);
  3867. Check.Check.typeOf.object("result", result);
  3868. //>>includeEnd('debug');
  3869. result[0] = left[0] + right[0];
  3870. result[1] = left[1] + right[1];
  3871. result[2] = left[2] + right[2];
  3872. result[3] = left[3] + right[3];
  3873. result[4] = left[4] + right[4];
  3874. result[5] = left[5] + right[5];
  3875. result[6] = left[6] + right[6];
  3876. result[7] = left[7] + right[7];
  3877. result[8] = left[8] + right[8];
  3878. result[9] = left[9] + right[9];
  3879. result[10] = left[10] + right[10];
  3880. result[11] = left[11] + right[11];
  3881. result[12] = left[12] + right[12];
  3882. result[13] = left[13] + right[13];
  3883. result[14] = left[14] + right[14];
  3884. result[15] = left[15] + right[15];
  3885. return result;
  3886. };
  3887. /**
  3888. * Computes the difference of two matrices.
  3889. *
  3890. * @param {Matrix4} left The first matrix.
  3891. * @param {Matrix4} right The second matrix.
  3892. * @param {Matrix4} result The object onto which to store the result.
  3893. * @returns {Matrix4} The modified result parameter.
  3894. */
  3895. Matrix4.subtract = function (left, right, result) {
  3896. //>>includeStart('debug', pragmas.debug);
  3897. Check.Check.typeOf.object("left", left);
  3898. Check.Check.typeOf.object("right", right);
  3899. Check.Check.typeOf.object("result", result);
  3900. //>>includeEnd('debug');
  3901. result[0] = left[0] - right[0];
  3902. result[1] = left[1] - right[1];
  3903. result[2] = left[2] - right[2];
  3904. result[3] = left[3] - right[3];
  3905. result[4] = left[4] - right[4];
  3906. result[5] = left[5] - right[5];
  3907. result[6] = left[6] - right[6];
  3908. result[7] = left[7] - right[7];
  3909. result[8] = left[8] - right[8];
  3910. result[9] = left[9] - right[9];
  3911. result[10] = left[10] - right[10];
  3912. result[11] = left[11] - right[11];
  3913. result[12] = left[12] - right[12];
  3914. result[13] = left[13] - right[13];
  3915. result[14] = left[14] - right[14];
  3916. result[15] = left[15] - right[15];
  3917. return result;
  3918. };
  3919. /**
  3920. * Computes the product of two matrices assuming the matrices are
  3921. * affine transformation matrices, where the upper left 3x3 elements
  3922. * are a rotation matrix, and the upper three elements in the fourth
  3923. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  3924. * The matrix is not verified to be in the proper form.
  3925. * This method is faster than computing the product for general 4x4
  3926. * matrices using {@link Matrix4.multiply}.
  3927. *
  3928. * @param {Matrix4} left The first matrix.
  3929. * @param {Matrix4} right The second matrix.
  3930. * @param {Matrix4} result The object onto which to store the result.
  3931. * @returns {Matrix4} The modified result parameter.
  3932. *
  3933. * @example
  3934. * var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3935. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  3936. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  3937. */
  3938. Matrix4.multiplyTransformation = function (left, right, result) {
  3939. //>>includeStart('debug', pragmas.debug);
  3940. Check.Check.typeOf.object("left", left);
  3941. Check.Check.typeOf.object("right", right);
  3942. Check.Check.typeOf.object("result", result);
  3943. //>>includeEnd('debug');
  3944. var left0 = left[0];
  3945. var left1 = left[1];
  3946. var left2 = left[2];
  3947. var left4 = left[4];
  3948. var left5 = left[5];
  3949. var left6 = left[6];
  3950. var left8 = left[8];
  3951. var left9 = left[9];
  3952. var left10 = left[10];
  3953. var left12 = left[12];
  3954. var left13 = left[13];
  3955. var left14 = left[14];
  3956. var right0 = right[0];
  3957. var right1 = right[1];
  3958. var right2 = right[2];
  3959. var right4 = right[4];
  3960. var right5 = right[5];
  3961. var right6 = right[6];
  3962. var right8 = right[8];
  3963. var right9 = right[9];
  3964. var right10 = right[10];
  3965. var right12 = right[12];
  3966. var right13 = right[13];
  3967. var right14 = right[14];
  3968. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  3969. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  3970. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  3971. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  3972. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  3973. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  3974. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  3975. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  3976. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  3977. var column3Row0 =
  3978. left0 * right12 + left4 * right13 + left8 * right14 + left12;
  3979. var column3Row1 =
  3980. left1 * right12 + left5 * right13 + left9 * right14 + left13;
  3981. var column3Row2 =
  3982. left2 * right12 + left6 * right13 + left10 * right14 + left14;
  3983. result[0] = column0Row0;
  3984. result[1] = column0Row1;
  3985. result[2] = column0Row2;
  3986. result[3] = 0.0;
  3987. result[4] = column1Row0;
  3988. result[5] = column1Row1;
  3989. result[6] = column1Row2;
  3990. result[7] = 0.0;
  3991. result[8] = column2Row0;
  3992. result[9] = column2Row1;
  3993. result[10] = column2Row2;
  3994. result[11] = 0.0;
  3995. result[12] = column3Row0;
  3996. result[13] = column3Row1;
  3997. result[14] = column3Row2;
  3998. result[15] = 1.0;
  3999. return result;
  4000. };
  4001. /**
  4002. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  4003. * by a 3x3 rotation matrix. This is an optimization
  4004. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  4005. *
  4006. * @param {Matrix4} matrix The matrix on the left-hand side.
  4007. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  4008. * @param {Matrix4} result The object onto which to store the result.
  4009. * @returns {Matrix4} The modified result parameter.
  4010. *
  4011. * @example
  4012. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  4013. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  4014. */
  4015. Matrix4.multiplyByMatrix3 = function (matrix, rotation, result) {
  4016. //>>includeStart('debug', pragmas.debug);
  4017. Check.Check.typeOf.object("matrix", matrix);
  4018. Check.Check.typeOf.object("rotation", rotation);
  4019. Check.Check.typeOf.object("result", result);
  4020. //>>includeEnd('debug');
  4021. var left0 = matrix[0];
  4022. var left1 = matrix[1];
  4023. var left2 = matrix[2];
  4024. var left4 = matrix[4];
  4025. var left5 = matrix[5];
  4026. var left6 = matrix[6];
  4027. var left8 = matrix[8];
  4028. var left9 = matrix[9];
  4029. var left10 = matrix[10];
  4030. var right0 = rotation[0];
  4031. var right1 = rotation[1];
  4032. var right2 = rotation[2];
  4033. var right4 = rotation[3];
  4034. var right5 = rotation[4];
  4035. var right6 = rotation[5];
  4036. var right8 = rotation[6];
  4037. var right9 = rotation[7];
  4038. var right10 = rotation[8];
  4039. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  4040. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  4041. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  4042. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  4043. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  4044. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  4045. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  4046. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  4047. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  4048. result[0] = column0Row0;
  4049. result[1] = column0Row1;
  4050. result[2] = column0Row2;
  4051. result[3] = 0.0;
  4052. result[4] = column1Row0;
  4053. result[5] = column1Row1;
  4054. result[6] = column1Row2;
  4055. result[7] = 0.0;
  4056. result[8] = column2Row0;
  4057. result[9] = column2Row1;
  4058. result[10] = column2Row2;
  4059. result[11] = 0.0;
  4060. result[12] = matrix[12];
  4061. result[13] = matrix[13];
  4062. result[14] = matrix[14];
  4063. result[15] = matrix[15];
  4064. return result;
  4065. };
  4066. /**
  4067. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  4068. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  4069. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  4070. *
  4071. * @param {Matrix4} matrix The matrix on the left-hand side.
  4072. * @param {Cartesian3} translation The translation on the right-hand side.
  4073. * @param {Matrix4} result The object onto which to store the result.
  4074. * @returns {Matrix4} The modified result parameter.
  4075. *
  4076. * @example
  4077. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  4078. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  4079. */
  4080. Matrix4.multiplyByTranslation = function (matrix, translation, result) {
  4081. //>>includeStart('debug', pragmas.debug);
  4082. Check.Check.typeOf.object("matrix", matrix);
  4083. Check.Check.typeOf.object("translation", translation);
  4084. Check.Check.typeOf.object("result", result);
  4085. //>>includeEnd('debug');
  4086. var x = translation.x;
  4087. var y = translation.y;
  4088. var z = translation.z;
  4089. var tx = x * matrix[0] + y * matrix[4] + z * matrix[8] + matrix[12];
  4090. var ty = x * matrix[1] + y * matrix[5] + z * matrix[9] + matrix[13];
  4091. var tz = x * matrix[2] + y * matrix[6] + z * matrix[10] + matrix[14];
  4092. result[0] = matrix[0];
  4093. result[1] = matrix[1];
  4094. result[2] = matrix[2];
  4095. result[3] = matrix[3];
  4096. result[4] = matrix[4];
  4097. result[5] = matrix[5];
  4098. result[6] = matrix[6];
  4099. result[7] = matrix[7];
  4100. result[8] = matrix[8];
  4101. result[9] = matrix[9];
  4102. result[10] = matrix[10];
  4103. result[11] = matrix[11];
  4104. result[12] = tx;
  4105. result[13] = ty;
  4106. result[14] = tz;
  4107. result[15] = matrix[15];
  4108. return result;
  4109. };
  4110. var uniformScaleScratch = new Cartesian2.Cartesian3();
  4111. /**
  4112. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  4113. * by an implicit uniform scale matrix. This is an optimization
  4114. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  4115. * <code>m</code> must be an affine matrix.
  4116. * This function performs fewer allocations and arithmetic operations.
  4117. *
  4118. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  4119. * @param {Number} scale The uniform scale on the right-hand side.
  4120. * @param {Matrix4} result The object onto which to store the result.
  4121. * @returns {Matrix4} The modified result parameter.
  4122. *
  4123. *
  4124. * @example
  4125. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  4126. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  4127. *
  4128. * @see Matrix4.fromUniformScale
  4129. * @see Matrix4.multiplyByScale
  4130. */
  4131. Matrix4.multiplyByUniformScale = function (matrix, scale, result) {
  4132. //>>includeStart('debug', pragmas.debug);
  4133. Check.Check.typeOf.object("matrix", matrix);
  4134. Check.Check.typeOf.number("scale", scale);
  4135. Check.Check.typeOf.object("result", result);
  4136. //>>includeEnd('debug');
  4137. uniformScaleScratch.x = scale;
  4138. uniformScaleScratch.y = scale;
  4139. uniformScaleScratch.z = scale;
  4140. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  4141. };
  4142. /**
  4143. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  4144. * by an implicit non-uniform scale matrix. This is an optimization
  4145. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  4146. * <code>m</code> must be an affine matrix.
  4147. * This function performs fewer allocations and arithmetic operations.
  4148. *
  4149. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  4150. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  4151. * @param {Matrix4} result The object onto which to store the result.
  4152. * @returns {Matrix4} The modified result parameter.
  4153. *
  4154. *
  4155. * @example
  4156. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  4157. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  4158. *
  4159. * @see Matrix4.fromScale
  4160. * @see Matrix4.multiplyByUniformScale
  4161. */
  4162. Matrix4.multiplyByScale = function (matrix, scale, result) {
  4163. //>>includeStart('debug', pragmas.debug);
  4164. Check.Check.typeOf.object("matrix", matrix);
  4165. Check.Check.typeOf.object("scale", scale);
  4166. Check.Check.typeOf.object("result", result);
  4167. //>>includeEnd('debug');
  4168. var scaleX = scale.x;
  4169. var scaleY = scale.y;
  4170. var scaleZ = scale.z;
  4171. // Faster than Cartesian3.equals
  4172. if (scaleX === 1.0 && scaleY === 1.0 && scaleZ === 1.0) {
  4173. return Matrix4.clone(matrix, result);
  4174. }
  4175. result[0] = scaleX * matrix[0];
  4176. result[1] = scaleX * matrix[1];
  4177. result[2] = scaleX * matrix[2];
  4178. result[3] = 0.0;
  4179. result[4] = scaleY * matrix[4];
  4180. result[5] = scaleY * matrix[5];
  4181. result[6] = scaleY * matrix[6];
  4182. result[7] = 0.0;
  4183. result[8] = scaleZ * matrix[8];
  4184. result[9] = scaleZ * matrix[9];
  4185. result[10] = scaleZ * matrix[10];
  4186. result[11] = 0.0;
  4187. result[12] = matrix[12];
  4188. result[13] = matrix[13];
  4189. result[14] = matrix[14];
  4190. result[15] = 1.0;
  4191. return result;
  4192. };
  4193. /**
  4194. * Computes the product of a matrix and a column vector.
  4195. *
  4196. * @param {Matrix4} matrix The matrix.
  4197. * @param {Cartesian4} cartesian The vector.
  4198. * @param {Cartesian4} result The object onto which to store the result.
  4199. * @returns {Cartesian4} The modified result parameter.
  4200. */
  4201. Matrix4.multiplyByVector = function (matrix, cartesian, result) {
  4202. //>>includeStart('debug', pragmas.debug);
  4203. Check.Check.typeOf.object("matrix", matrix);
  4204. Check.Check.typeOf.object("cartesian", cartesian);
  4205. Check.Check.typeOf.object("result", result);
  4206. //>>includeEnd('debug');
  4207. var vX = cartesian.x;
  4208. var vY = cartesian.y;
  4209. var vZ = cartesian.z;
  4210. var vW = cartesian.w;
  4211. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  4212. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  4213. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  4214. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  4215. result.x = x;
  4216. result.y = y;
  4217. result.z = z;
  4218. result.w = w;
  4219. return result;
  4220. };
  4221. /**
  4222. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  4223. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  4224. *
  4225. * @param {Matrix4} matrix The matrix.
  4226. * @param {Cartesian3} cartesian The point.
  4227. * @param {Cartesian3} result The object onto which to store the result.
  4228. * @returns {Cartesian3} The modified result parameter.
  4229. *
  4230. * @example
  4231. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  4232. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  4233. * // A shortcut for
  4234. * // Cartesian3 p = ...
  4235. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  4236. */
  4237. Matrix4.multiplyByPointAsVector = function (matrix, cartesian, result) {
  4238. //>>includeStart('debug', pragmas.debug);
  4239. Check.Check.typeOf.object("matrix", matrix);
  4240. Check.Check.typeOf.object("cartesian", cartesian);
  4241. Check.Check.typeOf.object("result", result);
  4242. //>>includeEnd('debug');
  4243. var vX = cartesian.x;
  4244. var vY = cartesian.y;
  4245. var vZ = cartesian.z;
  4246. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  4247. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  4248. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  4249. result.x = x;
  4250. result.y = y;
  4251. result.z = z;
  4252. return result;
  4253. };
  4254. /**
  4255. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  4256. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  4257. *
  4258. * @param {Matrix4} matrix The matrix.
  4259. * @param {Cartesian3} cartesian The point.
  4260. * @param {Cartesian3} result The object onto which to store the result.
  4261. * @returns {Cartesian3} The modified result parameter.
  4262. *
  4263. * @example
  4264. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  4265. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  4266. */
  4267. Matrix4.multiplyByPoint = function (matrix, cartesian, result) {
  4268. //>>includeStart('debug', pragmas.debug);
  4269. Check.Check.typeOf.object("matrix", matrix);
  4270. Check.Check.typeOf.object("cartesian", cartesian);
  4271. Check.Check.typeOf.object("result", result);
  4272. //>>includeEnd('debug');
  4273. var vX = cartesian.x;
  4274. var vY = cartesian.y;
  4275. var vZ = cartesian.z;
  4276. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  4277. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  4278. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  4279. result.x = x;
  4280. result.y = y;
  4281. result.z = z;
  4282. return result;
  4283. };
  4284. /**
  4285. * Computes the product of a matrix and a scalar.
  4286. *
  4287. * @param {Matrix4} matrix The matrix.
  4288. * @param {Number} scalar The number to multiply by.
  4289. * @param {Matrix4} result The object onto which to store the result.
  4290. * @returns {Matrix4} The modified result parameter.
  4291. *
  4292. * @example
  4293. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  4294. * // m = [10.0, 11.0, 12.0, 13.0]
  4295. * // [14.0, 15.0, 16.0, 17.0]
  4296. * // [18.0, 19.0, 20.0, 21.0]
  4297. * // [22.0, 23.0, 24.0, 25.0]
  4298. *
  4299. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  4300. *
  4301. * // m remains the same
  4302. * // a = [-20.0, -22.0, -24.0, -26.0]
  4303. * // [-28.0, -30.0, -32.0, -34.0]
  4304. * // [-36.0, -38.0, -40.0, -42.0]
  4305. * // [-44.0, -46.0, -48.0, -50.0]
  4306. */
  4307. Matrix4.multiplyByScalar = function (matrix, scalar, result) {
  4308. //>>includeStart('debug', pragmas.debug);
  4309. Check.Check.typeOf.object("matrix", matrix);
  4310. Check.Check.typeOf.number("scalar", scalar);
  4311. Check.Check.typeOf.object("result", result);
  4312. //>>includeEnd('debug');
  4313. result[0] = matrix[0] * scalar;
  4314. result[1] = matrix[1] * scalar;
  4315. result[2] = matrix[2] * scalar;
  4316. result[3] = matrix[3] * scalar;
  4317. result[4] = matrix[4] * scalar;
  4318. result[5] = matrix[5] * scalar;
  4319. result[6] = matrix[6] * scalar;
  4320. result[7] = matrix[7] * scalar;
  4321. result[8] = matrix[8] * scalar;
  4322. result[9] = matrix[9] * scalar;
  4323. result[10] = matrix[10] * scalar;
  4324. result[11] = matrix[11] * scalar;
  4325. result[12] = matrix[12] * scalar;
  4326. result[13] = matrix[13] * scalar;
  4327. result[14] = matrix[14] * scalar;
  4328. result[15] = matrix[15] * scalar;
  4329. return result;
  4330. };
  4331. /**
  4332. * Computes a negated copy of the provided matrix.
  4333. *
  4334. * @param {Matrix4} matrix The matrix to negate.
  4335. * @param {Matrix4} result The object onto which to store the result.
  4336. * @returns {Matrix4} The modified result parameter.
  4337. *
  4338. * @example
  4339. * //create a new Matrix4 instance which is a negation of a Matrix4
  4340. * // m = [10.0, 11.0, 12.0, 13.0]
  4341. * // [14.0, 15.0, 16.0, 17.0]
  4342. * // [18.0, 19.0, 20.0, 21.0]
  4343. * // [22.0, 23.0, 24.0, 25.0]
  4344. *
  4345. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  4346. *
  4347. * // m remains the same
  4348. * // a = [-10.0, -11.0, -12.0, -13.0]
  4349. * // [-14.0, -15.0, -16.0, -17.0]
  4350. * // [-18.0, -19.0, -20.0, -21.0]
  4351. * // [-22.0, -23.0, -24.0, -25.0]
  4352. */
  4353. Matrix4.negate = function (matrix, result) {
  4354. //>>includeStart('debug', pragmas.debug);
  4355. Check.Check.typeOf.object("matrix", matrix);
  4356. Check.Check.typeOf.object("result", result);
  4357. //>>includeEnd('debug');
  4358. result[0] = -matrix[0];
  4359. result[1] = -matrix[1];
  4360. result[2] = -matrix[2];
  4361. result[3] = -matrix[3];
  4362. result[4] = -matrix[4];
  4363. result[5] = -matrix[5];
  4364. result[6] = -matrix[6];
  4365. result[7] = -matrix[7];
  4366. result[8] = -matrix[8];
  4367. result[9] = -matrix[9];
  4368. result[10] = -matrix[10];
  4369. result[11] = -matrix[11];
  4370. result[12] = -matrix[12];
  4371. result[13] = -matrix[13];
  4372. result[14] = -matrix[14];
  4373. result[15] = -matrix[15];
  4374. return result;
  4375. };
  4376. /**
  4377. * Computes the transpose of the provided matrix.
  4378. *
  4379. * @param {Matrix4} matrix The matrix to transpose.
  4380. * @param {Matrix4} result The object onto which to store the result.
  4381. * @returns {Matrix4} The modified result parameter.
  4382. *
  4383. * @example
  4384. * //returns transpose of a Matrix4
  4385. * // m = [10.0, 11.0, 12.0, 13.0]
  4386. * // [14.0, 15.0, 16.0, 17.0]
  4387. * // [18.0, 19.0, 20.0, 21.0]
  4388. * // [22.0, 23.0, 24.0, 25.0]
  4389. *
  4390. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  4391. *
  4392. * // m remains the same
  4393. * // a = [10.0, 14.0, 18.0, 22.0]
  4394. * // [11.0, 15.0, 19.0, 23.0]
  4395. * // [12.0, 16.0, 20.0, 24.0]
  4396. * // [13.0, 17.0, 21.0, 25.0]
  4397. */
  4398. Matrix4.transpose = function (matrix, result) {
  4399. //>>includeStart('debug', pragmas.debug);
  4400. Check.Check.typeOf.object("matrix", matrix);
  4401. Check.Check.typeOf.object("result", result);
  4402. //>>includeEnd('debug');
  4403. var matrix1 = matrix[1];
  4404. var matrix2 = matrix[2];
  4405. var matrix3 = matrix[3];
  4406. var matrix6 = matrix[6];
  4407. var matrix7 = matrix[7];
  4408. var matrix11 = matrix[11];
  4409. result[0] = matrix[0];
  4410. result[1] = matrix[4];
  4411. result[2] = matrix[8];
  4412. result[3] = matrix[12];
  4413. result[4] = matrix1;
  4414. result[5] = matrix[5];
  4415. result[6] = matrix[9];
  4416. result[7] = matrix[13];
  4417. result[8] = matrix2;
  4418. result[9] = matrix6;
  4419. result[10] = matrix[10];
  4420. result[11] = matrix[14];
  4421. result[12] = matrix3;
  4422. result[13] = matrix7;
  4423. result[14] = matrix11;
  4424. result[15] = matrix[15];
  4425. return result;
  4426. };
  4427. /**
  4428. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  4429. *
  4430. * @param {Matrix4} matrix The matrix with signed elements.
  4431. * @param {Matrix4} result The object onto which to store the result.
  4432. * @returns {Matrix4} The modified result parameter.
  4433. */
  4434. Matrix4.abs = function (matrix, result) {
  4435. //>>includeStart('debug', pragmas.debug);
  4436. Check.Check.typeOf.object("matrix", matrix);
  4437. Check.Check.typeOf.object("result", result);
  4438. //>>includeEnd('debug');
  4439. result[0] = Math.abs(matrix[0]);
  4440. result[1] = Math.abs(matrix[1]);
  4441. result[2] = Math.abs(matrix[2]);
  4442. result[3] = Math.abs(matrix[3]);
  4443. result[4] = Math.abs(matrix[4]);
  4444. result[5] = Math.abs(matrix[5]);
  4445. result[6] = Math.abs(matrix[6]);
  4446. result[7] = Math.abs(matrix[7]);
  4447. result[8] = Math.abs(matrix[8]);
  4448. result[9] = Math.abs(matrix[9]);
  4449. result[10] = Math.abs(matrix[10]);
  4450. result[11] = Math.abs(matrix[11]);
  4451. result[12] = Math.abs(matrix[12]);
  4452. result[13] = Math.abs(matrix[13]);
  4453. result[14] = Math.abs(matrix[14]);
  4454. result[15] = Math.abs(matrix[15]);
  4455. return result;
  4456. };
  4457. /**
  4458. * Compares the provided matrices componentwise and returns
  4459. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4460. *
  4461. * @param {Matrix4} [left] The first matrix.
  4462. * @param {Matrix4} [right] The second matrix.
  4463. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  4464. *
  4465. * @example
  4466. * //compares two Matrix4 instances
  4467. *
  4468. * // a = [10.0, 14.0, 18.0, 22.0]
  4469. * // [11.0, 15.0, 19.0, 23.0]
  4470. * // [12.0, 16.0, 20.0, 24.0]
  4471. * // [13.0, 17.0, 21.0, 25.0]
  4472. *
  4473. * // b = [10.0, 14.0, 18.0, 22.0]
  4474. * // [11.0, 15.0, 19.0, 23.0]
  4475. * // [12.0, 16.0, 20.0, 24.0]
  4476. * // [13.0, 17.0, 21.0, 25.0]
  4477. *
  4478. * if(Cesium.Matrix4.equals(a,b)) {
  4479. * console.log("Both matrices are equal");
  4480. * } else {
  4481. * console.log("They are not equal");
  4482. * }
  4483. *
  4484. * //Prints "Both matrices are equal" on the console
  4485. */
  4486. Matrix4.equals = function (left, right) {
  4487. // Given that most matrices will be transformation matrices, the elements
  4488. // are tested in order such that the test is likely to fail as early
  4489. // as possible. I _think_ this is just as friendly to the L1 cache
  4490. // as testing in index order. It is certainty faster in practice.
  4491. return (
  4492. left === right ||
  4493. (when.defined(left) &&
  4494. when.defined(right) &&
  4495. // Translation
  4496. left[12] === right[12] &&
  4497. left[13] === right[13] &&
  4498. left[14] === right[14] &&
  4499. // Rotation/scale
  4500. left[0] === right[0] &&
  4501. left[1] === right[1] &&
  4502. left[2] === right[2] &&
  4503. left[4] === right[4] &&
  4504. left[5] === right[5] &&
  4505. left[6] === right[6] &&
  4506. left[8] === right[8] &&
  4507. left[9] === right[9] &&
  4508. left[10] === right[10] &&
  4509. // Bottom row
  4510. left[3] === right[3] &&
  4511. left[7] === right[7] &&
  4512. left[11] === right[11] &&
  4513. left[15] === right[15])
  4514. );
  4515. };
  4516. /**
  4517. * Compares the provided matrices componentwise and returns
  4518. * <code>true</code> if they are within the provided epsilon,
  4519. * <code>false</code> otherwise.
  4520. *
  4521. * @param {Matrix4} [left] The first matrix.
  4522. * @param {Matrix4} [right] The second matrix.
  4523. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  4524. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  4525. *
  4526. * @example
  4527. * //compares two Matrix4 instances
  4528. *
  4529. * // a = [10.5, 14.5, 18.5, 22.5]
  4530. * // [11.5, 15.5, 19.5, 23.5]
  4531. * // [12.5, 16.5, 20.5, 24.5]
  4532. * // [13.5, 17.5, 21.5, 25.5]
  4533. *
  4534. * // b = [10.0, 14.0, 18.0, 22.0]
  4535. * // [11.0, 15.0, 19.0, 23.0]
  4536. * // [12.0, 16.0, 20.0, 24.0]
  4537. * // [13.0, 17.0, 21.0, 25.0]
  4538. *
  4539. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  4540. * console.log("Difference between both the matrices is less than 0.1");
  4541. * } else {
  4542. * console.log("Difference between both the matrices is not less than 0.1");
  4543. * }
  4544. *
  4545. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  4546. */
  4547. Matrix4.equalsEpsilon = function (left, right, epsilon) {
  4548. epsilon = when.defaultValue(epsilon, 0);
  4549. return (
  4550. left === right ||
  4551. (when.defined(left) &&
  4552. when.defined(right) &&
  4553. Math.abs(left[0] - right[0]) <= epsilon &&
  4554. Math.abs(left[1] - right[1]) <= epsilon &&
  4555. Math.abs(left[2] - right[2]) <= epsilon &&
  4556. Math.abs(left[3] - right[3]) <= epsilon &&
  4557. Math.abs(left[4] - right[4]) <= epsilon &&
  4558. Math.abs(left[5] - right[5]) <= epsilon &&
  4559. Math.abs(left[6] - right[6]) <= epsilon &&
  4560. Math.abs(left[7] - right[7]) <= epsilon &&
  4561. Math.abs(left[8] - right[8]) <= epsilon &&
  4562. Math.abs(left[9] - right[9]) <= epsilon &&
  4563. Math.abs(left[10] - right[10]) <= epsilon &&
  4564. Math.abs(left[11] - right[11]) <= epsilon &&
  4565. Math.abs(left[12] - right[12]) <= epsilon &&
  4566. Math.abs(left[13] - right[13]) <= epsilon &&
  4567. Math.abs(left[14] - right[14]) <= epsilon &&
  4568. Math.abs(left[15] - right[15]) <= epsilon)
  4569. );
  4570. };
  4571. /**
  4572. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  4573. *
  4574. * @param {Matrix4} matrix The matrix to use.
  4575. * @param {Cartesian3} result The object onto which to store the result.
  4576. * @returns {Cartesian3} The modified result parameter.
  4577. */
  4578. Matrix4.getTranslation = function (matrix, result) {
  4579. //>>includeStart('debug', pragmas.debug);
  4580. Check.Check.typeOf.object("matrix", matrix);
  4581. Check.Check.typeOf.object("result", result);
  4582. //>>includeEnd('debug');
  4583. result.x = matrix[12];
  4584. result.y = matrix[13];
  4585. result.z = matrix[14];
  4586. return result;
  4587. };
  4588. /**
  4589. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is an affine transformation matrix.
  4590. *
  4591. * @param {Matrix4} matrix The matrix to use.
  4592. * @param {Matrix3} result The object onto which to store the result.
  4593. * @returns {Matrix3} The modified result parameter.
  4594. *
  4595. * @example
  4596. * // returns a Matrix3 instance from a Matrix4 instance
  4597. *
  4598. * // m = [10.0, 14.0, 18.0, 22.0]
  4599. * // [11.0, 15.0, 19.0, 23.0]
  4600. * // [12.0, 16.0, 20.0, 24.0]
  4601. * // [13.0, 17.0, 21.0, 25.0]
  4602. *
  4603. * var b = new Cesium.Matrix3();
  4604. * Cesium.Matrix4.getMatrix3(m,b);
  4605. *
  4606. * // b = [10.0, 14.0, 18.0]
  4607. * // [11.0, 15.0, 19.0]
  4608. * // [12.0, 16.0, 20.0]
  4609. */
  4610. Matrix4.getMatrix3 = function (matrix, result) {
  4611. //>>includeStart('debug', pragmas.debug);
  4612. Check.Check.typeOf.object("matrix", matrix);
  4613. Check.Check.typeOf.object("result", result);
  4614. //>>includeEnd('debug');
  4615. result[0] = matrix[0];
  4616. result[1] = matrix[1];
  4617. result[2] = matrix[2];
  4618. result[3] = matrix[4];
  4619. result[4] = matrix[5];
  4620. result[5] = matrix[6];
  4621. result[6] = matrix[8];
  4622. result[7] = matrix[9];
  4623. result[8] = matrix[10];
  4624. return result;
  4625. };
  4626. var scratchInverseRotation = new Matrix3();
  4627. var scratchMatrix3Zero = new Matrix3();
  4628. var scratchBottomRow = new Cartesian4();
  4629. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  4630. /**
  4631. * Computes the inverse of the provided matrix using Cramers Rule.
  4632. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  4633. * If the matrix is an affine transformation matrix, it is more efficient
  4634. * to invert it with {@link Matrix4.inverseTransformation}.
  4635. *
  4636. * @param {Matrix4} matrix The matrix to invert.
  4637. * @param {Matrix4} result The object onto which to store the result.
  4638. * @returns {Matrix4} The modified result parameter.
  4639. *
  4640. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  4641. */
  4642. Matrix4.inverse = function (matrix, result) {
  4643. //>>includeStart('debug', pragmas.debug);
  4644. Check.Check.typeOf.object("matrix", matrix);
  4645. Check.Check.typeOf.object("result", result);
  4646. //>>includeEnd('debug');
  4647. //
  4648. // Ported from:
  4649. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  4650. //
  4651. var src0 = matrix[0];
  4652. var src1 = matrix[4];
  4653. var src2 = matrix[8];
  4654. var src3 = matrix[12];
  4655. var src4 = matrix[1];
  4656. var src5 = matrix[5];
  4657. var src6 = matrix[9];
  4658. var src7 = matrix[13];
  4659. var src8 = matrix[2];
  4660. var src9 = matrix[6];
  4661. var src10 = matrix[10];
  4662. var src11 = matrix[14];
  4663. var src12 = matrix[3];
  4664. var src13 = matrix[7];
  4665. var src14 = matrix[11];
  4666. var src15 = matrix[15];
  4667. // calculate pairs for first 8 elements (cofactors)
  4668. var tmp0 = src10 * src15;
  4669. var tmp1 = src11 * src14;
  4670. var tmp2 = src9 * src15;
  4671. var tmp3 = src11 * src13;
  4672. var tmp4 = src9 * src14;
  4673. var tmp5 = src10 * src13;
  4674. var tmp6 = src8 * src15;
  4675. var tmp7 = src11 * src12;
  4676. var tmp8 = src8 * src14;
  4677. var tmp9 = src10 * src12;
  4678. var tmp10 = src8 * src13;
  4679. var tmp11 = src9 * src12;
  4680. // calculate first 8 elements (cofactors)
  4681. var dst0 =
  4682. tmp0 * src5 +
  4683. tmp3 * src6 +
  4684. tmp4 * src7 -
  4685. (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  4686. var dst1 =
  4687. tmp1 * src4 +
  4688. tmp6 * src6 +
  4689. tmp9 * src7 -
  4690. (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  4691. var dst2 =
  4692. tmp2 * src4 +
  4693. tmp7 * src5 +
  4694. tmp10 * src7 -
  4695. (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  4696. var dst3 =
  4697. tmp5 * src4 +
  4698. tmp8 * src5 +
  4699. tmp11 * src6 -
  4700. (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  4701. var dst4 =
  4702. tmp1 * src1 +
  4703. tmp2 * src2 +
  4704. tmp5 * src3 -
  4705. (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  4706. var dst5 =
  4707. tmp0 * src0 +
  4708. tmp7 * src2 +
  4709. tmp8 * src3 -
  4710. (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  4711. var dst6 =
  4712. tmp3 * src0 +
  4713. tmp6 * src1 +
  4714. tmp11 * src3 -
  4715. (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  4716. var dst7 =
  4717. tmp4 * src0 +
  4718. tmp9 * src1 +
  4719. tmp10 * src2 -
  4720. (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  4721. // calculate pairs for second 8 elements (cofactors)
  4722. tmp0 = src2 * src7;
  4723. tmp1 = src3 * src6;
  4724. tmp2 = src1 * src7;
  4725. tmp3 = src3 * src5;
  4726. tmp4 = src1 * src6;
  4727. tmp5 = src2 * src5;
  4728. tmp6 = src0 * src7;
  4729. tmp7 = src3 * src4;
  4730. tmp8 = src0 * src6;
  4731. tmp9 = src2 * src4;
  4732. tmp10 = src0 * src5;
  4733. tmp11 = src1 * src4;
  4734. // calculate second 8 elements (cofactors)
  4735. var dst8 =
  4736. tmp0 * src13 +
  4737. tmp3 * src14 +
  4738. tmp4 * src15 -
  4739. (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  4740. var dst9 =
  4741. tmp1 * src12 +
  4742. tmp6 * src14 +
  4743. tmp9 * src15 -
  4744. (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  4745. var dst10 =
  4746. tmp2 * src12 +
  4747. tmp7 * src13 +
  4748. tmp10 * src15 -
  4749. (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  4750. var dst11 =
  4751. tmp5 * src12 +
  4752. tmp8 * src13 +
  4753. tmp11 * src14 -
  4754. (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  4755. var dst12 =
  4756. tmp2 * src10 +
  4757. tmp5 * src11 +
  4758. tmp1 * src9 -
  4759. (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  4760. var dst13 =
  4761. tmp8 * src11 +
  4762. tmp0 * src8 +
  4763. tmp7 * src10 -
  4764. (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  4765. var dst14 =
  4766. tmp6 * src9 +
  4767. tmp11 * src11 +
  4768. tmp3 * src8 -
  4769. (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  4770. var dst15 =
  4771. tmp10 * src10 +
  4772. tmp4 * src8 +
  4773. tmp9 * src9 -
  4774. (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  4775. // calculate determinant
  4776. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  4777. if (Math.abs(det) < _Math.CesiumMath.EPSILON21) {
  4778. // Special case for a zero scale matrix that can occur, for example,
  4779. // when a model's node has a [0, 0, 0] scale.
  4780. if (
  4781. Matrix3.equalsEpsilon(
  4782. Matrix4.getMatrix3(matrix, scratchInverseRotation),
  4783. scratchMatrix3Zero,
  4784. _Math.CesiumMath.EPSILON7
  4785. ) &&
  4786. Cartesian4.equals(
  4787. Matrix4.getRow(matrix, 3, scratchBottomRow),
  4788. scratchExpectedBottomRow
  4789. )
  4790. ) {
  4791. result[0] = 0.0;
  4792. result[1] = 0.0;
  4793. result[2] = 0.0;
  4794. result[3] = 0.0;
  4795. result[4] = 0.0;
  4796. result[5] = 0.0;
  4797. result[6] = 0.0;
  4798. result[7] = 0.0;
  4799. result[8] = 0.0;
  4800. result[9] = 0.0;
  4801. result[10] = 0.0;
  4802. result[11] = 0.0;
  4803. result[12] = -matrix[12];
  4804. result[13] = -matrix[13];
  4805. result[14] = -matrix[14];
  4806. result[15] = 1.0;
  4807. return result;
  4808. }
  4809. throw new RuntimeError.RuntimeError(
  4810. "matrix is not invertible because its determinate is zero."
  4811. );
  4812. }
  4813. // calculate matrix inverse
  4814. det = 1.0 / det;
  4815. result[0] = dst0 * det;
  4816. result[1] = dst1 * det;
  4817. result[2] = dst2 * det;
  4818. result[3] = dst3 * det;
  4819. result[4] = dst4 * det;
  4820. result[5] = dst5 * det;
  4821. result[6] = dst6 * det;
  4822. result[7] = dst7 * det;
  4823. result[8] = dst8 * det;
  4824. result[9] = dst9 * det;
  4825. result[10] = dst10 * det;
  4826. result[11] = dst11 * det;
  4827. result[12] = dst12 * det;
  4828. result[13] = dst13 * det;
  4829. result[14] = dst14 * det;
  4830. result[15] = dst15 * det;
  4831. return result;
  4832. };
  4833. /**
  4834. * Computes the inverse of the provided matrix assuming it is
  4835. * an affine transformation matrix, where the upper left 3x3 elements
  4836. * are a rotation matrix, and the upper three elements in the fourth
  4837. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  4838. * The matrix is not verified to be in the proper form.
  4839. * This method is faster than computing the inverse for a general 4x4
  4840. * matrix using {@link Matrix4.inverse}.
  4841. *
  4842. * @param {Matrix4} matrix The matrix to invert.
  4843. * @param {Matrix4} result The object onto which to store the result.
  4844. * @returns {Matrix4} The modified result parameter.
  4845. */
  4846. Matrix4.inverseTransformation = function (matrix, result) {
  4847. //>>includeStart('debug', pragmas.debug);
  4848. Check.Check.typeOf.object("matrix", matrix);
  4849. Check.Check.typeOf.object("result", result);
  4850. //>>includeEnd('debug');
  4851. //This function is an optimized version of the below 4 lines.
  4852. //var rT = Matrix3.transpose(Matrix4.getMatrix3(matrix));
  4853. //var rTN = Matrix3.negate(rT);
  4854. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  4855. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  4856. var matrix0 = matrix[0];
  4857. var matrix1 = matrix[1];
  4858. var matrix2 = matrix[2];
  4859. var matrix4 = matrix[4];
  4860. var matrix5 = matrix[5];
  4861. var matrix6 = matrix[6];
  4862. var matrix8 = matrix[8];
  4863. var matrix9 = matrix[9];
  4864. var matrix10 = matrix[10];
  4865. var vX = matrix[12];
  4866. var vY = matrix[13];
  4867. var vZ = matrix[14];
  4868. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  4869. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  4870. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  4871. result[0] = matrix0;
  4872. result[1] = matrix4;
  4873. result[2] = matrix8;
  4874. result[3] = 0.0;
  4875. result[4] = matrix1;
  4876. result[5] = matrix5;
  4877. result[6] = matrix9;
  4878. result[7] = 0.0;
  4879. result[8] = matrix2;
  4880. result[9] = matrix6;
  4881. result[10] = matrix10;
  4882. result[11] = 0.0;
  4883. result[12] = x;
  4884. result[13] = y;
  4885. result[14] = z;
  4886. result[15] = 1.0;
  4887. return result;
  4888. };
  4889. /**
  4890. * An immutable Matrix4 instance initialized to the identity matrix.
  4891. *
  4892. * @type {Matrix4}
  4893. * @constant
  4894. */
  4895. Matrix4.IDENTITY = Object.freeze(
  4896. new Matrix4(
  4897. 1.0,
  4898. 0.0,
  4899. 0.0,
  4900. 0.0,
  4901. 0.0,
  4902. 1.0,
  4903. 0.0,
  4904. 0.0,
  4905. 0.0,
  4906. 0.0,
  4907. 1.0,
  4908. 0.0,
  4909. 0.0,
  4910. 0.0,
  4911. 0.0,
  4912. 1.0
  4913. )
  4914. );
  4915. /**
  4916. * An immutable Matrix4 instance initialized to the zero matrix.
  4917. *
  4918. * @type {Matrix4}
  4919. * @constant
  4920. */
  4921. Matrix4.ZERO = Object.freeze(
  4922. new Matrix4(
  4923. 0.0,
  4924. 0.0,
  4925. 0.0,
  4926. 0.0,
  4927. 0.0,
  4928. 0.0,
  4929. 0.0,
  4930. 0.0,
  4931. 0.0,
  4932. 0.0,
  4933. 0.0,
  4934. 0.0,
  4935. 0.0,
  4936. 0.0,
  4937. 0.0,
  4938. 0.0
  4939. )
  4940. );
  4941. /**
  4942. * The index into Matrix4 for column 0, row 0.
  4943. *
  4944. * @type {Number}
  4945. * @constant
  4946. */
  4947. Matrix4.COLUMN0ROW0 = 0;
  4948. /**
  4949. * The index into Matrix4 for column 0, row 1.
  4950. *
  4951. * @type {Number}
  4952. * @constant
  4953. */
  4954. Matrix4.COLUMN0ROW1 = 1;
  4955. /**
  4956. * The index into Matrix4 for column 0, row 2.
  4957. *
  4958. * @type {Number}
  4959. * @constant
  4960. */
  4961. Matrix4.COLUMN0ROW2 = 2;
  4962. /**
  4963. * The index into Matrix4 for column 0, row 3.
  4964. *
  4965. * @type {Number}
  4966. * @constant
  4967. */
  4968. Matrix4.COLUMN0ROW3 = 3;
  4969. /**
  4970. * The index into Matrix4 for column 1, row 0.
  4971. *
  4972. * @type {Number}
  4973. * @constant
  4974. */
  4975. Matrix4.COLUMN1ROW0 = 4;
  4976. /**
  4977. * The index into Matrix4 for column 1, row 1.
  4978. *
  4979. * @type {Number}
  4980. * @constant
  4981. */
  4982. Matrix4.COLUMN1ROW1 = 5;
  4983. /**
  4984. * The index into Matrix4 for column 1, row 2.
  4985. *
  4986. * @type {Number}
  4987. * @constant
  4988. */
  4989. Matrix4.COLUMN1ROW2 = 6;
  4990. /**
  4991. * The index into Matrix4 for column 1, row 3.
  4992. *
  4993. * @type {Number}
  4994. * @constant
  4995. */
  4996. Matrix4.COLUMN1ROW3 = 7;
  4997. /**
  4998. * The index into Matrix4 for column 2, row 0.
  4999. *
  5000. * @type {Number}
  5001. * @constant
  5002. */
  5003. Matrix4.COLUMN2ROW0 = 8;
  5004. /**
  5005. * The index into Matrix4 for column 2, row 1.
  5006. *
  5007. * @type {Number}
  5008. * @constant
  5009. */
  5010. Matrix4.COLUMN2ROW1 = 9;
  5011. /**
  5012. * The index into Matrix4 for column 2, row 2.
  5013. *
  5014. * @type {Number}
  5015. * @constant
  5016. */
  5017. Matrix4.COLUMN2ROW2 = 10;
  5018. /**
  5019. * The index into Matrix4 for column 2, row 3.
  5020. *
  5021. * @type {Number}
  5022. * @constant
  5023. */
  5024. Matrix4.COLUMN2ROW3 = 11;
  5025. /**
  5026. * The index into Matrix4 for column 3, row 0.
  5027. *
  5028. * @type {Number}
  5029. * @constant
  5030. */
  5031. Matrix4.COLUMN3ROW0 = 12;
  5032. /**
  5033. * The index into Matrix4 for column 3, row 1.
  5034. *
  5035. * @type {Number}
  5036. * @constant
  5037. */
  5038. Matrix4.COLUMN3ROW1 = 13;
  5039. /**
  5040. * The index into Matrix4 for column 3, row 2.
  5041. *
  5042. * @type {Number}
  5043. * @constant
  5044. */
  5045. Matrix4.COLUMN3ROW2 = 14;
  5046. /**
  5047. * The index into Matrix4 for column 3, row 3.
  5048. *
  5049. * @type {Number}
  5050. * @constant
  5051. */
  5052. Matrix4.COLUMN3ROW3 = 15;
  5053. Object.defineProperties(Matrix4.prototype, {
  5054. /**
  5055. * Gets the number of items in the collection.
  5056. * @memberof Matrix4.prototype
  5057. *
  5058. * @type {Number}
  5059. */
  5060. length: {
  5061. get: function () {
  5062. return Matrix4.packedLength;
  5063. },
  5064. },
  5065. });
  5066. /**
  5067. * Duplicates the provided Matrix4 instance.
  5068. *
  5069. * @param {Matrix4} [result] The object onto which to store the result.
  5070. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5071. */
  5072. Matrix4.prototype.clone = function (result) {
  5073. return Matrix4.clone(this, result);
  5074. };
  5075. /**
  5076. * Compares this matrix to the provided matrix componentwise and returns
  5077. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5078. *
  5079. * @param {Matrix4} [right] The right hand side matrix.
  5080. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5081. */
  5082. Matrix4.prototype.equals = function (right) {
  5083. return Matrix4.equals(this, right);
  5084. };
  5085. /**
  5086. * @private
  5087. */
  5088. Matrix4.equalsArray = function (matrix, array, offset) {
  5089. return (
  5090. matrix[0] === array[offset] &&
  5091. matrix[1] === array[offset + 1] &&
  5092. matrix[2] === array[offset + 2] &&
  5093. matrix[3] === array[offset + 3] &&
  5094. matrix[4] === array[offset + 4] &&
  5095. matrix[5] === array[offset + 5] &&
  5096. matrix[6] === array[offset + 6] &&
  5097. matrix[7] === array[offset + 7] &&
  5098. matrix[8] === array[offset + 8] &&
  5099. matrix[9] === array[offset + 9] &&
  5100. matrix[10] === array[offset + 10] &&
  5101. matrix[11] === array[offset + 11] &&
  5102. matrix[12] === array[offset + 12] &&
  5103. matrix[13] === array[offset + 13] &&
  5104. matrix[14] === array[offset + 14] &&
  5105. matrix[15] === array[offset + 15]
  5106. );
  5107. };
  5108. /**
  5109. * Compares this matrix to the provided matrix componentwise and returns
  5110. * <code>true</code> if they are within the provided epsilon,
  5111. * <code>false</code> otherwise.
  5112. *
  5113. * @param {Matrix4} [right] The right hand side matrix.
  5114. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  5115. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  5116. */
  5117. Matrix4.prototype.equalsEpsilon = function (right, epsilon) {
  5118. return Matrix4.equalsEpsilon(this, right, epsilon);
  5119. };
  5120. /**
  5121. * Computes a string representing this Matrix with each row being
  5122. * on a separate line and in the format '(column0, column1, column2, column3)'.
  5123. *
  5124. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  5125. */
  5126. Matrix4.prototype.toString = function () {
  5127. return (
  5128. "(" +
  5129. this[0] +
  5130. ", " +
  5131. this[4] +
  5132. ", " +
  5133. this[8] +
  5134. ", " +
  5135. this[12] +
  5136. ")\n" +
  5137. "(" +
  5138. this[1] +
  5139. ", " +
  5140. this[5] +
  5141. ", " +
  5142. this[9] +
  5143. ", " +
  5144. this[13] +
  5145. ")\n" +
  5146. "(" +
  5147. this[2] +
  5148. ", " +
  5149. this[6] +
  5150. ", " +
  5151. this[10] +
  5152. ", " +
  5153. this[14] +
  5154. ")\n" +
  5155. "(" +
  5156. this[3] +
  5157. ", " +
  5158. this[7] +
  5159. ", " +
  5160. this[11] +
  5161. ", " +
  5162. this[15] +
  5163. ")"
  5164. );
  5165. };
  5166. /**
  5167. * A bounding sphere with a center and a radius.
  5168. * @alias BoundingSphere
  5169. * @constructor
  5170. *
  5171. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  5172. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  5173. *
  5174. * @see AxisAlignedBoundingBox
  5175. * @see BoundingRectangle
  5176. * @see Packable
  5177. */
  5178. function BoundingSphere(center, radius) {
  5179. /**
  5180. * The center point of the sphere.
  5181. * @type {Cartesian3}
  5182. * @default {@link Cartesian3.ZERO}
  5183. */
  5184. this.center = Cartesian2.Cartesian3.clone(when.defaultValue(center, Cartesian2.Cartesian3.ZERO));
  5185. /**
  5186. * The radius of the sphere.
  5187. * @type {Number}
  5188. * @default 0.0
  5189. */
  5190. this.radius = when.defaultValue(radius, 0.0);
  5191. }
  5192. var fromPointsXMin = new Cartesian2.Cartesian3();
  5193. var fromPointsYMin = new Cartesian2.Cartesian3();
  5194. var fromPointsZMin = new Cartesian2.Cartesian3();
  5195. var fromPointsXMax = new Cartesian2.Cartesian3();
  5196. var fromPointsYMax = new Cartesian2.Cartesian3();
  5197. var fromPointsZMax = new Cartesian2.Cartesian3();
  5198. var fromPointsCurrentPos = new Cartesian2.Cartesian3();
  5199. var fromPointsScratch = new Cartesian2.Cartesian3();
  5200. var fromPointsRitterCenter = new Cartesian2.Cartesian3();
  5201. var fromPointsMinBoxPt = new Cartesian2.Cartesian3();
  5202. var fromPointsMaxBoxPt = new Cartesian2.Cartesian3();
  5203. var fromPointsNaiveCenterScratch = new Cartesian2.Cartesian3();
  5204. var volumeConstant = (4.0 / 3.0) * _Math.CesiumMath.PI;
  5205. /**
  5206. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  5207. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  5208. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  5209. *
  5210. * @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.
  5211. * @param {BoundingSphere} [result] The object onto which to store the result.
  5212. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5213. *
  5214. * @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
  5215. */
  5216. BoundingSphere.fromPoints = function (positions, result) {
  5217. if (!when.defined(result)) {
  5218. result = new BoundingSphere();
  5219. }
  5220. if (!when.defined(positions) || positions.length === 0) {
  5221. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5222. result.radius = 0.0;
  5223. return result;
  5224. }
  5225. var currentPos = Cartesian2.Cartesian3.clone(positions[0], fromPointsCurrentPos);
  5226. var xMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMin);
  5227. var yMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMin);
  5228. var zMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMin);
  5229. var xMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMax);
  5230. var yMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMax);
  5231. var zMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMax);
  5232. var numPositions = positions.length;
  5233. var i;
  5234. for (i = 1; i < numPositions; i++) {
  5235. Cartesian2.Cartesian3.clone(positions[i], currentPos);
  5236. var x = currentPos.x;
  5237. var y = currentPos.y;
  5238. var z = currentPos.z;
  5239. // Store points containing the the smallest and largest components
  5240. if (x < xMin.x) {
  5241. Cartesian2.Cartesian3.clone(currentPos, xMin);
  5242. }
  5243. if (x > xMax.x) {
  5244. Cartesian2.Cartesian3.clone(currentPos, xMax);
  5245. }
  5246. if (y < yMin.y) {
  5247. Cartesian2.Cartesian3.clone(currentPos, yMin);
  5248. }
  5249. if (y > yMax.y) {
  5250. Cartesian2.Cartesian3.clone(currentPos, yMax);
  5251. }
  5252. if (z < zMin.z) {
  5253. Cartesian2.Cartesian3.clone(currentPos, zMin);
  5254. }
  5255. if (z > zMax.z) {
  5256. Cartesian2.Cartesian3.clone(currentPos, zMax);
  5257. }
  5258. }
  5259. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  5260. var xSpan = Cartesian2.Cartesian3.magnitudeSquared(
  5261. Cartesian2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  5262. );
  5263. var ySpan = Cartesian2.Cartesian3.magnitudeSquared(
  5264. Cartesian2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  5265. );
  5266. var zSpan = Cartesian2.Cartesian3.magnitudeSquared(
  5267. Cartesian2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  5268. );
  5269. // Set the diameter endpoints to the largest span.
  5270. var diameter1 = xMin;
  5271. var diameter2 = xMax;
  5272. var maxSpan = xSpan;
  5273. if (ySpan > maxSpan) {
  5274. maxSpan = ySpan;
  5275. diameter1 = yMin;
  5276. diameter2 = yMax;
  5277. }
  5278. if (zSpan > maxSpan) {
  5279. maxSpan = zSpan;
  5280. diameter1 = zMin;
  5281. diameter2 = zMax;
  5282. }
  5283. // Calculate the center of the initial sphere found by Ritter's algorithm
  5284. var ritterCenter = fromPointsRitterCenter;
  5285. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  5286. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  5287. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  5288. // Calculate the radius of the initial sphere found by Ritter's algorithm
  5289. var radiusSquared = Cartesian2.Cartesian3.magnitudeSquared(
  5290. Cartesian2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  5291. );
  5292. var ritterRadius = Math.sqrt(radiusSquared);
  5293. // Find the center of the sphere found using the Naive method.
  5294. var minBoxPt = fromPointsMinBoxPt;
  5295. minBoxPt.x = xMin.x;
  5296. minBoxPt.y = yMin.y;
  5297. minBoxPt.z = zMin.z;
  5298. var maxBoxPt = fromPointsMaxBoxPt;
  5299. maxBoxPt.x = xMax.x;
  5300. maxBoxPt.y = yMax.y;
  5301. maxBoxPt.z = zMax.z;
  5302. var naiveCenter = Cartesian2.Cartesian3.midpoint(
  5303. minBoxPt,
  5304. maxBoxPt,
  5305. fromPointsNaiveCenterScratch
  5306. );
  5307. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  5308. var naiveRadius = 0;
  5309. for (i = 0; i < numPositions; i++) {
  5310. Cartesian2.Cartesian3.clone(positions[i], currentPos);
  5311. // Find the furthest point from the naive center to calculate the naive radius.
  5312. var r = Cartesian2.Cartesian3.magnitude(
  5313. Cartesian2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  5314. );
  5315. if (r > naiveRadius) {
  5316. naiveRadius = r;
  5317. }
  5318. // Make adjustments to the Ritter Sphere to include all points.
  5319. var oldCenterToPointSquared = Cartesian2.Cartesian3.magnitudeSquared(
  5320. Cartesian2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  5321. );
  5322. if (oldCenterToPointSquared > radiusSquared) {
  5323. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  5324. // Calculate new radius to include the point that lies outside
  5325. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  5326. radiusSquared = ritterRadius * ritterRadius;
  5327. // Calculate center of new Ritter sphere
  5328. var oldToNew = oldCenterToPoint - ritterRadius;
  5329. ritterCenter.x =
  5330. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  5331. oldCenterToPoint;
  5332. ritterCenter.y =
  5333. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  5334. oldCenterToPoint;
  5335. ritterCenter.z =
  5336. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  5337. oldCenterToPoint;
  5338. }
  5339. }
  5340. if (ritterRadius < naiveRadius) {
  5341. Cartesian2.Cartesian3.clone(ritterCenter, result.center);
  5342. result.radius = ritterRadius;
  5343. } else {
  5344. Cartesian2.Cartesian3.clone(naiveCenter, result.center);
  5345. result.radius = naiveRadius;
  5346. }
  5347. return result;
  5348. };
  5349. var defaultProjection = new GeographicProjection();
  5350. var fromRectangle2DLowerLeft = new Cartesian2.Cartesian3();
  5351. var fromRectangle2DUpperRight = new Cartesian2.Cartesian3();
  5352. var fromRectangle2DSouthwest = new Cartesian2.Cartographic();
  5353. var fromRectangle2DNortheast = new Cartesian2.Cartographic();
  5354. /**
  5355. * Computes a bounding sphere from a rectangle projected in 2D.
  5356. *
  5357. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  5358. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  5359. * @param {BoundingSphere} [result] The object onto which to store the result.
  5360. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5361. */
  5362. BoundingSphere.fromRectangle2D = function (rectangle, projection, result) {
  5363. return BoundingSphere.fromRectangleWithHeights2D(
  5364. rectangle,
  5365. projection,
  5366. 0.0,
  5367. 0.0,
  5368. result
  5369. );
  5370. };
  5371. /**
  5372. * Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
  5373. * object's minimum and maximum heights over the rectangle.
  5374. *
  5375. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  5376. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  5377. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  5378. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  5379. * @param {BoundingSphere} [result] The object onto which to store the result.
  5380. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5381. */
  5382. BoundingSphere.fromRectangleWithHeights2D = function (
  5383. rectangle,
  5384. projection,
  5385. minimumHeight,
  5386. maximumHeight,
  5387. result
  5388. ) {
  5389. if (!when.defined(result)) {
  5390. result = new BoundingSphere();
  5391. }
  5392. if (!when.defined(rectangle)) {
  5393. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5394. result.radius = 0.0;
  5395. return result;
  5396. }
  5397. projection = when.defaultValue(projection, defaultProjection);
  5398. Cartesian2.Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  5399. fromRectangle2DSouthwest.height = minimumHeight;
  5400. Cartesian2.Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  5401. fromRectangle2DNortheast.height = maximumHeight;
  5402. var lowerLeft = projection.project(
  5403. fromRectangle2DSouthwest,
  5404. fromRectangle2DLowerLeft
  5405. );
  5406. var upperRight = projection.project(
  5407. fromRectangle2DNortheast,
  5408. fromRectangle2DUpperRight
  5409. );
  5410. var width = upperRight.x - lowerLeft.x;
  5411. var height = upperRight.y - lowerLeft.y;
  5412. var elevation = upperRight.z - lowerLeft.z;
  5413. result.radius =
  5414. Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  5415. var center = result.center;
  5416. center.x = lowerLeft.x + width * 0.5;
  5417. center.y = lowerLeft.y + height * 0.5;
  5418. center.z = lowerLeft.z + elevation * 0.5;
  5419. return result;
  5420. };
  5421. var fromRectangle3DScratch = [];
  5422. /**
  5423. * Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
  5424. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  5425. *
  5426. * @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
  5427. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  5428. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  5429. * @param {BoundingSphere} [result] The object onto which to store the result.
  5430. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5431. */
  5432. BoundingSphere.fromRectangle3D = function (
  5433. rectangle,
  5434. ellipsoid,
  5435. surfaceHeight,
  5436. result
  5437. ) {
  5438. ellipsoid = when.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  5439. surfaceHeight = when.defaultValue(surfaceHeight, 0.0);
  5440. if (!when.defined(result)) {
  5441. result = new BoundingSphere();
  5442. }
  5443. if (!when.defined(rectangle)) {
  5444. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5445. result.radius = 0.0;
  5446. return result;
  5447. }
  5448. var positions = Cartesian2.Rectangle.subsample(
  5449. rectangle,
  5450. ellipsoid,
  5451. surfaceHeight,
  5452. fromRectangle3DScratch
  5453. );
  5454. return BoundingSphere.fromPoints(positions, result);
  5455. };
  5456. /**
  5457. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  5458. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  5459. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  5460. * ensure a tight fit.
  5461. *
  5462. * @param {Number[]} [positions] An array of points that the bounding sphere will enclose. Each point
  5463. * is formed from three elements in the array in the order X, Y, Z.
  5464. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  5465. * origin of the coordinate system. This is useful when the positions are to be used for
  5466. * relative-to-center (RTC) rendering.
  5467. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  5468. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  5469. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  5470. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  5471. * the stride is 5, however, two array elements are skipped and the next position begins at array
  5472. * index 5.
  5473. * @param {BoundingSphere} [result] The object onto which to store the result.
  5474. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5475. *
  5476. * @example
  5477. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  5478. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  5479. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  5480. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  5481. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  5482. * 4.0, 5.0, 6.0, 0.1, 0.2,
  5483. * 7.0, 8.0, 9.0, 0.1, 0.2];
  5484. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  5485. *
  5486. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  5487. */
  5488. BoundingSphere.fromVertices = function (positions, center, stride, result) {
  5489. if (!when.defined(result)) {
  5490. result = new BoundingSphere();
  5491. }
  5492. if (!when.defined(positions) || positions.length === 0) {
  5493. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5494. result.radius = 0.0;
  5495. return result;
  5496. }
  5497. center = when.defaultValue(center, Cartesian2.Cartesian3.ZERO);
  5498. stride = when.defaultValue(stride, 3);
  5499. //>>includeStart('debug', pragmas.debug);
  5500. Check.Check.typeOf.number.greaterThanOrEquals("stride", stride, 3);
  5501. //>>includeEnd('debug');
  5502. var currentPos = fromPointsCurrentPos;
  5503. currentPos.x = positions[0] + center.x;
  5504. currentPos.y = positions[1] + center.y;
  5505. currentPos.z = positions[2] + center.z;
  5506. var xMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMin);
  5507. var yMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMin);
  5508. var zMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMin);
  5509. var xMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMax);
  5510. var yMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMax);
  5511. var zMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMax);
  5512. var numElements = positions.length;
  5513. var i;
  5514. for (i = 0; i < numElements; i += stride) {
  5515. var x = positions[i] + center.x;
  5516. var y = positions[i + 1] + center.y;
  5517. var z = positions[i + 2] + center.z;
  5518. currentPos.x = x;
  5519. currentPos.y = y;
  5520. currentPos.z = z;
  5521. // Store points containing the the smallest and largest components
  5522. if (x < xMin.x) {
  5523. Cartesian2.Cartesian3.clone(currentPos, xMin);
  5524. }
  5525. if (x > xMax.x) {
  5526. Cartesian2.Cartesian3.clone(currentPos, xMax);
  5527. }
  5528. if (y < yMin.y) {
  5529. Cartesian2.Cartesian3.clone(currentPos, yMin);
  5530. }
  5531. if (y > yMax.y) {
  5532. Cartesian2.Cartesian3.clone(currentPos, yMax);
  5533. }
  5534. if (z < zMin.z) {
  5535. Cartesian2.Cartesian3.clone(currentPos, zMin);
  5536. }
  5537. if (z > zMax.z) {
  5538. Cartesian2.Cartesian3.clone(currentPos, zMax);
  5539. }
  5540. }
  5541. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  5542. var xSpan = Cartesian2.Cartesian3.magnitudeSquared(
  5543. Cartesian2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  5544. );
  5545. var ySpan = Cartesian2.Cartesian3.magnitudeSquared(
  5546. Cartesian2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  5547. );
  5548. var zSpan = Cartesian2.Cartesian3.magnitudeSquared(
  5549. Cartesian2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  5550. );
  5551. // Set the diameter endpoints to the largest span.
  5552. var diameter1 = xMin;
  5553. var diameter2 = xMax;
  5554. var maxSpan = xSpan;
  5555. if (ySpan > maxSpan) {
  5556. maxSpan = ySpan;
  5557. diameter1 = yMin;
  5558. diameter2 = yMax;
  5559. }
  5560. if (zSpan > maxSpan) {
  5561. maxSpan = zSpan;
  5562. diameter1 = zMin;
  5563. diameter2 = zMax;
  5564. }
  5565. // Calculate the center of the initial sphere found by Ritter's algorithm
  5566. var ritterCenter = fromPointsRitterCenter;
  5567. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  5568. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  5569. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  5570. // Calculate the radius of the initial sphere found by Ritter's algorithm
  5571. var radiusSquared = Cartesian2.Cartesian3.magnitudeSquared(
  5572. Cartesian2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  5573. );
  5574. var ritterRadius = Math.sqrt(radiusSquared);
  5575. // Find the center of the sphere found using the Naive method.
  5576. var minBoxPt = fromPointsMinBoxPt;
  5577. minBoxPt.x = xMin.x;
  5578. minBoxPt.y = yMin.y;
  5579. minBoxPt.z = zMin.z;
  5580. var maxBoxPt = fromPointsMaxBoxPt;
  5581. maxBoxPt.x = xMax.x;
  5582. maxBoxPt.y = yMax.y;
  5583. maxBoxPt.z = zMax.z;
  5584. var naiveCenter = Cartesian2.Cartesian3.midpoint(
  5585. minBoxPt,
  5586. maxBoxPt,
  5587. fromPointsNaiveCenterScratch
  5588. );
  5589. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  5590. var naiveRadius = 0;
  5591. for (i = 0; i < numElements; i += stride) {
  5592. currentPos.x = positions[i] + center.x;
  5593. currentPos.y = positions[i + 1] + center.y;
  5594. currentPos.z = positions[i + 2] + center.z;
  5595. // Find the furthest point from the naive center to calculate the naive radius.
  5596. var r = Cartesian2.Cartesian3.magnitude(
  5597. Cartesian2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  5598. );
  5599. if (r > naiveRadius) {
  5600. naiveRadius = r;
  5601. }
  5602. // Make adjustments to the Ritter Sphere to include all points.
  5603. var oldCenterToPointSquared = Cartesian2.Cartesian3.magnitudeSquared(
  5604. Cartesian2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  5605. );
  5606. if (oldCenterToPointSquared > radiusSquared) {
  5607. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  5608. // Calculate new radius to include the point that lies outside
  5609. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  5610. radiusSquared = ritterRadius * ritterRadius;
  5611. // Calculate center of new Ritter sphere
  5612. var oldToNew = oldCenterToPoint - ritterRadius;
  5613. ritterCenter.x =
  5614. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  5615. oldCenterToPoint;
  5616. ritterCenter.y =
  5617. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  5618. oldCenterToPoint;
  5619. ritterCenter.z =
  5620. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  5621. oldCenterToPoint;
  5622. }
  5623. }
  5624. if (ritterRadius < naiveRadius) {
  5625. Cartesian2.Cartesian3.clone(ritterCenter, result.center);
  5626. result.radius = ritterRadius;
  5627. } else {
  5628. Cartesian2.Cartesian3.clone(naiveCenter, result.center);
  5629. result.radius = naiveRadius;
  5630. }
  5631. return result;
  5632. };
  5633. /**
  5634. * Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
  5635. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  5636. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  5637. * ensure a tight fit.
  5638. *
  5639. * @param {Number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  5640. * is formed from three elements in the array in the order X, Y, Z.
  5641. * @param {Number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  5642. * is formed from three elements in the array in the order X, Y, Z.
  5643. * @param {BoundingSphere} [result] The object onto which to store the result.
  5644. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5645. *
  5646. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  5647. */
  5648. BoundingSphere.fromEncodedCartesianVertices = function (
  5649. positionsHigh,
  5650. positionsLow,
  5651. result
  5652. ) {
  5653. if (!when.defined(result)) {
  5654. result = new BoundingSphere();
  5655. }
  5656. if (
  5657. !when.defined(positionsHigh) ||
  5658. !when.defined(positionsLow) ||
  5659. positionsHigh.length !== positionsLow.length ||
  5660. positionsHigh.length === 0
  5661. ) {
  5662. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5663. result.radius = 0.0;
  5664. return result;
  5665. }
  5666. var currentPos = fromPointsCurrentPos;
  5667. currentPos.x = positionsHigh[0] + positionsLow[0];
  5668. currentPos.y = positionsHigh[1] + positionsLow[1];
  5669. currentPos.z = positionsHigh[2] + positionsLow[2];
  5670. var xMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMin);
  5671. var yMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMin);
  5672. var zMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMin);
  5673. var xMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMax);
  5674. var yMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMax);
  5675. var zMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMax);
  5676. var numElements = positionsHigh.length;
  5677. var i;
  5678. for (i = 0; i < numElements; i += 3) {
  5679. var x = positionsHigh[i] + positionsLow[i];
  5680. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  5681. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  5682. currentPos.x = x;
  5683. currentPos.y = y;
  5684. currentPos.z = z;
  5685. // Store points containing the the smallest and largest components
  5686. if (x < xMin.x) {
  5687. Cartesian2.Cartesian3.clone(currentPos, xMin);
  5688. }
  5689. if (x > xMax.x) {
  5690. Cartesian2.Cartesian3.clone(currentPos, xMax);
  5691. }
  5692. if (y < yMin.y) {
  5693. Cartesian2.Cartesian3.clone(currentPos, yMin);
  5694. }
  5695. if (y > yMax.y) {
  5696. Cartesian2.Cartesian3.clone(currentPos, yMax);
  5697. }
  5698. if (z < zMin.z) {
  5699. Cartesian2.Cartesian3.clone(currentPos, zMin);
  5700. }
  5701. if (z > zMax.z) {
  5702. Cartesian2.Cartesian3.clone(currentPos, zMax);
  5703. }
  5704. }
  5705. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  5706. var xSpan = Cartesian2.Cartesian3.magnitudeSquared(
  5707. Cartesian2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
  5708. );
  5709. var ySpan = Cartesian2.Cartesian3.magnitudeSquared(
  5710. Cartesian2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
  5711. );
  5712. var zSpan = Cartesian2.Cartesian3.magnitudeSquared(
  5713. Cartesian2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
  5714. );
  5715. // Set the diameter endpoints to the largest span.
  5716. var diameter1 = xMin;
  5717. var diameter2 = xMax;
  5718. var maxSpan = xSpan;
  5719. if (ySpan > maxSpan) {
  5720. maxSpan = ySpan;
  5721. diameter1 = yMin;
  5722. diameter2 = yMax;
  5723. }
  5724. if (zSpan > maxSpan) {
  5725. maxSpan = zSpan;
  5726. diameter1 = zMin;
  5727. diameter2 = zMax;
  5728. }
  5729. // Calculate the center of the initial sphere found by Ritter's algorithm
  5730. var ritterCenter = fromPointsRitterCenter;
  5731. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  5732. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  5733. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  5734. // Calculate the radius of the initial sphere found by Ritter's algorithm
  5735. var radiusSquared = Cartesian2.Cartesian3.magnitudeSquared(
  5736. Cartesian2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
  5737. );
  5738. var ritterRadius = Math.sqrt(radiusSquared);
  5739. // Find the center of the sphere found using the Naive method.
  5740. var minBoxPt = fromPointsMinBoxPt;
  5741. minBoxPt.x = xMin.x;
  5742. minBoxPt.y = yMin.y;
  5743. minBoxPt.z = zMin.z;
  5744. var maxBoxPt = fromPointsMaxBoxPt;
  5745. maxBoxPt.x = xMax.x;
  5746. maxBoxPt.y = yMax.y;
  5747. maxBoxPt.z = zMax.z;
  5748. var naiveCenter = Cartesian2.Cartesian3.midpoint(
  5749. minBoxPt,
  5750. maxBoxPt,
  5751. fromPointsNaiveCenterScratch
  5752. );
  5753. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  5754. var naiveRadius = 0;
  5755. for (i = 0; i < numElements; i += 3) {
  5756. currentPos.x = positionsHigh[i] + positionsLow[i];
  5757. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  5758. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  5759. // Find the furthest point from the naive center to calculate the naive radius.
  5760. var r = Cartesian2.Cartesian3.magnitude(
  5761. Cartesian2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
  5762. );
  5763. if (r > naiveRadius) {
  5764. naiveRadius = r;
  5765. }
  5766. // Make adjustments to the Ritter Sphere to include all points.
  5767. var oldCenterToPointSquared = Cartesian2.Cartesian3.magnitudeSquared(
  5768. Cartesian2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
  5769. );
  5770. if (oldCenterToPointSquared > radiusSquared) {
  5771. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  5772. // Calculate new radius to include the point that lies outside
  5773. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  5774. radiusSquared = ritterRadius * ritterRadius;
  5775. // Calculate center of new Ritter sphere
  5776. var oldToNew = oldCenterToPoint - ritterRadius;
  5777. ritterCenter.x =
  5778. (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
  5779. oldCenterToPoint;
  5780. ritterCenter.y =
  5781. (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
  5782. oldCenterToPoint;
  5783. ritterCenter.z =
  5784. (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
  5785. oldCenterToPoint;
  5786. }
  5787. }
  5788. if (ritterRadius < naiveRadius) {
  5789. Cartesian2.Cartesian3.clone(ritterCenter, result.center);
  5790. result.radius = ritterRadius;
  5791. } else {
  5792. Cartesian2.Cartesian3.clone(naiveCenter, result.center);
  5793. result.radius = naiveRadius;
  5794. }
  5795. return result;
  5796. };
  5797. /**
  5798. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  5799. * tighly and fully encompases the box.
  5800. *
  5801. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  5802. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  5803. * @param {BoundingSphere} [result] The object onto which to store the result.
  5804. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5805. *
  5806. * @example
  5807. * // Create a bounding sphere around the unit cube
  5808. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  5809. */
  5810. BoundingSphere.fromCornerPoints = function (corner, oppositeCorner, result) {
  5811. //>>includeStart('debug', pragmas.debug);
  5812. Check.Check.typeOf.object("corner", corner);
  5813. Check.Check.typeOf.object("oppositeCorner", oppositeCorner);
  5814. //>>includeEnd('debug');
  5815. if (!when.defined(result)) {
  5816. result = new BoundingSphere();
  5817. }
  5818. var center = Cartesian2.Cartesian3.midpoint(corner, oppositeCorner, result.center);
  5819. result.radius = Cartesian2.Cartesian3.distance(center, oppositeCorner);
  5820. return result;
  5821. };
  5822. /**
  5823. * Creates a bounding sphere encompassing an ellipsoid.
  5824. *
  5825. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  5826. * @param {BoundingSphere} [result] The object onto which to store the result.
  5827. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5828. *
  5829. * @example
  5830. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  5831. */
  5832. BoundingSphere.fromEllipsoid = function (ellipsoid, result) {
  5833. //>>includeStart('debug', pragmas.debug);
  5834. Check.Check.typeOf.object("ellipsoid", ellipsoid);
  5835. //>>includeEnd('debug');
  5836. if (!when.defined(result)) {
  5837. result = new BoundingSphere();
  5838. }
  5839. Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5840. result.radius = ellipsoid.maximumRadius;
  5841. return result;
  5842. };
  5843. var fromBoundingSpheresScratch = new Cartesian2.Cartesian3();
  5844. /**
  5845. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  5846. *
  5847. * @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
  5848. * @param {BoundingSphere} [result] The object onto which to store the result.
  5849. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5850. */
  5851. BoundingSphere.fromBoundingSpheres = function (boundingSpheres, result) {
  5852. if (!when.defined(result)) {
  5853. result = new BoundingSphere();
  5854. }
  5855. if (!when.defined(boundingSpheres) || boundingSpheres.length === 0) {
  5856. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5857. result.radius = 0.0;
  5858. return result;
  5859. }
  5860. var length = boundingSpheres.length;
  5861. if (length === 1) {
  5862. return BoundingSphere.clone(boundingSpheres[0], result);
  5863. }
  5864. if (length === 2) {
  5865. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  5866. }
  5867. var positions = [];
  5868. var i;
  5869. for (i = 0; i < length; i++) {
  5870. positions.push(boundingSpheres[i].center);
  5871. }
  5872. result = BoundingSphere.fromPoints(positions, result);
  5873. var center = result.center;
  5874. var radius = result.radius;
  5875. for (i = 0; i < length; i++) {
  5876. var tmp = boundingSpheres[i];
  5877. radius = Math.max(
  5878. radius,
  5879. Cartesian2.Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) +
  5880. tmp.radius
  5881. );
  5882. }
  5883. result.radius = radius;
  5884. return result;
  5885. };
  5886. var fromOrientedBoundingBoxScratchU = new Cartesian2.Cartesian3();
  5887. var fromOrientedBoundingBoxScratchV = new Cartesian2.Cartesian3();
  5888. var fromOrientedBoundingBoxScratchW = new Cartesian2.Cartesian3();
  5889. /**
  5890. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  5891. *
  5892. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  5893. * @param {BoundingSphere} [result] The object onto which to store the result.
  5894. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5895. */
  5896. BoundingSphere.fromOrientedBoundingBox = function (
  5897. orientedBoundingBox,
  5898. result
  5899. ) {
  5900. //>>includeStart('debug', pragmas.debug);
  5901. Check.Check.defined("orientedBoundingBox", orientedBoundingBox);
  5902. //>>includeEnd('debug');
  5903. if (!when.defined(result)) {
  5904. result = new BoundingSphere();
  5905. }
  5906. var halfAxes = orientedBoundingBox.halfAxes;
  5907. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  5908. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  5909. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  5910. Cartesian2.Cartesian3.add(u, v, u);
  5911. Cartesian2.Cartesian3.add(u, w, u);
  5912. result.center = Cartesian2.Cartesian3.clone(orientedBoundingBox.center, result.center);
  5913. result.radius = Cartesian2.Cartesian3.magnitude(u);
  5914. return result;
  5915. };
  5916. /**
  5917. * Duplicates a BoundingSphere instance.
  5918. *
  5919. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  5920. * @param {BoundingSphere} [result] The object onto which to store the result.
  5921. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  5922. */
  5923. BoundingSphere.clone = function (sphere, result) {
  5924. if (!when.defined(sphere)) {
  5925. return undefined;
  5926. }
  5927. if (!when.defined(result)) {
  5928. return new BoundingSphere(sphere.center, sphere.radius);
  5929. }
  5930. result.center = Cartesian2.Cartesian3.clone(sphere.center, result.center);
  5931. result.radius = sphere.radius;
  5932. return result;
  5933. };
  5934. /**
  5935. * The number of elements used to pack the object into an array.
  5936. * @type {Number}
  5937. */
  5938. BoundingSphere.packedLength = 4;
  5939. /**
  5940. * Stores the provided instance into the provided array.
  5941. *
  5942. * @param {BoundingSphere} value The value to pack.
  5943. * @param {Number[]} array The array to pack into.
  5944. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5945. *
  5946. * @returns {Number[]} The array that was packed into
  5947. */
  5948. BoundingSphere.pack = function (value, array, startingIndex) {
  5949. //>>includeStart('debug', pragmas.debug);
  5950. Check.Check.typeOf.object("value", value);
  5951. Check.Check.defined("array", array);
  5952. //>>includeEnd('debug');
  5953. startingIndex = when.defaultValue(startingIndex, 0);
  5954. var center = value.center;
  5955. array[startingIndex++] = center.x;
  5956. array[startingIndex++] = center.y;
  5957. array[startingIndex++] = center.z;
  5958. array[startingIndex] = value.radius;
  5959. return array;
  5960. };
  5961. /**
  5962. * Retrieves an instance from a packed array.
  5963. *
  5964. * @param {Number[]} array The packed array.
  5965. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5966. * @param {BoundingSphere} [result] The object into which to store the result.
  5967. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5968. */
  5969. BoundingSphere.unpack = function (array, startingIndex, result) {
  5970. //>>includeStart('debug', pragmas.debug);
  5971. Check.Check.defined("array", array);
  5972. //>>includeEnd('debug');
  5973. startingIndex = when.defaultValue(startingIndex, 0);
  5974. if (!when.defined(result)) {
  5975. result = new BoundingSphere();
  5976. }
  5977. var center = result.center;
  5978. center.x = array[startingIndex++];
  5979. center.y = array[startingIndex++];
  5980. center.z = array[startingIndex++];
  5981. result.radius = array[startingIndex];
  5982. return result;
  5983. };
  5984. var unionScratch = new Cartesian2.Cartesian3();
  5985. var unionScratchCenter = new Cartesian2.Cartesian3();
  5986. /**
  5987. * Computes a bounding sphere that contains both the left and right bounding spheres.
  5988. *
  5989. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  5990. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  5991. * @param {BoundingSphere} [result] The object onto which to store the result.
  5992. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5993. */
  5994. BoundingSphere.union = function (left, right, result) {
  5995. //>>includeStart('debug', pragmas.debug);
  5996. Check.Check.typeOf.object("left", left);
  5997. Check.Check.typeOf.object("right", right);
  5998. //>>includeEnd('debug');
  5999. if (!when.defined(result)) {
  6000. result = new BoundingSphere();
  6001. }
  6002. var leftCenter = left.center;
  6003. var leftRadius = left.radius;
  6004. var rightCenter = right.center;
  6005. var rightRadius = right.radius;
  6006. var toRightCenter = Cartesian2.Cartesian3.subtract(
  6007. rightCenter,
  6008. leftCenter,
  6009. unionScratch
  6010. );
  6011. var centerSeparation = Cartesian2.Cartesian3.magnitude(toRightCenter);
  6012. if (leftRadius >= centerSeparation + rightRadius) {
  6013. // Left sphere wins.
  6014. left.clone(result);
  6015. return result;
  6016. }
  6017. if (rightRadius >= centerSeparation + leftRadius) {
  6018. // Right sphere wins.
  6019. right.clone(result);
  6020. return result;
  6021. }
  6022. // There are two tangent points, one on far side of each sphere.
  6023. var halfDistanceBetweenTangentPoints =
  6024. (leftRadius + centerSeparation + rightRadius) * 0.5;
  6025. // Compute the center point halfway between the two tangent points.
  6026. var center = Cartesian2.Cartesian3.multiplyByScalar(
  6027. toRightCenter,
  6028. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
  6029. unionScratchCenter
  6030. );
  6031. Cartesian2.Cartesian3.add(center, leftCenter, center);
  6032. Cartesian2.Cartesian3.clone(center, result.center);
  6033. result.radius = halfDistanceBetweenTangentPoints;
  6034. return result;
  6035. };
  6036. var expandScratch = new Cartesian2.Cartesian3();
  6037. /**
  6038. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  6039. *
  6040. * @param {BoundingSphere} sphere A sphere to expand.
  6041. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  6042. * @param {BoundingSphere} [result] The object onto which to store the result.
  6043. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  6044. */
  6045. BoundingSphere.expand = function (sphere, point, result) {
  6046. //>>includeStart('debug', pragmas.debug);
  6047. Check.Check.typeOf.object("sphere", sphere);
  6048. Check.Check.typeOf.object("point", point);
  6049. //>>includeEnd('debug');
  6050. result = BoundingSphere.clone(sphere, result);
  6051. var radius = Cartesian2.Cartesian3.magnitude(
  6052. Cartesian2.Cartesian3.subtract(point, result.center, expandScratch)
  6053. );
  6054. if (radius > result.radius) {
  6055. result.radius = radius;
  6056. }
  6057. return result;
  6058. };
  6059. /**
  6060. * Determines which side of a plane a sphere is located.
  6061. *
  6062. * @param {BoundingSphere} sphere The bounding sphere to test.
  6063. * @param {Plane} plane The plane to test against.
  6064. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  6065. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  6066. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  6067. * intersects the plane.
  6068. */
  6069. BoundingSphere.intersectPlane = function (sphere, plane) {
  6070. //>>includeStart('debug', pragmas.debug);
  6071. Check.Check.typeOf.object("sphere", sphere);
  6072. Check.Check.typeOf.object("plane", plane);
  6073. //>>includeEnd('debug');
  6074. var center = sphere.center;
  6075. var radius = sphere.radius;
  6076. var normal = plane.normal;
  6077. var distanceToPlane = Cartesian2.Cartesian3.dot(normal, center) + plane.distance;
  6078. if (distanceToPlane < -radius) {
  6079. // The center point is negative side of the plane normal
  6080. return Intersect$1.OUTSIDE;
  6081. } else if (distanceToPlane < radius) {
  6082. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  6083. return Intersect$1.INTERSECTING;
  6084. }
  6085. return Intersect$1.INSIDE;
  6086. };
  6087. /**
  6088. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  6089. *
  6090. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  6091. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  6092. * @param {BoundingSphere} [result] The object onto which to store the result.
  6093. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  6094. */
  6095. BoundingSphere.transform = function (sphere, transform, result) {
  6096. //>>includeStart('debug', pragmas.debug);
  6097. Check.Check.typeOf.object("sphere", sphere);
  6098. Check.Check.typeOf.object("transform", transform);
  6099. //>>includeEnd('debug');
  6100. if (!when.defined(result)) {
  6101. result = new BoundingSphere();
  6102. }
  6103. result.center = Matrix4.multiplyByPoint(
  6104. transform,
  6105. sphere.center,
  6106. result.center
  6107. );
  6108. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  6109. return result;
  6110. };
  6111. var distanceSquaredToScratch = new Cartesian2.Cartesian3();
  6112. /**
  6113. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  6114. *
  6115. * @param {BoundingSphere} sphere The sphere.
  6116. * @param {Cartesian3} cartesian The point
  6117. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  6118. *
  6119. * @example
  6120. * // Sort bounding spheres from back to front
  6121. * spheres.sort(function(a, b) {
  6122. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  6123. * });
  6124. */
  6125. BoundingSphere.distanceSquaredTo = function (sphere, cartesian) {
  6126. //>>includeStart('debug', pragmas.debug);
  6127. Check.Check.typeOf.object("sphere", sphere);
  6128. Check.Check.typeOf.object("cartesian", cartesian);
  6129. //>>includeEnd('debug');
  6130. var diff = Cartesian2.Cartesian3.subtract(
  6131. sphere.center,
  6132. cartesian,
  6133. distanceSquaredToScratch
  6134. );
  6135. return Cartesian2.Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  6136. };
  6137. /**
  6138. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  6139. * The transformation matrix is not verified to have a uniform scale of 1.
  6140. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  6141. *
  6142. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  6143. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  6144. * @param {BoundingSphere} [result] The object onto which to store the result.
  6145. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  6146. *
  6147. * @example
  6148. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  6149. * var boundingSphere = new Cesium.BoundingSphere();
  6150. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  6151. */
  6152. BoundingSphere.transformWithoutScale = function (sphere, transform, result) {
  6153. //>>includeStart('debug', pragmas.debug);
  6154. Check.Check.typeOf.object("sphere", sphere);
  6155. Check.Check.typeOf.object("transform", transform);
  6156. //>>includeEnd('debug');
  6157. if (!when.defined(result)) {
  6158. result = new BoundingSphere();
  6159. }
  6160. result.center = Matrix4.multiplyByPoint(
  6161. transform,
  6162. sphere.center,
  6163. result.center
  6164. );
  6165. result.radius = sphere.radius;
  6166. return result;
  6167. };
  6168. var scratchCartesian3 = new Cartesian2.Cartesian3();
  6169. /**
  6170. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  6171. * plus/minus the radius of the bounding sphere.
  6172. * <br>
  6173. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  6174. * closest and farthest planes from position that intersect the bounding sphere.
  6175. *
  6176. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  6177. * @param {Cartesian3} position The position to calculate the distance from.
  6178. * @param {Cartesian3} direction The direction from position.
  6179. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  6180. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  6181. */
  6182. BoundingSphere.computePlaneDistances = function (
  6183. sphere,
  6184. position,
  6185. direction,
  6186. result
  6187. ) {
  6188. //>>includeStart('debug', pragmas.debug);
  6189. Check.Check.typeOf.object("sphere", sphere);
  6190. Check.Check.typeOf.object("position", position);
  6191. Check.Check.typeOf.object("direction", direction);
  6192. //>>includeEnd('debug');
  6193. if (!when.defined(result)) {
  6194. result = new Interval();
  6195. }
  6196. var toCenter = Cartesian2.Cartesian3.subtract(
  6197. sphere.center,
  6198. position,
  6199. scratchCartesian3
  6200. );
  6201. var mag = Cartesian2.Cartesian3.dot(direction, toCenter);
  6202. result.start = mag - sphere.radius;
  6203. result.stop = mag + sphere.radius;
  6204. return result;
  6205. };
  6206. var projectTo2DNormalScratch = new Cartesian2.Cartesian3();
  6207. var projectTo2DEastScratch = new Cartesian2.Cartesian3();
  6208. var projectTo2DNorthScratch = new Cartesian2.Cartesian3();
  6209. var projectTo2DWestScratch = new Cartesian2.Cartesian3();
  6210. var projectTo2DSouthScratch = new Cartesian2.Cartesian3();
  6211. var projectTo2DCartographicScratch = new Cartesian2.Cartographic();
  6212. var projectTo2DPositionsScratch = new Array(8);
  6213. for (var n = 0; n < 8; ++n) {
  6214. projectTo2DPositionsScratch[n] = new Cartesian2.Cartesian3();
  6215. }
  6216. var projectTo2DProjection = new GeographicProjection();
  6217. /**
  6218. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  6219. *
  6220. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  6221. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  6222. * @param {BoundingSphere} [result] The object onto which to store the result.
  6223. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  6224. */
  6225. BoundingSphere.projectTo2D = function (sphere, projection, result) {
  6226. //>>includeStart('debug', pragmas.debug);
  6227. Check.Check.typeOf.object("sphere", sphere);
  6228. //>>includeEnd('debug');
  6229. projection = when.defaultValue(projection, projectTo2DProjection);
  6230. var ellipsoid = projection.ellipsoid;
  6231. var center = sphere.center;
  6232. var radius = sphere.radius;
  6233. var normal;
  6234. if (Cartesian2.Cartesian3.equals(center, Cartesian2.Cartesian3.ZERO)) {
  6235. // Bounding sphere is at the center. The geodetic surface normal is not
  6236. // defined here so pick the x-axis as a fallback.
  6237. normal = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.UNIT_X, projectTo2DNormalScratch);
  6238. } else {
  6239. normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  6240. }
  6241. var east = Cartesian2.Cartesian3.cross(
  6242. Cartesian2.Cartesian3.UNIT_Z,
  6243. normal,
  6244. projectTo2DEastScratch
  6245. );
  6246. Cartesian2.Cartesian3.normalize(east, east);
  6247. var north = Cartesian2.Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  6248. Cartesian2.Cartesian3.normalize(north, north);
  6249. Cartesian2.Cartesian3.multiplyByScalar(normal, radius, normal);
  6250. Cartesian2.Cartesian3.multiplyByScalar(north, radius, north);
  6251. Cartesian2.Cartesian3.multiplyByScalar(east, radius, east);
  6252. var south = Cartesian2.Cartesian3.negate(north, projectTo2DSouthScratch);
  6253. var west = Cartesian2.Cartesian3.negate(east, projectTo2DWestScratch);
  6254. var positions = projectTo2DPositionsScratch;
  6255. // top NE corner
  6256. var corner = positions[0];
  6257. Cartesian2.Cartesian3.add(normal, north, corner);
  6258. Cartesian2.Cartesian3.add(corner, east, corner);
  6259. // top NW corner
  6260. corner = positions[1];
  6261. Cartesian2.Cartesian3.add(normal, north, corner);
  6262. Cartesian2.Cartesian3.add(corner, west, corner);
  6263. // top SW corner
  6264. corner = positions[2];
  6265. Cartesian2.Cartesian3.add(normal, south, corner);
  6266. Cartesian2.Cartesian3.add(corner, west, corner);
  6267. // top SE corner
  6268. corner = positions[3];
  6269. Cartesian2.Cartesian3.add(normal, south, corner);
  6270. Cartesian2.Cartesian3.add(corner, east, corner);
  6271. Cartesian2.Cartesian3.negate(normal, normal);
  6272. // bottom NE corner
  6273. corner = positions[4];
  6274. Cartesian2.Cartesian3.add(normal, north, corner);
  6275. Cartesian2.Cartesian3.add(corner, east, corner);
  6276. // bottom NW corner
  6277. corner = positions[5];
  6278. Cartesian2.Cartesian3.add(normal, north, corner);
  6279. Cartesian2.Cartesian3.add(corner, west, corner);
  6280. // bottom SW corner
  6281. corner = positions[6];
  6282. Cartesian2.Cartesian3.add(normal, south, corner);
  6283. Cartesian2.Cartesian3.add(corner, west, corner);
  6284. // bottom SE corner
  6285. corner = positions[7];
  6286. Cartesian2.Cartesian3.add(normal, south, corner);
  6287. Cartesian2.Cartesian3.add(corner, east, corner);
  6288. var length = positions.length;
  6289. for (var i = 0; i < length; ++i) {
  6290. var position = positions[i];
  6291. Cartesian2.Cartesian3.add(center, position, position);
  6292. var cartographic = ellipsoid.cartesianToCartographic(
  6293. position,
  6294. projectTo2DCartographicScratch
  6295. );
  6296. projection.project(cartographic, position);
  6297. }
  6298. result = BoundingSphere.fromPoints(positions, result);
  6299. // swizzle center components
  6300. center = result.center;
  6301. var x = center.x;
  6302. var y = center.y;
  6303. var z = center.z;
  6304. center.x = z;
  6305. center.y = x;
  6306. center.z = y;
  6307. return result;
  6308. };
  6309. /**
  6310. * Determines whether or not a sphere is hidden from view by the occluder.
  6311. *
  6312. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  6313. * @param {Occluder} occluder The occluder.
  6314. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  6315. */
  6316. BoundingSphere.isOccluded = function (sphere, occluder) {
  6317. //>>includeStart('debug', pragmas.debug);
  6318. Check.Check.typeOf.object("sphere", sphere);
  6319. Check.Check.typeOf.object("occluder", occluder);
  6320. //>>includeEnd('debug');
  6321. return !occluder.isBoundingSphereVisible(sphere);
  6322. };
  6323. /**
  6324. * Compares the provided BoundingSphere componentwise and returns
  6325. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6326. *
  6327. * @param {BoundingSphere} [left] The first BoundingSphere.
  6328. * @param {BoundingSphere} [right] The second BoundingSphere.
  6329. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  6330. */
  6331. BoundingSphere.equals = function (left, right) {
  6332. return (
  6333. left === right ||
  6334. (when.defined(left) &&
  6335. when.defined(right) &&
  6336. Cartesian2.Cartesian3.equals(left.center, right.center) &&
  6337. left.radius === right.radius)
  6338. );
  6339. };
  6340. /**
  6341. * Determines which side of a plane the sphere is located.
  6342. *
  6343. * @param {Plane} plane The plane to test against.
  6344. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  6345. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  6346. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  6347. * intersects the plane.
  6348. */
  6349. BoundingSphere.prototype.intersectPlane = function (plane) {
  6350. return BoundingSphere.intersectPlane(this, plane);
  6351. };
  6352. /**
  6353. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  6354. *
  6355. * @param {Cartesian3} cartesian The point
  6356. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  6357. *
  6358. * @example
  6359. * // Sort bounding spheres from back to front
  6360. * spheres.sort(function(a, b) {
  6361. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  6362. * });
  6363. */
  6364. BoundingSphere.prototype.distanceSquaredTo = function (cartesian) {
  6365. return BoundingSphere.distanceSquaredTo(this, cartesian);
  6366. };
  6367. /**
  6368. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  6369. * plus/minus the radius of the bounding sphere.
  6370. * <br>
  6371. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  6372. * closest and farthest planes from position that intersect the bounding sphere.
  6373. *
  6374. * @param {Cartesian3} position The position to calculate the distance from.
  6375. * @param {Cartesian3} direction The direction from position.
  6376. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  6377. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  6378. */
  6379. BoundingSphere.prototype.computePlaneDistances = function (
  6380. position,
  6381. direction,
  6382. result
  6383. ) {
  6384. return BoundingSphere.computePlaneDistances(
  6385. this,
  6386. position,
  6387. direction,
  6388. result
  6389. );
  6390. };
  6391. /**
  6392. * Determines whether or not a sphere is hidden from view by the occluder.
  6393. *
  6394. * @param {Occluder} occluder The occluder.
  6395. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  6396. */
  6397. BoundingSphere.prototype.isOccluded = function (occluder) {
  6398. return BoundingSphere.isOccluded(this, occluder);
  6399. };
  6400. /**
  6401. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  6402. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6403. *
  6404. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  6405. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  6406. */
  6407. BoundingSphere.prototype.equals = function (right) {
  6408. return BoundingSphere.equals(this, right);
  6409. };
  6410. /**
  6411. * Duplicates this BoundingSphere instance.
  6412. *
  6413. * @param {BoundingSphere} [result] The object onto which to store the result.
  6414. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  6415. */
  6416. BoundingSphere.prototype.clone = function (result) {
  6417. return BoundingSphere.clone(this, result);
  6418. };
  6419. /**
  6420. * Computes the radius of the BoundingSphere.
  6421. * @returns {Number} The radius of the BoundingSphere.
  6422. */
  6423. BoundingSphere.prototype.volume = function () {
  6424. var radius = this.radius;
  6425. return volumeConstant * radius * radius * radius;
  6426. };
  6427. var _supportsFullscreen;
  6428. var _names = {
  6429. requestFullscreen: undefined,
  6430. exitFullscreen: undefined,
  6431. fullscreenEnabled: undefined,
  6432. fullscreenElement: undefined,
  6433. fullscreenchange: undefined,
  6434. fullscreenerror: undefined,
  6435. };
  6436. /**
  6437. * Browser-independent functions for working with the standard fullscreen API.
  6438. *
  6439. * @namespace Fullscreen
  6440. *
  6441. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  6442. */
  6443. var Fullscreen = {};
  6444. Object.defineProperties(Fullscreen, {
  6445. /**
  6446. * The element that is currently fullscreen, if any. To simply check if the
  6447. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  6448. * @memberof Fullscreen
  6449. * @type {Object}
  6450. * @readonly
  6451. */
  6452. element: {
  6453. get: function () {
  6454. if (!Fullscreen.supportsFullscreen()) {
  6455. return undefined;
  6456. }
  6457. return document[_names.fullscreenElement];
  6458. },
  6459. },
  6460. /**
  6461. * The name of the event on the document that is fired when fullscreen is
  6462. * entered or exited. This event name is intended for use with addEventListener.
  6463. * In your event handler, to determine if the browser is in fullscreen mode or not,
  6464. * use {@link Fullscreen#fullscreen}.
  6465. * @memberof Fullscreen
  6466. * @type {String}
  6467. * @readonly
  6468. */
  6469. changeEventName: {
  6470. get: function () {
  6471. if (!Fullscreen.supportsFullscreen()) {
  6472. return undefined;
  6473. }
  6474. return _names.fullscreenchange;
  6475. },
  6476. },
  6477. /**
  6478. * The name of the event that is fired when a fullscreen error
  6479. * occurs. This event name is intended for use with addEventListener.
  6480. * @memberof Fullscreen
  6481. * @type {String}
  6482. * @readonly
  6483. */
  6484. errorEventName: {
  6485. get: function () {
  6486. if (!Fullscreen.supportsFullscreen()) {
  6487. return undefined;
  6488. }
  6489. return _names.fullscreenerror;
  6490. },
  6491. },
  6492. /**
  6493. * Determine whether the browser will allow an element to be made fullscreen, or not.
  6494. * For example, by default, iframes cannot go fullscreen unless the containing page
  6495. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  6496. * @memberof Fullscreen
  6497. * @type {Boolean}
  6498. * @readonly
  6499. */
  6500. enabled: {
  6501. get: function () {
  6502. if (!Fullscreen.supportsFullscreen()) {
  6503. return undefined;
  6504. }
  6505. return document[_names.fullscreenEnabled];
  6506. },
  6507. },
  6508. /**
  6509. * Determines if the browser is currently in fullscreen mode.
  6510. * @memberof Fullscreen
  6511. * @type {Boolean}
  6512. * @readonly
  6513. */
  6514. fullscreen: {
  6515. get: function () {
  6516. if (!Fullscreen.supportsFullscreen()) {
  6517. return undefined;
  6518. }
  6519. return Fullscreen.element !== null;
  6520. },
  6521. },
  6522. });
  6523. /**
  6524. * Detects whether the browser supports the standard fullscreen API.
  6525. *
  6526. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  6527. * <code>false</code> otherwise.
  6528. */
  6529. Fullscreen.supportsFullscreen = function () {
  6530. if (when.defined(_supportsFullscreen)) {
  6531. return _supportsFullscreen;
  6532. }
  6533. _supportsFullscreen = false;
  6534. var body = document.body;
  6535. if (typeof body.requestFullscreen === "function") {
  6536. // go with the unprefixed, standard set of names
  6537. _names.requestFullscreen = "requestFullscreen";
  6538. _names.exitFullscreen = "exitFullscreen";
  6539. _names.fullscreenEnabled = "fullscreenEnabled";
  6540. _names.fullscreenElement = "fullscreenElement";
  6541. _names.fullscreenchange = "fullscreenchange";
  6542. _names.fullscreenerror = "fullscreenerror";
  6543. _supportsFullscreen = true;
  6544. return _supportsFullscreen;
  6545. }
  6546. //check for the correct combination of prefix plus the various names that browsers use
  6547. var prefixes = ["webkit", "moz", "o", "ms", "khtml"];
  6548. var name;
  6549. for (var i = 0, len = prefixes.length; i < len; ++i) {
  6550. var prefix = prefixes[i];
  6551. // casing of Fullscreen differs across browsers
  6552. name = prefix + "RequestFullscreen";
  6553. if (typeof body[name] === "function") {
  6554. _names.requestFullscreen = name;
  6555. _supportsFullscreen = true;
  6556. } else {
  6557. name = prefix + "RequestFullScreen";
  6558. if (typeof body[name] === "function") {
  6559. _names.requestFullscreen = name;
  6560. _supportsFullscreen = true;
  6561. }
  6562. }
  6563. // disagreement about whether it's "exit" as per spec, or "cancel"
  6564. name = prefix + "ExitFullscreen";
  6565. if (typeof document[name] === "function") {
  6566. _names.exitFullscreen = name;
  6567. } else {
  6568. name = prefix + "CancelFullScreen";
  6569. if (typeof document[name] === "function") {
  6570. _names.exitFullscreen = name;
  6571. }
  6572. }
  6573. // casing of Fullscreen differs across browsers
  6574. name = prefix + "FullscreenEnabled";
  6575. if (document[name] !== undefined) {
  6576. _names.fullscreenEnabled = name;
  6577. } else {
  6578. name = prefix + "FullScreenEnabled";
  6579. if (document[name] !== undefined) {
  6580. _names.fullscreenEnabled = name;
  6581. }
  6582. }
  6583. // casing of Fullscreen differs across browsers
  6584. name = prefix + "FullscreenElement";
  6585. if (document[name] !== undefined) {
  6586. _names.fullscreenElement = name;
  6587. } else {
  6588. name = prefix + "FullScreenElement";
  6589. if (document[name] !== undefined) {
  6590. _names.fullscreenElement = name;
  6591. }
  6592. }
  6593. // thankfully, event names are all lowercase per spec
  6594. name = prefix + "fullscreenchange";
  6595. // event names do not have 'on' in the front, but the property on the document does
  6596. if (document["on" + name] !== undefined) {
  6597. //except on IE
  6598. if (prefix === "ms") {
  6599. name = "MSFullscreenChange";
  6600. }
  6601. _names.fullscreenchange = name;
  6602. }
  6603. name = prefix + "fullscreenerror";
  6604. if (document["on" + name] !== undefined) {
  6605. //except on IE
  6606. if (prefix === "ms") {
  6607. name = "MSFullscreenError";
  6608. }
  6609. _names.fullscreenerror = name;
  6610. }
  6611. }
  6612. return _supportsFullscreen;
  6613. };
  6614. /**
  6615. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  6616. * If fullscreen mode is not supported by the browser, does nothing.
  6617. *
  6618. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  6619. * @param {Object} [vrDevice] The HMDVRDevice device.
  6620. *
  6621. * @example
  6622. * // Put the entire page into fullscreen.
  6623. * Cesium.Fullscreen.requestFullscreen(document.body)
  6624. *
  6625. * // Place only the Cesium canvas into fullscreen.
  6626. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  6627. */
  6628. Fullscreen.requestFullscreen = function (element, vrDevice) {
  6629. if (!Fullscreen.supportsFullscreen()) {
  6630. return;
  6631. }
  6632. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  6633. };
  6634. /**
  6635. * Asynchronously exits fullscreen mode. If the browser is not currently
  6636. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  6637. */
  6638. Fullscreen.exitFullscreen = function () {
  6639. if (!Fullscreen.supportsFullscreen()) {
  6640. return;
  6641. }
  6642. document[_names.exitFullscreen]();
  6643. };
  6644. //For unit tests
  6645. Fullscreen._names = _names;
  6646. var theNavigator;
  6647. if (typeof navigator !== "undefined") {
  6648. theNavigator = navigator;
  6649. } else {
  6650. theNavigator = {};
  6651. }
  6652. function extractVersion(versionString) {
  6653. var parts = versionString.split(".");
  6654. for (var i = 0, len = parts.length; i < len; ++i) {
  6655. parts[i] = parseInt(parts[i], 10);
  6656. }
  6657. return parts;
  6658. }
  6659. var isChromeResult;
  6660. var chromeVersionResult;
  6661. function isChrome() {
  6662. if (!when.defined(isChromeResult)) {
  6663. isChromeResult = false;
  6664. // Edge contains Chrome in the user agent too
  6665. if (!isEdge()) {
  6666. var fields = / Chrome\/([\.0-9]+)/.exec(theNavigator.userAgent);
  6667. if (fields !== null) {
  6668. isChromeResult = true;
  6669. chromeVersionResult = extractVersion(fields[1]);
  6670. }
  6671. }
  6672. }
  6673. return isChromeResult;
  6674. }
  6675. function chromeVersion() {
  6676. return isChrome() && chromeVersionResult;
  6677. }
  6678. var isSafariResult;
  6679. var safariVersionResult;
  6680. function isSafari() {
  6681. if (!when.defined(isSafariResult)) {
  6682. isSafariResult = false;
  6683. // Chrome and Edge contain Safari in the user agent too
  6684. if (
  6685. !isChrome() &&
  6686. !isEdge() &&
  6687. / Safari\/[\.0-9]+/.test(theNavigator.userAgent)
  6688. ) {
  6689. var fields = / Version\/([\.0-9]+)/.exec(theNavigator.userAgent);
  6690. if (fields !== null) {
  6691. isSafariResult = true;
  6692. safariVersionResult = extractVersion(fields[1]);
  6693. }
  6694. }
  6695. }
  6696. return isSafariResult;
  6697. }
  6698. function safariVersion() {
  6699. return isSafari() && safariVersionResult;
  6700. }
  6701. var isWebkitResult;
  6702. var webkitVersionResult;
  6703. function isWebkit() {
  6704. if (!when.defined(isWebkitResult)) {
  6705. isWebkitResult = false;
  6706. var fields = / AppleWebKit\/([\.0-9]+)(\+?)/.exec(theNavigator.userAgent);
  6707. if (fields !== null) {
  6708. isWebkitResult = true;
  6709. webkitVersionResult = extractVersion(fields[1]);
  6710. webkitVersionResult.isNightly = !!fields[2];
  6711. }
  6712. }
  6713. return isWebkitResult;
  6714. }
  6715. function webkitVersion() {
  6716. return isWebkit() && webkitVersionResult;
  6717. }
  6718. var isInternetExplorerResult;
  6719. var internetExplorerVersionResult;
  6720. function isInternetExplorer() {
  6721. if (!when.defined(isInternetExplorerResult)) {
  6722. isInternetExplorerResult = false;
  6723. var fields;
  6724. if (theNavigator.appName === "Microsoft Internet Explorer") {
  6725. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  6726. if (fields !== null) {
  6727. isInternetExplorerResult = true;
  6728. internetExplorerVersionResult = extractVersion(fields[1]);
  6729. }
  6730. } else if (theNavigator.appName === "Netscape") {
  6731. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(
  6732. theNavigator.userAgent
  6733. );
  6734. if (fields !== null) {
  6735. isInternetExplorerResult = true;
  6736. internetExplorerVersionResult = extractVersion(fields[1]);
  6737. }
  6738. }
  6739. }
  6740. return isInternetExplorerResult;
  6741. }
  6742. function internetExplorerVersion() {
  6743. return isInternetExplorer() && internetExplorerVersionResult;
  6744. }
  6745. var isEdgeResult;
  6746. var edgeVersionResult;
  6747. function isEdge() {
  6748. if (!when.defined(isEdgeResult)) {
  6749. isEdgeResult = false;
  6750. var fields = / Edge\/([\.0-9]+)/.exec(theNavigator.userAgent);
  6751. if (fields !== null) {
  6752. isEdgeResult = true;
  6753. edgeVersionResult = extractVersion(fields[1]);
  6754. }
  6755. }
  6756. return isEdgeResult;
  6757. }
  6758. function edgeVersion() {
  6759. return isEdge() && edgeVersionResult;
  6760. }
  6761. var isFirefoxResult;
  6762. var firefoxVersionResult;
  6763. function isFirefox() {
  6764. if (!when.defined(isFirefoxResult)) {
  6765. isFirefoxResult = false;
  6766. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  6767. if (fields !== null) {
  6768. isFirefoxResult = true;
  6769. firefoxVersionResult = extractVersion(fields[1]);
  6770. }
  6771. }
  6772. return isFirefoxResult;
  6773. }
  6774. var isWindowsResult;
  6775. function isWindows() {
  6776. if (!when.defined(isWindowsResult)) {
  6777. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  6778. }
  6779. return isWindowsResult;
  6780. }
  6781. function firefoxVersion() {
  6782. return isFirefox() && firefoxVersionResult;
  6783. }
  6784. var hasPointerEvents;
  6785. function supportsPointerEvents() {
  6786. if (!when.defined(hasPointerEvents)) {
  6787. //While navigator.pointerEnabled is deprecated in the W3C specification
  6788. //we still need to use it if it exists in order to support browsers
  6789. //that rely on it, such as the Windows WebBrowser control which defines
  6790. //PointerEvent but sets navigator.pointerEnabled to false.
  6791. //Firefox disabled because of https://github.com/CesiumGS/cesium/issues/6372
  6792. hasPointerEvents =
  6793. !isFirefox() &&
  6794. typeof PointerEvent !== "undefined" &&
  6795. (!when.defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  6796. }
  6797. return hasPointerEvents;
  6798. }
  6799. var imageRenderingValueResult;
  6800. var supportsImageRenderingPixelatedResult;
  6801. function supportsImageRenderingPixelated() {
  6802. if (!when.defined(supportsImageRenderingPixelatedResult)) {
  6803. var canvas = document.createElement("canvas");
  6804. canvas.setAttribute(
  6805. "style",
  6806. "image-rendering: -moz-crisp-edges;" + "image-rendering: pixelated;"
  6807. );
  6808. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  6809. var tmp = canvas.style.imageRendering;
  6810. supportsImageRenderingPixelatedResult = when.defined(tmp) && tmp !== "";
  6811. if (supportsImageRenderingPixelatedResult) {
  6812. imageRenderingValueResult = tmp;
  6813. }
  6814. }
  6815. return supportsImageRenderingPixelatedResult;
  6816. }
  6817. function imageRenderingValue() {
  6818. return supportsImageRenderingPixelated()
  6819. ? imageRenderingValueResult
  6820. : undefined;
  6821. }
  6822. function supportsWebP() {
  6823. //>>includeStart('debug', pragmas.debug);
  6824. if (!supportsWebP.initialized) {
  6825. throw new Check.DeveloperError(
  6826. "You must call FeatureDetection.supportsWebP.initialize and wait for the promise to resolve before calling FeatureDetection.supportsWebP"
  6827. );
  6828. }
  6829. //>>includeEnd('debug');
  6830. return supportsWebP._result;
  6831. }
  6832. supportsWebP._promise = undefined;
  6833. supportsWebP._result = undefined;
  6834. supportsWebP.initialize = function () {
  6835. // From https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp
  6836. if (when.defined(supportsWebP._promise)) {
  6837. return supportsWebP._promise;
  6838. }
  6839. var supportsWebPDeferred = when.when.defer();
  6840. supportsWebP._promise = supportsWebPDeferred.promise;
  6841. if (isEdge()) {
  6842. // Edge's WebP support with WebGL is incomplete.
  6843. // See bug report: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/19221241/
  6844. supportsWebP._result = false;
  6845. supportsWebPDeferred.resolve(supportsWebP._result);
  6846. return supportsWebPDeferred.promise;
  6847. }
  6848. var image = new Image();
  6849. image.onload = function () {
  6850. supportsWebP._result = image.width > 0 && image.height > 0;
  6851. supportsWebPDeferred.resolve(supportsWebP._result);
  6852. };
  6853. image.onerror = function () {
  6854. supportsWebP._result = false;
  6855. supportsWebPDeferred.resolve(supportsWebP._result);
  6856. };
  6857. image.src =
  6858. "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
  6859. return supportsWebPDeferred.promise;
  6860. };
  6861. Object.defineProperties(supportsWebP, {
  6862. initialized: {
  6863. get: function () {
  6864. return when.defined(supportsWebP._result);
  6865. },
  6866. },
  6867. });
  6868. var typedArrayTypes = [];
  6869. if (typeof ArrayBuffer !== "undefined") {
  6870. typedArrayTypes.push(
  6871. Int8Array,
  6872. Uint8Array,
  6873. Int16Array,
  6874. Uint16Array,
  6875. Int32Array,
  6876. Uint32Array,
  6877. Float32Array,
  6878. Float64Array
  6879. );
  6880. if (typeof Uint8ClampedArray !== "undefined") {
  6881. typedArrayTypes.push(Uint8ClampedArray);
  6882. }
  6883. if (typeof Uint8ClampedArray !== "undefined") {
  6884. typedArrayTypes.push(Uint8ClampedArray);
  6885. }
  6886. }
  6887. /**
  6888. * A set of functions to detect whether the current browser supports
  6889. * various features.
  6890. *
  6891. * @namespace FeatureDetection
  6892. */
  6893. var FeatureDetection = {
  6894. isChrome: isChrome,
  6895. chromeVersion: chromeVersion,
  6896. isSafari: isSafari,
  6897. safariVersion: safariVersion,
  6898. isWebkit: isWebkit,
  6899. webkitVersion: webkitVersion,
  6900. isInternetExplorer: isInternetExplorer,
  6901. internetExplorerVersion: internetExplorerVersion,
  6902. isEdge: isEdge,
  6903. edgeVersion: edgeVersion,
  6904. isFirefox: isFirefox,
  6905. firefoxVersion: firefoxVersion,
  6906. isWindows: isWindows,
  6907. hardwareConcurrency: when.defaultValue(theNavigator.hardwareConcurrency, 3),
  6908. supportsPointerEvents: supportsPointerEvents,
  6909. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  6910. supportsWebP: supportsWebP,
  6911. imageRenderingValue: imageRenderingValue,
  6912. typedArrayTypes: typedArrayTypes,
  6913. };
  6914. /**
  6915. * Detects whether the current browser supports the full screen standard.
  6916. *
  6917. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  6918. *
  6919. * @see Fullscreen
  6920. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  6921. */
  6922. FeatureDetection.supportsFullscreen = function () {
  6923. return Fullscreen.supportsFullscreen();
  6924. };
  6925. /**
  6926. * Detects whether the current browser supports typed arrays.
  6927. *
  6928. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  6929. *
  6930. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  6931. */
  6932. FeatureDetection.supportsTypedArrays = function () {
  6933. return typeof ArrayBuffer !== "undefined";
  6934. };
  6935. /**
  6936. * Detects whether the current browser supports Web Workers.
  6937. *
  6938. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  6939. *
  6940. * @see {@link http://www.w3.org/TR/workers/}
  6941. */
  6942. FeatureDetection.supportsWebWorkers = function () {
  6943. return typeof Worker !== "undefined";
  6944. };
  6945. /**
  6946. * Detects whether the current browser supports Web Assembly.
  6947. *
  6948. * @returns {Boolean} true if the browsers supports Web Assembly, false if not.
  6949. *
  6950. * @see {@link https://developer.mozilla.org/en-US/docs/WebAssembly}
  6951. */
  6952. FeatureDetection.supportsWebAssembly = function () {
  6953. return typeof WebAssembly !== "undefined" && !FeatureDetection.isEdge();
  6954. };
  6955. /**
  6956. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  6957. * @alias Quaternion
  6958. * @constructor
  6959. *
  6960. * @param {Number} [x=0.0] The X component.
  6961. * @param {Number} [y=0.0] The Y component.
  6962. * @param {Number} [z=0.0] The Z component.
  6963. * @param {Number} [w=0.0] The W component.
  6964. *
  6965. * @see PackableForInterpolation
  6966. */
  6967. function Quaternion(x, y, z, w) {
  6968. /**
  6969. * The X component.
  6970. * @type {Number}
  6971. * @default 0.0
  6972. */
  6973. this.x = when.defaultValue(x, 0.0);
  6974. /**
  6975. * The Y component.
  6976. * @type {Number}
  6977. * @default 0.0
  6978. */
  6979. this.y = when.defaultValue(y, 0.0);
  6980. /**
  6981. * The Z component.
  6982. * @type {Number}
  6983. * @default 0.0
  6984. */
  6985. this.z = when.defaultValue(z, 0.0);
  6986. /**
  6987. * The W component.
  6988. * @type {Number}
  6989. * @default 0.0
  6990. */
  6991. this.w = when.defaultValue(w, 0.0);
  6992. }
  6993. var fromAxisAngleScratch = new Cartesian2.Cartesian3();
  6994. /**
  6995. * Computes a quaternion representing a rotation around an axis.
  6996. *
  6997. * @param {Cartesian3} axis The axis of rotation.
  6998. * @param {Number} angle The angle in radians to rotate around the axis.
  6999. * @param {Quaternion} [result] The object onto which to store the result.
  7000. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  7001. */
  7002. Quaternion.fromAxisAngle = function (axis, angle, result) {
  7003. //>>includeStart('debug', pragmas.debug);
  7004. Check.Check.typeOf.object("axis", axis);
  7005. Check.Check.typeOf.number("angle", angle);
  7006. //>>includeEnd('debug');
  7007. var halfAngle = angle / 2.0;
  7008. var s = Math.sin(halfAngle);
  7009. fromAxisAngleScratch = Cartesian2.Cartesian3.normalize(axis, fromAxisAngleScratch);
  7010. var x = fromAxisAngleScratch.x * s;
  7011. var y = fromAxisAngleScratch.y * s;
  7012. var z = fromAxisAngleScratch.z * s;
  7013. var w = Math.cos(halfAngle);
  7014. if (!when.defined(result)) {
  7015. return new Quaternion(x, y, z, w);
  7016. }
  7017. result.x = x;
  7018. result.y = y;
  7019. result.z = z;
  7020. result.w = w;
  7021. return result;
  7022. };
  7023. var fromRotationMatrixNext = [1, 2, 0];
  7024. var fromRotationMatrixQuat = new Array(3);
  7025. /**
  7026. * Computes a Quaternion from the provided Matrix3 instance.
  7027. *
  7028. * @param {Matrix3} matrix The rotation matrix.
  7029. * @param {Quaternion} [result] The object onto which to store the result.
  7030. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  7031. *
  7032. * @see Matrix3.fromQuaternion
  7033. */
  7034. Quaternion.fromRotationMatrix = function (matrix, result) {
  7035. //>>includeStart('debug', pragmas.debug);
  7036. Check.Check.typeOf.object("matrix", matrix);
  7037. //>>includeEnd('debug');
  7038. var root;
  7039. var x;
  7040. var y;
  7041. var z;
  7042. var w;
  7043. var m00 = matrix[Matrix3.COLUMN0ROW0];
  7044. var m11 = matrix[Matrix3.COLUMN1ROW1];
  7045. var m22 = matrix[Matrix3.COLUMN2ROW2];
  7046. var trace = m00 + m11 + m22;
  7047. if (trace > 0.0) {
  7048. // |w| > 1/2, may as well choose w > 1/2
  7049. root = Math.sqrt(trace + 1.0); // 2w
  7050. w = 0.5 * root;
  7051. root = 0.5 / root; // 1/(4w)
  7052. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  7053. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  7054. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  7055. } else {
  7056. // |w| <= 1/2
  7057. var next = fromRotationMatrixNext;
  7058. var i = 0;
  7059. if (m11 > m00) {
  7060. i = 1;
  7061. }
  7062. if (m22 > m00 && m22 > m11) {
  7063. i = 2;
  7064. }
  7065. var j = next[i];
  7066. var k = next[j];
  7067. root = Math.sqrt(
  7068. matrix[Matrix3.getElementIndex(i, i)] -
  7069. matrix[Matrix3.getElementIndex(j, j)] -
  7070. matrix[Matrix3.getElementIndex(k, k)] +
  7071. 1.0
  7072. );
  7073. var quat = fromRotationMatrixQuat;
  7074. quat[i] = 0.5 * root;
  7075. root = 0.5 / root;
  7076. w =
  7077. (matrix[Matrix3.getElementIndex(k, j)] -
  7078. matrix[Matrix3.getElementIndex(j, k)]) *
  7079. root;
  7080. quat[j] =
  7081. (matrix[Matrix3.getElementIndex(j, i)] +
  7082. matrix[Matrix3.getElementIndex(i, j)]) *
  7083. root;
  7084. quat[k] =
  7085. (matrix[Matrix3.getElementIndex(k, i)] +
  7086. matrix[Matrix3.getElementIndex(i, k)]) *
  7087. root;
  7088. x = -quat[0];
  7089. y = -quat[1];
  7090. z = -quat[2];
  7091. }
  7092. if (!when.defined(result)) {
  7093. return new Quaternion(x, y, z, w);
  7094. }
  7095. result.x = x;
  7096. result.y = y;
  7097. result.z = z;
  7098. result.w = w;
  7099. return result;
  7100. };
  7101. var scratchHPRQuaternion = new Quaternion();
  7102. var scratchHeadingQuaternion = new Quaternion();
  7103. var scratchPitchQuaternion = new Quaternion();
  7104. var scratchRollQuaternion = new Quaternion();
  7105. /**
  7106. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  7107. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  7108. * the positive x axis.
  7109. *
  7110. * @param {HeadingPitchRoll} headingPitchRoll The rotation expressed as a heading, pitch and roll.
  7111. * @param {Quaternion} [result] The object onto which to store the result.
  7112. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  7113. */
  7114. Quaternion.fromHeadingPitchRoll = function (headingPitchRoll, result) {
  7115. //>>includeStart('debug', pragmas.debug);
  7116. Check.Check.typeOf.object("headingPitchRoll", headingPitchRoll);
  7117. //>>includeEnd('debug');
  7118. scratchRollQuaternion = Quaternion.fromAxisAngle(
  7119. Cartesian2.Cartesian3.UNIT_X,
  7120. headingPitchRoll.roll,
  7121. scratchHPRQuaternion
  7122. );
  7123. scratchPitchQuaternion = Quaternion.fromAxisAngle(
  7124. Cartesian2.Cartesian3.UNIT_Y,
  7125. -headingPitchRoll.pitch,
  7126. result
  7127. );
  7128. result = Quaternion.multiply(
  7129. scratchPitchQuaternion,
  7130. scratchRollQuaternion,
  7131. scratchPitchQuaternion
  7132. );
  7133. scratchHeadingQuaternion = Quaternion.fromAxisAngle(
  7134. Cartesian2.Cartesian3.UNIT_Z,
  7135. -headingPitchRoll.heading,
  7136. scratchHPRQuaternion
  7137. );
  7138. return Quaternion.multiply(scratchHeadingQuaternion, result, result);
  7139. };
  7140. var sampledQuaternionAxis = new Cartesian2.Cartesian3();
  7141. var sampledQuaternionRotation = new Cartesian2.Cartesian3();
  7142. var sampledQuaternionTempQuaternion = new Quaternion();
  7143. var sampledQuaternionQuaternion0 = new Quaternion();
  7144. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  7145. /**
  7146. * The number of elements used to pack the object into an array.
  7147. * @type {Number}
  7148. */
  7149. Quaternion.packedLength = 4;
  7150. /**
  7151. * Stores the provided instance into the provided array.
  7152. *
  7153. * @param {Quaternion} value The value to pack.
  7154. * @param {Number[]} array The array to pack into.
  7155. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  7156. *
  7157. * @returns {Number[]} The array that was packed into
  7158. */
  7159. Quaternion.pack = function (value, array, startingIndex) {
  7160. //>>includeStart('debug', pragmas.debug);
  7161. Check.Check.typeOf.object("value", value);
  7162. Check.Check.defined("array", array);
  7163. //>>includeEnd('debug');
  7164. startingIndex = when.defaultValue(startingIndex, 0);
  7165. array[startingIndex++] = value.x;
  7166. array[startingIndex++] = value.y;
  7167. array[startingIndex++] = value.z;
  7168. array[startingIndex] = value.w;
  7169. return array;
  7170. };
  7171. /**
  7172. * Retrieves an instance from a packed array.
  7173. *
  7174. * @param {Number[]} array The packed array.
  7175. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  7176. * @param {Quaternion} [result] The object into which to store the result.
  7177. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  7178. */
  7179. Quaternion.unpack = function (array, startingIndex, result) {
  7180. //>>includeStart('debug', pragmas.debug);
  7181. Check.Check.defined("array", array);
  7182. //>>includeEnd('debug');
  7183. startingIndex = when.defaultValue(startingIndex, 0);
  7184. if (!when.defined(result)) {
  7185. result = new Quaternion();
  7186. }
  7187. result.x = array[startingIndex];
  7188. result.y = array[startingIndex + 1];
  7189. result.z = array[startingIndex + 2];
  7190. result.w = array[startingIndex + 3];
  7191. return result;
  7192. };
  7193. /**
  7194. * The number of elements used to store the object into an array in its interpolatable form.
  7195. * @type {Number}
  7196. */
  7197. Quaternion.packedInterpolationLength = 3;
  7198. /**
  7199. * Converts a packed array into a form suitable for interpolation.
  7200. *
  7201. * @param {Number[]} packedArray The packed array.
  7202. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  7203. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  7204. * @param {Number[]} [result] The object into which to store the result.
  7205. */
  7206. Quaternion.convertPackedArrayForInterpolation = function (
  7207. packedArray,
  7208. startingIndex,
  7209. lastIndex,
  7210. result
  7211. ) {
  7212. Quaternion.unpack(
  7213. packedArray,
  7214. lastIndex * 4,
  7215. sampledQuaternionQuaternion0Conjugate
  7216. );
  7217. Quaternion.conjugate(
  7218. sampledQuaternionQuaternion0Conjugate,
  7219. sampledQuaternionQuaternion0Conjugate
  7220. );
  7221. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  7222. var offset = i * 3;
  7223. Quaternion.unpack(
  7224. packedArray,
  7225. (startingIndex + i) * 4,
  7226. sampledQuaternionTempQuaternion
  7227. );
  7228. Quaternion.multiply(
  7229. sampledQuaternionTempQuaternion,
  7230. sampledQuaternionQuaternion0Conjugate,
  7231. sampledQuaternionTempQuaternion
  7232. );
  7233. if (sampledQuaternionTempQuaternion.w < 0) {
  7234. Quaternion.negate(
  7235. sampledQuaternionTempQuaternion,
  7236. sampledQuaternionTempQuaternion
  7237. );
  7238. }
  7239. Quaternion.computeAxis(
  7240. sampledQuaternionTempQuaternion,
  7241. sampledQuaternionAxis
  7242. );
  7243. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  7244. if (!when.defined(result)) {
  7245. result = [];
  7246. }
  7247. result[offset] = sampledQuaternionAxis.x * angle;
  7248. result[offset + 1] = sampledQuaternionAxis.y * angle;
  7249. result[offset + 2] = sampledQuaternionAxis.z * angle;
  7250. }
  7251. };
  7252. /**
  7253. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  7254. *
  7255. * @param {Number[]} array The array previously packed for interpolation.
  7256. * @param {Number[]} sourceArray The original packed array.
  7257. * @param {Number} [firstIndex=0] The firstIndex used to convert the array.
  7258. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  7259. * @param {Quaternion} [result] The object into which to store the result.
  7260. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  7261. */
  7262. Quaternion.unpackInterpolationResult = function (
  7263. array,
  7264. sourceArray,
  7265. firstIndex,
  7266. lastIndex,
  7267. result
  7268. ) {
  7269. if (!when.defined(result)) {
  7270. result = new Quaternion();
  7271. }
  7272. Cartesian2.Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  7273. var magnitude = Cartesian2.Cartesian3.magnitude(sampledQuaternionRotation);
  7274. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  7275. if (magnitude === 0) {
  7276. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  7277. } else {
  7278. Quaternion.fromAxisAngle(
  7279. sampledQuaternionRotation,
  7280. magnitude,
  7281. sampledQuaternionTempQuaternion
  7282. );
  7283. }
  7284. return Quaternion.multiply(
  7285. sampledQuaternionTempQuaternion,
  7286. sampledQuaternionQuaternion0,
  7287. result
  7288. );
  7289. };
  7290. /**
  7291. * Duplicates a Quaternion instance.
  7292. *
  7293. * @param {Quaternion} quaternion The quaternion to duplicate.
  7294. * @param {Quaternion} [result] The object onto which to store the result.
  7295. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  7296. */
  7297. Quaternion.clone = function (quaternion, result) {
  7298. if (!when.defined(quaternion)) {
  7299. return undefined;
  7300. }
  7301. if (!when.defined(result)) {
  7302. return new Quaternion(
  7303. quaternion.x,
  7304. quaternion.y,
  7305. quaternion.z,
  7306. quaternion.w
  7307. );
  7308. }
  7309. result.x = quaternion.x;
  7310. result.y = quaternion.y;
  7311. result.z = quaternion.z;
  7312. result.w = quaternion.w;
  7313. return result;
  7314. };
  7315. /**
  7316. * Computes the conjugate of the provided quaternion.
  7317. *
  7318. * @param {Quaternion} quaternion The quaternion to conjugate.
  7319. * @param {Quaternion} result The object onto which to store the result.
  7320. * @returns {Quaternion} The modified result parameter.
  7321. */
  7322. Quaternion.conjugate = function (quaternion, result) {
  7323. //>>includeStart('debug', pragmas.debug);
  7324. Check.Check.typeOf.object("quaternion", quaternion);
  7325. Check.Check.typeOf.object("result", result);
  7326. //>>includeEnd('debug');
  7327. result.x = -quaternion.x;
  7328. result.y = -quaternion.y;
  7329. result.z = -quaternion.z;
  7330. result.w = quaternion.w;
  7331. return result;
  7332. };
  7333. /**
  7334. * Computes magnitude squared for the provided quaternion.
  7335. *
  7336. * @param {Quaternion} quaternion The quaternion to conjugate.
  7337. * @returns {Number} The magnitude squared.
  7338. */
  7339. Quaternion.magnitudeSquared = function (quaternion) {
  7340. //>>includeStart('debug', pragmas.debug);
  7341. Check.Check.typeOf.object("quaternion", quaternion);
  7342. //>>includeEnd('debug');
  7343. return (
  7344. quaternion.x * quaternion.x +
  7345. quaternion.y * quaternion.y +
  7346. quaternion.z * quaternion.z +
  7347. quaternion.w * quaternion.w
  7348. );
  7349. };
  7350. /**
  7351. * Computes magnitude for the provided quaternion.
  7352. *
  7353. * @param {Quaternion} quaternion The quaternion to conjugate.
  7354. * @returns {Number} The magnitude.
  7355. */
  7356. Quaternion.magnitude = function (quaternion) {
  7357. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  7358. };
  7359. /**
  7360. * Computes the normalized form of the provided quaternion.
  7361. *
  7362. * @param {Quaternion} quaternion The quaternion to normalize.
  7363. * @param {Quaternion} result The object onto which to store the result.
  7364. * @returns {Quaternion} The modified result parameter.
  7365. */
  7366. Quaternion.normalize = function (quaternion, result) {
  7367. //>>includeStart('debug', pragmas.debug);
  7368. Check.Check.typeOf.object("result", result);
  7369. //>>includeEnd('debug');
  7370. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  7371. var x = quaternion.x * inverseMagnitude;
  7372. var y = quaternion.y * inverseMagnitude;
  7373. var z = quaternion.z * inverseMagnitude;
  7374. var w = quaternion.w * inverseMagnitude;
  7375. result.x = x;
  7376. result.y = y;
  7377. result.z = z;
  7378. result.w = w;
  7379. return result;
  7380. };
  7381. /**
  7382. * Computes the inverse of the provided quaternion.
  7383. *
  7384. * @param {Quaternion} quaternion The quaternion to normalize.
  7385. * @param {Quaternion} result The object onto which to store the result.
  7386. * @returns {Quaternion} The modified result parameter.
  7387. */
  7388. Quaternion.inverse = function (quaternion, result) {
  7389. //>>includeStart('debug', pragmas.debug);
  7390. Check.Check.typeOf.object("result", result);
  7391. //>>includeEnd('debug');
  7392. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  7393. result = Quaternion.conjugate(quaternion, result);
  7394. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  7395. };
  7396. /**
  7397. * Computes the componentwise sum of two quaternions.
  7398. *
  7399. * @param {Quaternion} left The first quaternion.
  7400. * @param {Quaternion} right The second quaternion.
  7401. * @param {Quaternion} result The object onto which to store the result.
  7402. * @returns {Quaternion} The modified result parameter.
  7403. */
  7404. Quaternion.add = function (left, right, result) {
  7405. //>>includeStart('debug', pragmas.debug);
  7406. Check.Check.typeOf.object("left", left);
  7407. Check.Check.typeOf.object("right", right);
  7408. Check.Check.typeOf.object("result", result);
  7409. //>>includeEnd('debug');
  7410. result.x = left.x + right.x;
  7411. result.y = left.y + right.y;
  7412. result.z = left.z + right.z;
  7413. result.w = left.w + right.w;
  7414. return result;
  7415. };
  7416. /**
  7417. * Computes the componentwise difference of two quaternions.
  7418. *
  7419. * @param {Quaternion} left The first quaternion.
  7420. * @param {Quaternion} right The second quaternion.
  7421. * @param {Quaternion} result The object onto which to store the result.
  7422. * @returns {Quaternion} The modified result parameter.
  7423. */
  7424. Quaternion.subtract = function (left, right, result) {
  7425. //>>includeStart('debug', pragmas.debug);
  7426. Check.Check.typeOf.object("left", left);
  7427. Check.Check.typeOf.object("right", right);
  7428. Check.Check.typeOf.object("result", result);
  7429. //>>includeEnd('debug');
  7430. result.x = left.x - right.x;
  7431. result.y = left.y - right.y;
  7432. result.z = left.z - right.z;
  7433. result.w = left.w - right.w;
  7434. return result;
  7435. };
  7436. /**
  7437. * Negates the provided quaternion.
  7438. *
  7439. * @param {Quaternion} quaternion The quaternion to be negated.
  7440. * @param {Quaternion} result The object onto which to store the result.
  7441. * @returns {Quaternion} The modified result parameter.
  7442. */
  7443. Quaternion.negate = function (quaternion, result) {
  7444. //>>includeStart('debug', pragmas.debug);
  7445. Check.Check.typeOf.object("quaternion", quaternion);
  7446. Check.Check.typeOf.object("result", result);
  7447. //>>includeEnd('debug');
  7448. result.x = -quaternion.x;
  7449. result.y = -quaternion.y;
  7450. result.z = -quaternion.z;
  7451. result.w = -quaternion.w;
  7452. return result;
  7453. };
  7454. /**
  7455. * Computes the dot (scalar) product of two quaternions.
  7456. *
  7457. * @param {Quaternion} left The first quaternion.
  7458. * @param {Quaternion} right The second quaternion.
  7459. * @returns {Number} The dot product.
  7460. */
  7461. Quaternion.dot = function (left, right) {
  7462. //>>includeStart('debug', pragmas.debug);
  7463. Check.Check.typeOf.object("left", left);
  7464. Check.Check.typeOf.object("right", right);
  7465. //>>includeEnd('debug');
  7466. return (
  7467. left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
  7468. );
  7469. };
  7470. /**
  7471. * Computes the product of two quaternions.
  7472. *
  7473. * @param {Quaternion} left The first quaternion.
  7474. * @param {Quaternion} right The second quaternion.
  7475. * @param {Quaternion} result The object onto which to store the result.
  7476. * @returns {Quaternion} The modified result parameter.
  7477. */
  7478. Quaternion.multiply = function (left, right, result) {
  7479. //>>includeStart('debug', pragmas.debug);
  7480. Check.Check.typeOf.object("left", left);
  7481. Check.Check.typeOf.object("right", right);
  7482. Check.Check.typeOf.object("result", result);
  7483. //>>includeEnd('debug');
  7484. var leftX = left.x;
  7485. var leftY = left.y;
  7486. var leftZ = left.z;
  7487. var leftW = left.w;
  7488. var rightX = right.x;
  7489. var rightY = right.y;
  7490. var rightZ = right.z;
  7491. var rightW = right.w;
  7492. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  7493. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  7494. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  7495. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  7496. result.x = x;
  7497. result.y = y;
  7498. result.z = z;
  7499. result.w = w;
  7500. return result;
  7501. };
  7502. /**
  7503. * Multiplies the provided quaternion componentwise by the provided scalar.
  7504. *
  7505. * @param {Quaternion} quaternion The quaternion to be scaled.
  7506. * @param {Number} scalar The scalar to multiply with.
  7507. * @param {Quaternion} result The object onto which to store the result.
  7508. * @returns {Quaternion} The modified result parameter.
  7509. */
  7510. Quaternion.multiplyByScalar = function (quaternion, scalar, result) {
  7511. //>>includeStart('debug', pragmas.debug);
  7512. Check.Check.typeOf.object("quaternion", quaternion);
  7513. Check.Check.typeOf.number("scalar", scalar);
  7514. Check.Check.typeOf.object("result", result);
  7515. //>>includeEnd('debug');
  7516. result.x = quaternion.x * scalar;
  7517. result.y = quaternion.y * scalar;
  7518. result.z = quaternion.z * scalar;
  7519. result.w = quaternion.w * scalar;
  7520. return result;
  7521. };
  7522. /**
  7523. * Divides the provided quaternion componentwise by the provided scalar.
  7524. *
  7525. * @param {Quaternion} quaternion The quaternion to be divided.
  7526. * @param {Number} scalar The scalar to divide by.
  7527. * @param {Quaternion} result The object onto which to store the result.
  7528. * @returns {Quaternion} The modified result parameter.
  7529. */
  7530. Quaternion.divideByScalar = function (quaternion, scalar, result) {
  7531. //>>includeStart('debug', pragmas.debug);
  7532. Check.Check.typeOf.object("quaternion", quaternion);
  7533. Check.Check.typeOf.number("scalar", scalar);
  7534. Check.Check.typeOf.object("result", result);
  7535. //>>includeEnd('debug');
  7536. result.x = quaternion.x / scalar;
  7537. result.y = quaternion.y / scalar;
  7538. result.z = quaternion.z / scalar;
  7539. result.w = quaternion.w / scalar;
  7540. return result;
  7541. };
  7542. /**
  7543. * Computes the axis of rotation of the provided quaternion.
  7544. *
  7545. * @param {Quaternion} quaternion The quaternion to use.
  7546. * @param {Cartesian3} result The object onto which to store the result.
  7547. * @returns {Cartesian3} The modified result parameter.
  7548. */
  7549. Quaternion.computeAxis = function (quaternion, result) {
  7550. //>>includeStart('debug', pragmas.debug);
  7551. Check.Check.typeOf.object("quaternion", quaternion);
  7552. Check.Check.typeOf.object("result", result);
  7553. //>>includeEnd('debug');
  7554. var w = quaternion.w;
  7555. if (Math.abs(w - 1.0) < _Math.CesiumMath.EPSILON6) {
  7556. result.x = result.y = result.z = 0;
  7557. return result;
  7558. }
  7559. var scalar = 1.0 / Math.sqrt(1.0 - w * w);
  7560. result.x = quaternion.x * scalar;
  7561. result.y = quaternion.y * scalar;
  7562. result.z = quaternion.z * scalar;
  7563. return result;
  7564. };
  7565. /**
  7566. * Computes the angle of rotation of the provided quaternion.
  7567. *
  7568. * @param {Quaternion} quaternion The quaternion to use.
  7569. * @returns {Number} The angle of rotation.
  7570. */
  7571. Quaternion.computeAngle = function (quaternion) {
  7572. //>>includeStart('debug', pragmas.debug);
  7573. Check.Check.typeOf.object("quaternion", quaternion);
  7574. //>>includeEnd('debug');
  7575. if (Math.abs(quaternion.w - 1.0) < _Math.CesiumMath.EPSILON6) {
  7576. return 0.0;
  7577. }
  7578. return 2.0 * Math.acos(quaternion.w);
  7579. };
  7580. var lerpScratch$1 = new Quaternion();
  7581. /**
  7582. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  7583. *
  7584. * @param {Quaternion} start The value corresponding to t at 0.0.
  7585. * @param {Quaternion} end The value corresponding to t at 1.0.
  7586. * @param {Number} t The point along t at which to interpolate.
  7587. * @param {Quaternion} result The object onto which to store the result.
  7588. * @returns {Quaternion} The modified result parameter.
  7589. */
  7590. Quaternion.lerp = function (start, end, t, result) {
  7591. //>>includeStart('debug', pragmas.debug);
  7592. Check.Check.typeOf.object("start", start);
  7593. Check.Check.typeOf.object("end", end);
  7594. Check.Check.typeOf.number("t", t);
  7595. Check.Check.typeOf.object("result", result);
  7596. //>>includeEnd('debug');
  7597. lerpScratch$1 = Quaternion.multiplyByScalar(end, t, lerpScratch$1);
  7598. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  7599. return Quaternion.add(lerpScratch$1, result, result);
  7600. };
  7601. var slerpEndNegated = new Quaternion();
  7602. var slerpScaledP = new Quaternion();
  7603. var slerpScaledR = new Quaternion();
  7604. /**
  7605. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  7606. *
  7607. * @param {Quaternion} start The value corresponding to t at 0.0.
  7608. * @param {Quaternion} end The value corresponding to t at 1.0.
  7609. * @param {Number} t The point along t at which to interpolate.
  7610. * @param {Quaternion} result The object onto which to store the result.
  7611. * @returns {Quaternion} The modified result parameter.
  7612. *
  7613. * @see Quaternion#fastSlerp
  7614. */
  7615. Quaternion.slerp = function (start, end, t, result) {
  7616. //>>includeStart('debug', pragmas.debug);
  7617. Check.Check.typeOf.object("start", start);
  7618. Check.Check.typeOf.object("end", end);
  7619. Check.Check.typeOf.number("t", t);
  7620. Check.Check.typeOf.object("result", result);
  7621. //>>includeEnd('debug');
  7622. var dot = Quaternion.dot(start, end);
  7623. // The angle between start must be acute. Since q and -q represent
  7624. // the same rotation, negate q to get the acute angle.
  7625. var r = end;
  7626. if (dot < 0.0) {
  7627. dot = -dot;
  7628. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  7629. }
  7630. // dot > 0, as the dot product approaches 1, the angle between the
  7631. // quaternions vanishes. use linear interpolation.
  7632. if (1.0 - dot < _Math.CesiumMath.EPSILON6) {
  7633. return Quaternion.lerp(start, r, t, result);
  7634. }
  7635. var theta = Math.acos(dot);
  7636. slerpScaledP = Quaternion.multiplyByScalar(
  7637. start,
  7638. Math.sin((1 - t) * theta),
  7639. slerpScaledP
  7640. );
  7641. slerpScaledR = Quaternion.multiplyByScalar(
  7642. r,
  7643. Math.sin(t * theta),
  7644. slerpScaledR
  7645. );
  7646. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  7647. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  7648. };
  7649. /**
  7650. * The logarithmic quaternion function.
  7651. *
  7652. * @param {Quaternion} quaternion The unit quaternion.
  7653. * @param {Cartesian3} result The object onto which to store the result.
  7654. * @returns {Cartesian3} The modified result parameter.
  7655. */
  7656. Quaternion.log = function (quaternion, result) {
  7657. //>>includeStart('debug', pragmas.debug);
  7658. Check.Check.typeOf.object("quaternion", quaternion);
  7659. Check.Check.typeOf.object("result", result);
  7660. //>>includeEnd('debug');
  7661. var theta = _Math.CesiumMath.acosClamped(quaternion.w);
  7662. var thetaOverSinTheta = 0.0;
  7663. if (theta !== 0.0) {
  7664. thetaOverSinTheta = theta / Math.sin(theta);
  7665. }
  7666. return Cartesian2.Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  7667. };
  7668. /**
  7669. * The exponential quaternion function.
  7670. *
  7671. * @param {Cartesian3} cartesian The cartesian.
  7672. * @param {Quaternion} result The object onto which to store the result.
  7673. * @returns {Quaternion} The modified result parameter.
  7674. */
  7675. Quaternion.exp = function (cartesian, result) {
  7676. //>>includeStart('debug', pragmas.debug);
  7677. Check.Check.typeOf.object("cartesian", cartesian);
  7678. Check.Check.typeOf.object("result", result);
  7679. //>>includeEnd('debug');
  7680. var theta = Cartesian2.Cartesian3.magnitude(cartesian);
  7681. var sinThetaOverTheta = 0.0;
  7682. if (theta !== 0.0) {
  7683. sinThetaOverTheta = Math.sin(theta) / theta;
  7684. }
  7685. result.x = cartesian.x * sinThetaOverTheta;
  7686. result.y = cartesian.y * sinThetaOverTheta;
  7687. result.z = cartesian.z * sinThetaOverTheta;
  7688. result.w = Math.cos(theta);
  7689. return result;
  7690. };
  7691. var squadScratchCartesian0 = new Cartesian2.Cartesian3();
  7692. var squadScratchCartesian1 = new Cartesian2.Cartesian3();
  7693. var squadScratchQuaternion0 = new Quaternion();
  7694. var squadScratchQuaternion1 = new Quaternion();
  7695. /**
  7696. * Computes an inner quadrangle point.
  7697. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  7698. *
  7699. * @param {Quaternion} q0 The first quaternion.
  7700. * @param {Quaternion} q1 The second quaternion.
  7701. * @param {Quaternion} q2 The third quaternion.
  7702. * @param {Quaternion} result The object onto which to store the result.
  7703. * @returns {Quaternion} The modified result parameter.
  7704. *
  7705. * @see Quaternion#squad
  7706. */
  7707. Quaternion.computeInnerQuadrangle = function (q0, q1, q2, result) {
  7708. //>>includeStart('debug', pragmas.debug);
  7709. Check.Check.typeOf.object("q0", q0);
  7710. Check.Check.typeOf.object("q1", q1);
  7711. Check.Check.typeOf.object("q2", q2);
  7712. Check.Check.typeOf.object("result", result);
  7713. //>>includeEnd('debug');
  7714. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  7715. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  7716. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  7717. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  7718. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  7719. Cartesian2.Cartesian3.add(cart0, cart1, cart0);
  7720. Cartesian2.Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  7721. Cartesian2.Cartesian3.negate(cart0, cart0);
  7722. Quaternion.exp(cart0, squadScratchQuaternion0);
  7723. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  7724. };
  7725. /**
  7726. * Computes the spherical quadrangle interpolation between quaternions.
  7727. *
  7728. * @param {Quaternion} q0 The first quaternion.
  7729. * @param {Quaternion} q1 The second quaternion.
  7730. * @param {Quaternion} s0 The first inner quadrangle.
  7731. * @param {Quaternion} s1 The second inner quadrangle.
  7732. * @param {Number} t The time in [0,1] used to interpolate.
  7733. * @param {Quaternion} result The object onto which to store the result.
  7734. * @returns {Quaternion} The modified result parameter.
  7735. *
  7736. *
  7737. * @example
  7738. * // 1. compute the squad interpolation between two quaternions on a curve
  7739. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  7740. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  7741. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  7742. *
  7743. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  7744. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  7745. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  7746. *
  7747. * @see Quaternion#computeInnerQuadrangle
  7748. */
  7749. Quaternion.squad = function (q0, q1, s0, s1, t, result) {
  7750. //>>includeStart('debug', pragmas.debug);
  7751. Check.Check.typeOf.object("q0", q0);
  7752. Check.Check.typeOf.object("q1", q1);
  7753. Check.Check.typeOf.object("s0", s0);
  7754. Check.Check.typeOf.object("s1", s1);
  7755. Check.Check.typeOf.number("t", t);
  7756. Check.Check.typeOf.object("result", result);
  7757. //>>includeEnd('debug');
  7758. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  7759. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  7760. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  7761. };
  7762. var fastSlerpScratchQuaternion = new Quaternion();
  7763. var opmu = 1.90110745351730037;
  7764. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7765. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7766. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7767. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7768. for (var i = 0; i < 7; ++i) {
  7769. var s = i + 1.0;
  7770. var t = 2.0 * s + 1.0;
  7771. u[i] = 1.0 / (s * t);
  7772. v[i] = s / t;
  7773. }
  7774. u[7] = opmu / (8.0 * 17.0);
  7775. v[7] = (opmu * 8.0) / 17.0;
  7776. /**
  7777. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  7778. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  7779. *
  7780. * @param {Quaternion} start The value corresponding to t at 0.0.
  7781. * @param {Quaternion} end The value corresponding to t at 1.0.
  7782. * @param {Number} t The point along t at which to interpolate.
  7783. * @param {Quaternion} result The object onto which to store the result.
  7784. * @returns {Quaternion} The modified result parameter.
  7785. *
  7786. * @see Quaternion#slerp
  7787. */
  7788. Quaternion.fastSlerp = function (start, end, t, result) {
  7789. //>>includeStart('debug', pragmas.debug);
  7790. Check.Check.typeOf.object("start", start);
  7791. Check.Check.typeOf.object("end", end);
  7792. Check.Check.typeOf.number("t", t);
  7793. Check.Check.typeOf.object("result", result);
  7794. //>>includeEnd('debug');
  7795. var x = Quaternion.dot(start, end);
  7796. var sign;
  7797. if (x >= 0) {
  7798. sign = 1.0;
  7799. } else {
  7800. sign = -1.0;
  7801. x = -x;
  7802. }
  7803. var xm1 = x - 1.0;
  7804. var d = 1.0 - t;
  7805. var sqrT = t * t;
  7806. var sqrD = d * d;
  7807. for (var i = 7; i >= 0; --i) {
  7808. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  7809. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  7810. }
  7811. var cT =
  7812. sign *
  7813. t *
  7814. (1.0 +
  7815. bT[0] *
  7816. (1.0 +
  7817. bT[1] *
  7818. (1.0 +
  7819. bT[2] *
  7820. (1.0 +
  7821. bT[3] *
  7822. (1.0 +
  7823. bT[4] *
  7824. (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  7825. var cD =
  7826. d *
  7827. (1.0 +
  7828. bD[0] *
  7829. (1.0 +
  7830. bD[1] *
  7831. (1.0 +
  7832. bD[2] *
  7833. (1.0 +
  7834. bD[3] *
  7835. (1.0 +
  7836. bD[4] *
  7837. (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  7838. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  7839. Quaternion.multiplyByScalar(end, cT, result);
  7840. return Quaternion.add(temp, result, result);
  7841. };
  7842. /**
  7843. * Computes the spherical quadrangle interpolation between quaternions.
  7844. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  7845. *
  7846. * @param {Quaternion} q0 The first quaternion.
  7847. * @param {Quaternion} q1 The second quaternion.
  7848. * @param {Quaternion} s0 The first inner quadrangle.
  7849. * @param {Quaternion} s1 The second inner quadrangle.
  7850. * @param {Number} t The time in [0,1] used to interpolate.
  7851. * @param {Quaternion} result The object onto which to store the result.
  7852. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  7853. *
  7854. * @see Quaternion#squad
  7855. */
  7856. Quaternion.fastSquad = function (q0, q1, s0, s1, t, result) {
  7857. //>>includeStart('debug', pragmas.debug);
  7858. Check.Check.typeOf.object("q0", q0);
  7859. Check.Check.typeOf.object("q1", q1);
  7860. Check.Check.typeOf.object("s0", s0);
  7861. Check.Check.typeOf.object("s1", s1);
  7862. Check.Check.typeOf.number("t", t);
  7863. Check.Check.typeOf.object("result", result);
  7864. //>>includeEnd('debug');
  7865. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  7866. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  7867. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  7868. };
  7869. /**
  7870. * Compares the provided quaternions componentwise and returns
  7871. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7872. *
  7873. * @param {Quaternion} [left] The first quaternion.
  7874. * @param {Quaternion} [right] The second quaternion.
  7875. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7876. */
  7877. Quaternion.equals = function (left, right) {
  7878. return (
  7879. left === right ||
  7880. (when.defined(left) &&
  7881. when.defined(right) &&
  7882. left.x === right.x &&
  7883. left.y === right.y &&
  7884. left.z === right.z &&
  7885. left.w === right.w)
  7886. );
  7887. };
  7888. /**
  7889. * Compares the provided quaternions componentwise and returns
  7890. * <code>true</code> if they are within the provided epsilon,
  7891. * <code>false</code> otherwise.
  7892. *
  7893. * @param {Quaternion} [left] The first quaternion.
  7894. * @param {Quaternion} [right] The second quaternion.
  7895. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  7896. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7897. */
  7898. Quaternion.equalsEpsilon = function (left, right, epsilon) {
  7899. epsilon = when.defaultValue(epsilon, 0);
  7900. return (
  7901. left === right ||
  7902. (when.defined(left) &&
  7903. when.defined(right) &&
  7904. Math.abs(left.x - right.x) <= epsilon &&
  7905. Math.abs(left.y - right.y) <= epsilon &&
  7906. Math.abs(left.z - right.z) <= epsilon &&
  7907. Math.abs(left.w - right.w) <= epsilon)
  7908. );
  7909. };
  7910. /**
  7911. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  7912. *
  7913. * @type {Quaternion}
  7914. * @constant
  7915. */
  7916. Quaternion.ZERO = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 0.0));
  7917. /**
  7918. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  7919. *
  7920. * @type {Quaternion}
  7921. * @constant
  7922. */
  7923. Quaternion.IDENTITY = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 1.0));
  7924. /**
  7925. * Duplicates this Quaternion instance.
  7926. *
  7927. * @param {Quaternion} [result] The object onto which to store the result.
  7928. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  7929. */
  7930. Quaternion.prototype.clone = function (result) {
  7931. return Quaternion.clone(this, result);
  7932. };
  7933. /**
  7934. * Compares this and the provided quaternion componentwise and returns
  7935. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7936. *
  7937. * @param {Quaternion} [right] The right hand side quaternion.
  7938. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7939. */
  7940. Quaternion.prototype.equals = function (right) {
  7941. return Quaternion.equals(this, right);
  7942. };
  7943. /**
  7944. * Compares this and the provided quaternion componentwise and returns
  7945. * <code>true</code> if they are within the provided epsilon,
  7946. * <code>false</code> otherwise.
  7947. *
  7948. * @param {Quaternion} [right] The right hand side quaternion.
  7949. * @param {Number} [epsilon=0] The epsilon to use for equality testing.
  7950. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7951. */
  7952. Quaternion.prototype.equalsEpsilon = function (right, epsilon) {
  7953. return Quaternion.equalsEpsilon(this, right, epsilon);
  7954. };
  7955. /**
  7956. * Returns a string representing this quaternion in the format (x, y, z, w).
  7957. *
  7958. * @returns {String} A string representing this Quaternion.
  7959. */
  7960. Quaternion.prototype.toString = function () {
  7961. return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")";
  7962. };
  7963. /**
  7964. * Finds an item in a sorted array.
  7965. *
  7966. * @function
  7967. * @param {Array} array The sorted array to search.
  7968. * @param {*} itemToFind The item to find in the array.
  7969. * @param {binarySearchComparator} comparator The function to use to compare the item to
  7970. * elements in the array.
  7971. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  7972. * does not exist, the return value is a negative number which is the bitwise complement (~)
  7973. * of the index before which the itemToFind should be inserted in order to maintain the
  7974. * sorted order of the array.
  7975. *
  7976. * @example
  7977. * // Create a comparator function to search through an array of numbers.
  7978. * function comparator(a, b) {
  7979. * return a - b;
  7980. * };
  7981. * var numbers = [0, 2, 4, 6, 8];
  7982. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  7983. */
  7984. function binarySearch(array, itemToFind, comparator) {
  7985. //>>includeStart('debug', pragmas.debug);
  7986. Check.Check.defined("array", array);
  7987. Check.Check.defined("itemToFind", itemToFind);
  7988. Check.Check.defined("comparator", comparator);
  7989. //>>includeEnd('debug');
  7990. var low = 0;
  7991. var high = array.length - 1;
  7992. var i;
  7993. var comparison;
  7994. while (low <= high) {
  7995. i = ~~((low + high) / 2);
  7996. comparison = comparator(array[i], itemToFind);
  7997. if (comparison < 0) {
  7998. low = i + 1;
  7999. continue;
  8000. }
  8001. if (comparison > 0) {
  8002. high = i - 1;
  8003. continue;
  8004. }
  8005. return i;
  8006. }
  8007. return ~(high + 1);
  8008. }
  8009. /**
  8010. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  8011. *
  8012. * @alias EarthOrientationParametersSample
  8013. * @constructor
  8014. *
  8015. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  8016. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  8017. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  8018. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  8019. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  8020. *
  8021. * @private
  8022. */
  8023. function EarthOrientationParametersSample(
  8024. xPoleWander,
  8025. yPoleWander,
  8026. xPoleOffset,
  8027. yPoleOffset,
  8028. ut1MinusUtc
  8029. ) {
  8030. /**
  8031. * The pole wander about the X axis, in radians.
  8032. * @type {Number}
  8033. */
  8034. this.xPoleWander = xPoleWander;
  8035. /**
  8036. * The pole wander about the Y axis, in radians.
  8037. * @type {Number}
  8038. */
  8039. this.yPoleWander = yPoleWander;
  8040. /**
  8041. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  8042. * @type {Number}
  8043. */
  8044. this.xPoleOffset = xPoleOffset;
  8045. /**
  8046. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  8047. * @type {Number}
  8048. */
  8049. this.yPoleOffset = yPoleOffset;
  8050. /**
  8051. * The difference in time standards, UT1 - UTC, in seconds.
  8052. * @type {Number}
  8053. */
  8054. this.ut1MinusUtc = ut1MinusUtc;
  8055. }
  8056. /**
  8057. @license
  8058. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  8059. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  8060. php.js is copyright 2012 Kevin van Zonneveld.
  8061. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  8062. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  8063. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  8064. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  8065. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  8066. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  8067. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  8068. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  8069. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  8070. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  8071. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  8072. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  8073. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  8074. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  8075. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  8076. (http://geekfg.blogspot.com), Andrea Giammarchi
  8077. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  8078. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  8079. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  8080. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  8081. Marc Palau, Martin
  8082. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  8083. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  8084. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  8085. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  8086. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  8087. Ariede (http://caioariede.com), Robin, Kankrelune
  8088. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  8089. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  8090. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  8091. David, Aman Gupta, Michael White, Public Domain
  8092. (http://www.json.org/json2.js), Steven Levithan
  8093. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  8094. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  8095. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  8096. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  8097. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  8098. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  8099. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  8100. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  8101. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  8102. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  8103. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  8104. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  8105. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  8106. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  8107. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  8108. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  8109. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  8110. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  8111. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  8112. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  8113. (http://yass.meetcweb.com), Peter-Paul Koch
  8114. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  8115. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  8116. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  8117. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  8118. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  8119. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  8120. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  8121. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  8122. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  8123. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  8124. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  8125. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  8126. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  8127. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  8128. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  8129. (http://www.premasolutions.com/), Philippe Jausions
  8130. (http://pear.php.net/user/jausions), Aidan Lister
  8131. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  8132. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  8133. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  8134. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  8135. (http://www.pedrotainha.com), James, Arnout Kazemier
  8136. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  8137. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  8138. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  8139. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  8140. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  8141. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  8142. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  8143. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  8144. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  8145. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  8146. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  8147. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  8148. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  8149. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  8150. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  8151. (http://benblume.co.uk/), DtTvB
  8152. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  8153. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  8154. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  8155. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  8156. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  8157. Bryan
  8158. Licensed under the MIT (MIT-LICENSE.txt) license.
  8159. Permission is hereby granted, free of charge, to any person obtaining a
  8160. copy of this software and associated documentation files (the
  8161. "Software"), to deal in the Software without restriction, including
  8162. without limitation the rights to use, copy, modify, merge, publish,
  8163. distribute, sublicense, and/or sell copies of the Software, and to
  8164. permit persons to whom the Software is furnished to do so, subject to
  8165. the following conditions:
  8166. The above copyright notice and this permission notice shall be included
  8167. in all copies or substantial portions of the Software.
  8168. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8169. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8170. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  8171. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  8172. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  8173. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  8174. OTHER DEALINGS IN THE SOFTWARE.
  8175. */
  8176. function sprintf () {
  8177. // http://kevin.vanzonneveld.net
  8178. // + original by: Ash Searle (http://hexmen.com/blog/)
  8179. // + namespaced by: Michael White (http://getsprink.com)
  8180. // + tweaked by: Jack
  8181. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  8182. // + input by: Paulo Freitas
  8183. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  8184. // + input by: Brett Zamir (http://brett-zamir.me)
  8185. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  8186. // + improved by: Dj
  8187. // + improved by: Allidylls
  8188. // * example 1: sprintf("%01.2f", 123.1);
  8189. // * returns 1: 123.10
  8190. // * example 2: sprintf("[%10s]", 'monkey');
  8191. // * returns 2: '[ monkey]'
  8192. // * example 3: sprintf("[%'#10s]", 'monkey');
  8193. // * returns 3: '[####monkey]'
  8194. // * example 4: sprintf("%d", 123456789012345);
  8195. // * returns 4: '123456789012345'
  8196. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  8197. var a = arguments,
  8198. i = 0,
  8199. format = a[i++];
  8200. // pad()
  8201. var pad = function (str, len, chr, leftJustify) {
  8202. if (!chr) {
  8203. chr = ' ';
  8204. }
  8205. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  8206. return leftJustify ? str + padding : padding + str;
  8207. };
  8208. // justify()
  8209. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  8210. var diff = minWidth - value.length;
  8211. if (diff > 0) {
  8212. if (leftJustify || !zeroPad) {
  8213. value = pad(value, minWidth, customPadChar, leftJustify);
  8214. } else {
  8215. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  8216. }
  8217. }
  8218. return value;
  8219. };
  8220. // formatBaseX()
  8221. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  8222. // Note: casts negative numbers to positive ones
  8223. var number = value >>> 0;
  8224. prefix = prefix && number && {
  8225. '2': '0b',
  8226. '8': '0',
  8227. '16': '0x'
  8228. }[base] || '';
  8229. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  8230. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  8231. };
  8232. // formatString()
  8233. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  8234. if (precision != null) {
  8235. value = value.slice(0, precision);
  8236. }
  8237. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  8238. };
  8239. // doFormat()
  8240. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  8241. var number;
  8242. var prefix;
  8243. var method;
  8244. var textTransform;
  8245. var value;
  8246. if (substring == '%%') {
  8247. return '%';
  8248. }
  8249. // parse flags
  8250. var leftJustify = false,
  8251. positivePrefix = '',
  8252. zeroPad = false,
  8253. prefixBaseX = false,
  8254. customPadChar = ' ';
  8255. var flagsl = flags.length;
  8256. for (var j = 0; flags && j < flagsl; j++) {
  8257. switch (flags.charAt(j)) {
  8258. case ' ':
  8259. positivePrefix = ' ';
  8260. break;
  8261. case '+':
  8262. positivePrefix = '+';
  8263. break;
  8264. case '-':
  8265. leftJustify = true;
  8266. break;
  8267. case "'":
  8268. customPadChar = flags.charAt(j + 1);
  8269. break;
  8270. case '0':
  8271. zeroPad = true;
  8272. break;
  8273. case '#':
  8274. prefixBaseX = true;
  8275. break;
  8276. }
  8277. }
  8278. // parameters may be null, undefined, empty-string or real valued
  8279. // we want to ignore null, undefined and empty-string values
  8280. if (!minWidth) {
  8281. minWidth = 0;
  8282. } else if (minWidth == '*') {
  8283. minWidth = +a[i++];
  8284. } else if (minWidth.charAt(0) == '*') {
  8285. minWidth = +a[minWidth.slice(1, -1)];
  8286. } else {
  8287. minWidth = +minWidth;
  8288. }
  8289. // Note: undocumented perl feature:
  8290. if (minWidth < 0) {
  8291. minWidth = -minWidth;
  8292. leftJustify = true;
  8293. }
  8294. if (!isFinite(minWidth)) {
  8295. throw new Error('sprintf: (minimum-)width must be finite');
  8296. }
  8297. if (!precision) {
  8298. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  8299. } else if (precision == '*') {
  8300. precision = +a[i++];
  8301. } else if (precision.charAt(0) == '*') {
  8302. precision = +a[precision.slice(1, -1)];
  8303. } else {
  8304. precision = +precision;
  8305. }
  8306. // grab value using valueIndex if required?
  8307. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  8308. switch (type) {
  8309. case 's':
  8310. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  8311. case 'c':
  8312. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  8313. case 'b':
  8314. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  8315. case 'o':
  8316. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  8317. case 'x':
  8318. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  8319. case 'X':
  8320. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  8321. case 'u':
  8322. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  8323. case 'i':
  8324. case 'd':
  8325. number = +value || 0;
  8326. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  8327. prefix = number < 0 ? '-' : positivePrefix;
  8328. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  8329. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  8330. case 'e':
  8331. case 'E':
  8332. case 'f': // Should handle locales (as per setlocale)
  8333. case 'F':
  8334. case 'g':
  8335. case 'G':
  8336. number = +value;
  8337. prefix = number < 0 ? '-' : positivePrefix;
  8338. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  8339. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  8340. value = prefix + Math.abs(number)[method](precision);
  8341. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  8342. default:
  8343. return substring;
  8344. }
  8345. };
  8346. return format.replace(regex, doFormat);
  8347. }
  8348. /**
  8349. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  8350. * In addition to submillisecond precision, this object can also represent leap seconds.
  8351. * @alias GregorianDate
  8352. * @constructor
  8353. *
  8354. * @param {Number} [year] The year as a whole number.
  8355. * @param {Number} [month] The month as a whole number with range [1, 12].
  8356. * @param {Number} [day] The day of the month as a whole number starting at 1.
  8357. * @param {Number} [hour] The hour as a whole number with range [0, 23].
  8358. * @param {Number} [minute] The minute of the hour as a whole number with range [0, 59].
  8359. * @param {Number} [second] The second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  8360. * @param {Number} [millisecond] The millisecond of the second as a floating point number with range [0.0, 1000.0).
  8361. * @param {Boolean} [isLeapSecond] Whether this time is during a leap second.
  8362. *
  8363. * @see JulianDate#toGregorianDate
  8364. */
  8365. function GregorianDate(
  8366. year,
  8367. month,
  8368. day,
  8369. hour,
  8370. minute,
  8371. second,
  8372. millisecond,
  8373. isLeapSecond
  8374. ) {
  8375. /**
  8376. * Gets or sets the year as a whole number.
  8377. * @type {Number}
  8378. */
  8379. this.year = year;
  8380. /**
  8381. * Gets or sets the month as a whole number with range [1, 12].
  8382. * @type {Number}
  8383. */
  8384. this.month = month;
  8385. /**
  8386. * Gets or sets the day of the month as a whole number starting at 1.
  8387. * @type {Number}
  8388. */
  8389. this.day = day;
  8390. /**
  8391. * Gets or sets the hour as a whole number with range [0, 23].
  8392. * @type {Number}
  8393. */
  8394. this.hour = hour;
  8395. /**
  8396. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  8397. * @type {Number}
  8398. */
  8399. this.minute = minute;
  8400. /**
  8401. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  8402. * @type {Number}
  8403. */
  8404. this.second = second;
  8405. /**
  8406. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  8407. * @type {Number}
  8408. */
  8409. this.millisecond = millisecond;
  8410. /**
  8411. * Gets or sets whether this time is during a leap second.
  8412. * @type {Boolean}
  8413. */
  8414. this.isLeapSecond = isLeapSecond;
  8415. }
  8416. /**
  8417. * Determines if a given date is a leap year.
  8418. *
  8419. * @function isLeapYear
  8420. *
  8421. * @param {Number} year The year to be tested.
  8422. * @returns {Boolean} True if <code>year</code> is a leap year.
  8423. *
  8424. * @example
  8425. * var leapYear = Cesium.isLeapYear(2000); // true
  8426. */
  8427. function isLeapYear(year) {
  8428. //>>includeStart('debug', pragmas.debug);
  8429. if (year === null || isNaN(year)) {
  8430. throw new Check.DeveloperError("year is required and must be a number.");
  8431. }
  8432. //>>includeEnd('debug');
  8433. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  8434. }
  8435. /**
  8436. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  8437. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  8438. * @alias LeapSecond
  8439. * @constructor
  8440. *
  8441. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  8442. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  8443. */
  8444. function LeapSecond(date, offset) {
  8445. /**
  8446. * Gets or sets the date at which this leap second occurs.
  8447. * @type {JulianDate}
  8448. */
  8449. this.julianDate = date;
  8450. /**
  8451. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  8452. * of this leap second.
  8453. * @type {Number}
  8454. */
  8455. this.offset = offset;
  8456. }
  8457. /**
  8458. * Constants for time conversions like those done by {@link JulianDate}.
  8459. *
  8460. * @namespace TimeConstants
  8461. *
  8462. * @see JulianDate
  8463. *
  8464. * @private
  8465. */
  8466. var TimeConstants = {
  8467. /**
  8468. * The number of seconds in one millisecond: <code>0.001</code>
  8469. * @type {Number}
  8470. * @constant
  8471. */
  8472. SECONDS_PER_MILLISECOND: 0.001,
  8473. /**
  8474. * The number of seconds in one minute: <code>60</code>.
  8475. * @type {Number}
  8476. * @constant
  8477. */
  8478. SECONDS_PER_MINUTE: 60.0,
  8479. /**
  8480. * The number of minutes in one hour: <code>60</code>.
  8481. * @type {Number}
  8482. * @constant
  8483. */
  8484. MINUTES_PER_HOUR: 60.0,
  8485. /**
  8486. * The number of hours in one day: <code>24</code>.
  8487. * @type {Number}
  8488. * @constant
  8489. */
  8490. HOURS_PER_DAY: 24.0,
  8491. /**
  8492. * The number of seconds in one hour: <code>3600</code>.
  8493. * @type {Number}
  8494. * @constant
  8495. */
  8496. SECONDS_PER_HOUR: 3600.0,
  8497. /**
  8498. * The number of minutes in one day: <code>1440</code>.
  8499. * @type {Number}
  8500. * @constant
  8501. */
  8502. MINUTES_PER_DAY: 1440.0,
  8503. /**
  8504. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  8505. * @type {Number}
  8506. * @constant
  8507. */
  8508. SECONDS_PER_DAY: 86400.0,
  8509. /**
  8510. * The number of days in one Julian century: <code>36525</code>.
  8511. * @type {Number}
  8512. * @constant
  8513. */
  8514. DAYS_PER_JULIAN_CENTURY: 36525.0,
  8515. /**
  8516. * One trillionth of a second.
  8517. * @type {Number}
  8518. * @constant
  8519. */
  8520. PICOSECOND: 0.000000001,
  8521. /**
  8522. * The number of days to subtract from a Julian date to determine the
  8523. * modified Julian date, which gives the number of days since midnight
  8524. * on November 17, 1858.
  8525. * @type {Number}
  8526. * @constant
  8527. */
  8528. MODIFIED_JULIAN_DATE_DIFFERENCE: 2400000.5,
  8529. };
  8530. var TimeConstants$1 = Object.freeze(TimeConstants);
  8531. /**
  8532. * Provides the type of time standards which JulianDate can take as input.
  8533. *
  8534. * @enum {Number}
  8535. *
  8536. * @see JulianDate
  8537. */
  8538. var TimeStandard = {
  8539. /**
  8540. * Represents the coordinated Universal Time (UTC) time standard.
  8541. *
  8542. * UTC is related to TAI according to the relationship
  8543. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  8544. * seconds which have been introduced as of the time in TAI.
  8545. *
  8546. * @type {Number}
  8547. * @constant
  8548. */
  8549. UTC: 0,
  8550. /**
  8551. * Represents the International Atomic Time (TAI) time standard.
  8552. * TAI is the principal time standard to which the other time standards are related.
  8553. *
  8554. * @type {Number}
  8555. * @constant
  8556. */
  8557. TAI: 1,
  8558. };
  8559. var TimeStandard$1 = Object.freeze(TimeStandard);
  8560. var gregorianDateScratch = new GregorianDate();
  8561. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  8562. var daysInLeapFeburary = 29;
  8563. function compareLeapSecondDates(leapSecond, dateToFind) {
  8564. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  8565. }
  8566. // we don't really need a leap second instance, anything with a julianDate property will do
  8567. var binarySearchScratchLeapSecond = new LeapSecond();
  8568. function convertUtcToTai(julianDate) {
  8569. //Even though julianDate is in UTC, we'll treat it as TAI and
  8570. //search the leap second table for it.
  8571. binarySearchScratchLeapSecond.julianDate = julianDate;
  8572. var leapSeconds = JulianDate.leapSeconds;
  8573. var index = binarySearch(
  8574. leapSeconds,
  8575. binarySearchScratchLeapSecond,
  8576. compareLeapSecondDates
  8577. );
  8578. if (index < 0) {
  8579. index = ~index;
  8580. }
  8581. if (index >= leapSeconds.length) {
  8582. index = leapSeconds.length - 1;
  8583. }
  8584. var offset = leapSeconds[index].offset;
  8585. if (index > 0) {
  8586. //Now we have the index of the closest leap second that comes on or after our UTC time.
  8587. //However, if the difference between the UTC date being converted and the TAI
  8588. //defined leap second is greater than the offset, we are off by one and need to use
  8589. //the previous leap second.
  8590. var difference = JulianDate.secondsDifference(
  8591. leapSeconds[index].julianDate,
  8592. julianDate
  8593. );
  8594. if (difference > offset) {
  8595. index--;
  8596. offset = leapSeconds[index].offset;
  8597. }
  8598. }
  8599. JulianDate.addSeconds(julianDate, offset, julianDate);
  8600. }
  8601. function convertTaiToUtc(julianDate, result) {
  8602. binarySearchScratchLeapSecond.julianDate = julianDate;
  8603. var leapSeconds = JulianDate.leapSeconds;
  8604. var index = binarySearch(
  8605. leapSeconds,
  8606. binarySearchScratchLeapSecond,
  8607. compareLeapSecondDates
  8608. );
  8609. if (index < 0) {
  8610. index = ~index;
  8611. }
  8612. //All times before our first leap second get the first offset.
  8613. if (index === 0) {
  8614. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  8615. }
  8616. //All times after our leap second get the last offset.
  8617. if (index >= leapSeconds.length) {
  8618. return JulianDate.addSeconds(
  8619. julianDate,
  8620. -leapSeconds[index - 1].offset,
  8621. result
  8622. );
  8623. }
  8624. //Compute the difference between the found leap second and the time we are converting.
  8625. var difference = JulianDate.secondsDifference(
  8626. leapSeconds[index].julianDate,
  8627. julianDate
  8628. );
  8629. if (difference === 0) {
  8630. //The date is in our leap second table.
  8631. return JulianDate.addSeconds(
  8632. julianDate,
  8633. -leapSeconds[index].offset,
  8634. result
  8635. );
  8636. }
  8637. if (difference <= 1.0) {
  8638. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  8639. return undefined;
  8640. }
  8641. //The time is in between two leap seconds, index is the leap second after the date
  8642. //we're converting, so we subtract one to get the correct LeapSecond instance.
  8643. return JulianDate.addSeconds(
  8644. julianDate,
  8645. -leapSeconds[--index].offset,
  8646. result
  8647. );
  8648. }
  8649. function setComponents(wholeDays, secondsOfDay, julianDate) {
  8650. var extraDays = (secondsOfDay / TimeConstants$1.SECONDS_PER_DAY) | 0;
  8651. wholeDays += extraDays;
  8652. secondsOfDay -= TimeConstants$1.SECONDS_PER_DAY * extraDays;
  8653. if (secondsOfDay < 0) {
  8654. wholeDays--;
  8655. secondsOfDay += TimeConstants$1.SECONDS_PER_DAY;
  8656. }
  8657. julianDate.dayNumber = wholeDays;
  8658. julianDate.secondsOfDay = secondsOfDay;
  8659. return julianDate;
  8660. }
  8661. function computeJulianDateComponents(
  8662. year,
  8663. month,
  8664. day,
  8665. hour,
  8666. minute,
  8667. second,
  8668. millisecond
  8669. ) {
  8670. // Algorithm from page 604 of the Explanatory Supplement to the
  8671. // Astronomical Almanac (Seidelmann 1992).
  8672. var a = ((month - 14) / 12) | 0;
  8673. var b = year + 4800 + a;
  8674. var dayNumber =
  8675. (((1461 * b) / 4) | 0) +
  8676. (((367 * (month - 2 - 12 * a)) / 12) | 0) -
  8677. (((3 * (((b + 100) / 100) | 0)) / 4) | 0) +
  8678. day -
  8679. 32075;
  8680. // JulianDates are noon-based
  8681. hour = hour - 12;
  8682. if (hour < 0) {
  8683. hour += 24;
  8684. }
  8685. var secondsOfDay =
  8686. second +
  8687. (hour * TimeConstants$1.SECONDS_PER_HOUR +
  8688. minute * TimeConstants$1.SECONDS_PER_MINUTE +
  8689. millisecond * TimeConstants$1.SECONDS_PER_MILLISECOND);
  8690. if (secondsOfDay >= 43200.0) {
  8691. dayNumber -= 1;
  8692. }
  8693. return [dayNumber, secondsOfDay];
  8694. }
  8695. //Regular expressions used for ISO8601 date parsing.
  8696. //YYYY
  8697. var matchCalendarYear = /^(\d{4})$/;
  8698. //YYYY-MM (YYYYMM is invalid)
  8699. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  8700. //YYYY-DDD or YYYYDDD
  8701. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  8702. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  8703. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  8704. //YYYY-MM-DD or YYYYMMDD
  8705. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  8706. // Match utc offset
  8707. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  8708. // Match hours HH or HH.xxxxx
  8709. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  8710. // Match hours/minutes HH:MM HHMM.xxxxx
  8711. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  8712. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  8713. var matchHoursMinutesSeconds =
  8714. /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  8715. var iso8601ErrorMessage = "Invalid ISO 8601 date.";
  8716. /**
  8717. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  8718. * For increased precision, this class stores the whole number part of the date and the seconds
  8719. * part of the date in separate components. In order to be safe for arithmetic and represent
  8720. * leap seconds, the date is always stored in the International Atomic Time standard
  8721. * {@link TimeStandard.TAI}.
  8722. * @alias JulianDate
  8723. * @constructor
  8724. *
  8725. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  8726. * @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.
  8727. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  8728. */
  8729. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  8730. /**
  8731. * Gets or sets the number of whole days.
  8732. * @type {Number}
  8733. */
  8734. this.dayNumber = undefined;
  8735. /**
  8736. * Gets or sets the number of seconds into the current day.
  8737. * @type {Number}
  8738. */
  8739. this.secondsOfDay = undefined;
  8740. julianDayNumber = when.defaultValue(julianDayNumber, 0.0);
  8741. secondsOfDay = when.defaultValue(secondsOfDay, 0.0);
  8742. timeStandard = when.defaultValue(timeStandard, TimeStandard$1.UTC);
  8743. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  8744. var wholeDays = julianDayNumber | 0;
  8745. secondsOfDay =
  8746. secondsOfDay +
  8747. (julianDayNumber - wholeDays) * TimeConstants$1.SECONDS_PER_DAY;
  8748. setComponents(wholeDays, secondsOfDay, this);
  8749. if (timeStandard === TimeStandard$1.UTC) {
  8750. convertUtcToTai(this);
  8751. }
  8752. }
  8753. /**
  8754. * Creates a new instance from a GregorianDate.
  8755. *
  8756. * @param {GregorianDate} date A GregorianDate.
  8757. * @param {JulianDate} [result] An existing instance to use for the result.
  8758. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8759. *
  8760. * @exception {DeveloperError} date must be a valid GregorianDate.
  8761. */
  8762. JulianDate.fromGregorianDate = function (date, result) {
  8763. //>>includeStart('debug', pragmas.debug);
  8764. if (!(date instanceof GregorianDate)) {
  8765. throw new Check.DeveloperError("date must be a valid GregorianDate.");
  8766. }
  8767. //>>includeEnd('debug');
  8768. var components = computeJulianDateComponents(
  8769. date.year,
  8770. date.month,
  8771. date.day,
  8772. date.hour,
  8773. date.minute,
  8774. date.second,
  8775. date.millisecond
  8776. );
  8777. if (!when.defined(result)) {
  8778. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  8779. }
  8780. setComponents(components[0], components[1], result);
  8781. convertUtcToTai(result);
  8782. return result;
  8783. };
  8784. /**
  8785. * Creates a new instance from a JavaScript Date.
  8786. *
  8787. * @param {Date} date A JavaScript Date.
  8788. * @param {JulianDate} [result] An existing instance to use for the result.
  8789. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8790. *
  8791. * @exception {DeveloperError} date must be a valid JavaScript Date.
  8792. */
  8793. JulianDate.fromDate = function (date, result) {
  8794. //>>includeStart('debug', pragmas.debug);
  8795. if (!(date instanceof Date) || isNaN(date.getTime())) {
  8796. throw new Check.DeveloperError("date must be a valid JavaScript Date.");
  8797. }
  8798. //>>includeEnd('debug');
  8799. var components = computeJulianDateComponents(
  8800. date.getUTCFullYear(),
  8801. date.getUTCMonth() + 1,
  8802. date.getUTCDate(),
  8803. date.getUTCHours(),
  8804. date.getUTCMinutes(),
  8805. date.getUTCSeconds(),
  8806. date.getUTCMilliseconds()
  8807. );
  8808. if (!when.defined(result)) {
  8809. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  8810. }
  8811. setComponents(components[0], components[1], result);
  8812. convertUtcToTai(result);
  8813. return result;
  8814. };
  8815. /**
  8816. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  8817. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  8818. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  8819. *
  8820. * @param {String} iso8601String An ISO 8601 date.
  8821. * @param {JulianDate} [result] An existing instance to use for the result.
  8822. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8823. *
  8824. * @exception {DeveloperError} Invalid ISO 8601 date.
  8825. */
  8826. JulianDate.fromIso8601 = function (iso8601String, result) {
  8827. //>>includeStart('debug', pragmas.debug);
  8828. if (typeof iso8601String !== "string") {
  8829. throw new Check.DeveloperError(iso8601ErrorMessage);
  8830. }
  8831. //>>includeEnd('debug');
  8832. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  8833. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  8834. iso8601String = iso8601String.replace(",", ".");
  8835. //Split the string into its date and time components, denoted by a mandatory T
  8836. var tokens = iso8601String.split("T");
  8837. var year;
  8838. var month = 1;
  8839. var day = 1;
  8840. var hour = 0;
  8841. var minute = 0;
  8842. var second = 0;
  8843. var millisecond = 0;
  8844. //Lacking a time is okay, but a missing date is illegal.
  8845. var date = tokens[0];
  8846. var time = tokens[1];
  8847. var tmp;
  8848. var inLeapYear;
  8849. //>>includeStart('debug', pragmas.debug);
  8850. if (!when.defined(date)) {
  8851. throw new Check.DeveloperError(iso8601ErrorMessage);
  8852. }
  8853. var dashCount;
  8854. //>>includeEnd('debug');
  8855. //First match the date against possible regular expressions.
  8856. tokens = date.match(matchCalendarDate);
  8857. if (tokens !== null) {
  8858. //>>includeStart('debug', pragmas.debug);
  8859. dashCount = date.split("-").length - 1;
  8860. if (dashCount > 0 && dashCount !== 2) {
  8861. throw new Check.DeveloperError(iso8601ErrorMessage);
  8862. }
  8863. //>>includeEnd('debug');
  8864. year = +tokens[1];
  8865. month = +tokens[2];
  8866. day = +tokens[3];
  8867. } else {
  8868. tokens = date.match(matchCalendarMonth);
  8869. if (tokens !== null) {
  8870. year = +tokens[1];
  8871. month = +tokens[2];
  8872. } else {
  8873. tokens = date.match(matchCalendarYear);
  8874. if (tokens !== null) {
  8875. year = +tokens[1];
  8876. } else {
  8877. //Not a year/month/day so it must be an ordinal date.
  8878. var dayOfYear;
  8879. tokens = date.match(matchOrdinalDate);
  8880. if (tokens !== null) {
  8881. year = +tokens[1];
  8882. dayOfYear = +tokens[2];
  8883. inLeapYear = isLeapYear(year);
  8884. //This validation is only applicable for this format.
  8885. //>>includeStart('debug', pragmas.debug);
  8886. if (
  8887. dayOfYear < 1 ||
  8888. (inLeapYear && dayOfYear > 366) ||
  8889. (!inLeapYear && dayOfYear > 365)
  8890. ) {
  8891. throw new Check.DeveloperError(iso8601ErrorMessage);
  8892. }
  8893. //>>includeEnd('debug')
  8894. } else {
  8895. tokens = date.match(matchWeekDate);
  8896. if (tokens !== null) {
  8897. //ISO week date to ordinal date from
  8898. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  8899. year = +tokens[1];
  8900. var weekNumber = +tokens[2];
  8901. var dayOfWeek = +tokens[3] || 0;
  8902. //>>includeStart('debug', pragmas.debug);
  8903. dashCount = date.split("-").length - 1;
  8904. if (
  8905. dashCount > 0 &&
  8906. ((!when.defined(tokens[3]) && dashCount !== 1) ||
  8907. (when.defined(tokens[3]) && dashCount !== 2))
  8908. ) {
  8909. throw new Check.DeveloperError(iso8601ErrorMessage);
  8910. }
  8911. //>>includeEnd('debug')
  8912. var january4 = new Date(Date.UTC(year, 0, 4));
  8913. dayOfYear = weekNumber * 7 + dayOfWeek - january4.getUTCDay() - 3;
  8914. } else {
  8915. //None of our regular expressions succeeded in parsing the date properly.
  8916. //>>includeStart('debug', pragmas.debug);
  8917. throw new Check.DeveloperError(iso8601ErrorMessage);
  8918. //>>includeEnd('debug')
  8919. }
  8920. }
  8921. //Split an ordinal date into month/day.
  8922. tmp = new Date(Date.UTC(year, 0, 1));
  8923. tmp.setUTCDate(dayOfYear);
  8924. month = tmp.getUTCMonth() + 1;
  8925. day = tmp.getUTCDate();
  8926. }
  8927. }
  8928. }
  8929. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  8930. inLeapYear = isLeapYear(year);
  8931. //>>includeStart('debug', pragmas.debug);
  8932. if (
  8933. month < 1 ||
  8934. month > 12 ||
  8935. day < 1 ||
  8936. ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) ||
  8937. (inLeapYear && month === 2 && day > daysInLeapFeburary)
  8938. ) {
  8939. throw new Check.DeveloperError(iso8601ErrorMessage);
  8940. }
  8941. //>>includeEnd('debug')
  8942. //Now move onto the time string, which is much simpler.
  8943. //If no time is specified, it is considered the beginning of the day, UTC to match Javascript's implementation.
  8944. var offsetIndex;
  8945. if (when.defined(time)) {
  8946. tokens = time.match(matchHoursMinutesSeconds);
  8947. if (tokens !== null) {
  8948. //>>includeStart('debug', pragmas.debug);
  8949. dashCount = time.split(":").length - 1;
  8950. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  8951. throw new Check.DeveloperError(iso8601ErrorMessage);
  8952. }
  8953. //>>includeEnd('debug')
  8954. hour = +tokens[1];
  8955. minute = +tokens[2];
  8956. second = +tokens[3];
  8957. millisecond = +(tokens[4] || 0) * 1000.0;
  8958. offsetIndex = 5;
  8959. } else {
  8960. tokens = time.match(matchHoursMinutes);
  8961. if (tokens !== null) {
  8962. //>>includeStart('debug', pragmas.debug);
  8963. dashCount = time.split(":").length - 1;
  8964. if (dashCount > 2) {
  8965. throw new Check.DeveloperError(iso8601ErrorMessage);
  8966. }
  8967. //>>includeEnd('debug')
  8968. hour = +tokens[1];
  8969. minute = +tokens[2];
  8970. second = +(tokens[3] || 0) * 60.0;
  8971. offsetIndex = 4;
  8972. } else {
  8973. tokens = time.match(matchHours);
  8974. if (tokens !== null) {
  8975. hour = +tokens[1];
  8976. minute = +(tokens[2] || 0) * 60.0;
  8977. offsetIndex = 3;
  8978. } else {
  8979. //>>includeStart('debug', pragmas.debug);
  8980. throw new Check.DeveloperError(iso8601ErrorMessage);
  8981. //>>includeEnd('debug')
  8982. }
  8983. }
  8984. }
  8985. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  8986. //>>includeStart('debug', pragmas.debug);
  8987. if (
  8988. minute >= 60 ||
  8989. second >= 61 ||
  8990. hour > 24 ||
  8991. (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))
  8992. ) {
  8993. throw new Check.DeveloperError(iso8601ErrorMessage);
  8994. }
  8995. //>>includeEnd('debug');
  8996. //Check the UTC offset value, if no value exists, use local time
  8997. //a Z indicates UTC, + or - are offsets.
  8998. var offset = tokens[offsetIndex];
  8999. var offsetHours = +tokens[offsetIndex + 1];
  9000. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  9001. switch (offset) {
  9002. case "+":
  9003. hour = hour - offsetHours;
  9004. minute = minute - offsetMinutes;
  9005. break;
  9006. case "-":
  9007. hour = hour + offsetHours;
  9008. minute = minute + offsetMinutes;
  9009. break;
  9010. case "Z":
  9011. break;
  9012. default:
  9013. minute =
  9014. minute +
  9015. new Date(
  9016. Date.UTC(year, month - 1, day, hour, minute)
  9017. ).getTimezoneOffset();
  9018. break;
  9019. }
  9020. }
  9021. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  9022. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  9023. //Then we add it back in after converting to TAI.
  9024. var isLeapSecond = second === 60;
  9025. if (isLeapSecond) {
  9026. second--;
  9027. }
  9028. //Even if we successfully parsed the string into its components, after applying UTC offset or
  9029. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  9030. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  9031. while (minute >= 60) {
  9032. minute -= 60;
  9033. hour++;
  9034. }
  9035. while (hour >= 24) {
  9036. hour -= 24;
  9037. day++;
  9038. }
  9039. tmp = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  9040. while (day > tmp) {
  9041. day -= tmp;
  9042. month++;
  9043. if (month > 12) {
  9044. month -= 12;
  9045. year++;
  9046. }
  9047. tmp =
  9048. inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  9049. }
  9050. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  9051. while (minute < 0) {
  9052. minute += 60;
  9053. hour--;
  9054. }
  9055. while (hour < 0) {
  9056. hour += 24;
  9057. day--;
  9058. }
  9059. while (day < 1) {
  9060. month--;
  9061. if (month < 1) {
  9062. month += 12;
  9063. year--;
  9064. }
  9065. tmp =
  9066. inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
  9067. day += tmp;
  9068. }
  9069. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  9070. var components = computeJulianDateComponents(
  9071. year,
  9072. month,
  9073. day,
  9074. hour,
  9075. minute,
  9076. second,
  9077. millisecond
  9078. );
  9079. if (!when.defined(result)) {
  9080. result = new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  9081. } else {
  9082. setComponents(components[0], components[1], result);
  9083. convertUtcToTai(result);
  9084. }
  9085. //If we were on a leap second, add it back.
  9086. if (isLeapSecond) {
  9087. JulianDate.addSeconds(result, 1, result);
  9088. }
  9089. return result;
  9090. };
  9091. /**
  9092. * Creates a new instance that represents the current system time.
  9093. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  9094. *
  9095. * @param {JulianDate} [result] An existing instance to use for the result.
  9096. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  9097. */
  9098. JulianDate.now = function (result) {
  9099. return JulianDate.fromDate(new Date(), result);
  9100. };
  9101. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard$1.TAI);
  9102. /**
  9103. * Creates a {@link GregorianDate} from the provided instance.
  9104. *
  9105. * @param {JulianDate} julianDate The date to be converted.
  9106. * @param {GregorianDate} [result] An existing instance to use for the result.
  9107. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  9108. */
  9109. JulianDate.toGregorianDate = function (julianDate, result) {
  9110. //>>includeStart('debug', pragmas.debug);
  9111. if (!when.defined(julianDate)) {
  9112. throw new Check.DeveloperError("julianDate is required.");
  9113. }
  9114. //>>includeEnd('debug');
  9115. var isLeapSecond = false;
  9116. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  9117. if (!when.defined(thisUtc)) {
  9118. //Conversion to UTC will fail if we are during a leap second.
  9119. //If that's the case, subtract a second and convert again.
  9120. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  9121. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  9122. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  9123. isLeapSecond = true;
  9124. }
  9125. var julianDayNumber = thisUtc.dayNumber;
  9126. var secondsOfDay = thisUtc.secondsOfDay;
  9127. if (secondsOfDay >= 43200.0) {
  9128. julianDayNumber += 1;
  9129. }
  9130. // Algorithm from page 604 of the Explanatory Supplement to the
  9131. // Astronomical Almanac (Seidelmann 1992).
  9132. var L = (julianDayNumber + 68569) | 0;
  9133. var N = ((4 * L) / 146097) | 0;
  9134. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  9135. var I = ((4000 * (L + 1)) / 1461001) | 0;
  9136. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  9137. var J = ((80 * L) / 2447) | 0;
  9138. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  9139. L = (J / 11) | 0;
  9140. var month = (J + 2 - 12 * L) | 0;
  9141. var year = (100 * (N - 49) + I + L) | 0;
  9142. var hour = (secondsOfDay / TimeConstants$1.SECONDS_PER_HOUR) | 0;
  9143. var remainingSeconds = secondsOfDay - hour * TimeConstants$1.SECONDS_PER_HOUR;
  9144. var minute = (remainingSeconds / TimeConstants$1.SECONDS_PER_MINUTE) | 0;
  9145. remainingSeconds =
  9146. remainingSeconds - minute * TimeConstants$1.SECONDS_PER_MINUTE;
  9147. var second = remainingSeconds | 0;
  9148. var millisecond =
  9149. (remainingSeconds - second) / TimeConstants$1.SECONDS_PER_MILLISECOND;
  9150. // JulianDates are noon-based
  9151. hour += 12;
  9152. if (hour > 23) {
  9153. hour -= 24;
  9154. }
  9155. //If we were on a leap second, add it back.
  9156. if (isLeapSecond) {
  9157. second += 1;
  9158. }
  9159. if (!when.defined(result)) {
  9160. return new GregorianDate(
  9161. year,
  9162. month,
  9163. day,
  9164. hour,
  9165. minute,
  9166. second,
  9167. millisecond,
  9168. isLeapSecond
  9169. );
  9170. }
  9171. result.year = year;
  9172. result.month = month;
  9173. result.day = day;
  9174. result.hour = hour;
  9175. result.minute = minute;
  9176. result.second = second;
  9177. result.millisecond = millisecond;
  9178. result.isLeapSecond = isLeapSecond;
  9179. return result;
  9180. };
  9181. /**
  9182. * Creates a JavaScript Date from the provided instance.
  9183. * Since JavaScript dates are only accurate to the nearest millisecond and
  9184. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  9185. * If the provided JulianDate is during a leap second, the previous second is used.
  9186. *
  9187. * @param {JulianDate} julianDate The date to be converted.
  9188. * @returns {Date} A new instance representing the provided date.
  9189. */
  9190. JulianDate.toDate = function (julianDate) {
  9191. //>>includeStart('debug', pragmas.debug);
  9192. if (!when.defined(julianDate)) {
  9193. throw new Check.DeveloperError("julianDate is required.");
  9194. }
  9195. //>>includeEnd('debug');
  9196. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  9197. var second = gDate.second;
  9198. if (gDate.isLeapSecond) {
  9199. second -= 1;
  9200. }
  9201. return new Date(
  9202. Date.UTC(
  9203. gDate.year,
  9204. gDate.month - 1,
  9205. gDate.day,
  9206. gDate.hour,
  9207. gDate.minute,
  9208. second,
  9209. gDate.millisecond
  9210. )
  9211. );
  9212. };
  9213. /**
  9214. * Creates an ISO8601 representation of the provided date.
  9215. *
  9216. * @param {JulianDate} julianDate The date to be converted.
  9217. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  9218. * @returns {String} The ISO8601 representation of the provided date.
  9219. */
  9220. JulianDate.toIso8601 = function (julianDate, precision) {
  9221. //>>includeStart('debug', pragmas.debug);
  9222. if (!when.defined(julianDate)) {
  9223. throw new Check.DeveloperError("julianDate is required.");
  9224. }
  9225. //>>includeEnd('debug');
  9226. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  9227. var year = gDate.year;
  9228. var month = gDate.month;
  9229. var day = gDate.day;
  9230. var hour = gDate.hour;
  9231. var minute = gDate.minute;
  9232. var second = gDate.second;
  9233. var millisecond = gDate.millisecond;
  9234. // special case - Iso8601.MAXIMUM_VALUE produces a string which we can't parse unless we adjust.
  9235. // 10000-01-01T00:00:00 is the same instant as 9999-12-31T24:00:00
  9236. if (
  9237. year === 10000 &&
  9238. month === 1 &&
  9239. day === 1 &&
  9240. hour === 0 &&
  9241. minute === 0 &&
  9242. second === 0 &&
  9243. millisecond === 0
  9244. ) {
  9245. year = 9999;
  9246. month = 12;
  9247. day = 31;
  9248. hour = 24;
  9249. }
  9250. var millisecondStr;
  9251. if (!when.defined(precision) && millisecond !== 0) {
  9252. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  9253. millisecondStr = (millisecond * 0.01).toString().replace(".", "");
  9254. return sprintf(
  9255. "%04d-%02d-%02dT%02d:%02d:%02d.%sZ",
  9256. year,
  9257. month,
  9258. day,
  9259. hour,
  9260. minute,
  9261. second,
  9262. millisecondStr
  9263. );
  9264. }
  9265. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  9266. if (!when.defined(precision) || precision === 0) {
  9267. return sprintf(
  9268. "%04d-%02d-%02dT%02d:%02d:%02dZ",
  9269. year,
  9270. month,
  9271. day,
  9272. hour,
  9273. minute,
  9274. second
  9275. );
  9276. }
  9277. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  9278. millisecondStr = (millisecond * 0.01)
  9279. .toFixed(precision)
  9280. .replace(".", "")
  9281. .slice(0, precision);
  9282. return sprintf(
  9283. "%04d-%02d-%02dT%02d:%02d:%02d.%sZ",
  9284. year,
  9285. month,
  9286. day,
  9287. hour,
  9288. minute,
  9289. second,
  9290. millisecondStr
  9291. );
  9292. };
  9293. /**
  9294. * Duplicates a JulianDate instance.
  9295. *
  9296. * @param {JulianDate} julianDate The date to duplicate.
  9297. * @param {JulianDate} [result] An existing instance to use for the result.
  9298. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  9299. */
  9300. JulianDate.clone = function (julianDate, result) {
  9301. if (!when.defined(julianDate)) {
  9302. return undefined;
  9303. }
  9304. if (!when.defined(result)) {
  9305. return new JulianDate(
  9306. julianDate.dayNumber,
  9307. julianDate.secondsOfDay,
  9308. TimeStandard$1.TAI
  9309. );
  9310. }
  9311. result.dayNumber = julianDate.dayNumber;
  9312. result.secondsOfDay = julianDate.secondsOfDay;
  9313. return result;
  9314. };
  9315. /**
  9316. * Compares two instances.
  9317. *
  9318. * @param {JulianDate} left The first instance.
  9319. * @param {JulianDate} right The second instance.
  9320. * @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.
  9321. */
  9322. JulianDate.compare = function (left, right) {
  9323. //>>includeStart('debug', pragmas.debug);
  9324. if (!when.defined(left)) {
  9325. throw new Check.DeveloperError("left is required.");
  9326. }
  9327. if (!when.defined(right)) {
  9328. throw new Check.DeveloperError("right is required.");
  9329. }
  9330. //>>includeEnd('debug');
  9331. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  9332. if (julianDayNumberDifference !== 0) {
  9333. return julianDayNumberDifference;
  9334. }
  9335. return left.secondsOfDay - right.secondsOfDay;
  9336. };
  9337. /**
  9338. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  9339. *
  9340. * @param {JulianDate} [left] The first instance.
  9341. * @param {JulianDate} [right] The second instance.
  9342. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  9343. */
  9344. JulianDate.equals = function (left, right) {
  9345. return (
  9346. left === right ||
  9347. (when.defined(left) &&
  9348. when.defined(right) &&
  9349. left.dayNumber === right.dayNumber &&
  9350. left.secondsOfDay === right.secondsOfDay)
  9351. );
  9352. };
  9353. /**
  9354. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  9355. * each other. That is, in order for the dates to be considered equal (and for
  9356. * this function to return <code>true</code>), the absolute value of the difference between them, in
  9357. * seconds, must be less than <code>epsilon</code>.
  9358. *
  9359. * @param {JulianDate} [left] The first instance.
  9360. * @param {JulianDate} [right] The second instance.
  9361. * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
  9362. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  9363. */
  9364. JulianDate.equalsEpsilon = function (left, right, epsilon) {
  9365. epsilon = when.defaultValue(epsilon, 0);
  9366. return (
  9367. left === right ||
  9368. (when.defined(left) &&
  9369. when.defined(right) &&
  9370. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon)
  9371. );
  9372. };
  9373. /**
  9374. * Computes the total number of whole and fractional days represented by the provided instance.
  9375. *
  9376. * @param {JulianDate} julianDate The date.
  9377. * @returns {Number} The Julian date as single floating point number.
  9378. */
  9379. JulianDate.totalDays = function (julianDate) {
  9380. //>>includeStart('debug', pragmas.debug);
  9381. if (!when.defined(julianDate)) {
  9382. throw new Check.DeveloperError("julianDate is required.");
  9383. }
  9384. //>>includeEnd('debug');
  9385. return (
  9386. julianDate.dayNumber +
  9387. julianDate.secondsOfDay / TimeConstants$1.SECONDS_PER_DAY
  9388. );
  9389. };
  9390. /**
  9391. * Computes the difference in seconds between the provided instance.
  9392. *
  9393. * @param {JulianDate} left The first instance.
  9394. * @param {JulianDate} right The second instance.
  9395. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  9396. */
  9397. JulianDate.secondsDifference = function (left, right) {
  9398. //>>includeStart('debug', pragmas.debug);
  9399. if (!when.defined(left)) {
  9400. throw new Check.DeveloperError("left is required.");
  9401. }
  9402. if (!when.defined(right)) {
  9403. throw new Check.DeveloperError("right is required.");
  9404. }
  9405. //>>includeEnd('debug');
  9406. var dayDifference =
  9407. (left.dayNumber - right.dayNumber) * TimeConstants$1.SECONDS_PER_DAY;
  9408. return dayDifference + (left.secondsOfDay - right.secondsOfDay);
  9409. };
  9410. /**
  9411. * Computes the difference in days between the provided instance.
  9412. *
  9413. * @param {JulianDate} left The first instance.
  9414. * @param {JulianDate} right The second instance.
  9415. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  9416. */
  9417. JulianDate.daysDifference = function (left, right) {
  9418. //>>includeStart('debug', pragmas.debug);
  9419. if (!when.defined(left)) {
  9420. throw new Check.DeveloperError("left is required.");
  9421. }
  9422. if (!when.defined(right)) {
  9423. throw new Check.DeveloperError("right is required.");
  9424. }
  9425. //>>includeEnd('debug');
  9426. var dayDifference = left.dayNumber - right.dayNumber;
  9427. var secondDifference =
  9428. (left.secondsOfDay - right.secondsOfDay) / TimeConstants$1.SECONDS_PER_DAY;
  9429. return dayDifference + secondDifference;
  9430. };
  9431. /**
  9432. * Computes the number of seconds the provided instance is ahead of UTC.
  9433. *
  9434. * @param {JulianDate} julianDate The date.
  9435. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  9436. */
  9437. JulianDate.computeTaiMinusUtc = function (julianDate) {
  9438. binarySearchScratchLeapSecond.julianDate = julianDate;
  9439. var leapSeconds = JulianDate.leapSeconds;
  9440. var index = binarySearch(
  9441. leapSeconds,
  9442. binarySearchScratchLeapSecond,
  9443. compareLeapSecondDates
  9444. );
  9445. if (index < 0) {
  9446. index = ~index;
  9447. --index;
  9448. if (index < 0) {
  9449. index = 0;
  9450. }
  9451. }
  9452. return leapSeconds[index].offset;
  9453. };
  9454. /**
  9455. * Adds the provided number of seconds to the provided date instance.
  9456. *
  9457. * @param {JulianDate} julianDate The date.
  9458. * @param {Number} seconds The number of seconds to add or subtract.
  9459. * @param {JulianDate} result An existing instance to use for the result.
  9460. * @returns {JulianDate} The modified result parameter.
  9461. */
  9462. JulianDate.addSeconds = function (julianDate, seconds, result) {
  9463. //>>includeStart('debug', pragmas.debug);
  9464. if (!when.defined(julianDate)) {
  9465. throw new Check.DeveloperError("julianDate is required.");
  9466. }
  9467. if (!when.defined(seconds)) {
  9468. throw new Check.DeveloperError("seconds is required.");
  9469. }
  9470. if (!when.defined(result)) {
  9471. throw new Check.DeveloperError("result is required.");
  9472. }
  9473. //>>includeEnd('debug');
  9474. return setComponents(
  9475. julianDate.dayNumber,
  9476. julianDate.secondsOfDay + seconds,
  9477. result
  9478. );
  9479. };
  9480. /**
  9481. * Adds the provided number of minutes to the provided date instance.
  9482. *
  9483. * @param {JulianDate} julianDate The date.
  9484. * @param {Number} minutes The number of minutes to add or subtract.
  9485. * @param {JulianDate} result An existing instance to use for the result.
  9486. * @returns {JulianDate} The modified result parameter.
  9487. */
  9488. JulianDate.addMinutes = function (julianDate, minutes, result) {
  9489. //>>includeStart('debug', pragmas.debug);
  9490. if (!when.defined(julianDate)) {
  9491. throw new Check.DeveloperError("julianDate is required.");
  9492. }
  9493. if (!when.defined(minutes)) {
  9494. throw new Check.DeveloperError("minutes is required.");
  9495. }
  9496. if (!when.defined(result)) {
  9497. throw new Check.DeveloperError("result is required.");
  9498. }
  9499. //>>includeEnd('debug');
  9500. var newSecondsOfDay =
  9501. julianDate.secondsOfDay + minutes * TimeConstants$1.SECONDS_PER_MINUTE;
  9502. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  9503. };
  9504. /**
  9505. * Adds the provided number of hours to the provided date instance.
  9506. *
  9507. * @param {JulianDate} julianDate The date.
  9508. * @param {Number} hours The number of hours to add or subtract.
  9509. * @param {JulianDate} result An existing instance to use for the result.
  9510. * @returns {JulianDate} The modified result parameter.
  9511. */
  9512. JulianDate.addHours = function (julianDate, hours, result) {
  9513. //>>includeStart('debug', pragmas.debug);
  9514. if (!when.defined(julianDate)) {
  9515. throw new Check.DeveloperError("julianDate is required.");
  9516. }
  9517. if (!when.defined(hours)) {
  9518. throw new Check.DeveloperError("hours is required.");
  9519. }
  9520. if (!when.defined(result)) {
  9521. throw new Check.DeveloperError("result is required.");
  9522. }
  9523. //>>includeEnd('debug');
  9524. var newSecondsOfDay =
  9525. julianDate.secondsOfDay + hours * TimeConstants$1.SECONDS_PER_HOUR;
  9526. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  9527. };
  9528. /**
  9529. * Adds the provided number of days to the provided date instance.
  9530. *
  9531. * @param {JulianDate} julianDate The date.
  9532. * @param {Number} days The number of days to add or subtract.
  9533. * @param {JulianDate} result An existing instance to use for the result.
  9534. * @returns {JulianDate} The modified result parameter.
  9535. */
  9536. JulianDate.addDays = function (julianDate, days, result) {
  9537. //>>includeStart('debug', pragmas.debug);
  9538. if (!when.defined(julianDate)) {
  9539. throw new Check.DeveloperError("julianDate is required.");
  9540. }
  9541. if (!when.defined(days)) {
  9542. throw new Check.DeveloperError("days is required.");
  9543. }
  9544. if (!when.defined(result)) {
  9545. throw new Check.DeveloperError("result is required.");
  9546. }
  9547. //>>includeEnd('debug');
  9548. var newJulianDayNumber = julianDate.dayNumber + days;
  9549. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  9550. };
  9551. /**
  9552. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  9553. *
  9554. * @param {JulianDate} left The first instance.
  9555. * @param {JulianDate} right The second instance.
  9556. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  9557. */
  9558. JulianDate.lessThan = function (left, right) {
  9559. return JulianDate.compare(left, right) < 0;
  9560. };
  9561. /**
  9562. * 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.
  9563. *
  9564. * @param {JulianDate} left The first instance.
  9565. * @param {JulianDate} right The second instance.
  9566. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  9567. */
  9568. JulianDate.lessThanOrEquals = function (left, right) {
  9569. return JulianDate.compare(left, right) <= 0;
  9570. };
  9571. /**
  9572. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  9573. *
  9574. * @param {JulianDate} left The first instance.
  9575. * @param {JulianDate} right The second instance.
  9576. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  9577. */
  9578. JulianDate.greaterThan = function (left, right) {
  9579. return JulianDate.compare(left, right) > 0;
  9580. };
  9581. /**
  9582. * 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.
  9583. *
  9584. * @param {JulianDate} left The first instance.
  9585. * @param {JulianDate} right The second instance.
  9586. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  9587. */
  9588. JulianDate.greaterThanOrEquals = function (left, right) {
  9589. return JulianDate.compare(left, right) >= 0;
  9590. };
  9591. /**
  9592. * Duplicates this instance.
  9593. *
  9594. * @param {JulianDate} [result] An existing instance to use for the result.
  9595. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  9596. */
  9597. JulianDate.prototype.clone = function (result) {
  9598. return JulianDate.clone(this, result);
  9599. };
  9600. /**
  9601. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  9602. *
  9603. * @param {JulianDate} [right] The second instance.
  9604. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  9605. */
  9606. JulianDate.prototype.equals = function (right) {
  9607. return JulianDate.equals(this, right);
  9608. };
  9609. /**
  9610. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  9611. * each other. That is, in order for the dates to be considered equal (and for
  9612. * this function to return <code>true</code>), the absolute value of the difference between them, in
  9613. * seconds, must be less than <code>epsilon</code>.
  9614. *
  9615. * @param {JulianDate} [right] The second instance.
  9616. * @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
  9617. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  9618. */
  9619. JulianDate.prototype.equalsEpsilon = function (right, epsilon) {
  9620. return JulianDate.equalsEpsilon(this, right, epsilon);
  9621. };
  9622. /**
  9623. * Creates a string representing this date in ISO8601 format.
  9624. *
  9625. * @returns {String} A string representing this date in ISO8601 format.
  9626. */
  9627. JulianDate.prototype.toString = function () {
  9628. return JulianDate.toIso8601(this);
  9629. };
  9630. /**
  9631. * Gets or sets the list of leap seconds used throughout Cesium.
  9632. * @memberof JulianDate
  9633. * @type {LeapSecond[]}
  9634. */
  9635. JulianDate.leapSeconds = [
  9636. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard$1.TAI), 10), // January 1, 1972 00:00:00 UTC
  9637. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard$1.TAI), 11), // July 1, 1972 00:00:00 UTC
  9638. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard$1.TAI), 12), // January 1, 1973 00:00:00 UTC
  9639. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard$1.TAI), 13), // January 1, 1974 00:00:00 UTC
  9640. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard$1.TAI), 14), // January 1, 1975 00:00:00 UTC
  9641. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard$1.TAI), 15), // January 1, 1976 00:00:00 UTC
  9642. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard$1.TAI), 16), // January 1, 1977 00:00:00 UTC
  9643. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard$1.TAI), 17), // January 1, 1978 00:00:00 UTC
  9644. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard$1.TAI), 18), // January 1, 1979 00:00:00 UTC
  9645. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard$1.TAI), 19), // January 1, 1980 00:00:00 UTC
  9646. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard$1.TAI), 20), // July 1, 1981 00:00:00 UTC
  9647. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard$1.TAI), 21), // July 1, 1982 00:00:00 UTC
  9648. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard$1.TAI), 22), // July 1, 1983 00:00:00 UTC
  9649. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard$1.TAI), 23), // July 1, 1985 00:00:00 UTC
  9650. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard$1.TAI), 24), // January 1, 1988 00:00:00 UTC
  9651. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard$1.TAI), 25), // January 1, 1990 00:00:00 UTC
  9652. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard$1.TAI), 26), // January 1, 1991 00:00:00 UTC
  9653. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard$1.TAI), 27), // July 1, 1992 00:00:00 UTC
  9654. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard$1.TAI), 28), // July 1, 1993 00:00:00 UTC
  9655. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard$1.TAI), 29), // July 1, 1994 00:00:00 UTC
  9656. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard$1.TAI), 30), // January 1, 1996 00:00:00 UTC
  9657. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard$1.TAI), 31), // July 1, 1997 00:00:00 UTC
  9658. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard$1.TAI), 32), // January 1, 1999 00:00:00 UTC
  9659. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard$1.TAI), 33), // January 1, 2006 00:00:00 UTC
  9660. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard$1.TAI), 34), // January 1, 2009 00:00:00 UTC
  9661. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard$1.TAI), 35), // July 1, 2012 00:00:00 UTC
  9662. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard$1.TAI), 36), // July 1, 2015 00:00:00 UTC
  9663. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard$1.TAI), 37), // January 1, 2017 00:00:00 UTC
  9664. ];
  9665. /**
  9666. * @license
  9667. *
  9668. * Grauw URI utilities
  9669. *
  9670. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  9671. *
  9672. * @author Laurens Holst (http://www.grauw.nl/)
  9673. *
  9674. * Copyright 2012 Laurens Holst
  9675. *
  9676. * Licensed under the Apache License, Version 2.0 (the "License");
  9677. * you may not use this file except in compliance with the License.
  9678. * You may obtain a copy of the License at
  9679. *
  9680. * http://www.apache.org/licenses/LICENSE-2.0
  9681. *
  9682. * Unless required by applicable law or agreed to in writing, software
  9683. * distributed under the License is distributed on an "AS IS" BASIS,
  9684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9685. * See the License for the specific language governing permissions and
  9686. * limitations under the License.
  9687. *
  9688. */
  9689. /**
  9690. * Constructs a URI object.
  9691. * @constructor
  9692. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  9693. * @param {string|URI} uri A string or URI object to create the object from.
  9694. */
  9695. function URI(uri) {
  9696. if (uri instanceof URI) { // copy constructor
  9697. this.scheme = uri.scheme;
  9698. this.authority = uri.authority;
  9699. this.path = uri.path;
  9700. this.query = uri.query;
  9701. this.fragment = uri.fragment;
  9702. } else if (uri) { // uri is URI string or cast to string
  9703. var c = parseRegex.exec(uri);
  9704. this.scheme = c[1];
  9705. this.authority = c[2];
  9706. this.path = c[3];
  9707. this.query = c[4];
  9708. this.fragment = c[5];
  9709. }
  9710. }
  9711. // Initial values on the prototype
  9712. URI.prototype.scheme = null;
  9713. URI.prototype.authority = null;
  9714. URI.prototype.path = '';
  9715. URI.prototype.query = null;
  9716. URI.prototype.fragment = null;
  9717. // Regular expression from RFC 3986 appendix B
  9718. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  9719. /**
  9720. * Returns the scheme part of the URI.
  9721. * In "http://example.com:80/a/b?x#y" this is "http".
  9722. */
  9723. URI.prototype.getScheme = function() {
  9724. return this.scheme;
  9725. };
  9726. /**
  9727. * Returns the authority part of the URI.
  9728. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  9729. */
  9730. URI.prototype.getAuthority = function() {
  9731. return this.authority;
  9732. };
  9733. /**
  9734. * Returns the path part of the URI.
  9735. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  9736. * In "mailto:mike@example.com" this is "mike@example.com".
  9737. */
  9738. URI.prototype.getPath = function() {
  9739. return this.path;
  9740. };
  9741. /**
  9742. * Returns the query part of the URI.
  9743. * In "http://example.com:80/a/b?x#y" this is "x".
  9744. */
  9745. URI.prototype.getQuery = function() {
  9746. return this.query;
  9747. };
  9748. /**
  9749. * Returns the fragment part of the URI.
  9750. * In "http://example.com:80/a/b?x#y" this is "y".
  9751. */
  9752. URI.prototype.getFragment = function() {
  9753. return this.fragment;
  9754. };
  9755. /**
  9756. * Tests whether the URI is an absolute URI.
  9757. * See RFC 3986 section 4.3.
  9758. */
  9759. URI.prototype.isAbsolute = function() {
  9760. return !!this.scheme && !this.fragment;
  9761. };
  9762. ///**
  9763. //* Extensive validation of the URI against the ABNF in RFC 3986
  9764. //*/
  9765. //URI.prototype.validate
  9766. /**
  9767. * Tests whether the URI is a same-document reference.
  9768. * See RFC 3986 section 4.4.
  9769. *
  9770. * To perform more thorough comparison, you can normalise the URI objects.
  9771. */
  9772. URI.prototype.isSameDocumentAs = function(uri) {
  9773. return uri.scheme == this.scheme &&
  9774. uri.authority == this.authority &&
  9775. uri.path == this.path &&
  9776. uri.query == this.query;
  9777. };
  9778. /**
  9779. * Simple String Comparison of two URIs.
  9780. * See RFC 3986 section 6.2.1.
  9781. *
  9782. * To perform more thorough comparison, you can normalise the URI objects.
  9783. */
  9784. URI.prototype.equals = function(uri) {
  9785. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  9786. };
  9787. /**
  9788. * Normalizes the URI using syntax-based normalization.
  9789. * This includes case normalization, percent-encoding normalization and path segment normalization.
  9790. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  9791. * (Although that would not be a valid URI in the first place. See validate().)
  9792. * See RFC 3986 section 6.2.2.
  9793. */
  9794. URI.prototype.normalize = function() {
  9795. this.removeDotSegments();
  9796. if (this.scheme)
  9797. this.scheme = this.scheme.toLowerCase();
  9798. if (this.authority)
  9799. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  9800. replace(caseRegex, replaceCase);
  9801. if (this.path)
  9802. this.path = this.path.replace(caseRegex, replaceCase);
  9803. if (this.query)
  9804. this.query = this.query.replace(caseRegex, replaceCase);
  9805. if (this.fragment)
  9806. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  9807. };
  9808. var caseRegex = /%[0-9a-z]{2}/gi;
  9809. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  9810. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  9811. function replaceCase(str) {
  9812. var dec = unescape(str);
  9813. return percentRegex.test(dec) ? dec : str.toUpperCase();
  9814. }
  9815. function replaceAuthority(str, p1, p2, p3) {
  9816. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  9817. }
  9818. /**
  9819. * Resolve a relative URI (this) against a base URI.
  9820. * The base URI must be an absolute URI.
  9821. * See RFC 3986 section 5.2
  9822. */
  9823. URI.prototype.resolve = function(baseURI) {
  9824. var uri = new URI();
  9825. if (this.scheme) {
  9826. uri.scheme = this.scheme;
  9827. uri.authority = this.authority;
  9828. uri.path = this.path;
  9829. uri.query = this.query;
  9830. } else {
  9831. uri.scheme = baseURI.scheme;
  9832. if (this.authority) {
  9833. uri.authority = this.authority;
  9834. uri.path = this.path;
  9835. uri.query = this.query;
  9836. } else {
  9837. uri.authority = baseURI.authority;
  9838. if (this.path == '') {
  9839. uri.path = baseURI.path;
  9840. uri.query = this.query || baseURI.query;
  9841. } else {
  9842. if (this.path.charAt(0) == '/') {
  9843. uri.path = this.path;
  9844. uri.removeDotSegments();
  9845. } else {
  9846. if (baseURI.authority && baseURI.path == '') {
  9847. uri.path = '/' + this.path;
  9848. } else {
  9849. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  9850. }
  9851. uri.removeDotSegments();
  9852. }
  9853. uri.query = this.query;
  9854. }
  9855. }
  9856. }
  9857. uri.fragment = this.fragment;
  9858. return uri;
  9859. };
  9860. /**
  9861. * Remove dot segments from path.
  9862. * See RFC 3986 section 5.2.4
  9863. * @private
  9864. */
  9865. URI.prototype.removeDotSegments = function() {
  9866. var input = this.path.split('/'),
  9867. output = [],
  9868. segment,
  9869. absPath = input[0] == '';
  9870. if (absPath)
  9871. input.shift();
  9872. var sFirst = input[0] == '' ? input.shift() : null;
  9873. while (input.length) {
  9874. segment = input.shift();
  9875. if (segment == '..') {
  9876. output.pop();
  9877. } else if (segment != '.') {
  9878. output.push(segment);
  9879. }
  9880. }
  9881. if (segment == '.' || segment == '..')
  9882. output.push('');
  9883. if (absPath)
  9884. output.unshift('');
  9885. this.path = output.join('/');
  9886. };
  9887. // We don't like this function because it builds up a cache that is never cleared.
  9888. // /**
  9889. // * Resolves a relative URI against an absolute base URI.
  9890. // * Convenience method.
  9891. // * @param {String} uri the relative URI to resolve
  9892. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  9893. // */
  9894. // URI.resolve = function(sURI, sBaseURI) {
  9895. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  9896. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  9897. // return uri.resolve(baseURI).toString();
  9898. // };
  9899. // var cache = {};
  9900. /**
  9901. * Serialises the URI to a string.
  9902. */
  9903. URI.prototype.toString = function() {
  9904. var result = '';
  9905. if (this.scheme)
  9906. result += this.scheme + ':';
  9907. if (this.authority)
  9908. result += '//' + this.authority;
  9909. result += this.path;
  9910. if (this.query)
  9911. result += '?' + this.query;
  9912. if (this.fragment)
  9913. result += '#' + this.fragment;
  9914. return result;
  9915. };
  9916. /**
  9917. * @private
  9918. */
  9919. function appendForwardSlash(url) {
  9920. if (url.length === 0 || url[url.length - 1] !== "/") {
  9921. url = url + "/";
  9922. }
  9923. return url;
  9924. }
  9925. /**
  9926. * Clones an object, returning a new object containing the same properties.
  9927. *
  9928. * @function
  9929. *
  9930. * @param {Object} object The object to clone.
  9931. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  9932. * @returns {Object} The cloned object.
  9933. */
  9934. function clone(object, deep) {
  9935. if (object === null || typeof object !== "object") {
  9936. return object;
  9937. }
  9938. deep = when.defaultValue(deep, false);
  9939. var result = new object.constructor();
  9940. for (var propertyName in object) {
  9941. if (object.hasOwnProperty(propertyName)) {
  9942. var value = object[propertyName];
  9943. if (deep) {
  9944. value = clone(value, deep);
  9945. }
  9946. result[propertyName] = value;
  9947. }
  9948. }
  9949. return result;
  9950. }
  9951. /**
  9952. * Merges two objects, copying their properties onto a new combined object. When two objects have the same
  9953. * property, the value of the property on the first object is used. If either object is undefined,
  9954. * it will be treated as an empty object.
  9955. *
  9956. * @example
  9957. * var object1 = {
  9958. * propOne : 1,
  9959. * propTwo : {
  9960. * value1 : 10
  9961. * }
  9962. * }
  9963. * var object2 = {
  9964. * propTwo : 2
  9965. * }
  9966. * var final = Cesium.combine(object1, object2);
  9967. *
  9968. * // final === {
  9969. * // propOne : 1,
  9970. * // propTwo : {
  9971. * // value1 : 10
  9972. * // }
  9973. * // }
  9974. *
  9975. * @param {Object} [object1] The first object to merge.
  9976. * @param {Object} [object2] The second object to merge.
  9977. * @param {Boolean} [deep=false] Perform a recursive merge.
  9978. * @returns {Object} The combined object containing all properties from both objects.
  9979. *
  9980. * @function
  9981. */
  9982. function combine(object1, object2, deep) {
  9983. deep = when.defaultValue(deep, false);
  9984. var result = {};
  9985. var object1Defined = when.defined(object1);
  9986. var object2Defined = when.defined(object2);
  9987. var property;
  9988. var object1Value;
  9989. var object2Value;
  9990. if (object1Defined) {
  9991. for (property in object1) {
  9992. if (object1.hasOwnProperty(property)) {
  9993. object1Value = object1[property];
  9994. if (
  9995. object2Defined &&
  9996. deep &&
  9997. typeof object1Value === "object" &&
  9998. object2.hasOwnProperty(property)
  9999. ) {
  10000. object2Value = object2[property];
  10001. if (typeof object2Value === "object") {
  10002. result[property] = combine(object1Value, object2Value, deep);
  10003. } else {
  10004. result[property] = object1Value;
  10005. }
  10006. } else {
  10007. result[property] = object1Value;
  10008. }
  10009. }
  10010. }
  10011. }
  10012. if (object2Defined) {
  10013. for (property in object2) {
  10014. if (
  10015. object2.hasOwnProperty(property) &&
  10016. !result.hasOwnProperty(property)
  10017. ) {
  10018. object2Value = object2[property];
  10019. result[property] = object2Value;
  10020. }
  10021. }
  10022. }
  10023. return result;
  10024. }
  10025. /**
  10026. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  10027. * @function
  10028. *
  10029. * @param {String} relative The relative Uri.
  10030. * @param {String} [base] The base Uri.
  10031. * @returns {String} The absolute Uri of the given relative Uri.
  10032. *
  10033. * @example
  10034. * //absolute Uri will be "https://test.com/awesome.png";
  10035. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  10036. */
  10037. function getAbsoluteUri(relative, base) {
  10038. var documentObject;
  10039. if (typeof document !== "undefined") {
  10040. documentObject = document;
  10041. }
  10042. return getAbsoluteUri._implementation(relative, base, documentObject);
  10043. }
  10044. getAbsoluteUri._implementation = function (relative, base, documentObject) {
  10045. //>>includeStart('debug', pragmas.debug);
  10046. if (!when.defined(relative)) {
  10047. throw new Check.DeveloperError("relative uri is required.");
  10048. }
  10049. //>>includeEnd('debug');
  10050. if (!when.defined(base)) {
  10051. if (typeof documentObject === "undefined") {
  10052. return relative;
  10053. }
  10054. base = when.defaultValue(documentObject.baseURI, documentObject.location.href);
  10055. }
  10056. var baseUri = new URI(base);
  10057. var relativeUri = new URI(relative);
  10058. return relativeUri.resolve(baseUri).toString();
  10059. };
  10060. /**
  10061. * Given a URI, returns the base path of the URI.
  10062. * @function
  10063. *
  10064. * @param {String} uri The Uri.
  10065. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  10066. * @returns {String} The base path of the Uri.
  10067. *
  10068. * @example
  10069. * // basePath will be "/Gallery/";
  10070. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
  10071. *
  10072. * // basePath will be "/Gallery/?value=true&example=false";
  10073. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
  10074. */
  10075. function getBaseUri(uri, includeQuery) {
  10076. //>>includeStart('debug', pragmas.debug);
  10077. if (!when.defined(uri)) {
  10078. throw new Check.DeveloperError("uri is required.");
  10079. }
  10080. //>>includeEnd('debug');
  10081. var basePath = "";
  10082. var i = uri.lastIndexOf("/");
  10083. if (i !== -1) {
  10084. basePath = uri.substring(0, i + 1);
  10085. }
  10086. if (!includeQuery) {
  10087. return basePath;
  10088. }
  10089. uri = new URI(uri);
  10090. if (when.defined(uri.query)) {
  10091. basePath += "?" + uri.query;
  10092. }
  10093. if (when.defined(uri.fragment)) {
  10094. basePath += "#" + uri.fragment;
  10095. }
  10096. return basePath;
  10097. }
  10098. /**
  10099. * Given a URI, returns the extension of the URI.
  10100. * @function getExtensionFromUri
  10101. *
  10102. * @param {String} uri The Uri.
  10103. * @returns {String} The extension of the Uri.
  10104. *
  10105. * @example
  10106. * //extension will be "czml";
  10107. * var extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
  10108. */
  10109. function getExtensionFromUri(uri) {
  10110. //>>includeStart('debug', pragmas.debug);
  10111. if (!when.defined(uri)) {
  10112. throw new Check.DeveloperError("uri is required.");
  10113. }
  10114. //>>includeEnd('debug');
  10115. var uriObject = new URI(uri);
  10116. uriObject.normalize();
  10117. var path = uriObject.path;
  10118. var index = path.lastIndexOf("/");
  10119. if (index !== -1) {
  10120. path = path.substr(index + 1);
  10121. }
  10122. index = path.lastIndexOf(".");
  10123. if (index === -1) {
  10124. path = "";
  10125. } else {
  10126. path = path.substr(index + 1);
  10127. }
  10128. return path;
  10129. }
  10130. var blobUriRegex = /^blob:/i;
  10131. /**
  10132. * Determines if the specified uri is a blob uri.
  10133. *
  10134. * @function isBlobUri
  10135. *
  10136. * @param {String} uri The uri to test.
  10137. * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
  10138. *
  10139. * @private
  10140. */
  10141. function isBlobUri(uri) {
  10142. //>>includeStart('debug', pragmas.debug);
  10143. Check.Check.typeOf.string("uri", uri);
  10144. //>>includeEnd('debug');
  10145. return blobUriRegex.test(uri);
  10146. }
  10147. var a;
  10148. /**
  10149. * Given a URL, determine whether that URL is considered cross-origin to the current page.
  10150. *
  10151. * @private
  10152. */
  10153. function isCrossOriginUrl(url) {
  10154. if (!when.defined(a)) {
  10155. a = document.createElement("a");
  10156. }
  10157. // copy window location into the anchor to get consistent results
  10158. // when the port is default for the protocol (e.g. 80 for HTTP)
  10159. a.href = window.location.href;
  10160. // host includes both hostname and port if the port is not standard
  10161. var host = a.host;
  10162. var protocol = a.protocol;
  10163. a.href = url;
  10164. // IE only absolutizes href on get, not set
  10165. // eslint-disable-next-line no-self-assign
  10166. a.href = a.href;
  10167. return protocol !== a.protocol || host !== a.host;
  10168. }
  10169. var dataUriRegex = /^data:/i;
  10170. /**
  10171. * Determines if the specified uri is a data uri.
  10172. *
  10173. * @function isDataUri
  10174. *
  10175. * @param {String} uri The uri to test.
  10176. * @returns {Boolean} true when the uri is a data uri; otherwise, false.
  10177. *
  10178. * @private
  10179. */
  10180. function isDataUri(uri) {
  10181. //>>includeStart('debug', pragmas.debug);
  10182. Check.Check.typeOf.string("uri", uri);
  10183. //>>includeEnd('debug');
  10184. return dataUriRegex.test(uri);
  10185. }
  10186. /**
  10187. * @private
  10188. */
  10189. function loadAndExecuteScript(url) {
  10190. var deferred = when.when.defer();
  10191. var script = document.createElement("script");
  10192. script.async = true;
  10193. script.src = url;
  10194. var head = document.getElementsByTagName("head")[0];
  10195. script.onload = function () {
  10196. script.onload = undefined;
  10197. head.removeChild(script);
  10198. deferred.resolve();
  10199. };
  10200. script.onerror = function (e) {
  10201. deferred.reject(e);
  10202. };
  10203. head.appendChild(script);
  10204. return deferred.promise;
  10205. }
  10206. /**
  10207. * Converts an object representing a set of name/value pairs into a query string,
  10208. * with names and values encoded properly for use in a URL. Values that are arrays
  10209. * will produce multiple values with the same name.
  10210. * @function objectToQuery
  10211. *
  10212. * @param {Object} obj The object containing data to encode.
  10213. * @returns {String} An encoded query string.
  10214. *
  10215. *
  10216. * @example
  10217. * var str = Cesium.objectToQuery({
  10218. * key1 : 'some value',
  10219. * key2 : 'a/b',
  10220. * key3 : ['x', 'y']
  10221. * });
  10222. *
  10223. * @see queryToObject
  10224. * // str will be:
  10225. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  10226. */
  10227. function objectToQuery(obj) {
  10228. //>>includeStart('debug', pragmas.debug);
  10229. if (!when.defined(obj)) {
  10230. throw new Check.DeveloperError("obj is required.");
  10231. }
  10232. //>>includeEnd('debug');
  10233. var result = "";
  10234. for (var propName in obj) {
  10235. if (obj.hasOwnProperty(propName)) {
  10236. var value = obj[propName];
  10237. var part = encodeURIComponent(propName) + "=";
  10238. if (Array.isArray(value)) {
  10239. for (var i = 0, len = value.length; i < len; ++i) {
  10240. result += part + encodeURIComponent(value[i]) + "&";
  10241. }
  10242. } else {
  10243. result += part + encodeURIComponent(value) + "&";
  10244. }
  10245. }
  10246. }
  10247. // trim last &
  10248. result = result.slice(0, -1);
  10249. // This function used to replace %20 with + which is more compact and readable.
  10250. // However, some servers didn't properly handle + as a space.
  10251. // https://github.com/CesiumGS/cesium/issues/2192
  10252. return result;
  10253. }
  10254. /**
  10255. * Parses a query string into an object, where the keys and values of the object are the
  10256. * name/value pairs from the query string, decoded. If a name appears multiple times,
  10257. * the value in the object will be an array of values.
  10258. * @function queryToObject
  10259. *
  10260. * @param {String} queryString The query string.
  10261. * @returns {Object} An object containing the parameters parsed from the query string.
  10262. *
  10263. *
  10264. * @example
  10265. * var obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
  10266. * // obj will be:
  10267. * // {
  10268. * // key1 : 'some value',
  10269. * // key2 : 'a/b',
  10270. * // key3 : ['x', 'y']
  10271. * // }
  10272. *
  10273. * @see objectToQuery
  10274. */
  10275. function queryToObject(queryString) {
  10276. //>>includeStart('debug', pragmas.debug);
  10277. if (!when.defined(queryString)) {
  10278. throw new Check.DeveloperError("queryString is required.");
  10279. }
  10280. //>>includeEnd('debug');
  10281. var result = {};
  10282. if (queryString === "") {
  10283. return result;
  10284. }
  10285. var parts = queryString.replace(/\+/g, "%20").split(/[&;]/);
  10286. for (var i = 0, len = parts.length; i < len; ++i) {
  10287. var subparts = parts[i].split("=");
  10288. var name = decodeURIComponent(subparts[0]);
  10289. var value = subparts[1];
  10290. if (when.defined(value)) {
  10291. value = decodeURIComponent(value);
  10292. } else {
  10293. value = "";
  10294. }
  10295. var resultValue = result[name];
  10296. if (typeof resultValue === "string") {
  10297. // expand the single value to an array
  10298. result[name] = [resultValue, value];
  10299. } else if (Array.isArray(resultValue)) {
  10300. resultValue.push(value);
  10301. } else {
  10302. result[name] = value;
  10303. }
  10304. }
  10305. return result;
  10306. }
  10307. /**
  10308. * State of the request.
  10309. *
  10310. * @enum {Number}
  10311. */
  10312. var RequestState = {
  10313. /**
  10314. * Initial unissued state.
  10315. *
  10316. * @type Number
  10317. * @constant
  10318. */
  10319. UNISSUED: 0,
  10320. /**
  10321. * Issued but not yet active. Will become active when open slots are available.
  10322. *
  10323. * @type Number
  10324. * @constant
  10325. */
  10326. ISSUED: 1,
  10327. /**
  10328. * Actual http request has been sent.
  10329. *
  10330. * @type Number
  10331. * @constant
  10332. */
  10333. ACTIVE: 2,
  10334. /**
  10335. * Request completed successfully.
  10336. *
  10337. * @type Number
  10338. * @constant
  10339. */
  10340. RECEIVED: 3,
  10341. /**
  10342. * Request was cancelled, either explicitly or automatically because of low priority.
  10343. *
  10344. * @type Number
  10345. * @constant
  10346. */
  10347. CANCELLED: 4,
  10348. /**
  10349. * Request failed.
  10350. *
  10351. * @type Number
  10352. * @constant
  10353. */
  10354. FAILED: 5,
  10355. };
  10356. var RequestState$1 = Object.freeze(RequestState);
  10357. /**
  10358. * An enum identifying the type of request. Used for finer grained logging and priority sorting.
  10359. *
  10360. * @enum {Number}
  10361. */
  10362. var RequestType = {
  10363. /**
  10364. * Terrain request.
  10365. *
  10366. * @type Number
  10367. * @constant
  10368. */
  10369. TERRAIN: 0,
  10370. /**
  10371. * Imagery request.
  10372. *
  10373. * @type Number
  10374. * @constant
  10375. */
  10376. IMAGERY: 1,
  10377. /**
  10378. * 3D Tiles request.
  10379. *
  10380. * @type Number
  10381. * @constant
  10382. */
  10383. TILES3D: 2,
  10384. /**
  10385. * Other request.
  10386. *
  10387. * @type Number
  10388. * @constant
  10389. */
  10390. OTHER: 3,
  10391. };
  10392. var RequestType$1 = Object.freeze(RequestType);
  10393. /**
  10394. * Stores information for making a request. In general this does not need to be constructed directly.
  10395. *
  10396. * @alias Request
  10397. * @constructor
  10398. * @param {Object} [options] An object with the following properties:
  10399. * @param {String} [options.url] The url to request.
  10400. * @param {Request.RequestCallback} [options.requestFunction] The function that makes the actual data request.
  10401. * @param {Request.CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
  10402. * @param {Request.PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
  10403. * @param {Number} [options.priority=0.0] The initial priority of the request.
  10404. * @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.
  10405. * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
  10406. * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
  10407. */
  10408. function Request(options) {
  10409. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  10410. var throttleByServer = when.defaultValue(options.throttleByServer, false);
  10411. var throttle = when.defaultValue(options.throttle, false);
  10412. /**
  10413. * The URL to request.
  10414. *
  10415. * @type {String}
  10416. */
  10417. this.url = options.url;
  10418. /**
  10419. * The function that makes the actual data request.
  10420. *
  10421. * @type {Request.RequestCallback}
  10422. */
  10423. this.requestFunction = options.requestFunction;
  10424. /**
  10425. * The function that is called when the request is cancelled.
  10426. *
  10427. * @type {Request.CancelCallback}
  10428. */
  10429. this.cancelFunction = options.cancelFunction;
  10430. /**
  10431. * The function that is called to update the request's priority, which occurs once per frame.
  10432. *
  10433. * @type {Request.PriorityCallback}
  10434. */
  10435. this.priorityFunction = options.priorityFunction;
  10436. /**
  10437. * Priority is a unit-less value where lower values represent higher priority.
  10438. * For world-based objects, this is usually the distance from the camera.
  10439. * A request that does not have a priority function defaults to a priority of 0.
  10440. *
  10441. * If priorityFunction is defined, this value is updated every frame with the result of that call.
  10442. *
  10443. * @type {Number}
  10444. * @default 0.0
  10445. */
  10446. this.priority = when.defaultValue(options.priority, 0.0);
  10447. /**
  10448. * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
  10449. * request will be throttled and sent based on priority.
  10450. *
  10451. * @type {Boolean}
  10452. * @readonly
  10453. *
  10454. * @default false
  10455. */
  10456. this.throttle = throttle;
  10457. /**
  10458. * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
  10459. * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
  10460. * to <code>true</code> is preferable for requests going through HTTP/1 servers.
  10461. *
  10462. * @type {Boolean}
  10463. * @readonly
  10464. *
  10465. * @default false
  10466. */
  10467. this.throttleByServer = throttleByServer;
  10468. /**
  10469. * Type of request.
  10470. *
  10471. * @type {RequestType}
  10472. * @readonly
  10473. *
  10474. * @default RequestType.OTHER
  10475. */
  10476. this.type = when.defaultValue(options.type, RequestType$1.OTHER);
  10477. /**
  10478. * A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
  10479. *
  10480. * @type {String}
  10481. *
  10482. * @private
  10483. */
  10484. this.serverKey = undefined;
  10485. /**
  10486. * The current state of the request.
  10487. *
  10488. * @type {RequestState}
  10489. * @readonly
  10490. */
  10491. this.state = RequestState$1.UNISSUED;
  10492. /**
  10493. * The requests's deferred promise.
  10494. *
  10495. * @type {Object}
  10496. *
  10497. * @private
  10498. */
  10499. this.deferred = undefined;
  10500. /**
  10501. * Whether the request was explicitly cancelled.
  10502. *
  10503. * @type {Boolean}
  10504. *
  10505. * @private
  10506. */
  10507. this.cancelled = false;
  10508. }
  10509. /**
  10510. * Mark the request as cancelled.
  10511. *
  10512. * @private
  10513. */
  10514. Request.prototype.cancel = function () {
  10515. this.cancelled = true;
  10516. };
  10517. /**
  10518. * Duplicates a Request instance.
  10519. *
  10520. * @param {Request} [result] The object onto which to store the result.
  10521. *
  10522. * @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
  10523. */
  10524. Request.prototype.clone = function (result) {
  10525. if (!when.defined(result)) {
  10526. return new Request(this);
  10527. }
  10528. result.url = this.url;
  10529. result.requestFunction = this.requestFunction;
  10530. result.cancelFunction = this.cancelFunction;
  10531. result.priorityFunction = this.priorityFunction;
  10532. result.priority = this.priority;
  10533. result.throttle = this.throttle;
  10534. result.throttleByServer = this.throttleByServer;
  10535. result.type = this.type;
  10536. result.serverKey = this.serverKey;
  10537. // These get defaulted because the cloned request hasn't been issued
  10538. result.state = this.RequestState.UNISSUED;
  10539. result.deferred = undefined;
  10540. result.cancelled = false;
  10541. return result;
  10542. };
  10543. /**
  10544. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  10545. * a dictionary.
  10546. *
  10547. * @function parseResponseHeaders
  10548. *
  10549. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  10550. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  10551. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  10552. * is that header's value.
  10553. *
  10554. * @private
  10555. */
  10556. function parseResponseHeaders(headerString) {
  10557. var headers = {};
  10558. if (!headerString) {
  10559. return headers;
  10560. }
  10561. var headerPairs = headerString.split("\u000d\u000a");
  10562. for (var i = 0; i < headerPairs.length; ++i) {
  10563. var headerPair = headerPairs[i];
  10564. // Can't use split() here because it does the wrong thing
  10565. // if the header value has the string ": " in it.
  10566. var index = headerPair.indexOf("\u003a\u0020");
  10567. if (index > 0) {
  10568. var key = headerPair.substring(0, index);
  10569. var val = headerPair.substring(index + 2);
  10570. headers[key] = val;
  10571. }
  10572. }
  10573. return headers;
  10574. }
  10575. /**
  10576. * An event that is raised when a request encounters an error.
  10577. *
  10578. * @constructor
  10579. * @alias RequestErrorEvent
  10580. *
  10581. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  10582. * @param {Object} [response] The response included along with the error.
  10583. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  10584. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  10585. */
  10586. function RequestErrorEvent(statusCode, response, responseHeaders) {
  10587. /**
  10588. * The HTTP error status code, such as 404. If the error does not have a particular
  10589. * HTTP code, this property will be undefined.
  10590. *
  10591. * @type {Number}
  10592. */
  10593. this.statusCode = statusCode;
  10594. /**
  10595. * The response included along with the error. If the error does not include a response,
  10596. * this property will be undefined.
  10597. *
  10598. * @type {Object}
  10599. */
  10600. this.response = response;
  10601. /**
  10602. * The headers included in the response, represented as an object literal of key/value pairs.
  10603. * If the error does not include any headers, this property will be undefined.
  10604. *
  10605. * @type {Object}
  10606. */
  10607. this.responseHeaders = responseHeaders;
  10608. if (typeof this.responseHeaders === "string") {
  10609. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  10610. }
  10611. }
  10612. /**
  10613. * Creates a string representing this RequestErrorEvent.
  10614. * @memberof RequestErrorEvent
  10615. *
  10616. * @returns {String} A string representing the provided RequestErrorEvent.
  10617. */
  10618. RequestErrorEvent.prototype.toString = function () {
  10619. var str = "Request has failed.";
  10620. if (when.defined(this.statusCode)) {
  10621. str += " Status Code: " + this.statusCode;
  10622. }
  10623. return str;
  10624. };
  10625. /**
  10626. * A generic utility class for managing subscribers for a particular event.
  10627. * This class is usually instantiated inside of a container class and
  10628. * exposed as a property for others to subscribe to.
  10629. *
  10630. * @alias Event
  10631. * @constructor
  10632. * @example
  10633. * MyObject.prototype.myListener = function(arg1, arg2) {
  10634. * this.myArg1Copy = arg1;
  10635. * this.myArg2Copy = arg2;
  10636. * }
  10637. *
  10638. * var myObjectInstance = new MyObject();
  10639. * var evt = new Cesium.Event();
  10640. * evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
  10641. * evt.raiseEvent('1', '2');
  10642. * evt.removeEventListener(MyObject.prototype.myListener);
  10643. */
  10644. function Event() {
  10645. this._listeners = [];
  10646. this._scopes = [];
  10647. this._toRemove = [];
  10648. this._insideRaiseEvent = false;
  10649. }
  10650. Object.defineProperties(Event.prototype, {
  10651. /**
  10652. * The number of listeners currently subscribed to the event.
  10653. * @memberof Event.prototype
  10654. * @type {Number}
  10655. * @readonly
  10656. */
  10657. numberOfListeners: {
  10658. get: function () {
  10659. return this._listeners.length - this._toRemove.length;
  10660. },
  10661. },
  10662. });
  10663. /**
  10664. * Registers a callback function to be executed whenever the event is raised.
  10665. * An optional scope can be provided to serve as the <code>this</code> pointer
  10666. * in which the function will execute.
  10667. *
  10668. * @param {Function} listener The function to be executed when the event is raised.
  10669. * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
  10670. * pointer in which the listener function will execute.
  10671. * @returns {Event.RemoveCallback} A function that will remove this event listener when invoked.
  10672. *
  10673. * @see Event#raiseEvent
  10674. * @see Event#removeEventListener
  10675. */
  10676. Event.prototype.addEventListener = function (listener, scope) {
  10677. //>>includeStart('debug', pragmas.debug);
  10678. Check.Check.typeOf.func("listener", listener);
  10679. //>>includeEnd('debug');
  10680. this._listeners.push(listener);
  10681. this._scopes.push(scope);
  10682. var event = this;
  10683. return function () {
  10684. event.removeEventListener(listener, scope);
  10685. };
  10686. };
  10687. /**
  10688. * Unregisters a previously registered callback.
  10689. *
  10690. * @param {Function} listener The function to be unregistered.
  10691. * @param {Object} [scope] The scope that was originally passed to addEventListener.
  10692. * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> if the listener and scope are not registered with the event.
  10693. *
  10694. * @see Event#addEventListener
  10695. * @see Event#raiseEvent
  10696. */
  10697. Event.prototype.removeEventListener = function (listener, scope) {
  10698. //>>includeStart('debug', pragmas.debug);
  10699. Check.Check.typeOf.func("listener", listener);
  10700. //>>includeEnd('debug');
  10701. var listeners = this._listeners;
  10702. var scopes = this._scopes;
  10703. var index = -1;
  10704. for (var i = 0; i < listeners.length; i++) {
  10705. if (listeners[i] === listener && scopes[i] === scope) {
  10706. index = i;
  10707. break;
  10708. }
  10709. }
  10710. if (index !== -1) {
  10711. if (this._insideRaiseEvent) {
  10712. //In order to allow removing an event subscription from within
  10713. //a callback, we don't actually remove the items here. Instead
  10714. //remember the index they are at and undefined their value.
  10715. this._toRemove.push(index);
  10716. listeners[index] = undefined;
  10717. scopes[index] = undefined;
  10718. } else {
  10719. listeners.splice(index, 1);
  10720. scopes.splice(index, 1);
  10721. }
  10722. return true;
  10723. }
  10724. return false;
  10725. };
  10726. function compareNumber(a, b) {
  10727. return b - a;
  10728. }
  10729. /**
  10730. * Raises the event by calling each registered listener with all supplied arguments.
  10731. *
  10732. * @param {...Object} arguments This method takes any number of parameters and passes them through to the listener functions.
  10733. *
  10734. * @see Event#addEventListener
  10735. * @see Event#removeEventListener
  10736. */
  10737. Event.prototype.raiseEvent = function () {
  10738. this._insideRaiseEvent = true;
  10739. var i;
  10740. var listeners = this._listeners;
  10741. var scopes = this._scopes;
  10742. var length = listeners.length;
  10743. for (i = 0; i < length; i++) {
  10744. var listener = listeners[i];
  10745. if (when.defined(listener)) {
  10746. listeners[i].apply(scopes[i], arguments);
  10747. }
  10748. }
  10749. //Actually remove items removed in removeEventListener.
  10750. var toRemove = this._toRemove;
  10751. length = toRemove.length;
  10752. if (length > 0) {
  10753. toRemove.sort(compareNumber);
  10754. for (i = 0; i < length; i++) {
  10755. var index = toRemove[i];
  10756. listeners.splice(index, 1);
  10757. scopes.splice(index, 1);
  10758. }
  10759. toRemove.length = 0;
  10760. }
  10761. this._insideRaiseEvent = false;
  10762. };
  10763. /**
  10764. * Array implementation of a heap.
  10765. *
  10766. * @alias Heap
  10767. * @constructor
  10768. * @private
  10769. *
  10770. * @param {Object} options Object with the following properties:
  10771. * @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.
  10772. */
  10773. function Heap(options) {
  10774. //>>includeStart('debug', pragmas.debug);
  10775. Check.Check.typeOf.object("options", options);
  10776. Check.Check.defined("options.comparator", options.comparator);
  10777. //>>includeEnd('debug');
  10778. this._comparator = options.comparator;
  10779. this._array = [];
  10780. this._length = 0;
  10781. this._maximumLength = undefined;
  10782. }
  10783. Object.defineProperties(Heap.prototype, {
  10784. /**
  10785. * Gets the length of the heap.
  10786. *
  10787. * @memberof Heap.prototype
  10788. *
  10789. * @type {Number}
  10790. * @readonly
  10791. */
  10792. length: {
  10793. get: function () {
  10794. return this._length;
  10795. },
  10796. },
  10797. /**
  10798. * Gets the internal array.
  10799. *
  10800. * @memberof Heap.prototype
  10801. *
  10802. * @type {Array}
  10803. * @readonly
  10804. */
  10805. internalArray: {
  10806. get: function () {
  10807. return this._array;
  10808. },
  10809. },
  10810. /**
  10811. * Gets and sets the maximum length of the heap.
  10812. *
  10813. * @memberof Heap.prototype
  10814. *
  10815. * @type {Number}
  10816. */
  10817. maximumLength: {
  10818. get: function () {
  10819. return this._maximumLength;
  10820. },
  10821. set: function (value) {
  10822. //>>includeStart('debug', pragmas.debug);
  10823. Check.Check.typeOf.number.greaterThanOrEquals("maximumLength", value, 0);
  10824. //>>includeEnd('debug');
  10825. var originalLength = this._length;
  10826. if (value < originalLength) {
  10827. var array = this._array;
  10828. // Remove trailing references
  10829. for (var i = value; i < originalLength; ++i) {
  10830. array[i] = undefined;
  10831. }
  10832. this._length = value;
  10833. array.length = value;
  10834. }
  10835. this._maximumLength = value;
  10836. },
  10837. },
  10838. /**
  10839. * 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.
  10840. *
  10841. * @memberof Heap.prototype
  10842. *
  10843. * @type {Heap.ComparatorCallback}
  10844. */
  10845. comparator: {
  10846. get: function () {
  10847. return this._comparator;
  10848. },
  10849. },
  10850. });
  10851. function swap(array, a, b) {
  10852. var temp = array[a];
  10853. array[a] = array[b];
  10854. array[b] = temp;
  10855. }
  10856. /**
  10857. * Resizes the internal array of the heap.
  10858. *
  10859. * @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
  10860. */
  10861. Heap.prototype.reserve = function (length) {
  10862. length = when.defaultValue(length, this._length);
  10863. this._array.length = length;
  10864. };
  10865. /**
  10866. * Update the heap so that index and all descendants satisfy the heap property.
  10867. *
  10868. * @param {Number} [index=0] The starting index to heapify from.
  10869. */
  10870. Heap.prototype.heapify = function (index) {
  10871. index = when.defaultValue(index, 0);
  10872. var length = this._length;
  10873. var comparator = this._comparator;
  10874. var array = this._array;
  10875. var candidate = -1;
  10876. var inserting = true;
  10877. while (inserting) {
  10878. var right = 2 * (index + 1);
  10879. var left = right - 1;
  10880. if (left < length && comparator(array[left], array[index]) < 0) {
  10881. candidate = left;
  10882. } else {
  10883. candidate = index;
  10884. }
  10885. if (right < length && comparator(array[right], array[candidate]) < 0) {
  10886. candidate = right;
  10887. }
  10888. if (candidate !== index) {
  10889. swap(array, candidate, index);
  10890. index = candidate;
  10891. } else {
  10892. inserting = false;
  10893. }
  10894. }
  10895. };
  10896. /**
  10897. * Resort the heap.
  10898. */
  10899. Heap.prototype.resort = function () {
  10900. var length = this._length;
  10901. for (var i = Math.ceil(length / 2); i >= 0; --i) {
  10902. this.heapify(i);
  10903. }
  10904. };
  10905. /**
  10906. * Insert an element into the heap. If the length would grow greater than maximumLength
  10907. * of the heap, extra elements are removed.
  10908. *
  10909. * @param {*} element The element to insert
  10910. *
  10911. * @return {*} The element that was removed from the heap if the heap is at full capacity.
  10912. */
  10913. Heap.prototype.insert = function (element) {
  10914. //>>includeStart('debug', pragmas.debug);
  10915. Check.Check.defined("element", element);
  10916. //>>includeEnd('debug');
  10917. var array = this._array;
  10918. var comparator = this._comparator;
  10919. var maximumLength = this._maximumLength;
  10920. var index = this._length++;
  10921. if (index < array.length) {
  10922. array[index] = element;
  10923. } else {
  10924. array.push(element);
  10925. }
  10926. while (index !== 0) {
  10927. var parent = Math.floor((index - 1) / 2);
  10928. if (comparator(array[index], array[parent]) < 0) {
  10929. swap(array, index, parent);
  10930. index = parent;
  10931. } else {
  10932. break;
  10933. }
  10934. }
  10935. var removedElement;
  10936. if (when.defined(maximumLength) && this._length > maximumLength) {
  10937. removedElement = array[maximumLength];
  10938. this._length = maximumLength;
  10939. }
  10940. return removedElement;
  10941. };
  10942. /**
  10943. * Remove the element specified by index from the heap and return it.
  10944. *
  10945. * @param {Number} [index=0] The index to remove.
  10946. * @returns {*} The specified element of the heap.
  10947. */
  10948. Heap.prototype.pop = function (index) {
  10949. index = when.defaultValue(index, 0);
  10950. if (this._length === 0) {
  10951. return undefined;
  10952. }
  10953. //>>includeStart('debug', pragmas.debug);
  10954. Check.Check.typeOf.number.lessThan("index", index, this._length);
  10955. //>>includeEnd('debug');
  10956. var array = this._array;
  10957. var root = array[index];
  10958. swap(array, index, --this._length);
  10959. this.heapify(index);
  10960. array[this._length] = undefined; // Remove trailing reference
  10961. return root;
  10962. };
  10963. function sortRequests(a, b) {
  10964. return a.priority - b.priority;
  10965. }
  10966. var statistics = {
  10967. numberOfAttemptedRequests: 0,
  10968. numberOfActiveRequests: 0,
  10969. numberOfCancelledRequests: 0,
  10970. numberOfCancelledActiveRequests: 0,
  10971. numberOfFailedRequests: 0,
  10972. numberOfActiveRequestsEver: 0,
  10973. lastNumberOfActiveRequests: 0,
  10974. };
  10975. var priorityHeapLength = 20;
  10976. var requestHeap = new Heap({
  10977. comparator: sortRequests,
  10978. });
  10979. requestHeap.maximumLength = priorityHeapLength;
  10980. requestHeap.reserve(priorityHeapLength);
  10981. var activeRequests = [];
  10982. var numberOfActiveRequestsByServer = {};
  10983. var pageUri =
  10984. typeof document !== "undefined" ? new URI(document.location.href) : new URI();
  10985. var requestCompletedEvent = new Event();
  10986. /**
  10987. * The request scheduler is used to track and constrain the number of active requests in order to prioritize incoming requests. The ability
  10988. * to retain control over the number of requests in CesiumJS is important because due to events such as changes in the camera position,
  10989. * a lot of new requests may be generated and a lot of in-flight requests may become redundant. The request scheduler manually constrains the
  10990. * 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.
  10991. *
  10992. * @namespace RequestScheduler
  10993. *
  10994. */
  10995. function RequestScheduler() {}
  10996. /**
  10997. * The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
  10998. * @type {Number}
  10999. * @default 50
  11000. */
  11001. RequestScheduler.maximumRequests = 50;
  11002. /**
  11003. * The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
  11004. * listed in {@link requestsByServer} do not observe this limit.
  11005. * @type {Number}
  11006. * @default 6
  11007. */
  11008. RequestScheduler.maximumRequestsPerServer = 6;
  11009. /**
  11010. * A per server key list of overrides to use for throttling instead of <code>maximumRequestsPerServer</code>
  11011. * @type {Object}
  11012. *
  11013. * @example
  11014. * RequestScheduler.requestsByServer = {
  11015. * 'api.cesium.com:443': 18,
  11016. * 'assets.cesium.com:443': 18
  11017. * };
  11018. */
  11019. RequestScheduler.requestsByServer = {
  11020. "api.cesium.com:443": 18,
  11021. "assets.cesium.com:443": 18,
  11022. };
  11023. /**
  11024. * Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
  11025. * @type {Boolean}
  11026. * @default true
  11027. */
  11028. RequestScheduler.throttleRequests = true;
  11029. /**
  11030. * When true, log statistics to the console every frame
  11031. * @type {Boolean}
  11032. * @default false
  11033. * @private
  11034. */
  11035. RequestScheduler.debugShowStatistics = false;
  11036. /**
  11037. * An event that's raised when a request is completed. Event handlers are passed
  11038. * the error object if the request fails.
  11039. *
  11040. * @type {Event}
  11041. * @default Event()
  11042. * @private
  11043. */
  11044. RequestScheduler.requestCompletedEvent = requestCompletedEvent;
  11045. Object.defineProperties(RequestScheduler, {
  11046. /**
  11047. * Returns the statistics used by the request scheduler.
  11048. *
  11049. * @memberof RequestScheduler
  11050. *
  11051. * @type Object
  11052. * @readonly
  11053. * @private
  11054. */
  11055. statistics: {
  11056. get: function () {
  11057. return statistics;
  11058. },
  11059. },
  11060. /**
  11061. * 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.
  11062. *
  11063. * @memberof RequestScheduler
  11064. *
  11065. * @type {Number}
  11066. * @default 20
  11067. * @private
  11068. */
  11069. priorityHeapLength: {
  11070. get: function () {
  11071. return priorityHeapLength;
  11072. },
  11073. set: function (value) {
  11074. // If the new length shrinks the heap, need to cancel some of the requests.
  11075. // Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
  11076. if (value < priorityHeapLength) {
  11077. while (requestHeap.length > value) {
  11078. var request = requestHeap.pop();
  11079. cancelRequest(request);
  11080. }
  11081. }
  11082. priorityHeapLength = value;
  11083. requestHeap.maximumLength = value;
  11084. requestHeap.reserve(value);
  11085. },
  11086. },
  11087. });
  11088. function updatePriority(request) {
  11089. if (when.defined(request.priorityFunction)) {
  11090. request.priority = request.priorityFunction();
  11091. }
  11092. }
  11093. function serverHasOpenSlots(serverKey) {
  11094. var maxRequests = when.defaultValue(
  11095. RequestScheduler.requestsByServer[serverKey],
  11096. RequestScheduler.maximumRequestsPerServer
  11097. );
  11098. return numberOfActiveRequestsByServer[serverKey] < maxRequests;
  11099. }
  11100. function issueRequest(request) {
  11101. if (request.state === RequestState$1.UNISSUED) {
  11102. request.state = RequestState$1.ISSUED;
  11103. request.deferred = when.when.defer();
  11104. }
  11105. return request.deferred.promise;
  11106. }
  11107. function getRequestReceivedFunction(request) {
  11108. return function (results) {
  11109. if (request.state === RequestState$1.CANCELLED) {
  11110. // If the data request comes back but the request is cancelled, ignore it.
  11111. return;
  11112. }
  11113. --statistics.numberOfActiveRequests;
  11114. --numberOfActiveRequestsByServer[request.serverKey];
  11115. requestCompletedEvent.raiseEvent();
  11116. request.state = RequestState$1.RECEIVED;
  11117. request.deferred.resolve(results);
  11118. // explicitly set to undefined to ensure GC of request response data. See #8843
  11119. request.deferred = undefined;
  11120. };
  11121. }
  11122. function getRequestFailedFunction(request) {
  11123. return function (error) {
  11124. if (request.state === RequestState$1.CANCELLED) {
  11125. // If the data request comes back but the request is cancelled, ignore it.
  11126. return;
  11127. }
  11128. ++statistics.numberOfFailedRequests;
  11129. --statistics.numberOfActiveRequests;
  11130. --numberOfActiveRequestsByServer[request.serverKey];
  11131. requestCompletedEvent.raiseEvent(error);
  11132. request.state = RequestState$1.FAILED;
  11133. request.deferred.reject(error);
  11134. };
  11135. }
  11136. function startRequest(request) {
  11137. var promise = issueRequest(request);
  11138. request.state = RequestState$1.ACTIVE;
  11139. activeRequests.push(request);
  11140. ++statistics.numberOfActiveRequests;
  11141. ++statistics.numberOfActiveRequestsEver;
  11142. ++numberOfActiveRequestsByServer[request.serverKey];
  11143. request
  11144. .requestFunction()
  11145. .then(getRequestReceivedFunction(request))
  11146. .otherwise(getRequestFailedFunction(request));
  11147. return promise;
  11148. }
  11149. function cancelRequest(request) {
  11150. var active = request.state === RequestState$1.ACTIVE;
  11151. request.state = RequestState$1.CANCELLED;
  11152. ++statistics.numberOfCancelledRequests;
  11153. // check that deferred has not been cleared since cancelRequest can be called
  11154. // on a finished request, e.g. by clearForSpecs during tests
  11155. if (when.defined(request.deferred)) {
  11156. request.deferred.reject();
  11157. request.deferred = undefined;
  11158. }
  11159. if (active) {
  11160. --statistics.numberOfActiveRequests;
  11161. --numberOfActiveRequestsByServer[request.serverKey];
  11162. ++statistics.numberOfCancelledActiveRequests;
  11163. }
  11164. if (when.defined(request.cancelFunction)) {
  11165. request.cancelFunction();
  11166. }
  11167. }
  11168. /**
  11169. * Sort requests by priority and start requests.
  11170. * @private
  11171. */
  11172. RequestScheduler.update = function () {
  11173. var i;
  11174. var request;
  11175. // Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
  11176. var removeCount = 0;
  11177. var activeLength = activeRequests.length;
  11178. for (i = 0; i < activeLength; ++i) {
  11179. request = activeRequests[i];
  11180. if (request.cancelled) {
  11181. // Request was explicitly cancelled
  11182. cancelRequest(request);
  11183. }
  11184. if (request.state !== RequestState$1.ACTIVE) {
  11185. // Request is no longer active, remove from array
  11186. ++removeCount;
  11187. continue;
  11188. }
  11189. if (removeCount > 0) {
  11190. // Shift back to fill in vacated slots from completed requests
  11191. activeRequests[i - removeCount] = request;
  11192. }
  11193. }
  11194. activeRequests.length -= removeCount;
  11195. // Update priority of issued requests and resort the heap
  11196. var issuedRequests = requestHeap.internalArray;
  11197. var issuedLength = requestHeap.length;
  11198. for (i = 0; i < issuedLength; ++i) {
  11199. updatePriority(issuedRequests[i]);
  11200. }
  11201. requestHeap.resort();
  11202. // Get the number of open slots and fill with the highest priority requests.
  11203. // Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
  11204. var openSlots = Math.max(
  11205. RequestScheduler.maximumRequests - activeRequests.length,
  11206. 0
  11207. );
  11208. var filledSlots = 0;
  11209. while (filledSlots < openSlots && requestHeap.length > 0) {
  11210. // Loop until all open slots are filled or the heap becomes empty
  11211. request = requestHeap.pop();
  11212. if (request.cancelled) {
  11213. // Request was explicitly cancelled
  11214. cancelRequest(request);
  11215. continue;
  11216. }
  11217. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  11218. // Open slots are available, but the request is throttled by its server. Cancel and try again later.
  11219. cancelRequest(request);
  11220. continue;
  11221. }
  11222. startRequest(request);
  11223. ++filledSlots;
  11224. }
  11225. updateStatistics();
  11226. };
  11227. /**
  11228. * Get the server key from a given url.
  11229. *
  11230. * @param {String} url The url.
  11231. * @returns {String} The server key.
  11232. * @private
  11233. */
  11234. RequestScheduler.getServerKey = function (url) {
  11235. //>>includeStart('debug', pragmas.debug);
  11236. Check.Check.typeOf.string("url", url);
  11237. //>>includeEnd('debug');
  11238. var uri = new URI(url).resolve(pageUri);
  11239. uri.normalize();
  11240. var serverKey = uri.authority;
  11241. if (!/:/.test(serverKey)) {
  11242. // If the authority does not contain a port number, add port 443 for https or port 80 for http
  11243. serverKey = serverKey + ":" + (uri.scheme === "https" ? "443" : "80");
  11244. }
  11245. var length = numberOfActiveRequestsByServer[serverKey];
  11246. if (!when.defined(length)) {
  11247. numberOfActiveRequestsByServer[serverKey] = 0;
  11248. }
  11249. return serverKey;
  11250. };
  11251. /**
  11252. * Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
  11253. * queued and sorted by priority before being sent.
  11254. *
  11255. * @param {Request} request The request object.
  11256. *
  11257. * @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
  11258. *
  11259. * @private
  11260. */
  11261. RequestScheduler.request = function (request) {
  11262. //>>includeStart('debug', pragmas.debug);
  11263. Check.Check.typeOf.object("request", request);
  11264. Check.Check.typeOf.string("request.url", request.url);
  11265. Check.Check.typeOf.func("request.requestFunction", request.requestFunction);
  11266. //>>includeEnd('debug');
  11267. if (isDataUri(request.url) || isBlobUri(request.url)) {
  11268. requestCompletedEvent.raiseEvent();
  11269. request.state = RequestState$1.RECEIVED;
  11270. return request.requestFunction();
  11271. }
  11272. ++statistics.numberOfAttemptedRequests;
  11273. if (!when.defined(request.serverKey)) {
  11274. request.serverKey = RequestScheduler.getServerKey(request.url);
  11275. }
  11276. if (
  11277. RequestScheduler.throttleRequests &&
  11278. request.throttleByServer &&
  11279. !serverHasOpenSlots(request.serverKey)
  11280. ) {
  11281. // Server is saturated. Try again later.
  11282. return undefined;
  11283. }
  11284. if (!RequestScheduler.throttleRequests || !request.throttle) {
  11285. return startRequest(request);
  11286. }
  11287. if (activeRequests.length >= RequestScheduler.maximumRequests) {
  11288. // Active requests are saturated. Try again later.
  11289. return undefined;
  11290. }
  11291. // Insert into the priority heap and see if a request was bumped off. If this request is the lowest
  11292. // priority it will be returned.
  11293. updatePriority(request);
  11294. var removedRequest = requestHeap.insert(request);
  11295. if (when.defined(removedRequest)) {
  11296. if (removedRequest === request) {
  11297. // Request does not have high enough priority to be issued
  11298. return undefined;
  11299. }
  11300. // A previously issued request has been bumped off the priority heap, so cancel it
  11301. cancelRequest(removedRequest);
  11302. }
  11303. return issueRequest(request);
  11304. };
  11305. function updateStatistics() {
  11306. if (!RequestScheduler.debugShowStatistics) {
  11307. return;
  11308. }
  11309. if (
  11310. statistics.numberOfActiveRequests === 0 &&
  11311. statistics.lastNumberOfActiveRequests > 0
  11312. ) {
  11313. if (statistics.numberOfAttemptedRequests > 0) {
  11314. console.log(
  11315. "Number of attempted requests: " + statistics.numberOfAttemptedRequests
  11316. );
  11317. statistics.numberOfAttemptedRequests = 0;
  11318. }
  11319. if (statistics.numberOfCancelledRequests > 0) {
  11320. console.log(
  11321. "Number of cancelled requests: " + statistics.numberOfCancelledRequests
  11322. );
  11323. statistics.numberOfCancelledRequests = 0;
  11324. }
  11325. if (statistics.numberOfCancelledActiveRequests > 0) {
  11326. console.log(
  11327. "Number of cancelled active requests: " +
  11328. statistics.numberOfCancelledActiveRequests
  11329. );
  11330. statistics.numberOfCancelledActiveRequests = 0;
  11331. }
  11332. if (statistics.numberOfFailedRequests > 0) {
  11333. console.log(
  11334. "Number of failed requests: " + statistics.numberOfFailedRequests
  11335. );
  11336. statistics.numberOfFailedRequests = 0;
  11337. }
  11338. }
  11339. statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
  11340. }
  11341. /**
  11342. * For testing only. Clears any requests that may not have completed from previous tests.
  11343. *
  11344. * @private
  11345. */
  11346. RequestScheduler.clearForSpecs = function () {
  11347. while (requestHeap.length > 0) {
  11348. var request = requestHeap.pop();
  11349. cancelRequest(request);
  11350. }
  11351. var length = activeRequests.length;
  11352. for (var i = 0; i < length; ++i) {
  11353. cancelRequest(activeRequests[i]);
  11354. }
  11355. activeRequests.length = 0;
  11356. numberOfActiveRequestsByServer = {};
  11357. // Clear stats
  11358. statistics.numberOfAttemptedRequests = 0;
  11359. statistics.numberOfActiveRequests = 0;
  11360. statistics.numberOfCancelledRequests = 0;
  11361. statistics.numberOfCancelledActiveRequests = 0;
  11362. statistics.numberOfFailedRequests = 0;
  11363. statistics.numberOfActiveRequestsEver = 0;
  11364. statistics.lastNumberOfActiveRequests = 0;
  11365. };
  11366. /**
  11367. * For testing only.
  11368. *
  11369. * @private
  11370. */
  11371. RequestScheduler.numberOfActiveRequestsByServer = function (serverKey) {
  11372. return numberOfActiveRequestsByServer[serverKey];
  11373. };
  11374. /**
  11375. * For testing only.
  11376. *
  11377. * @private
  11378. */
  11379. RequestScheduler.requestHeap = requestHeap;
  11380. /**
  11381. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  11382. * any requests to these servers.
  11383. *
  11384. * @namespace TrustedServers
  11385. *
  11386. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11387. */
  11388. var TrustedServers = {};
  11389. var _servers = {};
  11390. /**
  11391. * Adds a trusted server to the registry
  11392. *
  11393. * @param {String} host The host to be added.
  11394. * @param {Number} port The port used to access the host.
  11395. *
  11396. * @example
  11397. * // Add a trusted server
  11398. * TrustedServers.add('my.server.com', 80);
  11399. */
  11400. TrustedServers.add = function (host, port) {
  11401. //>>includeStart('debug', pragmas.debug);
  11402. if (!when.defined(host)) {
  11403. throw new Check.DeveloperError("host is required.");
  11404. }
  11405. if (!when.defined(port) || port <= 0) {
  11406. throw new Check.DeveloperError("port is required to be greater than 0.");
  11407. }
  11408. //>>includeEnd('debug');
  11409. var authority = host.toLowerCase() + ":" + port;
  11410. if (!when.defined(_servers[authority])) {
  11411. _servers[authority] = true;
  11412. }
  11413. };
  11414. /**
  11415. * Removes a trusted server from the registry
  11416. *
  11417. * @param {String} host The host to be removed.
  11418. * @param {Number} port The port used to access the host.
  11419. *
  11420. * @example
  11421. * // Remove a trusted server
  11422. * TrustedServers.remove('my.server.com', 80);
  11423. */
  11424. TrustedServers.remove = function (host, port) {
  11425. //>>includeStart('debug', pragmas.debug);
  11426. if (!when.defined(host)) {
  11427. throw new Check.DeveloperError("host is required.");
  11428. }
  11429. if (!when.defined(port) || port <= 0) {
  11430. throw new Check.DeveloperError("port is required to be greater than 0.");
  11431. }
  11432. //>>includeEnd('debug');
  11433. var authority = host.toLowerCase() + ":" + port;
  11434. if (when.defined(_servers[authority])) {
  11435. delete _servers[authority];
  11436. }
  11437. };
  11438. function getAuthority(url) {
  11439. var uri = new URI(url);
  11440. uri.normalize();
  11441. // Removes username:password@ so we just have host[:port]
  11442. var authority = uri.getAuthority();
  11443. if (!when.defined(authority)) {
  11444. return undefined; // Relative URL
  11445. }
  11446. if (authority.indexOf("@") !== -1) {
  11447. var parts = authority.split("@");
  11448. authority = parts[1];
  11449. }
  11450. // If the port is missing add one based on the scheme
  11451. if (authority.indexOf(":") === -1) {
  11452. var scheme = uri.getScheme();
  11453. if (!when.defined(scheme)) {
  11454. scheme = window.location.protocol;
  11455. scheme = scheme.substring(0, scheme.length - 1);
  11456. }
  11457. if (scheme === "http") {
  11458. authority += ":80";
  11459. } else if (scheme === "https") {
  11460. authority += ":443";
  11461. } else {
  11462. return undefined;
  11463. }
  11464. }
  11465. return authority;
  11466. }
  11467. /**
  11468. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  11469. *
  11470. * @param {String} url The url to be tested against the trusted list
  11471. *
  11472. * @returns {boolean} Returns true if url is trusted, false otherwise.
  11473. *
  11474. * @example
  11475. * // Add server
  11476. * TrustedServers.add('my.server.com', 81);
  11477. *
  11478. * // Check if server is trusted
  11479. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  11480. * // my.server.com:81 is trusted
  11481. * }
  11482. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  11483. * // my.server.com isn't trusted
  11484. * }
  11485. */
  11486. TrustedServers.contains = function (url) {
  11487. //>>includeStart('debug', pragmas.debug);
  11488. if (!when.defined(url)) {
  11489. throw new Check.DeveloperError("url is required.");
  11490. }
  11491. //>>includeEnd('debug');
  11492. var authority = getAuthority(url);
  11493. if (when.defined(authority) && when.defined(_servers[authority])) {
  11494. return true;
  11495. }
  11496. return false;
  11497. };
  11498. /**
  11499. * Clears the registry
  11500. *
  11501. * @example
  11502. * // Remove a trusted server
  11503. * TrustedServers.clear();
  11504. */
  11505. TrustedServers.clear = function () {
  11506. _servers = {};
  11507. };
  11508. var xhrBlobSupported = (function () {
  11509. try {
  11510. var xhr = new XMLHttpRequest();
  11511. xhr.open("GET", "#", true);
  11512. xhr.responseType = "blob";
  11513. return xhr.responseType === "blob";
  11514. } catch (e) {
  11515. return false;
  11516. }
  11517. })();
  11518. /**
  11519. * Parses a query string and returns the object equivalent.
  11520. *
  11521. * @param {Uri} uri The Uri with a query object.
  11522. * @param {Resource} resource The Resource that will be assigned queryParameters.
  11523. * @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
  11524. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
  11525. *
  11526. * @private
  11527. */
  11528. function parseQuery(uri, resource, merge, preserveQueryParameters) {
  11529. var queryString = uri.query;
  11530. if (!when.defined(queryString) || queryString.length === 0) {
  11531. return {};
  11532. }
  11533. var query;
  11534. // Special case we run into where the querystring is just a string, not key/value pairs
  11535. if (queryString.indexOf("=") === -1) {
  11536. var result = {};
  11537. result[queryString] = undefined;
  11538. query = result;
  11539. } else {
  11540. query = queryToObject(queryString);
  11541. }
  11542. if (merge) {
  11543. resource._queryParameters = combineQueryParameters(
  11544. query,
  11545. resource._queryParameters,
  11546. preserveQueryParameters
  11547. );
  11548. } else {
  11549. resource._queryParameters = query;
  11550. }
  11551. uri.query = undefined;
  11552. }
  11553. /**
  11554. * Converts a query object into a string.
  11555. *
  11556. * @param {Uri} uri The Uri object that will have the query object set.
  11557. * @param {Resource} resource The resource that has queryParameters
  11558. *
  11559. * @private
  11560. */
  11561. function stringifyQuery(uri, resource) {
  11562. var queryObject = resource._queryParameters;
  11563. var keys = Object.keys(queryObject);
  11564. // We have 1 key with an undefined value, so this is just a string, not key/value pairs
  11565. if (keys.length === 1 && !when.defined(queryObject[keys[0]])) {
  11566. uri.query = keys[0];
  11567. } else {
  11568. uri.query = objectToQuery(queryObject);
  11569. }
  11570. }
  11571. /**
  11572. * Clones a value if it is defined, otherwise returns the default value
  11573. *
  11574. * @param {*} [val] The value to clone.
  11575. * @param {*} [defaultVal] The default value.
  11576. *
  11577. * @returns {*} A clone of val or the defaultVal.
  11578. *
  11579. * @private
  11580. */
  11581. function defaultClone(val, defaultVal) {
  11582. if (!when.defined(val)) {
  11583. return defaultVal;
  11584. }
  11585. return when.defined(val.clone) ? val.clone() : clone(val);
  11586. }
  11587. /**
  11588. * Checks to make sure the Resource isn't already being requested.
  11589. *
  11590. * @param {Request} request The request to check.
  11591. *
  11592. * @private
  11593. */
  11594. function checkAndResetRequest(request) {
  11595. if (
  11596. request.state === RequestState$1.ISSUED ||
  11597. request.state === RequestState$1.ACTIVE
  11598. ) {
  11599. throw new RuntimeError.RuntimeError("The Resource is already being fetched.");
  11600. }
  11601. request.state = RequestState$1.UNISSUED;
  11602. request.deferred = undefined;
  11603. }
  11604. /**
  11605. * This combines a map of query parameters.
  11606. *
  11607. * @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
  11608. * @param {Object} q2 The second map of query parameters.
  11609. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
  11610. *
  11611. * @returns {Object} The combined map of query parameters.
  11612. *
  11613. * @example
  11614. * var q1 = {
  11615. * a: 1,
  11616. * b: 2
  11617. * };
  11618. * var q2 = {
  11619. * a: 3,
  11620. * c: 4
  11621. * };
  11622. * var q3 = {
  11623. * b: [5, 6],
  11624. * d: 7
  11625. * }
  11626. *
  11627. * // Returns
  11628. * // {
  11629. * // a: [1, 3],
  11630. * // b: 2,
  11631. * // c: 4
  11632. * // };
  11633. * combineQueryParameters(q1, q2, true);
  11634. *
  11635. * // Returns
  11636. * // {
  11637. * // a: 1,
  11638. * // b: 2,
  11639. * // c: 4
  11640. * // };
  11641. * combineQueryParameters(q1, q2, false);
  11642. *
  11643. * // Returns
  11644. * // {
  11645. * // a: 1,
  11646. * // b: [2, 5, 6],
  11647. * // d: 7
  11648. * // };
  11649. * combineQueryParameters(q1, q3, true);
  11650. *
  11651. * // Returns
  11652. * // {
  11653. * // a: 1,
  11654. * // b: 2,
  11655. * // d: 7
  11656. * // };
  11657. * combineQueryParameters(q1, q3, false);
  11658. *
  11659. * @private
  11660. */
  11661. function combineQueryParameters(q1, q2, preserveQueryParameters) {
  11662. if (!preserveQueryParameters) {
  11663. return combine(q1, q2);
  11664. }
  11665. var result = clone(q1, true);
  11666. for (var param in q2) {
  11667. if (q2.hasOwnProperty(param)) {
  11668. var value = result[param];
  11669. var q2Value = q2[param];
  11670. if (when.defined(value)) {
  11671. if (!Array.isArray(value)) {
  11672. value = result[param] = [value];
  11673. }
  11674. result[param] = value.concat(q2Value);
  11675. } else {
  11676. result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
  11677. }
  11678. }
  11679. }
  11680. return result;
  11681. }
  11682. /**
  11683. * 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.
  11684. *
  11685. * @alias Resource
  11686. * @constructor
  11687. *
  11688. * @param {String|Object} options A url or an object with the following properties
  11689. * @param {String} options.url The url of the resource.
  11690. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11691. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11692. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11693. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  11694. * @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.
  11695. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11696. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11697. *
  11698. * @example
  11699. * function refreshTokenRetryCallback(resource, error) {
  11700. * if (error.statusCode === 403) {
  11701. * // 403 status code means a new token should be generated
  11702. * return getNewAccessToken()
  11703. * .then(function(token) {
  11704. * resource.queryParameters.access_token = token;
  11705. * return true;
  11706. * })
  11707. * .otherwise(function() {
  11708. * return false;
  11709. * });
  11710. * }
  11711. *
  11712. * return false;
  11713. * }
  11714. *
  11715. * var resource = new Resource({
  11716. * url: 'http://server.com/path/to/resource.json',
  11717. * proxy: new DefaultProxy('/proxy/'),
  11718. * headers: {
  11719. * 'X-My-Header': 'valueOfHeader'
  11720. * },
  11721. * queryParameters: {
  11722. * 'access_token': '123-435-456-000'
  11723. * },
  11724. * retryCallback: refreshTokenRetryCallback,
  11725. * retryAttempts: 1
  11726. * });
  11727. */
  11728. function Resource(options) {
  11729. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  11730. if (typeof options === "string") {
  11731. options = {
  11732. url: options,
  11733. };
  11734. }
  11735. //>>includeStart('debug', pragmas.debug);
  11736. Check.Check.typeOf.string("options.url", options.url);
  11737. //>>includeEnd('debug');
  11738. this._url = undefined;
  11739. this._templateValues = defaultClone(options.templateValues, {});
  11740. this._queryParameters = defaultClone(options.queryParameters, {});
  11741. /**
  11742. * Additional HTTP headers that will be sent with the request.
  11743. *
  11744. * @type {Object}
  11745. */
  11746. this.headers = defaultClone(options.headers, {});
  11747. /**
  11748. * A Request object that will be used. Intended for internal use only.
  11749. *
  11750. * @type {Request}
  11751. */
  11752. this.request = when.defaultValue(options.request, new Request());
  11753. /**
  11754. * A proxy to be used when loading the resource.
  11755. *
  11756. * @type {Proxy}
  11757. */
  11758. this.proxy = options.proxy;
  11759. /**
  11760. * 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.
  11761. *
  11762. * @type {Function}
  11763. */
  11764. this.retryCallback = options.retryCallback;
  11765. /**
  11766. * The number of times the retryCallback should be called before giving up.
  11767. *
  11768. * @type {Number}
  11769. */
  11770. this.retryAttempts = when.defaultValue(options.retryAttempts, 0);
  11771. this._retryCount = 0;
  11772. var uri = new URI(options.url);
  11773. parseQuery(uri, this, true, true);
  11774. // Remove the fragment as it's not sent with a request
  11775. uri.fragment = undefined;
  11776. this._url = uri.toString();
  11777. }
  11778. /**
  11779. * A helper function to create a resource depending on whether we have a String or a Resource
  11780. *
  11781. * @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
  11782. *
  11783. * @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
  11784. *
  11785. * @private
  11786. */
  11787. Resource.createIfNeeded = function (resource) {
  11788. if (resource instanceof Resource) {
  11789. // Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
  11790. // be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
  11791. // 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
  11792. // in the underlying tiling code the requests for this resource will use it.
  11793. return resource.getDerivedResource({
  11794. request: resource.request,
  11795. });
  11796. }
  11797. if (typeof resource !== "string") {
  11798. return resource;
  11799. }
  11800. return new Resource({
  11801. url: resource,
  11802. });
  11803. };
  11804. var supportsImageBitmapOptionsPromise;
  11805. /**
  11806. * A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
  11807. *
  11808. * @returns {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
  11809. *
  11810. * @private
  11811. */
  11812. Resource.supportsImageBitmapOptions = function () {
  11813. // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
  11814. // know if this browser supports passing options to the createImageBitmap function.
  11815. // https://github.com/whatwg/html/pull/4248
  11816. if (when.defined(supportsImageBitmapOptionsPromise)) {
  11817. return supportsImageBitmapOptionsPromise;
  11818. }
  11819. if (typeof createImageBitmap !== "function") {
  11820. supportsImageBitmapOptionsPromise = when.when.resolve(false);
  11821. return supportsImageBitmapOptionsPromise;
  11822. }
  11823. var imageDataUri =
  11824. "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWP4////fwAJ+wP9CNHoHgAAAABJRU5ErkJggg==";
  11825. supportsImageBitmapOptionsPromise = Resource.fetchBlob({
  11826. url: imageDataUri,
  11827. })
  11828. .then(function (blob) {
  11829. return createImageBitmap(blob, {
  11830. imageOrientation: "flipY",
  11831. premultiplyAlpha: "none",
  11832. });
  11833. })
  11834. .then(function (imageBitmap) {
  11835. return true;
  11836. })
  11837. .otherwise(function () {
  11838. return false;
  11839. });
  11840. return supportsImageBitmapOptionsPromise;
  11841. };
  11842. Object.defineProperties(Resource, {
  11843. /**
  11844. * Returns true if blobs are supported.
  11845. *
  11846. * @memberof Resource
  11847. * @type {Boolean}
  11848. *
  11849. * @readonly
  11850. */
  11851. isBlobSupported: {
  11852. get: function () {
  11853. return xhrBlobSupported;
  11854. },
  11855. },
  11856. });
  11857. Object.defineProperties(Resource.prototype, {
  11858. /**
  11859. * Query parameters appended to the url.
  11860. *
  11861. * @memberof Resource.prototype
  11862. * @type {Object}
  11863. *
  11864. * @readonly
  11865. */
  11866. queryParameters: {
  11867. get: function () {
  11868. return this._queryParameters;
  11869. },
  11870. },
  11871. /**
  11872. * The key/value pairs used to replace template parameters in the url.
  11873. *
  11874. * @memberof Resource.prototype
  11875. * @type {Object}
  11876. *
  11877. * @readonly
  11878. */
  11879. templateValues: {
  11880. get: function () {
  11881. return this._templateValues;
  11882. },
  11883. },
  11884. /**
  11885. * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
  11886. *
  11887. * @memberof Resource.prototype
  11888. * @type {String}
  11889. */
  11890. url: {
  11891. get: function () {
  11892. return this.getUrlComponent(true, true);
  11893. },
  11894. set: function (value) {
  11895. var uri = new URI(value);
  11896. parseQuery(uri, this, false);
  11897. // Remove the fragment as it's not sent with a request
  11898. uri.fragment = undefined;
  11899. this._url = uri.toString();
  11900. },
  11901. },
  11902. /**
  11903. * The file extension of the resource.
  11904. *
  11905. * @memberof Resource.prototype
  11906. * @type {String}
  11907. *
  11908. * @readonly
  11909. */
  11910. extension: {
  11911. get: function () {
  11912. return getExtensionFromUri(this._url);
  11913. },
  11914. },
  11915. /**
  11916. * True if the Resource refers to a data URI.
  11917. *
  11918. * @memberof Resource.prototype
  11919. * @type {Boolean}
  11920. */
  11921. isDataUri: {
  11922. get: function () {
  11923. return isDataUri(this._url);
  11924. },
  11925. },
  11926. /**
  11927. * True if the Resource refers to a blob URI.
  11928. *
  11929. * @memberof Resource.prototype
  11930. * @type {Boolean}
  11931. */
  11932. isBlobUri: {
  11933. get: function () {
  11934. return isBlobUri(this._url);
  11935. },
  11936. },
  11937. /**
  11938. * True if the Resource refers to a cross origin URL.
  11939. *
  11940. * @memberof Resource.prototype
  11941. * @type {Boolean}
  11942. */
  11943. isCrossOriginUrl: {
  11944. get: function () {
  11945. return isCrossOriginUrl(this._url);
  11946. },
  11947. },
  11948. /**
  11949. * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
  11950. *
  11951. * @memberof Resource.prototype
  11952. * @type {Boolean}
  11953. */
  11954. hasHeaders: {
  11955. get: function () {
  11956. return Object.keys(this.headers).length > 0;
  11957. },
  11958. },
  11959. });
  11960. /**
  11961. * Override Object#toString so that implicit string conversion gives the
  11962. * complete URL represented by this Resource.
  11963. *
  11964. * @returns {String} The URL represented by this Resource
  11965. */
  11966. Resource.prototype.toString = function () {
  11967. return this.getUrlComponent(true, true);
  11968. };
  11969. /**
  11970. * Returns the url, optional with the query string and processed by a proxy.
  11971. *
  11972. * @param {Boolean} [query=false] If true, the query string is included.
  11973. * @param {Boolean} [proxy=false] If true, the url is processed by the proxy object, if defined.
  11974. *
  11975. * @returns {String} The url with all the requested components.
  11976. */
  11977. Resource.prototype.getUrlComponent = function (query, proxy) {
  11978. if (this.isDataUri) {
  11979. return this._url;
  11980. }
  11981. var uri = new URI(this._url);
  11982. if (query) {
  11983. stringifyQuery(uri, this);
  11984. }
  11985. // objectToQuery escapes the placeholders. Undo that.
  11986. var url = uri.toString().replace(/%7B/g, "{").replace(/%7D/g, "}");
  11987. var templateValues = this._templateValues;
  11988. url = url.replace(/{(.*?)}/g, function (match, key) {
  11989. var replacement = templateValues[key];
  11990. if (when.defined(replacement)) {
  11991. // use the replacement value from templateValues if there is one...
  11992. return encodeURIComponent(replacement);
  11993. }
  11994. // otherwise leave it unchanged
  11995. return match;
  11996. });
  11997. if (proxy && when.defined(this.proxy)) {
  11998. url = this.proxy.getURL(url);
  11999. }
  12000. return url;
  12001. };
  12002. /**
  12003. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  12004. * 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.
  12005. *
  12006. * @param {Object} params The query parameters
  12007. * @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.
  12008. */
  12009. Resource.prototype.setQueryParameters = function (params, useAsDefault) {
  12010. if (useAsDefault) {
  12011. this._queryParameters = combineQueryParameters(
  12012. this._queryParameters,
  12013. params,
  12014. false
  12015. );
  12016. } else {
  12017. this._queryParameters = combineQueryParameters(
  12018. params,
  12019. this._queryParameters,
  12020. false
  12021. );
  12022. }
  12023. };
  12024. /**
  12025. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  12026. * as opposed to adding them one at a time to the queryParameters property.
  12027. *
  12028. * @param {Object} params The query parameters
  12029. */
  12030. Resource.prototype.appendQueryParameters = function (params) {
  12031. this._queryParameters = combineQueryParameters(
  12032. params,
  12033. this._queryParameters,
  12034. true
  12035. );
  12036. };
  12037. /**
  12038. * Combines the specified object and the existing template values. This allows you to add many values at once,
  12039. * 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.
  12040. *
  12041. * @param {Object} template The template values
  12042. * @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.
  12043. */
  12044. Resource.prototype.setTemplateValues = function (template, useAsDefault) {
  12045. if (useAsDefault) {
  12046. this._templateValues = combine(this._templateValues, template);
  12047. } else {
  12048. this._templateValues = combine(template, this._templateValues);
  12049. }
  12050. };
  12051. /**
  12052. * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
  12053. *
  12054. * @param {Object} options An object with the following properties
  12055. * @param {String} [options.url] The url that will be resolved relative to the url of the current instance.
  12056. * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
  12057. * @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.
  12058. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12059. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12060. * @param {Resource.RetryCallback} [options.retryCallback] The function to call when loading the resource fails.
  12061. * @param {Number} [options.retryAttempts] The number of times the retryCallback should be called before giving up.
  12062. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12063. * @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.
  12064. *
  12065. * @returns {Resource} The resource derived from the current one.
  12066. */
  12067. Resource.prototype.getDerivedResource = function (options) {
  12068. var resource = this.clone();
  12069. resource._retryCount = 0;
  12070. if (when.defined(options.url)) {
  12071. var uri = new URI(options.url);
  12072. var preserveQueryParameters = when.defaultValue(
  12073. options.preserveQueryParameters,
  12074. false
  12075. );
  12076. parseQuery(uri, resource, true, preserveQueryParameters);
  12077. // Remove the fragment as it's not sent with a request
  12078. uri.fragment = undefined;
  12079. resource._url = uri.resolve(new URI(getAbsoluteUri(this._url))).toString();
  12080. }
  12081. if (when.defined(options.queryParameters)) {
  12082. resource._queryParameters = combine(
  12083. options.queryParameters,
  12084. resource._queryParameters
  12085. );
  12086. }
  12087. if (when.defined(options.templateValues)) {
  12088. resource._templateValues = combine(
  12089. options.templateValues,
  12090. resource.templateValues
  12091. );
  12092. }
  12093. if (when.defined(options.headers)) {
  12094. resource.headers = combine(options.headers, resource.headers);
  12095. }
  12096. if (when.defined(options.proxy)) {
  12097. resource.proxy = options.proxy;
  12098. }
  12099. if (when.defined(options.request)) {
  12100. resource.request = options.request;
  12101. }
  12102. if (when.defined(options.retryCallback)) {
  12103. resource.retryCallback = options.retryCallback;
  12104. }
  12105. if (when.defined(options.retryAttempts)) {
  12106. resource.retryAttempts = options.retryAttempts;
  12107. }
  12108. return resource;
  12109. };
  12110. /**
  12111. * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
  12112. *
  12113. * @param {Error} [error] The error that was encountered.
  12114. *
  12115. * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
  12116. *
  12117. * @private
  12118. */
  12119. Resource.prototype.retryOnError = function (error) {
  12120. var retryCallback = this.retryCallback;
  12121. if (
  12122. typeof retryCallback !== "function" ||
  12123. this._retryCount >= this.retryAttempts
  12124. ) {
  12125. return when.when(false);
  12126. }
  12127. var that = this;
  12128. return when.when(retryCallback(this, error)).then(function (result) {
  12129. ++that._retryCount;
  12130. return result;
  12131. });
  12132. };
  12133. /**
  12134. * Duplicates a Resource instance.
  12135. *
  12136. * @param {Resource} [result] The object onto which to store the result.
  12137. *
  12138. * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
  12139. */
  12140. Resource.prototype.clone = function (result) {
  12141. if (!when.defined(result)) {
  12142. result = new Resource({
  12143. url: this._url,
  12144. });
  12145. }
  12146. result._url = this._url;
  12147. result._queryParameters = clone(this._queryParameters);
  12148. result._templateValues = clone(this._templateValues);
  12149. result.headers = clone(this.headers);
  12150. result.proxy = this.proxy;
  12151. result.retryCallback = this.retryCallback;
  12152. result.retryAttempts = this.retryAttempts;
  12153. result._retryCount = 0;
  12154. result.request = this.request.clone();
  12155. return result;
  12156. };
  12157. /**
  12158. * Returns the base path of the Resource.
  12159. *
  12160. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  12161. *
  12162. * @returns {String} The base URI of the resource
  12163. */
  12164. Resource.prototype.getBaseUri = function (includeQuery) {
  12165. return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  12166. };
  12167. /**
  12168. * Appends a forward slash to the URL.
  12169. */
  12170. Resource.prototype.appendForwardSlash = function () {
  12171. this._url = appendForwardSlash(this._url);
  12172. };
  12173. /**
  12174. * Asynchronously loads the resource as raw binary data. Returns a promise that will resolve to
  12175. * an ArrayBuffer once loaded, or reject if the resource failed to load. The data is loaded
  12176. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12177. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12178. *
  12179. * @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.
  12180. *
  12181. * @example
  12182. * // load a single URL asynchronously
  12183. * resource.fetchArrayBuffer().then(function(arrayBuffer) {
  12184. * // use the data
  12185. * }).otherwise(function(error) {
  12186. * // an error occurred
  12187. * });
  12188. *
  12189. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12190. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12191. */
  12192. Resource.prototype.fetchArrayBuffer = function () {
  12193. return this.fetch({
  12194. responseType: "arraybuffer",
  12195. });
  12196. };
  12197. /**
  12198. * Creates a Resource and calls fetchArrayBuffer() on it.
  12199. *
  12200. * @param {String|Object} options A url or an object with the following properties
  12201. * @param {String} options.url The url of the resource.
  12202. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12203. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12204. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12205. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12206. * @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.
  12207. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12208. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12209. * @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.
  12210. */
  12211. Resource.fetchArrayBuffer = function (options) {
  12212. var resource = new Resource(options);
  12213. return resource.fetchArrayBuffer();
  12214. };
  12215. /**
  12216. * Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
  12217. * a Blob once loaded, or reject if the resource failed to load. The data is loaded
  12218. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12219. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12220. *
  12221. * @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.
  12222. *
  12223. * @example
  12224. * // load a single URL asynchronously
  12225. * resource.fetchBlob().then(function(blob) {
  12226. * // use the data
  12227. * }).otherwise(function(error) {
  12228. * // an error occurred
  12229. * });
  12230. *
  12231. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12232. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12233. */
  12234. Resource.prototype.fetchBlob = function () {
  12235. return this.fetch({
  12236. responseType: "blob",
  12237. });
  12238. };
  12239. /**
  12240. * Creates a Resource and calls fetchBlob() on it.
  12241. *
  12242. * @param {String|Object} options A url or an object with the following properties
  12243. * @param {String} options.url The url of the resource.
  12244. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12245. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12246. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12247. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12248. * @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.
  12249. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12250. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12251. * @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.
  12252. */
  12253. Resource.fetchBlob = function (options) {
  12254. var resource = new Resource(options);
  12255. return resource.fetchBlob();
  12256. };
  12257. /**
  12258. * Asynchronously loads the given image resource. Returns a promise that will resolve to
  12259. * 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
  12260. * {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
  12261. *
  12262. * @param {Object} [options] An object with the following properties.
  12263. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  12264. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  12265. * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  12266. * @returns {Promise.<ImageBitmap>|Promise.<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.
  12267. *
  12268. *
  12269. * @example
  12270. * // load a single image asynchronously
  12271. * resource.fetchImage().then(function(image) {
  12272. * // use the loaded image
  12273. * }).otherwise(function(error) {
  12274. * // an error occurred
  12275. * });
  12276. *
  12277. * // load several images in parallel
  12278. * when.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
  12279. * // images is an array containing all the loaded images
  12280. * });
  12281. *
  12282. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12283. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12284. */
  12285. Resource.prototype.fetchImage = function (options) {
  12286. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  12287. var preferImageBitmap = when.defaultValue(options.preferImageBitmap, false);
  12288. var preferBlob = when.defaultValue(options.preferBlob, false);
  12289. var flipY = when.defaultValue(options.flipY, false);
  12290. checkAndResetRequest(this.request);
  12291. // We try to load the image normally if
  12292. // 1. Blobs aren't supported
  12293. // 2. It's a data URI
  12294. // 3. It's a blob URI
  12295. // 4. It doesn't have request headers and we preferBlob is false
  12296. if (
  12297. !xhrBlobSupported ||
  12298. this.isDataUri ||
  12299. this.isBlobUri ||
  12300. (!this.hasHeaders && !preferBlob)
  12301. ) {
  12302. return fetchImage({
  12303. resource: this,
  12304. flipY: flipY,
  12305. preferImageBitmap: preferImageBitmap,
  12306. });
  12307. }
  12308. var blobPromise = this.fetchBlob();
  12309. if (!when.defined(blobPromise)) {
  12310. return;
  12311. }
  12312. var supportsImageBitmap;
  12313. var useImageBitmap;
  12314. var generatedBlobResource;
  12315. var generatedBlob;
  12316. return Resource.supportsImageBitmapOptions()
  12317. .then(function (result) {
  12318. supportsImageBitmap = result;
  12319. useImageBitmap = supportsImageBitmap && preferImageBitmap;
  12320. return blobPromise;
  12321. })
  12322. .then(function (blob) {
  12323. if (!when.defined(blob)) {
  12324. return;
  12325. }
  12326. generatedBlob = blob;
  12327. if (useImageBitmap) {
  12328. return Resource.createImageBitmapFromBlob(blob, {
  12329. flipY: flipY,
  12330. premultiplyAlpha: false,
  12331. });
  12332. }
  12333. var blobUrl = window.URL.createObjectURL(blob);
  12334. generatedBlobResource = new Resource({
  12335. url: blobUrl,
  12336. });
  12337. return fetchImage({
  12338. resource: generatedBlobResource,
  12339. flipY: flipY,
  12340. preferImageBitmap: false,
  12341. });
  12342. })
  12343. .then(function (image) {
  12344. if (!when.defined(image)) {
  12345. return;
  12346. }
  12347. // The blob object may be needed for use by a TileDiscardPolicy,
  12348. // so attach it to the image.
  12349. image.blob = generatedBlob;
  12350. if (useImageBitmap) {
  12351. return image;
  12352. }
  12353. window.URL.revokeObjectURL(generatedBlobResource.url);
  12354. return image;
  12355. })
  12356. .otherwise(function (error) {
  12357. if (when.defined(generatedBlobResource)) {
  12358. window.URL.revokeObjectURL(generatedBlobResource.url);
  12359. }
  12360. // If the blob load succeeded but the image decode failed, attach the blob
  12361. // to the error object for use by a TileDiscardPolicy.
  12362. // In particular, BingMapsImageryProvider uses this to detect the
  12363. // zero-length response that is returned when a tile is not available.
  12364. error.blob = generatedBlob;
  12365. return when.when.reject(error);
  12366. });
  12367. };
  12368. /**
  12369. * Fetches an image and returns a promise to it.
  12370. *
  12371. * @param {Object} [options] An object with the following properties.
  12372. * @param {Resource} [options.resource] Resource object that points to an image to fetch.
  12373. * @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  12374. * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  12375. *
  12376. * @private
  12377. */
  12378. function fetchImage(options) {
  12379. var resource = options.resource;
  12380. var flipY = options.flipY;
  12381. var preferImageBitmap = options.preferImageBitmap;
  12382. var request = resource.request;
  12383. request.url = resource.url;
  12384. request.requestFunction = function () {
  12385. var crossOrigin = false;
  12386. // data URIs can't have crossorigin set.
  12387. if (!resource.isDataUri && !resource.isBlobUri) {
  12388. crossOrigin = resource.isCrossOriginUrl;
  12389. }
  12390. var deferred = when.when.defer();
  12391. Resource._Implementations.createImage(
  12392. request,
  12393. crossOrigin,
  12394. deferred,
  12395. flipY,
  12396. preferImageBitmap
  12397. );
  12398. return deferred.promise;
  12399. };
  12400. var promise = RequestScheduler.request(request);
  12401. if (!when.defined(promise)) {
  12402. return;
  12403. }
  12404. return promise.otherwise(function (e) {
  12405. // Don't retry cancelled or otherwise aborted requests
  12406. if (request.state !== RequestState$1.FAILED) {
  12407. return when.when.reject(e);
  12408. }
  12409. return resource.retryOnError(e).then(function (retry) {
  12410. if (retry) {
  12411. // Reset request so it can try again
  12412. request.state = RequestState$1.UNISSUED;
  12413. request.deferred = undefined;
  12414. return fetchImage({
  12415. resource: resource,
  12416. flipY: flipY,
  12417. preferImageBitmap: preferImageBitmap,
  12418. });
  12419. }
  12420. return when.when.reject(e);
  12421. });
  12422. });
  12423. }
  12424. /**
  12425. * Creates a Resource and calls fetchImage() on it.
  12426. *
  12427. * @param {String|Object} options A url or an object with the following properties
  12428. * @param {String} options.url The url of the resource.
  12429. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12430. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12431. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12432. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12433. * @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>.
  12434. * @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.
  12435. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12436. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12437. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  12438. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  12439. * @returns {Promise.<ImageBitmap>|Promise.<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.
  12440. */
  12441. Resource.fetchImage = function (options) {
  12442. var resource = new Resource(options);
  12443. return resource.fetchImage({
  12444. flipY: options.flipY,
  12445. preferBlob: options.preferBlob,
  12446. preferImageBitmap: options.preferImageBitmap,
  12447. });
  12448. };
  12449. /**
  12450. * Asynchronously loads the given resource as text. Returns a promise that will resolve to
  12451. * a String once loaded, or reject if the resource failed to load. The data is loaded
  12452. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12453. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12454. *
  12455. * @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.
  12456. *
  12457. * @example
  12458. * // load text from a URL, setting a custom header
  12459. * var resource = new Resource({
  12460. * url: 'http://someUrl.com/someJson.txt',
  12461. * headers: {
  12462. * 'X-Custom-Header' : 'some value'
  12463. * }
  12464. * });
  12465. * resource.fetchText().then(function(text) {
  12466. * // Do something with the text
  12467. * }).otherwise(function(error) {
  12468. * // an error occurred
  12469. * });
  12470. *
  12471. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  12472. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12473. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12474. */
  12475. Resource.prototype.fetchText = function () {
  12476. return this.fetch({
  12477. responseType: "text",
  12478. });
  12479. };
  12480. /**
  12481. * Creates a Resource and calls fetchText() on it.
  12482. *
  12483. * @param {String|Object} options A url or an object with the following properties
  12484. * @param {String} options.url The url of the resource.
  12485. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12486. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12487. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12488. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12489. * @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.
  12490. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12491. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12492. * @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.
  12493. */
  12494. Resource.fetchText = function (options) {
  12495. var resource = new Resource(options);
  12496. return resource.fetchText();
  12497. };
  12498. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  12499. /**
  12500. * Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
  12501. * a JSON object once loaded, or reject if the resource failed to load. The data is loaded
  12502. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12503. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  12504. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  12505. * already specified.
  12506. *
  12507. * @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.
  12508. *
  12509. *
  12510. * @example
  12511. * resource.fetchJson().then(function(jsonData) {
  12512. * // Do something with the JSON object
  12513. * }).otherwise(function(error) {
  12514. * // an error occurred
  12515. * });
  12516. *
  12517. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12518. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12519. */
  12520. Resource.prototype.fetchJson = function () {
  12521. var promise = this.fetch({
  12522. responseType: "text",
  12523. headers: {
  12524. Accept: "application/json,*/*;q=0.01",
  12525. },
  12526. });
  12527. if (!when.defined(promise)) {
  12528. return undefined;
  12529. }
  12530. return promise.then(function (value) {
  12531. if (!when.defined(value)) {
  12532. return;
  12533. }
  12534. return JSON.parse(value);
  12535. });
  12536. };
  12537. /**
  12538. * Creates a Resource and calls fetchJson() on it.
  12539. *
  12540. * @param {String|Object} options A url or an object with the following properties
  12541. * @param {String} options.url The url of the resource.
  12542. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12543. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12544. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12545. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12546. * @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.
  12547. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12548. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12549. * @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.
  12550. */
  12551. Resource.fetchJson = function (options) {
  12552. var resource = new Resource(options);
  12553. return resource.fetchJson();
  12554. };
  12555. /**
  12556. * Asynchronously loads the given resource as XML. Returns a promise that will resolve to
  12557. * an XML Document once loaded, or reject if the resource failed to load. The data is loaded
  12558. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12559. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12560. *
  12561. * @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.
  12562. *
  12563. *
  12564. * @example
  12565. * // load XML from a URL, setting a custom header
  12566. * Cesium.loadXML('http://someUrl.com/someXML.xml', {
  12567. * 'X-Custom-Header' : 'some value'
  12568. * }).then(function(document) {
  12569. * // Do something with the document
  12570. * }).otherwise(function(error) {
  12571. * // an error occurred
  12572. * });
  12573. *
  12574. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  12575. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12576. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12577. */
  12578. Resource.prototype.fetchXML = function () {
  12579. return this.fetch({
  12580. responseType: "document",
  12581. overrideMimeType: "text/xml",
  12582. });
  12583. };
  12584. /**
  12585. * Creates a Resource and calls fetchXML() on it.
  12586. *
  12587. * @param {String|Object} options A url or an object with the following properties
  12588. * @param {String} options.url The url of the resource.
  12589. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12590. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12591. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12592. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12593. * @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.
  12594. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12595. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12596. * @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.
  12597. */
  12598. Resource.fetchXML = function (options) {
  12599. var resource = new Resource(options);
  12600. return resource.fetchXML();
  12601. };
  12602. /**
  12603. * Requests a resource using JSONP.
  12604. *
  12605. * @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
  12606. * @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.
  12607. *
  12608. *
  12609. * @example
  12610. * // load a data asynchronously
  12611. * resource.fetchJsonp().then(function(data) {
  12612. * // use the loaded data
  12613. * }).otherwise(function(error) {
  12614. * // an error occurred
  12615. * });
  12616. *
  12617. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12618. */
  12619. Resource.prototype.fetchJsonp = function (callbackParameterName) {
  12620. callbackParameterName = when.defaultValue(callbackParameterName, "callback");
  12621. checkAndResetRequest(this.request);
  12622. //generate a unique function name
  12623. var functionName;
  12624. do {
  12625. functionName = "loadJsonp" + Math.random().toString().substring(2, 8);
  12626. } while (when.defined(window[functionName]));
  12627. return fetchJsonp(this, callbackParameterName, functionName);
  12628. };
  12629. function fetchJsonp(resource, callbackParameterName, functionName) {
  12630. var callbackQuery = {};
  12631. callbackQuery[callbackParameterName] = functionName;
  12632. resource.setQueryParameters(callbackQuery);
  12633. var request = resource.request;
  12634. request.url = resource.url;
  12635. request.requestFunction = function () {
  12636. var deferred = when.when.defer();
  12637. //assign a function with that name in the global scope
  12638. window[functionName] = function (data) {
  12639. deferred.resolve(data);
  12640. try {
  12641. delete window[functionName];
  12642. } catch (e) {
  12643. window[functionName] = undefined;
  12644. }
  12645. };
  12646. Resource._Implementations.loadAndExecuteScript(
  12647. resource.url,
  12648. functionName,
  12649. deferred
  12650. );
  12651. return deferred.promise;
  12652. };
  12653. var promise = RequestScheduler.request(request);
  12654. if (!when.defined(promise)) {
  12655. return;
  12656. }
  12657. return promise.otherwise(function (e) {
  12658. if (request.state !== RequestState$1.FAILED) {
  12659. return when.when.reject(e);
  12660. }
  12661. return resource.retryOnError(e).then(function (retry) {
  12662. if (retry) {
  12663. // Reset request so it can try again
  12664. request.state = RequestState$1.UNISSUED;
  12665. request.deferred = undefined;
  12666. return fetchJsonp(resource, callbackParameterName, functionName);
  12667. }
  12668. return when.when.reject(e);
  12669. });
  12670. });
  12671. }
  12672. /**
  12673. * Creates a Resource from a URL and calls fetchJsonp() on it.
  12674. *
  12675. * @param {String|Object} options A url or an object with the following properties
  12676. * @param {String} options.url The url of the resource.
  12677. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12678. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12679. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12680. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12681. * @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.
  12682. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12683. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12684. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
  12685. * @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.
  12686. */
  12687. Resource.fetchJsonp = function (options) {
  12688. var resource = new Resource(options);
  12689. return resource.fetchJsonp(options.callbackParameterName);
  12690. };
  12691. /**
  12692. * @private
  12693. */
  12694. Resource.prototype._makeRequest = function (options) {
  12695. var resource = this;
  12696. checkAndResetRequest(resource.request);
  12697. var request = resource.request;
  12698. request.url = resource.url;
  12699. request.requestFunction = function () {
  12700. var responseType = options.responseType;
  12701. var headers = combine(options.headers, resource.headers);
  12702. var overrideMimeType = options.overrideMimeType;
  12703. var method = options.method;
  12704. var data = options.data;
  12705. var deferred = when.when.defer();
  12706. var xhr = Resource._Implementations.loadWithXhr(
  12707. resource.url,
  12708. responseType,
  12709. method,
  12710. data,
  12711. headers,
  12712. deferred,
  12713. overrideMimeType
  12714. );
  12715. if (when.defined(xhr) && when.defined(xhr.abort)) {
  12716. request.cancelFunction = function () {
  12717. xhr.abort();
  12718. };
  12719. }
  12720. return deferred.promise;
  12721. };
  12722. var promise = RequestScheduler.request(request);
  12723. if (!when.defined(promise)) {
  12724. return;
  12725. }
  12726. return promise
  12727. .then(function (data) {
  12728. // explicitly set to undefined to ensure GC of request response data. See #8843
  12729. request.cancelFunction = undefined;
  12730. return data;
  12731. })
  12732. .otherwise(function (e) {
  12733. request.cancelFunction = undefined;
  12734. if (request.state !== RequestState$1.FAILED) {
  12735. return when.when.reject(e);
  12736. }
  12737. return resource.retryOnError(e).then(function (retry) {
  12738. if (retry) {
  12739. // Reset request so it can try again
  12740. request.state = RequestState$1.UNISSUED;
  12741. request.deferred = undefined;
  12742. return resource.fetch(options);
  12743. }
  12744. return when.when.reject(e);
  12745. });
  12746. });
  12747. };
  12748. var dataUriRegex$1 = /^data:(.*?)(;base64)?,(.*)$/;
  12749. function decodeDataUriText(isBase64, data) {
  12750. var result = decodeURIComponent(data);
  12751. if (isBase64) {
  12752. return atob(result);
  12753. }
  12754. return result;
  12755. }
  12756. function decodeDataUriArrayBuffer(isBase64, data) {
  12757. var byteString = decodeDataUriText(isBase64, data);
  12758. var buffer = new ArrayBuffer(byteString.length);
  12759. var view = new Uint8Array(buffer);
  12760. for (var i = 0; i < byteString.length; i++) {
  12761. view[i] = byteString.charCodeAt(i);
  12762. }
  12763. return buffer;
  12764. }
  12765. function decodeDataUri(dataUriRegexResult, responseType) {
  12766. responseType = when.defaultValue(responseType, "");
  12767. var mimeType = dataUriRegexResult[1];
  12768. var isBase64 = !!dataUriRegexResult[2];
  12769. var data = dataUriRegexResult[3];
  12770. switch (responseType) {
  12771. case "":
  12772. case "text":
  12773. return decodeDataUriText(isBase64, data);
  12774. case "arraybuffer":
  12775. return decodeDataUriArrayBuffer(isBase64, data);
  12776. case "blob":
  12777. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  12778. return new Blob([buffer], {
  12779. type: mimeType,
  12780. });
  12781. case "document":
  12782. var parser = new DOMParser();
  12783. return parser.parseFromString(
  12784. decodeDataUriText(isBase64, data),
  12785. mimeType
  12786. );
  12787. case "json":
  12788. return JSON.parse(decodeDataUriText(isBase64, data));
  12789. default:
  12790. //>>includeStart('debug', pragmas.debug);
  12791. throw new Check.DeveloperError("Unhandled responseType: " + responseType);
  12792. //>>includeEnd('debug');
  12793. }
  12794. }
  12795. /**
  12796. * Asynchronously loads the given resource. Returns a promise that will resolve to
  12797. * the result once loaded, or reject if the resource failed to load. The data is loaded
  12798. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12799. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
  12800. * the more specific functions eg. fetchJson, fetchBlob, etc.
  12801. *
  12802. * @param {Object} [options] Object with the following properties:
  12803. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12804. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12805. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12806. * @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.
  12807. *
  12808. *
  12809. * @example
  12810. * resource.fetch()
  12811. * .then(function(body) {
  12812. * // use the data
  12813. * }).otherwise(function(error) {
  12814. * // an error occurred
  12815. * });
  12816. *
  12817. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12818. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12819. */
  12820. Resource.prototype.fetch = function (options) {
  12821. options = defaultClone(options, {});
  12822. options.method = "GET";
  12823. return this._makeRequest(options);
  12824. };
  12825. /**
  12826. * Creates a Resource from a URL and calls fetch() on it.
  12827. *
  12828. * @param {String|Object} options A url or an object with the following properties
  12829. * @param {String} options.url The url of the resource.
  12830. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12831. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12832. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12833. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12834. * @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.
  12835. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12836. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12837. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12838. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12839. * @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.
  12840. */
  12841. Resource.fetch = function (options) {
  12842. var resource = new Resource(options);
  12843. return resource.fetch({
  12844. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  12845. responseType: options.responseType,
  12846. overrideMimeType: options.overrideMimeType,
  12847. });
  12848. };
  12849. /**
  12850. * Asynchronously deletes the given resource. Returns a promise that will resolve to
  12851. * the result once loaded, or reject if the resource failed to load. The data is loaded
  12852. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12853. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12854. *
  12855. * @param {Object} [options] Object with the following properties:
  12856. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12857. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12858. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12859. * @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.
  12860. *
  12861. *
  12862. * @example
  12863. * resource.delete()
  12864. * .then(function(body) {
  12865. * // use the data
  12866. * }).otherwise(function(error) {
  12867. * // an error occurred
  12868. * });
  12869. *
  12870. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12871. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12872. */
  12873. Resource.prototype.delete = function (options) {
  12874. options = defaultClone(options, {});
  12875. options.method = "DELETE";
  12876. return this._makeRequest(options);
  12877. };
  12878. /**
  12879. * Creates a Resource from a URL and calls delete() on it.
  12880. *
  12881. * @param {String|Object} options A url or an object with the following properties
  12882. * @param {String} options.url The url of the resource.
  12883. * @param {Object} [options.data] Data that is posted with the resource.
  12884. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12885. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12886. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12887. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12888. * @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.
  12889. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12890. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12891. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12892. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12893. * @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.
  12894. */
  12895. Resource.delete = function (options) {
  12896. var resource = new Resource(options);
  12897. return resource.delete({
  12898. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  12899. responseType: options.responseType,
  12900. overrideMimeType: options.overrideMimeType,
  12901. data: options.data,
  12902. });
  12903. };
  12904. /**
  12905. * Asynchronously gets headers the given resource. Returns a promise that will resolve to
  12906. * the result once loaded, or reject if the resource failed to load. The data is loaded
  12907. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12908. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12909. *
  12910. * @param {Object} [options] Object with the following properties:
  12911. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12912. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12913. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12914. * @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.
  12915. *
  12916. *
  12917. * @example
  12918. * resource.head()
  12919. * .then(function(headers) {
  12920. * // use the data
  12921. * }).otherwise(function(error) {
  12922. * // an error occurred
  12923. * });
  12924. *
  12925. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12926. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12927. */
  12928. Resource.prototype.head = function (options) {
  12929. options = defaultClone(options, {});
  12930. options.method = "HEAD";
  12931. return this._makeRequest(options);
  12932. };
  12933. /**
  12934. * Creates a Resource from a URL and calls head() on it.
  12935. *
  12936. * @param {String|Object} options A url or an object with the following properties
  12937. * @param {String} options.url The url of the resource.
  12938. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12939. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12940. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12941. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12942. * @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.
  12943. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12944. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12945. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12946. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12947. * @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.
  12948. */
  12949. Resource.head = function (options) {
  12950. var resource = new Resource(options);
  12951. return resource.head({
  12952. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  12953. responseType: options.responseType,
  12954. overrideMimeType: options.overrideMimeType,
  12955. });
  12956. };
  12957. /**
  12958. * Asynchronously gets options the given resource. Returns a promise that will resolve to
  12959. * the result once loaded, or reject if the resource failed to load. The data is loaded
  12960. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12961. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12962. *
  12963. * @param {Object} [options] Object with the following properties:
  12964. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12965. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12966. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12967. * @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.
  12968. *
  12969. *
  12970. * @example
  12971. * resource.options()
  12972. * .then(function(headers) {
  12973. * // use the data
  12974. * }).otherwise(function(error) {
  12975. * // an error occurred
  12976. * });
  12977. *
  12978. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12979. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12980. */
  12981. Resource.prototype.options = function (options) {
  12982. options = defaultClone(options, {});
  12983. options.method = "OPTIONS";
  12984. return this._makeRequest(options);
  12985. };
  12986. /**
  12987. * Creates a Resource from a URL and calls options() on it.
  12988. *
  12989. * @param {String|Object} options A url or an object with the following properties
  12990. * @param {String} options.url The url of the resource.
  12991. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12992. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12993. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12994. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  12995. * @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.
  12996. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12997. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12998. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12999. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13000. * @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.
  13001. */
  13002. Resource.options = function (options) {
  13003. var resource = new Resource(options);
  13004. return resource.options({
  13005. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  13006. responseType: options.responseType,
  13007. overrideMimeType: options.overrideMimeType,
  13008. });
  13009. };
  13010. /**
  13011. * Asynchronously posts data to the given resource. Returns a promise that will resolve to
  13012. * the result once loaded, or reject if the resource failed to load. The data is loaded
  13013. * using XMLHttpRequest, which means that in order to make requests to another origin,
  13014. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  13015. *
  13016. * @param {Object} data Data that is posted with the resource.
  13017. * @param {Object} [options] Object with the following properties:
  13018. * @param {Object} [options.data] Data that is posted with the resource.
  13019. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  13020. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  13021. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13022. * @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.
  13023. *
  13024. *
  13025. * @example
  13026. * resource.post(data)
  13027. * .then(function(result) {
  13028. * // use the result
  13029. * }).otherwise(function(error) {
  13030. * // an error occurred
  13031. * });
  13032. *
  13033. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  13034. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  13035. */
  13036. Resource.prototype.post = function (data, options) {
  13037. Check.Check.defined("data", data);
  13038. options = defaultClone(options, {});
  13039. options.method = "POST";
  13040. options.data = data;
  13041. return this._makeRequest(options);
  13042. };
  13043. /**
  13044. * Creates a Resource from a URL and calls post() on it.
  13045. *
  13046. * @param {Object} options A url or an object with the following properties
  13047. * @param {String} options.url The url of the resource.
  13048. * @param {Object} options.data Data that is posted with the resource.
  13049. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  13050. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  13051. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  13052. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  13053. * @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.
  13054. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  13055. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  13056. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  13057. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13058. * @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.
  13059. */
  13060. Resource.post = function (options) {
  13061. var resource = new Resource(options);
  13062. return resource.post(options.data, {
  13063. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  13064. responseType: options.responseType,
  13065. overrideMimeType: options.overrideMimeType,
  13066. });
  13067. };
  13068. /**
  13069. * Asynchronously puts data to the given resource. Returns a promise that will resolve to
  13070. * the result once loaded, or reject if the resource failed to load. The data is loaded
  13071. * using XMLHttpRequest, which means that in order to make requests to another origin,
  13072. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  13073. *
  13074. * @param {Object} data Data that is posted with the resource.
  13075. * @param {Object} [options] Object with the following properties:
  13076. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  13077. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  13078. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13079. * @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.
  13080. *
  13081. *
  13082. * @example
  13083. * resource.put(data)
  13084. * .then(function(result) {
  13085. * // use the result
  13086. * }).otherwise(function(error) {
  13087. * // an error occurred
  13088. * });
  13089. *
  13090. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  13091. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  13092. */
  13093. Resource.prototype.put = function (data, options) {
  13094. Check.Check.defined("data", data);
  13095. options = defaultClone(options, {});
  13096. options.method = "PUT";
  13097. options.data = data;
  13098. return this._makeRequest(options);
  13099. };
  13100. /**
  13101. * Creates a Resource from a URL and calls put() on it.
  13102. *
  13103. * @param {Object} options A url or an object with the following properties
  13104. * @param {String} options.url The url of the resource.
  13105. * @param {Object} options.data Data that is posted with the resource.
  13106. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  13107. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  13108. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  13109. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  13110. * @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.
  13111. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  13112. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  13113. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  13114. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13115. * @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.
  13116. */
  13117. Resource.put = function (options) {
  13118. var resource = new Resource(options);
  13119. return resource.put(options.data, {
  13120. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  13121. responseType: options.responseType,
  13122. overrideMimeType: options.overrideMimeType,
  13123. });
  13124. };
  13125. /**
  13126. * Asynchronously patches data to the given resource. Returns a promise that will resolve to
  13127. * the result once loaded, or reject if the resource failed to load. The data is loaded
  13128. * using XMLHttpRequest, which means that in order to make requests to another origin,
  13129. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  13130. *
  13131. * @param {Object} data Data that is posted with the resource.
  13132. * @param {Object} [options] Object with the following properties:
  13133. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  13134. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  13135. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13136. * @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.
  13137. *
  13138. *
  13139. * @example
  13140. * resource.patch(data)
  13141. * .then(function(result) {
  13142. * // use the result
  13143. * }).otherwise(function(error) {
  13144. * // an error occurred
  13145. * });
  13146. *
  13147. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  13148. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  13149. */
  13150. Resource.prototype.patch = function (data, options) {
  13151. Check.Check.defined("data", data);
  13152. options = defaultClone(options, {});
  13153. options.method = "PATCH";
  13154. options.data = data;
  13155. return this._makeRequest(options);
  13156. };
  13157. /**
  13158. * Creates a Resource from a URL and calls patch() on it.
  13159. *
  13160. * @param {Object} options A url or an object with the following properties
  13161. * @param {String} options.url The url of the resource.
  13162. * @param {Object} options.data Data that is posted with the resource.
  13163. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  13164. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  13165. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  13166. * @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
  13167. * @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.
  13168. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  13169. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  13170. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  13171. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  13172. * @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.
  13173. */
  13174. Resource.patch = function (options) {
  13175. var resource = new Resource(options);
  13176. return resource.patch(options.data, {
  13177. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  13178. responseType: options.responseType,
  13179. overrideMimeType: options.overrideMimeType,
  13180. });
  13181. };
  13182. /**
  13183. * Contains implementations of functions that can be replaced for testing
  13184. *
  13185. * @private
  13186. */
  13187. Resource._Implementations = {};
  13188. function loadImageElement(url, crossOrigin, deferred) {
  13189. var image = new Image();
  13190. image.onload = function () {
  13191. deferred.resolve(image);
  13192. };
  13193. image.onerror = function (e) {
  13194. deferred.reject(e);
  13195. };
  13196. if (crossOrigin) {
  13197. if (TrustedServers.contains(url)) {
  13198. image.crossOrigin = "use-credentials";
  13199. } else {
  13200. image.crossOrigin = "";
  13201. }
  13202. }
  13203. image.src = url;
  13204. }
  13205. Resource._Implementations.createImage = function (
  13206. request,
  13207. crossOrigin,
  13208. deferred,
  13209. flipY,
  13210. preferImageBitmap
  13211. ) {
  13212. var url = request.url;
  13213. // Passing an Image to createImageBitmap will force it to run on the main thread
  13214. // since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
  13215. // See:
  13216. // https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
  13217. // https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
  13218. Resource.supportsImageBitmapOptions()
  13219. .then(function (supportsImageBitmap) {
  13220. // We can only use ImageBitmap if we can flip on decode.
  13221. // See: https://github.com/CesiumGS/cesium/pull/7579#issuecomment-466146898
  13222. if (!(supportsImageBitmap && preferImageBitmap)) {
  13223. loadImageElement(url, crossOrigin, deferred);
  13224. return;
  13225. }
  13226. var responseType = "blob";
  13227. var method = "GET";
  13228. var xhrDeferred = when.when.defer();
  13229. var xhr = Resource._Implementations.loadWithXhr(
  13230. url,
  13231. responseType,
  13232. method,
  13233. undefined,
  13234. undefined,
  13235. xhrDeferred,
  13236. undefined,
  13237. undefined,
  13238. undefined
  13239. );
  13240. if (when.defined(xhr) && when.defined(xhr.abort)) {
  13241. request.cancelFunction = function () {
  13242. xhr.abort();
  13243. };
  13244. }
  13245. return xhrDeferred.promise
  13246. .then(function (blob) {
  13247. if (!when.defined(blob)) {
  13248. deferred.reject(
  13249. new RuntimeError.RuntimeError(
  13250. "Successfully retrieved " +
  13251. url +
  13252. " but it contained no content."
  13253. )
  13254. );
  13255. return;
  13256. }
  13257. return Resource.createImageBitmapFromBlob(blob, {
  13258. flipY: flipY,
  13259. premultiplyAlpha: false,
  13260. });
  13261. })
  13262. .then(deferred.resolve);
  13263. })
  13264. .otherwise(deferred.reject);
  13265. };
  13266. /**
  13267. * Wrapper for createImageBitmap
  13268. *
  13269. * @private
  13270. */
  13271. Resource.createImageBitmapFromBlob = function (blob, options) {
  13272. Check.Check.defined("options", options);
  13273. Check.Check.typeOf.bool("options.flipY", options.flipY);
  13274. Check.Check.typeOf.bool("options.premultiplyAlpha", options.premultiplyAlpha);
  13275. return createImageBitmap(blob, {
  13276. imageOrientation: options.flipY ? "flipY" : "none",
  13277. premultiplyAlpha: options.premultiplyAlpha ? "premultiply" : "none",
  13278. });
  13279. };
  13280. function decodeResponse(loadWithHttpResponse, responseType) {
  13281. switch (responseType) {
  13282. case "text":
  13283. return loadWithHttpResponse.toString("utf8");
  13284. case "json":
  13285. return JSON.parse(loadWithHttpResponse.toString("utf8"));
  13286. default:
  13287. return new Uint8Array(loadWithHttpResponse).buffer;
  13288. }
  13289. }
  13290. function loadWithHttpRequest(
  13291. url,
  13292. responseType,
  13293. method,
  13294. data,
  13295. headers,
  13296. deferred,
  13297. overrideMimeType
  13298. ) {
  13299. // Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
  13300. /* eslint-disable no-undef */
  13301. var URL = require("url").parse(url);
  13302. var http = URL.protocol === "https:" ? require("https") : require("http");
  13303. var zlib = require("zlib");
  13304. /* eslint-enable no-undef */
  13305. var options = {
  13306. protocol: URL.protocol,
  13307. hostname: URL.hostname,
  13308. port: URL.port,
  13309. path: URL.path,
  13310. query: URL.query,
  13311. method: method,
  13312. headers: headers,
  13313. };
  13314. http
  13315. .request(options)
  13316. .on("response", function (res) {
  13317. if (res.statusCode < 200 || res.statusCode >= 300) {
  13318. deferred.reject(
  13319. new RequestErrorEvent(res.statusCode, res, res.headers)
  13320. );
  13321. return;
  13322. }
  13323. var chunkArray = [];
  13324. res.on("data", function (chunk) {
  13325. chunkArray.push(chunk);
  13326. });
  13327. res.on("end", function () {
  13328. // eslint-disable-next-line no-undef
  13329. var result = Buffer.concat(chunkArray);
  13330. if (res.headers["content-encoding"] === "gzip") {
  13331. zlib.gunzip(result, function (error, resultUnzipped) {
  13332. if (error) {
  13333. deferred.reject(
  13334. new RuntimeError.RuntimeError("Error decompressing response.")
  13335. );
  13336. } else {
  13337. deferred.resolve(decodeResponse(resultUnzipped, responseType));
  13338. }
  13339. });
  13340. } else {
  13341. deferred.resolve(decodeResponse(result, responseType));
  13342. }
  13343. });
  13344. })
  13345. .on("error", function (e) {
  13346. deferred.reject(new RequestErrorEvent());
  13347. })
  13348. .end();
  13349. }
  13350. var noXMLHttpRequest = typeof XMLHttpRequest === "undefined";
  13351. Resource._Implementations.loadWithXhr = function (
  13352. url,
  13353. responseType,
  13354. method,
  13355. data,
  13356. headers,
  13357. deferred,
  13358. overrideMimeType
  13359. ) {
  13360. var dataUriRegexResult = dataUriRegex$1.exec(url);
  13361. if (dataUriRegexResult !== null) {
  13362. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  13363. return;
  13364. }
  13365. if (noXMLHttpRequest) {
  13366. loadWithHttpRequest(
  13367. url,
  13368. responseType,
  13369. method,
  13370. data,
  13371. headers,
  13372. deferred);
  13373. return;
  13374. }
  13375. var xhr = new XMLHttpRequest();
  13376. if (TrustedServers.contains(url)) {
  13377. xhr.withCredentials = true;
  13378. }
  13379. xhr.open(method, url, true);
  13380. if (when.defined(overrideMimeType) && when.defined(xhr.overrideMimeType)) {
  13381. xhr.overrideMimeType(overrideMimeType);
  13382. }
  13383. if (when.defined(headers)) {
  13384. for (var key in headers) {
  13385. if (headers.hasOwnProperty(key)) {
  13386. xhr.setRequestHeader(key, headers[key]);
  13387. }
  13388. }
  13389. }
  13390. if (when.defined(responseType)) {
  13391. xhr.responseType = responseType;
  13392. }
  13393. // While non-standard, file protocol always returns a status of 0 on success
  13394. var localFile = false;
  13395. if (typeof url === "string") {
  13396. localFile =
  13397. url.indexOf("file://") === 0 ||
  13398. (typeof window !== "undefined" && window.location.origin === "file://");
  13399. }
  13400. xhr.onload = function () {
  13401. if (
  13402. (xhr.status < 200 || xhr.status >= 300) &&
  13403. !(localFile && xhr.status === 0)
  13404. ) {
  13405. deferred.reject(
  13406. new RequestErrorEvent(
  13407. xhr.status,
  13408. xhr.response,
  13409. xhr.getAllResponseHeaders()
  13410. )
  13411. );
  13412. return;
  13413. }
  13414. var response = xhr.response;
  13415. var browserResponseType = xhr.responseType;
  13416. if (method === "HEAD" || method === "OPTIONS") {
  13417. var responseHeaderString = xhr.getAllResponseHeaders();
  13418. var splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
  13419. var responseHeaders = {};
  13420. splitHeaders.forEach(function (line) {
  13421. var parts = line.split(": ");
  13422. var header = parts.shift();
  13423. responseHeaders[header] = parts.join(": ");
  13424. });
  13425. deferred.resolve(responseHeaders);
  13426. return;
  13427. }
  13428. //All modern browsers will go into either the first or second if block or last else block.
  13429. //Other code paths support older browsers that either do not support the supplied responseType
  13430. //or do not support the xhr.response property.
  13431. if (xhr.status === 204) {
  13432. // accept no content
  13433. deferred.resolve();
  13434. } else if (
  13435. when.defined(response) &&
  13436. (!when.defined(responseType) || browserResponseType === responseType)
  13437. ) {
  13438. deferred.resolve(response);
  13439. } else if (responseType === "json" && typeof response === "string") {
  13440. try {
  13441. deferred.resolve(JSON.parse(response));
  13442. } catch (e) {
  13443. deferred.reject(e);
  13444. }
  13445. } else if (
  13446. (browserResponseType === "" || browserResponseType === "document") &&
  13447. when.defined(xhr.responseXML) &&
  13448. xhr.responseXML.hasChildNodes()
  13449. ) {
  13450. deferred.resolve(xhr.responseXML);
  13451. } else if (
  13452. (browserResponseType === "" || browserResponseType === "text") &&
  13453. when.defined(xhr.responseText)
  13454. ) {
  13455. deferred.resolve(xhr.responseText);
  13456. } else {
  13457. deferred.reject(
  13458. new RuntimeError.RuntimeError("Invalid XMLHttpRequest response type.")
  13459. );
  13460. }
  13461. };
  13462. xhr.onerror = function (e) {
  13463. deferred.reject(new RequestErrorEvent());
  13464. };
  13465. xhr.send(data);
  13466. return xhr;
  13467. };
  13468. Resource._Implementations.loadAndExecuteScript = function (
  13469. url,
  13470. functionName,
  13471. deferred
  13472. ) {
  13473. return loadAndExecuteScript(url).otherwise(deferred.reject);
  13474. };
  13475. /**
  13476. * The default implementations
  13477. *
  13478. * @private
  13479. */
  13480. Resource._DefaultImplementations = {};
  13481. Resource._DefaultImplementations.createImage =
  13482. Resource._Implementations.createImage;
  13483. Resource._DefaultImplementations.loadWithXhr =
  13484. Resource._Implementations.loadWithXhr;
  13485. Resource._DefaultImplementations.loadAndExecuteScript =
  13486. Resource._Implementations.loadAndExecuteScript;
  13487. /**
  13488. * A resource instance initialized to the current browser location
  13489. *
  13490. * @type {Resource}
  13491. * @constant
  13492. */
  13493. Resource.DEFAULT = Object.freeze(
  13494. new Resource({
  13495. url:
  13496. typeof document === "undefined"
  13497. ? ""
  13498. : document.location.href.split("?")[0],
  13499. })
  13500. );
  13501. /**
  13502. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  13503. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  13504. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  13505. * Reference Frame (ITRF).
  13506. *
  13507. * @alias EarthOrientationParameters
  13508. * @constructor
  13509. *
  13510. * @param {Object} [options] Object with the following properties:
  13511. * @param {Resource|String} [options.url] The URL from which to obtain EOP data. If neither this
  13512. * parameter nor options.data is specified, all EOP values are assumed
  13513. * to be 0.0. If options.data is specified, this parameter is
  13514. * ignored.
  13515. * @param {Object} [options.data] The actual EOP data. If neither this
  13516. * parameter nor options.data is specified, all EOP values are assumed
  13517. * to be 0.0.
  13518. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  13519. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  13520. * should be added to {@link JulianDate.leapSeconds}. False if
  13521. * new leap seconds should be handled correctly in the context
  13522. * of the EOP data but otherwise ignored.
  13523. *
  13524. * @example
  13525. * // An example EOP data file, EOP.json:
  13526. * {
  13527. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  13528. * "samples" : [
  13529. * "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,
  13530. * "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,
  13531. * "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
  13532. * ]
  13533. * }
  13534. *
  13535. * @example
  13536. * // Loading the EOP data
  13537. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  13538. * Cesium.Transforms.earthOrientationParameters = eop;
  13539. *
  13540. * @private
  13541. */
  13542. function EarthOrientationParameters(options) {
  13543. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  13544. this._dates = undefined;
  13545. this._samples = undefined;
  13546. this._dateColumn = -1;
  13547. this._xPoleWanderRadiansColumn = -1;
  13548. this._yPoleWanderRadiansColumn = -1;
  13549. this._ut1MinusUtcSecondsColumn = -1;
  13550. this._xCelestialPoleOffsetRadiansColumn = -1;
  13551. this._yCelestialPoleOffsetRadiansColumn = -1;
  13552. this._taiMinusUtcSecondsColumn = -1;
  13553. this._columnCount = 0;
  13554. this._lastIndex = -1;
  13555. this._downloadPromise = undefined;
  13556. this._dataError = undefined;
  13557. this._addNewLeapSeconds = when.defaultValue(options.addNewLeapSeconds, true);
  13558. if (when.defined(options.data)) {
  13559. // Use supplied EOP data.
  13560. onDataReady(this, options.data);
  13561. } else if (when.defined(options.url)) {
  13562. var resource = Resource.createIfNeeded(options.url);
  13563. // Download EOP data.
  13564. var that = this;
  13565. this._downloadPromise = resource
  13566. .fetchJson()
  13567. .then(function (eopData) {
  13568. onDataReady(that, eopData);
  13569. })
  13570. .otherwise(function () {
  13571. that._dataError =
  13572. "An error occurred while retrieving the EOP data from the URL " +
  13573. resource.url +
  13574. ".";
  13575. });
  13576. } else {
  13577. // Use all zeros for EOP data.
  13578. onDataReady(this, {
  13579. columnNames: [
  13580. "dateIso8601",
  13581. "modifiedJulianDateUtc",
  13582. "xPoleWanderRadians",
  13583. "yPoleWanderRadians",
  13584. "ut1MinusUtcSeconds",
  13585. "lengthOfDayCorrectionSeconds",
  13586. "xCelestialPoleOffsetRadians",
  13587. "yCelestialPoleOffsetRadians",
  13588. "taiMinusUtcSeconds",
  13589. ],
  13590. samples: [],
  13591. });
  13592. }
  13593. }
  13594. /**
  13595. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  13596. */
  13597. EarthOrientationParameters.NONE = Object.freeze({
  13598. getPromiseToLoad: function () {
  13599. return when.when.resolve();
  13600. },
  13601. compute: function (date, result) {
  13602. if (!when.defined(result)) {
  13603. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  13604. } else {
  13605. result.xPoleWander = 0.0;
  13606. result.yPoleWander = 0.0;
  13607. result.xPoleOffset = 0.0;
  13608. result.yPoleOffset = 0.0;
  13609. result.ut1MinusUtc = 0.0;
  13610. }
  13611. return result;
  13612. },
  13613. });
  13614. /**
  13615. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  13616. * ready to use.
  13617. *
  13618. * @returns {Promise<void>} The promise.
  13619. */
  13620. EarthOrientationParameters.prototype.getPromiseToLoad = function () {
  13621. return when.when(this._downloadPromise);
  13622. };
  13623. /**
  13624. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  13625. * If the EOP data has not yet been download, this method returns undefined.
  13626. *
  13627. * @param {JulianDate} date The date for each to evaluate the EOP.
  13628. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  13629. * If this parameter is undefined, a new instance is created and returned.
  13630. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  13631. * undefined if the data necessary to evaluate EOP at the date has not yet been
  13632. * downloaded.
  13633. *
  13634. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  13635. *
  13636. * @see EarthOrientationParameters#getPromiseToLoad
  13637. */
  13638. EarthOrientationParameters.prototype.compute = function (date, result) {
  13639. // We cannot compute until the samples are available.
  13640. if (!when.defined(this._samples)) {
  13641. if (when.defined(this._dataError)) {
  13642. throw new RuntimeError.RuntimeError(this._dataError);
  13643. }
  13644. return undefined;
  13645. }
  13646. if (!when.defined(result)) {
  13647. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  13648. }
  13649. if (this._samples.length === 0) {
  13650. result.xPoleWander = 0.0;
  13651. result.yPoleWander = 0.0;
  13652. result.xPoleOffset = 0.0;
  13653. result.yPoleOffset = 0.0;
  13654. result.ut1MinusUtc = 0.0;
  13655. return result;
  13656. }
  13657. var dates = this._dates;
  13658. var lastIndex = this._lastIndex;
  13659. var before = 0;
  13660. var after = 0;
  13661. if (when.defined(lastIndex)) {
  13662. var previousIndexDate = dates[lastIndex];
  13663. var nextIndexDate = dates[lastIndex + 1];
  13664. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  13665. var isAfterLastSample = !when.defined(nextIndexDate);
  13666. var isBeforeNext =
  13667. isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  13668. if (isAfterPrevious && isBeforeNext) {
  13669. before = lastIndex;
  13670. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  13671. ++before;
  13672. }
  13673. after = before + 1;
  13674. interpolate(this, dates, this._samples, date, before, after, result);
  13675. return result;
  13676. }
  13677. }
  13678. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  13679. if (index >= 0) {
  13680. // If the next entry is the same date, use the later entry. This way, if two entries
  13681. // describe the same moment, one before a leap second and the other after, then we will use
  13682. // the post-leap second data.
  13683. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  13684. ++index;
  13685. }
  13686. before = index;
  13687. after = index;
  13688. } else {
  13689. after = ~index;
  13690. before = after - 1;
  13691. // Use the first entry if the date requested is before the beginning of the data.
  13692. if (before < 0) {
  13693. before = 0;
  13694. }
  13695. }
  13696. this._lastIndex = before;
  13697. interpolate(this, dates, this._samples, date, before, after, result);
  13698. return result;
  13699. };
  13700. function compareLeapSecondDates$1(leapSecond, dateToFind) {
  13701. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  13702. }
  13703. function onDataReady(eop, eopData) {
  13704. if (!when.defined(eopData.columnNames)) {
  13705. eop._dataError =
  13706. "Error in loaded EOP data: The columnNames property is required.";
  13707. return;
  13708. }
  13709. if (!when.defined(eopData.samples)) {
  13710. eop._dataError =
  13711. "Error in loaded EOP data: The samples property is required.";
  13712. return;
  13713. }
  13714. var dateColumn = eopData.columnNames.indexOf("modifiedJulianDateUtc");
  13715. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf(
  13716. "xPoleWanderRadians"
  13717. );
  13718. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf(
  13719. "yPoleWanderRadians"
  13720. );
  13721. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf(
  13722. "ut1MinusUtcSeconds"
  13723. );
  13724. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
  13725. "xCelestialPoleOffsetRadians"
  13726. );
  13727. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf(
  13728. "yCelestialPoleOffsetRadians"
  13729. );
  13730. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf(
  13731. "taiMinusUtcSeconds"
  13732. );
  13733. if (
  13734. dateColumn < 0 ||
  13735. xPoleWanderRadiansColumn < 0 ||
  13736. yPoleWanderRadiansColumn < 0 ||
  13737. ut1MinusUtcSecondsColumn < 0 ||
  13738. xCelestialPoleOffsetRadiansColumn < 0 ||
  13739. yCelestialPoleOffsetRadiansColumn < 0 ||
  13740. taiMinusUtcSecondsColumn < 0
  13741. ) {
  13742. eop._dataError =
  13743. "Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns";
  13744. return;
  13745. }
  13746. var samples = (eop._samples = eopData.samples);
  13747. var dates = (eop._dates = []);
  13748. eop._dateColumn = dateColumn;
  13749. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  13750. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  13751. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  13752. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  13753. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  13754. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  13755. eop._columnCount = eopData.columnNames.length;
  13756. eop._lastIndex = undefined;
  13757. var lastTaiMinusUtc;
  13758. var addNewLeapSeconds = eop._addNewLeapSeconds;
  13759. // Convert the ISO8601 dates to JulianDates.
  13760. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  13761. var mjd = samples[i + dateColumn];
  13762. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  13763. var day = mjd + TimeConstants$1.MODIFIED_JULIAN_DATE_DIFFERENCE;
  13764. var date = new JulianDate(day, taiMinusUtc, TimeStandard$1.TAI);
  13765. dates.push(date);
  13766. if (addNewLeapSeconds) {
  13767. if (taiMinusUtc !== lastTaiMinusUtc && when.defined(lastTaiMinusUtc)) {
  13768. // We crossed a leap second boundary, so add the leap second
  13769. // if it does not already exist.
  13770. var leapSeconds = JulianDate.leapSeconds;
  13771. var leapSecondIndex = binarySearch(
  13772. leapSeconds,
  13773. date,
  13774. compareLeapSecondDates$1
  13775. );
  13776. if (leapSecondIndex < 0) {
  13777. var leapSecond = new LeapSecond(date, taiMinusUtc);
  13778. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  13779. }
  13780. }
  13781. lastTaiMinusUtc = taiMinusUtc;
  13782. }
  13783. }
  13784. }
  13785. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  13786. var start = index * columnCount;
  13787. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  13788. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  13789. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  13790. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  13791. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  13792. }
  13793. function linearInterp(dx, y1, y2) {
  13794. return y1 + dx * (y2 - y1);
  13795. }
  13796. function interpolate(eop, dates, samples, date, before, after, result) {
  13797. var columnCount = eop._columnCount;
  13798. // First check the bounds on the EOP data
  13799. // If we are after the bounds of the data, return zeros.
  13800. // The 'before' index should never be less than zero.
  13801. if (after > dates.length - 1) {
  13802. result.xPoleWander = 0;
  13803. result.yPoleWander = 0;
  13804. result.xPoleOffset = 0;
  13805. result.yPoleOffset = 0;
  13806. result.ut1MinusUtc = 0;
  13807. return result;
  13808. }
  13809. var beforeDate = dates[before];
  13810. var afterDate = dates[after];
  13811. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  13812. fillResultFromIndex(eop, samples, before, columnCount, result);
  13813. return result;
  13814. } else if (date.equals(afterDate)) {
  13815. fillResultFromIndex(eop, samples, after, columnCount, result);
  13816. return result;
  13817. }
  13818. var factor =
  13819. JulianDate.secondsDifference(date, beforeDate) /
  13820. JulianDate.secondsDifference(afterDate, beforeDate);
  13821. var startBefore = before * columnCount;
  13822. var startAfter = after * columnCount;
  13823. // Handle UT1 leap second edge case
  13824. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  13825. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  13826. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  13827. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  13828. // The absolute difference between the values is more than 0.5, so we may have
  13829. // crossed a leap second. Check if this is the case and, if so, adjust the
  13830. // afterValue to account for the leap second. This way, our interpolation will
  13831. // produce reasonable results.
  13832. var beforeTaiMinusUtc =
  13833. samples[startBefore + eop._taiMinusUtcSecondsColumn];
  13834. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  13835. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  13836. if (afterDate.equals(date)) {
  13837. // If we are at the end of the leap second interval, take the second value
  13838. // Otherwise, the interpolation below will yield the wrong side of the
  13839. // discontinuity
  13840. // At the end of the leap second, we need to start accounting for the jump
  13841. beforeUt1MinusUtc = afterUt1MinusUtc;
  13842. } else {
  13843. // Otherwise, remove the leap second so that the interpolation is correct
  13844. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  13845. }
  13846. }
  13847. }
  13848. result.xPoleWander = linearInterp(
  13849. factor,
  13850. samples[startBefore + eop._xPoleWanderRadiansColumn],
  13851. samples[startAfter + eop._xPoleWanderRadiansColumn]
  13852. );
  13853. result.yPoleWander = linearInterp(
  13854. factor,
  13855. samples[startBefore + eop._yPoleWanderRadiansColumn],
  13856. samples[startAfter + eop._yPoleWanderRadiansColumn]
  13857. );
  13858. result.xPoleOffset = linearInterp(
  13859. factor,
  13860. samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn],
  13861. samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]
  13862. );
  13863. result.yPoleOffset = linearInterp(
  13864. factor,
  13865. samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn],
  13866. samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]
  13867. );
  13868. result.ut1MinusUtc = linearInterp(
  13869. factor,
  13870. beforeUt1MinusUtc,
  13871. afterUt1MinusUtc
  13872. );
  13873. return result;
  13874. }
  13875. /**
  13876. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  13877. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  13878. * the positive x axis.
  13879. * @alias HeadingPitchRoll
  13880. * @constructor
  13881. *
  13882. * @param {Number} [heading=0.0] The heading component in radians.
  13883. * @param {Number} [pitch=0.0] The pitch component in radians.
  13884. * @param {Number} [roll=0.0] The roll component in radians.
  13885. */
  13886. function HeadingPitchRoll(heading, pitch, roll) {
  13887. /**
  13888. * Gets or sets the heading.
  13889. * @type {Number}
  13890. * @default 0.0
  13891. */
  13892. this.heading = when.defaultValue(heading, 0.0);
  13893. /**
  13894. * Gets or sets the pitch.
  13895. * @type {Number}
  13896. * @default 0.0
  13897. */
  13898. this.pitch = when.defaultValue(pitch, 0.0);
  13899. /**
  13900. * Gets or sets the roll.
  13901. * @type {Number}
  13902. * @default 0.0
  13903. */
  13904. this.roll = when.defaultValue(roll, 0.0);
  13905. }
  13906. /**
  13907. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  13908. *
  13909. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  13910. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  13911. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  13912. */
  13913. HeadingPitchRoll.fromQuaternion = function (quaternion, result) {
  13914. //>>includeStart('debug', pragmas.debug);
  13915. if (!when.defined(quaternion)) {
  13916. throw new Check.DeveloperError("quaternion is required");
  13917. }
  13918. //>>includeEnd('debug');
  13919. if (!when.defined(result)) {
  13920. result = new HeadingPitchRoll();
  13921. }
  13922. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  13923. var denominatorRoll =
  13924. 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  13925. var numeratorRoll =
  13926. 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  13927. var denominatorHeading =
  13928. 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  13929. var numeratorHeading =
  13930. 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  13931. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  13932. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  13933. result.pitch = -_Math.CesiumMath.asinClamped(test);
  13934. return result;
  13935. };
  13936. /**
  13937. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  13938. *
  13939. * @param {Number} heading the heading in degrees
  13940. * @param {Number} pitch the pitch in degrees
  13941. * @param {Number} roll the heading in degrees
  13942. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  13943. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  13944. */
  13945. HeadingPitchRoll.fromDegrees = function (heading, pitch, roll, result) {
  13946. //>>includeStart('debug', pragmas.debug);
  13947. if (!when.defined(heading)) {
  13948. throw new Check.DeveloperError("heading is required");
  13949. }
  13950. if (!when.defined(pitch)) {
  13951. throw new Check.DeveloperError("pitch is required");
  13952. }
  13953. if (!when.defined(roll)) {
  13954. throw new Check.DeveloperError("roll is required");
  13955. }
  13956. //>>includeEnd('debug');
  13957. if (!when.defined(result)) {
  13958. result = new HeadingPitchRoll();
  13959. }
  13960. result.heading = heading * _Math.CesiumMath.RADIANS_PER_DEGREE;
  13961. result.pitch = pitch * _Math.CesiumMath.RADIANS_PER_DEGREE;
  13962. result.roll = roll * _Math.CesiumMath.RADIANS_PER_DEGREE;
  13963. return result;
  13964. };
  13965. /**
  13966. * Duplicates a HeadingPitchRoll instance.
  13967. *
  13968. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  13969. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  13970. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  13971. */
  13972. HeadingPitchRoll.clone = function (headingPitchRoll, result) {
  13973. if (!when.defined(headingPitchRoll)) {
  13974. return undefined;
  13975. }
  13976. if (!when.defined(result)) {
  13977. return new HeadingPitchRoll(
  13978. headingPitchRoll.heading,
  13979. headingPitchRoll.pitch,
  13980. headingPitchRoll.roll
  13981. );
  13982. }
  13983. result.heading = headingPitchRoll.heading;
  13984. result.pitch = headingPitchRoll.pitch;
  13985. result.roll = headingPitchRoll.roll;
  13986. return result;
  13987. };
  13988. /**
  13989. * Compares the provided HeadingPitchRolls componentwise and returns
  13990. * <code>true</code> if they are equal, <code>false</code> otherwise.
  13991. *
  13992. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  13993. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  13994. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  13995. */
  13996. HeadingPitchRoll.equals = function (left, right) {
  13997. return (
  13998. left === right ||
  13999. (when.defined(left) &&
  14000. when.defined(right) &&
  14001. left.heading === right.heading &&
  14002. left.pitch === right.pitch &&
  14003. left.roll === right.roll)
  14004. );
  14005. };
  14006. /**
  14007. * Compares the provided HeadingPitchRolls componentwise and returns
  14008. * <code>true</code> if they pass an absolute or relative tolerance test,
  14009. * <code>false</code> otherwise.
  14010. *
  14011. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  14012. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  14013. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  14014. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  14015. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  14016. */
  14017. HeadingPitchRoll.equalsEpsilon = function (
  14018. left,
  14019. right,
  14020. relativeEpsilon,
  14021. absoluteEpsilon
  14022. ) {
  14023. return (
  14024. left === right ||
  14025. (when.defined(left) &&
  14026. when.defined(right) &&
  14027. _Math.CesiumMath.equalsEpsilon(
  14028. left.heading,
  14029. right.heading,
  14030. relativeEpsilon,
  14031. absoluteEpsilon
  14032. ) &&
  14033. _Math.CesiumMath.equalsEpsilon(
  14034. left.pitch,
  14035. right.pitch,
  14036. relativeEpsilon,
  14037. absoluteEpsilon
  14038. ) &&
  14039. _Math.CesiumMath.equalsEpsilon(
  14040. left.roll,
  14041. right.roll,
  14042. relativeEpsilon,
  14043. absoluteEpsilon
  14044. ))
  14045. );
  14046. };
  14047. /**
  14048. * Duplicates this HeadingPitchRoll instance.
  14049. *
  14050. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  14051. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  14052. */
  14053. HeadingPitchRoll.prototype.clone = function (result) {
  14054. return HeadingPitchRoll.clone(this, result);
  14055. };
  14056. /**
  14057. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  14058. * <code>true</code> if they are equal, <code>false</code> otherwise.
  14059. *
  14060. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  14061. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  14062. */
  14063. HeadingPitchRoll.prototype.equals = function (right) {
  14064. return HeadingPitchRoll.equals(this, right);
  14065. };
  14066. /**
  14067. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  14068. * <code>true</code> if they pass an absolute or relative tolerance test,
  14069. * <code>false</code> otherwise.
  14070. *
  14071. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  14072. * @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
  14073. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  14074. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  14075. */
  14076. HeadingPitchRoll.prototype.equalsEpsilon = function (
  14077. right,
  14078. relativeEpsilon,
  14079. absoluteEpsilon
  14080. ) {
  14081. return HeadingPitchRoll.equalsEpsilon(
  14082. this,
  14083. right,
  14084. relativeEpsilon,
  14085. absoluteEpsilon
  14086. );
  14087. };
  14088. /**
  14089. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  14090. *
  14091. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  14092. */
  14093. HeadingPitchRoll.prototype.toString = function () {
  14094. return "(" + this.heading + ", " + this.pitch + ", " + this.roll + ")";
  14095. };
  14096. /*global CESIUM_BASE_URL*/
  14097. var cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js(?:\?|\#|$)/;
  14098. function getBaseUrlFromCesiumScript() {
  14099. var scripts = document.getElementsByTagName("script");
  14100. for (var i = 0, len = scripts.length; i < len; ++i) {
  14101. var src = scripts[i].getAttribute("src");
  14102. var result = cesiumScriptRegex.exec(src);
  14103. if (result !== null) {
  14104. return result[1];
  14105. }
  14106. }
  14107. return undefined;
  14108. }
  14109. var a$1;
  14110. function tryMakeAbsolute(url) {
  14111. if (typeof document === "undefined") {
  14112. //Node.js and Web Workers. In both cases, the URL will already be absolute.
  14113. return url;
  14114. }
  14115. if (!when.defined(a$1)) {
  14116. a$1 = document.createElement("a");
  14117. }
  14118. a$1.href = url;
  14119. // IE only absolutizes href on get, not set
  14120. // eslint-disable-next-line no-self-assign
  14121. a$1.href = a$1.href;
  14122. return a$1.href;
  14123. }
  14124. var baseResource;
  14125. function getCesiumBaseUrl() {
  14126. if (when.defined(baseResource)) {
  14127. return baseResource;
  14128. }
  14129. var baseUrlString;
  14130. if (typeof CESIUM_BASE_URL !== "undefined") {
  14131. baseUrlString = CESIUM_BASE_URL;
  14132. } else if (
  14133. typeof define === "object" &&
  14134. when.defined(define.amd) &&
  14135. !define.amd.toUrlUndefined &&
  14136. when.defined(require.toUrl)
  14137. ) {
  14138. baseUrlString = getAbsoluteUri(
  14139. "..",
  14140. buildModuleUrl("Core/buildModuleUrl.js")
  14141. );
  14142. } else {
  14143. baseUrlString = getBaseUrlFromCesiumScript();
  14144. }
  14145. //>>includeStart('debug', pragmas.debug);
  14146. if (!when.defined(baseUrlString)) {
  14147. throw new Check.DeveloperError(
  14148. "Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL."
  14149. );
  14150. }
  14151. //>>includeEnd('debug');
  14152. baseResource = new Resource({
  14153. url: tryMakeAbsolute(baseUrlString),
  14154. });
  14155. baseResource.appendForwardSlash();
  14156. return baseResource;
  14157. }
  14158. function buildModuleUrlFromRequireToUrl(moduleID) {
  14159. //moduleID will be non-relative, so require it relative to this module, in Core.
  14160. return tryMakeAbsolute(require.toUrl("../" + moduleID));
  14161. }
  14162. function buildModuleUrlFromBaseUrl(moduleID) {
  14163. var resource = getCesiumBaseUrl().getDerivedResource({
  14164. url: moduleID,
  14165. });
  14166. return resource.url;
  14167. }
  14168. var implementation;
  14169. /**
  14170. * Given a relative URL under the Cesium base URL, returns an absolute URL.
  14171. * @function
  14172. *
  14173. * @param {String} relativeUrl The relative path.
  14174. * @returns {String} The absolutely URL representation of the provided path.
  14175. *
  14176. * @example
  14177. * var viewer = new Cesium.Viewer("cesiumContainer", {
  14178. * imageryProvider: new Cesium.TileMapServiceImageryProvider({
  14179. * url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
  14180. * }),
  14181. * baseLayerPicker: false,
  14182. * });
  14183. */
  14184. function buildModuleUrl(relativeUrl) {
  14185. if (!when.defined(implementation)) {
  14186. //select implementation
  14187. if (
  14188. typeof define === "object" &&
  14189. when.defined(define.amd) &&
  14190. !define.amd.toUrlUndefined &&
  14191. when.defined(require.toUrl)
  14192. ) {
  14193. implementation = buildModuleUrlFromRequireToUrl;
  14194. } else {
  14195. implementation = buildModuleUrlFromBaseUrl;
  14196. }
  14197. }
  14198. var url = implementation(relativeUrl);
  14199. return url;
  14200. }
  14201. // exposed for testing
  14202. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  14203. buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
  14204. buildModuleUrl._clearBaseResource = function () {
  14205. baseResource = undefined;
  14206. };
  14207. /**
  14208. * Sets the base URL for resolving modules.
  14209. * @param {String} value The new base URL.
  14210. */
  14211. buildModuleUrl.setBaseUrl = function (value) {
  14212. baseResource = Resource.DEFAULT.getDerivedResource({
  14213. url: value,
  14214. });
  14215. };
  14216. /**
  14217. * Gets the base URL for resolving modules.
  14218. */
  14219. buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
  14220. /**
  14221. * An IAU 2006 XYS value sampled at a particular time.
  14222. *
  14223. * @alias Iau2006XysSample
  14224. * @constructor
  14225. *
  14226. * @param {Number} x The X value.
  14227. * @param {Number} y The Y value.
  14228. * @param {Number} s The S value.
  14229. *
  14230. * @private
  14231. */
  14232. function Iau2006XysSample(x, y, s) {
  14233. /**
  14234. * The X value.
  14235. * @type {Number}
  14236. */
  14237. this.x = x;
  14238. /**
  14239. * The Y value.
  14240. * @type {Number}
  14241. */
  14242. this.y = y;
  14243. /**
  14244. * The S value.
  14245. * @type {Number}
  14246. */
  14247. this.s = s;
  14248. }
  14249. /**
  14250. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  14251. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  14252. *
  14253. * @alias Iau2006XysData
  14254. * @constructor
  14255. *
  14256. * @param {Object} [options] Object with the following properties:
  14257. * @param {Resource|String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  14258. * `{0}` will be replaced with the file index.
  14259. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  14260. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  14261. * first XYS sample.
  14262. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  14263. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  14264. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  14265. *
  14266. * @private
  14267. */
  14268. function Iau2006XysData(options) {
  14269. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  14270. this._xysFileUrlTemplate = Resource.createIfNeeded(
  14271. options.xysFileUrlTemplate
  14272. );
  14273. this._interpolationOrder = when.defaultValue(options.interpolationOrder, 9);
  14274. this._sampleZeroJulianEphemerisDate = when.defaultValue(
  14275. options.sampleZeroJulianEphemerisDate,
  14276. 2442396.5
  14277. );
  14278. this._sampleZeroDateTT = new JulianDate(
  14279. this._sampleZeroJulianEphemerisDate,
  14280. 0.0,
  14281. TimeStandard$1.TAI
  14282. );
  14283. this._stepSizeDays = when.defaultValue(options.stepSizeDays, 1.0);
  14284. this._samplesPerXysFile = when.defaultValue(options.samplesPerXysFile, 1000);
  14285. this._totalSamples = when.defaultValue(options.totalSamples, 27426);
  14286. this._samples = new Array(this._totalSamples * 3);
  14287. this._chunkDownloadsInProgress = [];
  14288. var order = this._interpolationOrder;
  14289. // Compute denominators and X values for interpolation.
  14290. var denom = (this._denominators = new Array(order + 1));
  14291. var xTable = (this._xTable = new Array(order + 1));
  14292. var stepN = Math.pow(this._stepSizeDays, order);
  14293. for (var i = 0; i <= order; ++i) {
  14294. denom[i] = stepN;
  14295. xTable[i] = i * this._stepSizeDays;
  14296. for (var j = 0; j <= order; ++j) {
  14297. if (j !== i) {
  14298. denom[i] *= i - j;
  14299. }
  14300. }
  14301. denom[i] = 1.0 / denom[i];
  14302. }
  14303. // Allocate scratch arrays for interpolation.
  14304. this._work = new Array(order + 1);
  14305. this._coef = new Array(order + 1);
  14306. }
  14307. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard$1.TAI);
  14308. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  14309. var dateTT = julianDateScratch;
  14310. dateTT.dayNumber = dayTT;
  14311. dateTT.secondsOfDay = secondTT;
  14312. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  14313. }
  14314. /**
  14315. * Preloads XYS data for a specified date range.
  14316. *
  14317. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  14318. * the Terrestrial Time (TT) time standard.
  14319. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  14320. * the Terrestrial Time (TT) time standard.
  14321. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  14322. * the Terrestrial Time (TT) time standard.
  14323. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  14324. * the Terrestrial Time (TT) time standard.
  14325. * @returns {Promise<void>} A promise that, when resolved, indicates that the requested interval has been
  14326. * preloaded.
  14327. */
  14328. Iau2006XysData.prototype.preload = function (
  14329. startDayTT,
  14330. startSecondTT,
  14331. stopDayTT,
  14332. stopSecondTT
  14333. ) {
  14334. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  14335. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  14336. var startIndex =
  14337. (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
  14338. 0;
  14339. if (startIndex < 0) {
  14340. startIndex = 0;
  14341. }
  14342. var stopIndex =
  14343. (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) |
  14344. (0 + this._interpolationOrder);
  14345. if (stopIndex >= this._totalSamples) {
  14346. stopIndex = this._totalSamples - 1;
  14347. }
  14348. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  14349. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  14350. var promises = [];
  14351. for (var i = startChunk; i <= stopChunk; ++i) {
  14352. promises.push(requestXysChunk(this, i));
  14353. }
  14354. return when.when.all(promises);
  14355. };
  14356. /**
  14357. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  14358. * this method will return undefined.
  14359. *
  14360. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  14361. * the Terrestrial Time (TT) time standard.
  14362. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  14363. * the Terrestrial Time (TT) time standard.
  14364. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  14365. * is undefined, a new instance is allocated and returned.
  14366. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  14367. * computation has not yet been downloaded.
  14368. *
  14369. * @see Iau2006XysData#preload
  14370. */
  14371. Iau2006XysData.prototype.computeXysRadians = function (
  14372. dayTT,
  14373. secondTT,
  14374. result
  14375. ) {
  14376. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  14377. if (daysSinceEpoch < 0.0) {
  14378. // Can't evaluate prior to the epoch of the data.
  14379. return undefined;
  14380. }
  14381. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  14382. if (centerIndex >= this._totalSamples) {
  14383. // Can't evaluate after the last sample in the data.
  14384. return undefined;
  14385. }
  14386. var degree = this._interpolationOrder;
  14387. var firstIndex = centerIndex - ((degree / 2) | 0);
  14388. if (firstIndex < 0) {
  14389. firstIndex = 0;
  14390. }
  14391. var lastIndex = firstIndex + degree;
  14392. if (lastIndex >= this._totalSamples) {
  14393. lastIndex = this._totalSamples - 1;
  14394. firstIndex = lastIndex - degree;
  14395. if (firstIndex < 0) {
  14396. firstIndex = 0;
  14397. }
  14398. }
  14399. // Are all the samples we need present?
  14400. // We can assume so if the first and last are present
  14401. var isDataMissing = false;
  14402. var samples = this._samples;
  14403. if (!when.defined(samples[firstIndex * 3])) {
  14404. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  14405. isDataMissing = true;
  14406. }
  14407. if (!when.defined(samples[lastIndex * 3])) {
  14408. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  14409. isDataMissing = true;
  14410. }
  14411. if (isDataMissing) {
  14412. return undefined;
  14413. }
  14414. if (!when.defined(result)) {
  14415. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  14416. } else {
  14417. result.x = 0.0;
  14418. result.y = 0.0;
  14419. result.s = 0.0;
  14420. }
  14421. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  14422. var work = this._work;
  14423. var denom = this._denominators;
  14424. var coef = this._coef;
  14425. var xTable = this._xTable;
  14426. var i, j;
  14427. for (i = 0; i <= degree; ++i) {
  14428. work[i] = x - xTable[i];
  14429. }
  14430. for (i = 0; i <= degree; ++i) {
  14431. coef[i] = 1.0;
  14432. for (j = 0; j <= degree; ++j) {
  14433. if (j !== i) {
  14434. coef[i] *= work[j];
  14435. }
  14436. }
  14437. coef[i] *= denom[i];
  14438. var sampleIndex = (firstIndex + i) * 3;
  14439. result.x += coef[i] * samples[sampleIndex++];
  14440. result.y += coef[i] * samples[sampleIndex++];
  14441. result.s += coef[i] * samples[sampleIndex];
  14442. }
  14443. return result;
  14444. };
  14445. function requestXysChunk(xysData, chunkIndex) {
  14446. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  14447. // Chunk has already been requested.
  14448. return xysData._chunkDownloadsInProgress[chunkIndex];
  14449. }
  14450. var deferred = when.when.defer();
  14451. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  14452. var chunkUrl;
  14453. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  14454. if (when.defined(xysFileUrlTemplate)) {
  14455. chunkUrl = xysFileUrlTemplate.getDerivedResource({
  14456. templateValues: {
  14457. "0": chunkIndex,
  14458. },
  14459. });
  14460. } else {
  14461. chunkUrl = new Resource({
  14462. url: buildModuleUrl(
  14463. "Assets/IAU2006_XYS/IAU2006_XYS_" + chunkIndex + ".json"
  14464. ),
  14465. });
  14466. }
  14467. when.when(chunkUrl.fetchJson(), function (chunk) {
  14468. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  14469. var samples = xysData._samples;
  14470. var newSamples = chunk.samples;
  14471. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  14472. for (var i = 0, len = newSamples.length; i < len; ++i) {
  14473. samples[startIndex + i] = newSamples[i];
  14474. }
  14475. deferred.resolve();
  14476. });
  14477. return deferred.promise;
  14478. }
  14479. /**
  14480. * Contains functions for transforming positions to various reference frames.
  14481. *
  14482. * @namespace Transforms
  14483. */
  14484. var Transforms = {};
  14485. var vectorProductLocalFrame = {
  14486. up: {
  14487. south: "east",
  14488. north: "west",
  14489. west: "south",
  14490. east: "north",
  14491. },
  14492. down: {
  14493. south: "west",
  14494. north: "east",
  14495. west: "north",
  14496. east: "south",
  14497. },
  14498. south: {
  14499. up: "west",
  14500. down: "east",
  14501. west: "down",
  14502. east: "up",
  14503. },
  14504. north: {
  14505. up: "east",
  14506. down: "west",
  14507. west: "up",
  14508. east: "down",
  14509. },
  14510. west: {
  14511. up: "north",
  14512. down: "south",
  14513. north: "down",
  14514. south: "up",
  14515. },
  14516. east: {
  14517. up: "south",
  14518. down: "north",
  14519. north: "up",
  14520. south: "down",
  14521. },
  14522. };
  14523. var degeneratePositionLocalFrame = {
  14524. north: [-1, 0, 0],
  14525. east: [0, 1, 0],
  14526. up: [0, 0, 1],
  14527. south: [1, 0, 0],
  14528. west: [0, -1, 0],
  14529. down: [0, 0, -1],
  14530. };
  14531. var localFrameToFixedFrameCache = {};
  14532. var scratchCalculateCartesian = {
  14533. east: new Cartesian2.Cartesian3(),
  14534. north: new Cartesian2.Cartesian3(),
  14535. up: new Cartesian2.Cartesian3(),
  14536. west: new Cartesian2.Cartesian3(),
  14537. south: new Cartesian2.Cartesian3(),
  14538. down: new Cartesian2.Cartesian3(),
  14539. };
  14540. var scratchFirstCartesian = new Cartesian2.Cartesian3();
  14541. var scratchSecondCartesian = new Cartesian2.Cartesian3();
  14542. var scratchThirdCartesian = new Cartesian2.Cartesian3();
  14543. /**
  14544. * Generates a function that computes a 4x4 transformation matrix from a reference frame
  14545. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  14546. * @param {String} firstAxis name of the first axis of the local reference frame. Must be
  14547. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  14548. * @param {String} secondAxis name of the second axis of the local reference frame. Must be
  14549. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  14550. * @return {Transforms.LocalFrameToFixedFrame} The function that will computes a
  14551. * 4x4 transformation matrix from a reference frame, with first axis and second axis compliant with the parameters,
  14552. */
  14553. Transforms.localFrameToFixedFrameGenerator = function (firstAxis, secondAxis) {
  14554. if (
  14555. !vectorProductLocalFrame.hasOwnProperty(firstAxis) ||
  14556. !vectorProductLocalFrame[firstAxis].hasOwnProperty(secondAxis)
  14557. ) {
  14558. throw new Check.DeveloperError(
  14559. "firstAxis and secondAxis must be east, north, up, west, south or down."
  14560. );
  14561. }
  14562. var thirdAxis = vectorProductLocalFrame[firstAxis][secondAxis];
  14563. /**
  14564. * Computes a 4x4 transformation matrix from a reference frame
  14565. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  14566. * @callback Transforms.LocalFrameToFixedFrame
  14567. * @param {Cartesian3} origin The center point of the local reference frame.
  14568. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14569. * @param {Matrix4} [result] The object onto which to store the result.
  14570. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  14571. */
  14572. var resultat;
  14573. var hashAxis = firstAxis + secondAxis;
  14574. if (when.defined(localFrameToFixedFrameCache[hashAxis])) {
  14575. resultat = localFrameToFixedFrameCache[hashAxis];
  14576. } else {
  14577. resultat = function (origin, ellipsoid, result) {
  14578. //>>includeStart('debug', pragmas.debug);
  14579. if (!when.defined(origin)) {
  14580. throw new Check.DeveloperError("origin is required.");
  14581. }
  14582. //>>includeEnd('debug');
  14583. if (!when.defined(result)) {
  14584. result = new Matrix4();
  14585. }
  14586. if (
  14587. Cartesian2.Cartesian3.equalsEpsilon(origin, Cartesian2.Cartesian3.ZERO, _Math.CesiumMath.EPSILON14)
  14588. ) {
  14589. // If x, y, and z are zero, use the degenerate local frame, which is a special case
  14590. Cartesian2.Cartesian3.unpack(
  14591. degeneratePositionLocalFrame[firstAxis],
  14592. 0,
  14593. scratchFirstCartesian
  14594. );
  14595. Cartesian2.Cartesian3.unpack(
  14596. degeneratePositionLocalFrame[secondAxis],
  14597. 0,
  14598. scratchSecondCartesian
  14599. );
  14600. Cartesian2.Cartesian3.unpack(
  14601. degeneratePositionLocalFrame[thirdAxis],
  14602. 0,
  14603. scratchThirdCartesian
  14604. );
  14605. } else if (
  14606. _Math.CesiumMath.equalsEpsilon(origin.x, 0.0, _Math.CesiumMath.EPSILON14) &&
  14607. _Math.CesiumMath.equalsEpsilon(origin.y, 0.0, _Math.CesiumMath.EPSILON14)
  14608. ) {
  14609. // If x and y are zero, assume origin is at a pole, which is a special case.
  14610. var sign = _Math.CesiumMath.sign(origin.z);
  14611. Cartesian2.Cartesian3.unpack(
  14612. degeneratePositionLocalFrame[firstAxis],
  14613. 0,
  14614. scratchFirstCartesian
  14615. );
  14616. if (firstAxis !== "east" && firstAxis !== "west") {
  14617. Cartesian2.Cartesian3.multiplyByScalar(
  14618. scratchFirstCartesian,
  14619. sign,
  14620. scratchFirstCartesian
  14621. );
  14622. }
  14623. Cartesian2.Cartesian3.unpack(
  14624. degeneratePositionLocalFrame[secondAxis],
  14625. 0,
  14626. scratchSecondCartesian
  14627. );
  14628. if (secondAxis !== "east" && secondAxis !== "west") {
  14629. Cartesian2.Cartesian3.multiplyByScalar(
  14630. scratchSecondCartesian,
  14631. sign,
  14632. scratchSecondCartesian
  14633. );
  14634. }
  14635. Cartesian2.Cartesian3.unpack(
  14636. degeneratePositionLocalFrame[thirdAxis],
  14637. 0,
  14638. scratchThirdCartesian
  14639. );
  14640. if (thirdAxis !== "east" && thirdAxis !== "west") {
  14641. Cartesian2.Cartesian3.multiplyByScalar(
  14642. scratchThirdCartesian,
  14643. sign,
  14644. scratchThirdCartesian
  14645. );
  14646. }
  14647. } else {
  14648. ellipsoid = when.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  14649. ellipsoid.geodeticSurfaceNormal(origin, scratchCalculateCartesian.up);
  14650. var up = scratchCalculateCartesian.up;
  14651. var east = scratchCalculateCartesian.east;
  14652. east.x = -origin.y;
  14653. east.y = origin.x;
  14654. east.z = 0.0;
  14655. Cartesian2.Cartesian3.normalize(east, scratchCalculateCartesian.east);
  14656. Cartesian2.Cartesian3.cross(up, east, scratchCalculateCartesian.north);
  14657. Cartesian2.Cartesian3.multiplyByScalar(
  14658. scratchCalculateCartesian.up,
  14659. -1,
  14660. scratchCalculateCartesian.down
  14661. );
  14662. Cartesian2.Cartesian3.multiplyByScalar(
  14663. scratchCalculateCartesian.east,
  14664. -1,
  14665. scratchCalculateCartesian.west
  14666. );
  14667. Cartesian2.Cartesian3.multiplyByScalar(
  14668. scratchCalculateCartesian.north,
  14669. -1,
  14670. scratchCalculateCartesian.south
  14671. );
  14672. scratchFirstCartesian = scratchCalculateCartesian[firstAxis];
  14673. scratchSecondCartesian = scratchCalculateCartesian[secondAxis];
  14674. scratchThirdCartesian = scratchCalculateCartesian[thirdAxis];
  14675. }
  14676. result[0] = scratchFirstCartesian.x;
  14677. result[1] = scratchFirstCartesian.y;
  14678. result[2] = scratchFirstCartesian.z;
  14679. result[3] = 0.0;
  14680. result[4] = scratchSecondCartesian.x;
  14681. result[5] = scratchSecondCartesian.y;
  14682. result[6] = scratchSecondCartesian.z;
  14683. result[7] = 0.0;
  14684. result[8] = scratchThirdCartesian.x;
  14685. result[9] = scratchThirdCartesian.y;
  14686. result[10] = scratchThirdCartesian.z;
  14687. result[11] = 0.0;
  14688. result[12] = origin.x;
  14689. result[13] = origin.y;
  14690. result[14] = origin.z;
  14691. result[15] = 1.0;
  14692. return result;
  14693. };
  14694. localFrameToFixedFrameCache[hashAxis] = resultat;
  14695. }
  14696. return resultat;
  14697. };
  14698. /**
  14699. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  14700. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  14701. * The local axes are defined as:
  14702. * <ul>
  14703. * <li>The <code>x</code> axis points in the local east direction.</li>
  14704. * <li>The <code>y</code> axis points in the local north direction.</li>
  14705. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  14706. * </ul>
  14707. *
  14708. * @function
  14709. * @param {Cartesian3} origin The center point of the local reference frame.
  14710. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14711. * @param {Matrix4} [result] The object onto which to store the result.
  14712. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  14713. *
  14714. * @example
  14715. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  14716. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  14717. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  14718. */
  14719. Transforms.eastNorthUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  14720. "east",
  14721. "north"
  14722. );
  14723. /**
  14724. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  14725. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  14726. * The local axes are defined as:
  14727. * <ul>
  14728. * <li>The <code>x</code> axis points in the local north direction.</li>
  14729. * <li>The <code>y</code> axis points in the local east direction.</li>
  14730. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  14731. * </ul>
  14732. *
  14733. * @function
  14734. * @param {Cartesian3} origin The center point of the local reference frame.
  14735. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14736. * @param {Matrix4} [result] The object onto which to store the result.
  14737. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  14738. *
  14739. * @example
  14740. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  14741. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  14742. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  14743. */
  14744. Transforms.northEastDownToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  14745. "north",
  14746. "east"
  14747. );
  14748. /**
  14749. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  14750. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  14751. * The local axes are defined as:
  14752. * <ul>
  14753. * <li>The <code>x</code> axis points in the local north direction.</li>
  14754. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  14755. * <li>The <code>z</code> axis points in the local east direction.</li>
  14756. * </ul>
  14757. *
  14758. * @function
  14759. * @param {Cartesian3} origin The center point of the local reference frame.
  14760. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14761. * @param {Matrix4} [result] The object onto which to store the result.
  14762. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  14763. *
  14764. * @example
  14765. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  14766. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  14767. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  14768. */
  14769. Transforms.northUpEastToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  14770. "north",
  14771. "up"
  14772. );
  14773. /**
  14774. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  14775. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  14776. * The local axes are defined as:
  14777. * <ul>
  14778. * <li>The <code>x</code> axis points in the local north direction.</li>
  14779. * <li>The <code>y</code> axis points in the local west direction.</li>
  14780. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  14781. * </ul>
  14782. *
  14783. * @function
  14784. * @param {Cartesian3} origin The center point of the local reference frame.
  14785. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14786. * @param {Matrix4} [result] The object onto which to store the result.
  14787. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  14788. *
  14789. * @example
  14790. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  14791. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  14792. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  14793. */
  14794. Transforms.northWestUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator(
  14795. "north",
  14796. "west"
  14797. );
  14798. var scratchHPRQuaternion$1 = new Quaternion();
  14799. var scratchScale$2 = new Cartesian2.Cartesian3(1.0, 1.0, 1.0);
  14800. var scratchHPRMatrix4 = new Matrix4();
  14801. /**
  14802. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  14803. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  14804. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  14805. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  14806. *
  14807. * @param {Cartesian3} origin The center point of the local reference frame.
  14808. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  14809. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14810. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  14811. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  14812. * @param {Matrix4} [result] The object onto which to store the result.
  14813. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  14814. *
  14815. * @example
  14816. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  14817. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  14818. * var heading = -Cesium.Math.PI_OVER_TWO;
  14819. * var pitch = Cesium.Math.PI_OVER_FOUR;
  14820. * var roll = 0.0;
  14821. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  14822. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  14823. */
  14824. Transforms.headingPitchRollToFixedFrame = function (
  14825. origin,
  14826. headingPitchRoll,
  14827. ellipsoid,
  14828. fixedFrameTransform,
  14829. result
  14830. ) {
  14831. //>>includeStart('debug', pragmas.debug);
  14832. Check.Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
  14833. //>>includeEnd('debug');
  14834. fixedFrameTransform = when.defaultValue(
  14835. fixedFrameTransform,
  14836. Transforms.eastNorthUpToFixedFrame
  14837. );
  14838. var hprQuaternion = Quaternion.fromHeadingPitchRoll(
  14839. headingPitchRoll,
  14840. scratchHPRQuaternion$1
  14841. );
  14842. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(
  14843. Cartesian2.Cartesian3.ZERO,
  14844. hprQuaternion,
  14845. scratchScale$2,
  14846. scratchHPRMatrix4
  14847. );
  14848. result = fixedFrameTransform(origin, ellipsoid, result);
  14849. return Matrix4.multiply(result, hprMatrix, result);
  14850. };
  14851. var scratchENUMatrix4 = new Matrix4();
  14852. var scratchHPRMatrix3 = new Matrix3();
  14853. /**
  14854. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  14855. * centered at the provided origin. Heading is the rotation from the local north
  14856. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  14857. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  14858. *
  14859. * @param {Cartesian3} origin The center point of the local reference frame.
  14860. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  14861. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14862. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  14863. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  14864. * @param {Quaternion} [result] The object onto which to store the result.
  14865. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  14866. *
  14867. * @example
  14868. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  14869. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  14870. * var heading = -Cesium.Math.PI_OVER_TWO;
  14871. * var pitch = Cesium.Math.PI_OVER_FOUR;
  14872. * var roll = 0.0;
  14873. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  14874. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  14875. */
  14876. Transforms.headingPitchRollQuaternion = function (
  14877. origin,
  14878. headingPitchRoll,
  14879. ellipsoid,
  14880. fixedFrameTransform,
  14881. result
  14882. ) {
  14883. //>>includeStart('debug', pragmas.debug);
  14884. Check.Check.typeOf.object("HeadingPitchRoll", headingPitchRoll);
  14885. //>>includeEnd('debug');
  14886. var transform = Transforms.headingPitchRollToFixedFrame(
  14887. origin,
  14888. headingPitchRoll,
  14889. ellipsoid,
  14890. fixedFrameTransform,
  14891. scratchENUMatrix4
  14892. );
  14893. var rotation = Matrix4.getMatrix3(transform, scratchHPRMatrix3);
  14894. return Quaternion.fromRotationMatrix(rotation, result);
  14895. };
  14896. var noScale = new Cartesian2.Cartesian3(1.0, 1.0, 1.0);
  14897. var hprCenterScratch = new Cartesian2.Cartesian3();
  14898. var ffScratch = new Matrix4();
  14899. var hprTransformScratch = new Matrix4();
  14900. var hprRotationScratch = new Matrix3();
  14901. var hprQuaternionScratch = new Quaternion();
  14902. /**
  14903. * Computes heading-pitch-roll angles from a transform in a particular reference frame. Heading is the rotation from the local north
  14904. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  14905. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  14906. *
  14907. * @param {Matrix4} transform The transform
  14908. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  14909. * @param {Transforms.LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  14910. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  14911. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  14912. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if none was provided.
  14913. */
  14914. Transforms.fixedFrameToHeadingPitchRoll = function (
  14915. transform,
  14916. ellipsoid,
  14917. fixedFrameTransform,
  14918. result
  14919. ) {
  14920. //>>includeStart('debug', pragmas.debug);
  14921. Check.Check.defined("transform", transform);
  14922. //>>includeEnd('debug');
  14923. ellipsoid = when.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  14924. fixedFrameTransform = when.defaultValue(
  14925. fixedFrameTransform,
  14926. Transforms.eastNorthUpToFixedFrame
  14927. );
  14928. if (!when.defined(result)) {
  14929. result = new HeadingPitchRoll();
  14930. }
  14931. var center = Matrix4.getTranslation(transform, hprCenterScratch);
  14932. if (Cartesian2.Cartesian3.equals(center, Cartesian2.Cartesian3.ZERO)) {
  14933. result.heading = 0;
  14934. result.pitch = 0;
  14935. result.roll = 0;
  14936. return result;
  14937. }
  14938. var toFixedFrame = Matrix4.inverseTransformation(
  14939. fixedFrameTransform(center, ellipsoid, ffScratch),
  14940. ffScratch
  14941. );
  14942. var transformCopy = Matrix4.setScale(transform, noScale, hprTransformScratch);
  14943. transformCopy = Matrix4.setTranslation(
  14944. transformCopy,
  14945. Cartesian2.Cartesian3.ZERO,
  14946. transformCopy
  14947. );
  14948. toFixedFrame = Matrix4.multiply(toFixedFrame, transformCopy, toFixedFrame);
  14949. var quaternionRotation = Quaternion.fromRotationMatrix(
  14950. Matrix4.getMatrix3(toFixedFrame, hprRotationScratch),
  14951. hprQuaternionScratch
  14952. );
  14953. quaternionRotation = Quaternion.normalize(
  14954. quaternionRotation,
  14955. quaternionRotation
  14956. );
  14957. return HeadingPitchRoll.fromQuaternion(quaternionRotation, result);
  14958. };
  14959. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  14960. var gmstConstant1 = 8640184.812866;
  14961. var gmstConstant2 = 0.093104;
  14962. var gmstConstant3 = -6.2e-6;
  14963. var rateCoef = 1.1772758384668e-19;
  14964. var wgs84WRPrecessing = 7.2921158553e-5;
  14965. var twoPiOverSecondsInDay = _Math.CesiumMath.TWO_PI / 86400.0;
  14966. var dateInUtc = new JulianDate();
  14967. /**
  14968. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  14969. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  14970. *
  14971. * @param {JulianDate} date The time at which to compute the rotation matrix.
  14972. * @param {Matrix3} [result] The object onto which to store the result.
  14973. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  14974. *
  14975. * @example
  14976. * //Set the view to the inertial frame.
  14977. * scene.postUpdate.addEventListener(function(scene, time) {
  14978. * var now = Cesium.JulianDate.now();
  14979. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  14980. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  14981. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  14982. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  14983. * camera.lookAtTransform(transform, offset);
  14984. * });
  14985. */
  14986. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  14987. //>>includeStart('debug', pragmas.debug);
  14988. if (!when.defined(date)) {
  14989. throw new Check.DeveloperError("date is required.");
  14990. }
  14991. //>>includeEnd('debug');
  14992. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  14993. // We do not want to use the function like convertTaiToUtc in JulianDate because
  14994. // we explicitly do not want to fail when inside the leap second.
  14995. dateInUtc = JulianDate.addSeconds(
  14996. date,
  14997. -JulianDate.computeTaiMinusUtc(date),
  14998. dateInUtc
  14999. );
  15000. var utcDayNumber = dateInUtc.dayNumber;
  15001. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  15002. var t;
  15003. var diffDays = utcDayNumber - 2451545;
  15004. if (utcSecondsIntoDay >= 43200.0) {
  15005. t = (diffDays + 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  15006. } else {
  15007. t = (diffDays - 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  15008. }
  15009. var gmst0 =
  15010. gmstConstant0 +
  15011. t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  15012. var angle = (gmst0 * twoPiOverSecondsInDay) % _Math.CesiumMath.TWO_PI;
  15013. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  15014. var secondsSinceMidnight =
  15015. (utcSecondsIntoDay + TimeConstants$1.SECONDS_PER_DAY * 0.5) %
  15016. TimeConstants$1.SECONDS_PER_DAY;
  15017. var gha = angle + ratio * secondsSinceMidnight;
  15018. var cosGha = Math.cos(gha);
  15019. var sinGha = Math.sin(gha);
  15020. if (!when.defined(result)) {
  15021. return new Matrix3(
  15022. cosGha,
  15023. sinGha,
  15024. 0.0,
  15025. -sinGha,
  15026. cosGha,
  15027. 0.0,
  15028. 0.0,
  15029. 0.0,
  15030. 1.0
  15031. );
  15032. }
  15033. result[0] = cosGha;
  15034. result[1] = -sinGha;
  15035. result[2] = 0.0;
  15036. result[3] = sinGha;
  15037. result[4] = cosGha;
  15038. result[5] = 0.0;
  15039. result[6] = 0.0;
  15040. result[7] = 0.0;
  15041. result[8] = 1.0;
  15042. return result;
  15043. };
  15044. /**
  15045. * The source of IAU 2006 XYS data, used for computing the transformation between the
  15046. * Fixed and ICRF axes.
  15047. * @type {Iau2006XysData}
  15048. *
  15049. * @see Transforms.computeIcrfToFixedMatrix
  15050. * @see Transforms.computeFixedToIcrfMatrix
  15051. *
  15052. * @private
  15053. */
  15054. Transforms.iau2006XysData = new Iau2006XysData();
  15055. /**
  15056. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  15057. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  15058. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  15059. * @type {EarthOrientationParameters}
  15060. *
  15061. * @see Transforms.computeIcrfToFixedMatrix
  15062. * @see Transforms.computeFixedToIcrfMatrix
  15063. *
  15064. * @private
  15065. */
  15066. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  15067. var ttMinusTai = 32.184;
  15068. var j2000ttDays = 2451545.0;
  15069. /**
  15070. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  15071. * direction, over a given interval. This function returns a promise that, when resolved,
  15072. * indicates that the preload has completed.
  15073. *
  15074. * @param {TimeInterval} timeInterval The interval to preload.
  15075. * @returns {Promise<void>} A promise that, when resolved, indicates that the preload has completed
  15076. * and evaluation of the transformation between the fixed and ICRF axes will
  15077. * no longer return undefined for a time inside the interval.
  15078. *
  15079. *
  15080. * @example
  15081. * var interval = new Cesium.TimeInterval(...);
  15082. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  15083. * // the data is now loaded
  15084. * });
  15085. *
  15086. * @see Transforms.computeIcrfToFixedMatrix
  15087. * @see Transforms.computeFixedToIcrfMatrix
  15088. * @see when
  15089. */
  15090. Transforms.preloadIcrfFixed = function (timeInterval) {
  15091. var startDayTT = timeInterval.start.dayNumber;
  15092. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  15093. var stopDayTT = timeInterval.stop.dayNumber;
  15094. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  15095. var xysPromise = Transforms.iau2006XysData.preload(
  15096. startDayTT,
  15097. startSecondTT,
  15098. stopDayTT,
  15099. stopSecondTT
  15100. );
  15101. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  15102. return when.when.all([xysPromise, eopPromise]);
  15103. };
  15104. /**
  15105. * Computes a rotation matrix to transform a point or vector from the International Celestial
  15106. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  15107. * at a given time. This function may return undefined if the data necessary to
  15108. * do the transformation is not yet loaded.
  15109. *
  15110. * @param {JulianDate} date The time at which to compute the rotation matrix.
  15111. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  15112. * not specified, a new instance is created and returned.
  15113. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  15114. * transformation is not yet loaded.
  15115. *
  15116. *
  15117. * @example
  15118. * scene.postUpdate.addEventListener(function(scene, time) {
  15119. * // View in ICRF.
  15120. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  15121. * if (Cesium.defined(icrfToFixed)) {
  15122. * var offset = Cesium.Cartesian3.clone(camera.position);
  15123. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
  15124. * camera.lookAtTransform(transform, offset);
  15125. * }
  15126. * });
  15127. *
  15128. * @see Transforms.preloadIcrfFixed
  15129. */
  15130. Transforms.computeIcrfToFixedMatrix = function (date, result) {
  15131. //>>includeStart('debug', pragmas.debug);
  15132. if (!when.defined(date)) {
  15133. throw new Check.DeveloperError("date is required.");
  15134. }
  15135. //>>includeEnd('debug');
  15136. if (!when.defined(result)) {
  15137. result = new Matrix3();
  15138. }
  15139. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  15140. if (!when.defined(fixedToIcrfMtx)) {
  15141. return undefined;
  15142. }
  15143. return Matrix3.transpose(fixedToIcrfMtx, result);
  15144. };
  15145. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  15146. var eopScratch = new EarthOrientationParametersSample(
  15147. 0.0,
  15148. 0.0,
  15149. 0.0,
  15150. 0.0,
  15151. 0.0,
  15152. 0.0
  15153. );
  15154. var rotation1Scratch = new Matrix3();
  15155. var rotation2Scratch = new Matrix3();
  15156. /**
  15157. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  15158. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  15159. * at a given time. This function may return undefined if the data necessary to
  15160. * do the transformation is not yet loaded.
  15161. *
  15162. * @param {JulianDate} date The time at which to compute the rotation matrix.
  15163. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  15164. * not specified, a new instance is created and returned.
  15165. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  15166. * transformation is not yet loaded.
  15167. *
  15168. *
  15169. * @example
  15170. * // Transform a point from the ICRF axes to the Fixed axes.
  15171. * var now = Cesium.JulianDate.now();
  15172. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  15173. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  15174. * var pointInInertial = new Cesium.Cartesian3();
  15175. * if (Cesium.defined(fixedToIcrf)) {
  15176. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  15177. * }
  15178. *
  15179. * @see Transforms.preloadIcrfFixed
  15180. */
  15181. Transforms.computeFixedToIcrfMatrix = function (date, result) {
  15182. //>>includeStart('debug', pragmas.debug);
  15183. if (!when.defined(date)) {
  15184. throw new Check.DeveloperError("date is required.");
  15185. }
  15186. //>>includeEnd('debug');
  15187. if (!when.defined(result)) {
  15188. result = new Matrix3();
  15189. }
  15190. // Compute pole wander
  15191. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  15192. if (!when.defined(eop)) {
  15193. return undefined;
  15194. }
  15195. // There is no external conversion to Terrestrial Time (TT).
  15196. // So use International Atomic Time (TAI) and convert using offsets.
  15197. // Here we are assuming that dayTT and secondTT are positive
  15198. var dayTT = date.dayNumber;
  15199. // It's possible here that secondTT could roll over 86400
  15200. // This does not seem to affect the precision (unit tests check for this)
  15201. var secondTT = date.secondsOfDay + ttMinusTai;
  15202. var xys = Transforms.iau2006XysData.computeXysRadians(
  15203. dayTT,
  15204. secondTT,
  15205. xysScratch
  15206. );
  15207. if (!when.defined(xys)) {
  15208. return undefined;
  15209. }
  15210. var x = xys.x + eop.xPoleOffset;
  15211. var y = xys.y + eop.yPoleOffset;
  15212. // Compute XYS rotation
  15213. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  15214. var rotation1 = rotation1Scratch;
  15215. rotation1[0] = 1.0 - a * x * x;
  15216. rotation1[3] = -a * x * y;
  15217. rotation1[6] = x;
  15218. rotation1[1] = -a * x * y;
  15219. rotation1[4] = 1 - a * y * y;
  15220. rotation1[7] = y;
  15221. rotation1[2] = -x;
  15222. rotation1[5] = -y;
  15223. rotation1[8] = 1 - a * (x * x + y * y);
  15224. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  15225. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  15226. // Similar to TT conversions above
  15227. // It's possible here that secondTT could roll over 86400
  15228. // This does not seem to affect the precision (unit tests check for this)
  15229. var dateUt1day = date.dayNumber;
  15230. var dateUt1sec =
  15231. date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  15232. // Compute Earth rotation angle
  15233. // The IERS standard for era is
  15234. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  15235. // where
  15236. // Tu = JulianDateInUt1 - 2451545.0
  15237. // However, you get much more precision if you make the following simplification
  15238. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  15239. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  15240. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  15241. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  15242. var daysSinceJ2000 = dateUt1day - 2451545;
  15243. var fractionOfDay = dateUt1sec / TimeConstants$1.SECONDS_PER_DAY;
  15244. var era =
  15245. 0.779057273264 +
  15246. fractionOfDay +
  15247. 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  15248. era = (era % 1.0) * _Math.CesiumMath.TWO_PI;
  15249. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  15250. // pseudoFixed to ICRF
  15251. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  15252. // Compute pole wander matrix
  15253. var cosxp = Math.cos(eop.xPoleWander);
  15254. var cosyp = Math.cos(eop.yPoleWander);
  15255. var sinxp = Math.sin(eop.xPoleWander);
  15256. var sinyp = Math.sin(eop.yPoleWander);
  15257. var ttt = dayTT - j2000ttDays + secondTT / TimeConstants$1.SECONDS_PER_DAY;
  15258. ttt /= 36525.0;
  15259. // approximate sp value in rad
  15260. var sp = (-47.0e-6 * ttt * _Math.CesiumMath.RADIANS_PER_DEGREE) / 3600.0;
  15261. var cossp = Math.cos(sp);
  15262. var sinsp = Math.sin(sp);
  15263. var fToPfMtx = rotation2Scratch;
  15264. fToPfMtx[0] = cosxp * cossp;
  15265. fToPfMtx[1] = cosxp * sinsp;
  15266. fToPfMtx[2] = sinxp;
  15267. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  15268. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  15269. fToPfMtx[5] = -sinyp * cosxp;
  15270. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  15271. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  15272. fToPfMtx[8] = cosyp * cosxp;
  15273. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  15274. };
  15275. var pointToWindowCoordinatesTemp = new Cartesian4();
  15276. /**
  15277. * Transform a point from model coordinates to window coordinates.
  15278. *
  15279. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  15280. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  15281. * @param {Cartesian3} point The point to transform.
  15282. * @param {Cartesian2} [result] The object onto which to store the result.
  15283. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  15284. */
  15285. Transforms.pointToWindowCoordinates = function (
  15286. modelViewProjectionMatrix,
  15287. viewportTransformation,
  15288. point,
  15289. result
  15290. ) {
  15291. result = Transforms.pointToGLWindowCoordinates(
  15292. modelViewProjectionMatrix,
  15293. viewportTransformation,
  15294. point,
  15295. result
  15296. );
  15297. result.y = 2.0 * viewportTransformation[5] - result.y;
  15298. return result;
  15299. };
  15300. /**
  15301. * @private
  15302. */
  15303. Transforms.pointToGLWindowCoordinates = function (
  15304. modelViewProjectionMatrix,
  15305. viewportTransformation,
  15306. point,
  15307. result
  15308. ) {
  15309. //>>includeStart('debug', pragmas.debug);
  15310. if (!when.defined(modelViewProjectionMatrix)) {
  15311. throw new Check.DeveloperError("modelViewProjectionMatrix is required.");
  15312. }
  15313. if (!when.defined(viewportTransformation)) {
  15314. throw new Check.DeveloperError("viewportTransformation is required.");
  15315. }
  15316. if (!when.defined(point)) {
  15317. throw new Check.DeveloperError("point is required.");
  15318. }
  15319. //>>includeEnd('debug');
  15320. if (!when.defined(result)) {
  15321. result = new Cartesian2.Cartesian2();
  15322. }
  15323. var tmp = pointToWindowCoordinatesTemp;
  15324. Matrix4.multiplyByVector(
  15325. modelViewProjectionMatrix,
  15326. Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp),
  15327. tmp
  15328. );
  15329. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  15330. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  15331. return Cartesian2.Cartesian2.fromCartesian4(tmp, result);
  15332. };
  15333. var normalScratch = new Cartesian2.Cartesian3();
  15334. var rightScratch = new Cartesian2.Cartesian3();
  15335. var upScratch = new Cartesian2.Cartesian3();
  15336. /**
  15337. * Transform a position and velocity to a rotation matrix.
  15338. *
  15339. * @param {Cartesian3} position The position to transform.
  15340. * @param {Cartesian3} velocity The velocity vector to transform.
  15341. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  15342. * @param {Matrix3} [result] The object onto which to store the result.
  15343. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  15344. */
  15345. Transforms.rotationMatrixFromPositionVelocity = function (
  15346. position,
  15347. velocity,
  15348. ellipsoid,
  15349. result
  15350. ) {
  15351. //>>includeStart('debug', pragmas.debug);
  15352. if (!when.defined(position)) {
  15353. throw new Check.DeveloperError("position is required.");
  15354. }
  15355. if (!when.defined(velocity)) {
  15356. throw new Check.DeveloperError("velocity is required.");
  15357. }
  15358. //>>includeEnd('debug');
  15359. var normal = when.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84).geodeticSurfaceNormal(
  15360. position,
  15361. normalScratch
  15362. );
  15363. var right = Cartesian2.Cartesian3.cross(velocity, normal, rightScratch);
  15364. if (Cartesian2.Cartesian3.equalsEpsilon(right, Cartesian2.Cartesian3.ZERO, _Math.CesiumMath.EPSILON6)) {
  15365. right = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.UNIT_X, right);
  15366. }
  15367. var up = Cartesian2.Cartesian3.cross(right, velocity, upScratch);
  15368. Cartesian2.Cartesian3.normalize(up, up);
  15369. Cartesian2.Cartesian3.cross(velocity, up, right);
  15370. Cartesian2.Cartesian3.negate(right, right);
  15371. Cartesian2.Cartesian3.normalize(right, right);
  15372. if (!when.defined(result)) {
  15373. result = new Matrix3();
  15374. }
  15375. result[0] = velocity.x;
  15376. result[1] = velocity.y;
  15377. result[2] = velocity.z;
  15378. result[3] = right.x;
  15379. result[4] = right.y;
  15380. result[5] = right.z;
  15381. result[6] = up.x;
  15382. result[7] = up.y;
  15383. result[8] = up.z;
  15384. return result;
  15385. };
  15386. var swizzleMatrix = new Matrix4(
  15387. 0.0,
  15388. 0.0,
  15389. 1.0,
  15390. 0.0,
  15391. 1.0,
  15392. 0.0,
  15393. 0.0,
  15394. 0.0,
  15395. 0.0,
  15396. 1.0,
  15397. 0.0,
  15398. 0.0,
  15399. 0.0,
  15400. 0.0,
  15401. 0.0,
  15402. 1.0
  15403. );
  15404. var scratchCartographic = new Cartesian2.Cartographic();
  15405. var scratchCartesian3Projection = new Cartesian2.Cartesian3();
  15406. var scratchCenter = new Cartesian2.Cartesian3();
  15407. var scratchRotation = new Matrix3();
  15408. var scratchFromENU = new Matrix4();
  15409. var scratchToENU = new Matrix4();
  15410. /**
  15411. * @private
  15412. */
  15413. Transforms.basisTo2D = function (projection, matrix, result) {
  15414. //>>includeStart('debug', pragmas.debug);
  15415. if (!when.defined(projection)) {
  15416. throw new Check.DeveloperError("projection is required.");
  15417. }
  15418. if (!when.defined(matrix)) {
  15419. throw new Check.DeveloperError("matrix is required.");
  15420. }
  15421. if (!when.defined(result)) {
  15422. throw new Check.DeveloperError("result is required.");
  15423. }
  15424. //>>includeEnd('debug');
  15425. var rtcCenter = Matrix4.getTranslation(matrix, scratchCenter);
  15426. var ellipsoid = projection.ellipsoid;
  15427. // Get the 2D Center
  15428. var cartographic = ellipsoid.cartesianToCartographic(
  15429. rtcCenter,
  15430. scratchCartographic
  15431. );
  15432. var projectedPosition = projection.project(
  15433. cartographic,
  15434. scratchCartesian3Projection
  15435. );
  15436. Cartesian2.Cartesian3.fromElements(
  15437. projectedPosition.z,
  15438. projectedPosition.x,
  15439. projectedPosition.y,
  15440. projectedPosition
  15441. );
  15442. // Assuming the instance are positioned in WGS84, invert the WGS84 transform to get the local transform and then convert to 2D
  15443. var fromENU = Transforms.eastNorthUpToFixedFrame(
  15444. rtcCenter,
  15445. ellipsoid,
  15446. scratchFromENU
  15447. );
  15448. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  15449. var rotation = Matrix4.getMatrix3(matrix, scratchRotation);
  15450. var local = Matrix4.multiplyByMatrix3(toENU, rotation, result);
  15451. Matrix4.multiply(swizzleMatrix, local, result); // Swap x, y, z for 2D
  15452. Matrix4.setTranslation(result, projectedPosition, result); // Use the projected center
  15453. return result;
  15454. };
  15455. /**
  15456. * @private
  15457. */
  15458. Transforms.wgs84To2DModelMatrix = function (projection, center, result) {
  15459. //>>includeStart('debug', pragmas.debug);
  15460. if (!when.defined(projection)) {
  15461. throw new Check.DeveloperError("projection is required.");
  15462. }
  15463. if (!when.defined(center)) {
  15464. throw new Check.DeveloperError("center is required.");
  15465. }
  15466. if (!when.defined(result)) {
  15467. throw new Check.DeveloperError("result is required.");
  15468. }
  15469. //>>includeEnd('debug');
  15470. var ellipsoid = projection.ellipsoid;
  15471. var fromENU = Transforms.eastNorthUpToFixedFrame(
  15472. center,
  15473. ellipsoid,
  15474. scratchFromENU
  15475. );
  15476. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  15477. var cartographic = ellipsoid.cartesianToCartographic(
  15478. center,
  15479. scratchCartographic
  15480. );
  15481. var projectedPosition = projection.project(
  15482. cartographic,
  15483. scratchCartesian3Projection
  15484. );
  15485. Cartesian2.Cartesian3.fromElements(
  15486. projectedPosition.z,
  15487. projectedPosition.x,
  15488. projectedPosition.y,
  15489. projectedPosition
  15490. );
  15491. var translation = Matrix4.fromTranslation(projectedPosition, scratchFromENU);
  15492. Matrix4.multiply(swizzleMatrix, toENU, result);
  15493. Matrix4.multiply(translation, result, result);
  15494. return result;
  15495. };
  15496. exports.BoundingSphere = BoundingSphere;
  15497. exports.Cartesian4 = Cartesian4;
  15498. exports.FeatureDetection = FeatureDetection;
  15499. exports.GeographicProjection = GeographicProjection;
  15500. exports.Intersect = Intersect$1;
  15501. exports.Interval = Interval;
  15502. exports.Matrix3 = Matrix3;
  15503. exports.Matrix4 = Matrix4;
  15504. exports.Quaternion = Quaternion;
  15505. exports.Resource = Resource;
  15506. exports.Transforms = Transforms;
  15507. exports.buildModuleUrl = buildModuleUrl;
  15508. });