Transforms-65aba0a4.js 663 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658
  1. /* This file is automatically rebuilt by the Cesium build process. */
  2. define(['exports', './defined-26bd4a03', './Check-da037458', './freezeObject-2d83f591', './defaultValue-f2e68450', './Math-fa6e45cb', './Cartesian2-2a723276', './defineProperties-6f7a50f2', './RuntimeError-ad75c885', './when-ee12a2cb'], function (exports, defined, Check, freezeObject, defaultValue, _Math, Cartesian2, defineProperties, RuntimeError, when) { 'use strict';
  3. /**
  4. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  5. * them by the {@link Ellipsoid#maximumRadius}. This projection
  6. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  7. * is also known as EPSG:4326.
  8. *
  9. * @alias GeographicProjection
  10. * @constructor
  11. *
  12. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  13. *
  14. * @see WebMercatorProjection
  15. */
  16. function GeographicProjection(ellipsoid) {
  17. this._ellipsoid = defaultValue.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  18. this._semimajorAxis = this._ellipsoid.maximumRadius;
  19. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  20. }
  21. defineProperties.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 (!defined.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 (!defined.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 (!defined.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 somwhere entirely
  96. * outside of the frustum's 6 planes (OUTSIDE).
  97. *
  98. * @exports Intersect
  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 = freezeObject.freezeObject(Intersect);
  124. /**
  125. * Represents the closed interval [start, stop].
  126. * @alias Interval
  127. * @constructor
  128. *
  129. * @param {Number} [start=0.0] The beginning of the interval.
  130. * @param {Number} [stop=0.0] The end of the interval.
  131. */
  132. function Interval(start, stop) {
  133. /**
  134. * The beginning of the interval.
  135. * @type {Number}
  136. * @default 0.0
  137. */
  138. this.start = defaultValue.defaultValue(start, 0.0);
  139. /**
  140. * The end of the interval.
  141. * @type {Number}
  142. * @default 0.0
  143. */
  144. this.stop = defaultValue.defaultValue(stop, 0.0);
  145. }
  146. /**
  147. * A 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. *
  152. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  153. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  154. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  155. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  156. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  157. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  158. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  159. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  160. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  161. *
  162. * @see Matrix3.fromColumnMajorArray
  163. * @see Matrix3.fromRowMajorArray
  164. * @see Matrix3.fromQuaternion
  165. * @see Matrix3.fromScale
  166. * @see Matrix3.fromUniformScale
  167. * @see Matrix2
  168. * @see Matrix4
  169. */
  170. function Matrix3(column0Row0, column1Row0, column2Row0,
  171. column0Row1, column1Row1, column2Row1,
  172. column0Row2, column1Row2, column2Row2) {
  173. this[0] = defaultValue.defaultValue(column0Row0, 0.0);
  174. this[1] = defaultValue.defaultValue(column0Row1, 0.0);
  175. this[2] = defaultValue.defaultValue(column0Row2, 0.0);
  176. this[3] = defaultValue.defaultValue(column1Row0, 0.0);
  177. this[4] = defaultValue.defaultValue(column1Row1, 0.0);
  178. this[5] = defaultValue.defaultValue(column1Row2, 0.0);
  179. this[6] = defaultValue.defaultValue(column2Row0, 0.0);
  180. this[7] = defaultValue.defaultValue(column2Row1, 0.0);
  181. this[8] = defaultValue.defaultValue(column2Row2, 0.0);
  182. }
  183. /**
  184. * The number of elements used to pack the object into an array.
  185. * @type {Number}
  186. */
  187. Matrix3.packedLength = 9;
  188. /**
  189. * Stores the provided instance into the provided array.
  190. *
  191. * @param {Matrix3} value The value to pack.
  192. * @param {Number[]} array The array to pack into.
  193. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  194. *
  195. * @returns {Number[]} The array that was packed into
  196. */
  197. Matrix3.pack = function(value, array, startingIndex) {
  198. //>>includeStart('debug', pragmas.debug);
  199. Check.Check.typeOf.object('value', value);
  200. Check.Check.defined('array', array);
  201. //>>includeEnd('debug');
  202. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  203. array[startingIndex++] = value[0];
  204. array[startingIndex++] = value[1];
  205. array[startingIndex++] = value[2];
  206. array[startingIndex++] = value[3];
  207. array[startingIndex++] = value[4];
  208. array[startingIndex++] = value[5];
  209. array[startingIndex++] = value[6];
  210. array[startingIndex++] = value[7];
  211. array[startingIndex++] = value[8];
  212. return array;
  213. };
  214. /**
  215. * Retrieves an instance from a packed array.
  216. *
  217. * @param {Number[]} array The packed array.
  218. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  219. * @param {Matrix3} [result] The object into which to store the result.
  220. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  221. */
  222. Matrix3.unpack = function(array, startingIndex, result) {
  223. //>>includeStart('debug', pragmas.debug);
  224. Check.Check.defined('array', array);
  225. //>>includeEnd('debug');
  226. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  227. if (!defined.defined(result)) {
  228. result = new Matrix3();
  229. }
  230. result[0] = array[startingIndex++];
  231. result[1] = array[startingIndex++];
  232. result[2] = array[startingIndex++];
  233. result[3] = array[startingIndex++];
  234. result[4] = array[startingIndex++];
  235. result[5] = array[startingIndex++];
  236. result[6] = array[startingIndex++];
  237. result[7] = array[startingIndex++];
  238. result[8] = array[startingIndex++];
  239. return result;
  240. };
  241. /**
  242. * Duplicates a Matrix3 instance.
  243. *
  244. * @param {Matrix3} matrix The matrix to duplicate.
  245. * @param {Matrix3} [result] The object onto which to store the result.
  246. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  247. */
  248. Matrix3.clone = function(matrix, result) {
  249. if (!defined.defined(matrix)) {
  250. return undefined;
  251. }
  252. if (!defined.defined(result)) {
  253. return new Matrix3(matrix[0], matrix[3], matrix[6],
  254. matrix[1], matrix[4], matrix[7],
  255. matrix[2], matrix[5], matrix[8]);
  256. }
  257. result[0] = matrix[0];
  258. result[1] = matrix[1];
  259. result[2] = matrix[2];
  260. result[3] = matrix[3];
  261. result[4] = matrix[4];
  262. result[5] = matrix[5];
  263. result[6] = matrix[6];
  264. result[7] = matrix[7];
  265. result[8] = matrix[8];
  266. return result;
  267. };
  268. /**
  269. * Creates a Matrix3 from 9 consecutive elements in an array.
  270. *
  271. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  272. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  273. * @param {Matrix3} [result] The object onto which to store the result.
  274. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  275. *
  276. * @example
  277. * // Create the Matrix3:
  278. * // [1.0, 2.0, 3.0]
  279. * // [1.0, 2.0, 3.0]
  280. * // [1.0, 2.0, 3.0]
  281. *
  282. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  283. * var m = Cesium.Matrix3.fromArray(v);
  284. *
  285. * // Create same Matrix3 with using an offset into an array
  286. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  287. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  288. */
  289. Matrix3.fromArray = function(array, startingIndex, result) {
  290. //>>includeStart('debug', pragmas.debug);
  291. Check.Check.defined('array', array);
  292. //>>includeEnd('debug');
  293. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  294. if (!defined.defined(result)) {
  295. result = new Matrix3();
  296. }
  297. result[0] = array[startingIndex];
  298. result[1] = array[startingIndex + 1];
  299. result[2] = array[startingIndex + 2];
  300. result[3] = array[startingIndex + 3];
  301. result[4] = array[startingIndex + 4];
  302. result[5] = array[startingIndex + 5];
  303. result[6] = array[startingIndex + 6];
  304. result[7] = array[startingIndex + 7];
  305. result[8] = array[startingIndex + 8];
  306. return result;
  307. };
  308. /**
  309. * Creates a Matrix3 instance from a column-major order array.
  310. *
  311. * @param {Number[]} values The column-major order array.
  312. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  313. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  314. */
  315. Matrix3.fromColumnMajorArray = function(values, result) {
  316. //>>includeStart('debug', pragmas.debug);
  317. Check.Check.defined('values', values);
  318. //>>includeEnd('debug');
  319. return Matrix3.clone(values, result);
  320. };
  321. /**
  322. * Creates a Matrix3 instance from a row-major order array.
  323. * The resulting matrix will be in column-major order.
  324. *
  325. * @param {Number[]} values The row-major order array.
  326. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  327. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  328. */
  329. Matrix3.fromRowMajorArray = function(values, result) {
  330. //>>includeStart('debug', pragmas.debug);
  331. Check.Check.defined('values', values);
  332. //>>includeEnd('debug');
  333. if (!defined.defined(result)) {
  334. return new Matrix3(values[0], values[1], values[2],
  335. values[3], values[4], values[5],
  336. values[6], values[7], values[8]);
  337. }
  338. result[0] = values[0];
  339. result[1] = values[3];
  340. result[2] = values[6];
  341. result[3] = values[1];
  342. result[4] = values[4];
  343. result[5] = values[7];
  344. result[6] = values[2];
  345. result[7] = values[5];
  346. result[8] = values[8];
  347. return result;
  348. };
  349. /**
  350. * Computes a 3x3 rotation matrix from the provided quaternion.
  351. *
  352. * @param {Quaternion} quaternion the quaternion to use.
  353. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  354. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  355. */
  356. Matrix3.fromQuaternion = function(quaternion, result) {
  357. //>>includeStart('debug', pragmas.debug);
  358. Check.Check.typeOf.object('quaternion', quaternion);
  359. //>>includeEnd('debug');
  360. var x2 = quaternion.x * quaternion.x;
  361. var xy = quaternion.x * quaternion.y;
  362. var xz = quaternion.x * quaternion.z;
  363. var xw = quaternion.x * quaternion.w;
  364. var y2 = quaternion.y * quaternion.y;
  365. var yz = quaternion.y * quaternion.z;
  366. var yw = quaternion.y * quaternion.w;
  367. var z2 = quaternion.z * quaternion.z;
  368. var zw = quaternion.z * quaternion.w;
  369. var w2 = quaternion.w * quaternion.w;
  370. var m00 = x2 - y2 - z2 + w2;
  371. var m01 = 2.0 * (xy - zw);
  372. var m02 = 2.0 * (xz + yw);
  373. var m10 = 2.0 * (xy + zw);
  374. var m11 = -x2 + y2 - z2 + w2;
  375. var m12 = 2.0 * (yz - xw);
  376. var m20 = 2.0 * (xz - yw);
  377. var m21 = 2.0 * (yz + xw);
  378. var m22 = -x2 - y2 + z2 + w2;
  379. if (!defined.defined(result)) {
  380. return new Matrix3(m00, m01, m02,
  381. m10, m11, m12,
  382. m20, m21, m22);
  383. }
  384. result[0] = m00;
  385. result[1] = m10;
  386. result[2] = m20;
  387. result[3] = m01;
  388. result[4] = m11;
  389. result[5] = m21;
  390. result[6] = m02;
  391. result[7] = m12;
  392. result[8] = m22;
  393. return result;
  394. };
  395. /**
  396. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  397. *
  398. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  399. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  400. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  401. */
  402. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  403. //>>includeStart('debug', pragmas.debug);
  404. Check.Check.typeOf.object('headingPitchRoll', headingPitchRoll);
  405. //>>includeEnd('debug');
  406. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  407. var cosPsi = Math.cos(-headingPitchRoll.heading);
  408. var cosPhi = Math.cos(headingPitchRoll.roll);
  409. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  410. var sinPsi = Math.sin(-headingPitchRoll.heading);
  411. var sinPhi = Math.sin(headingPitchRoll.roll);
  412. var m00 = cosTheta * cosPsi;
  413. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  414. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  415. var m10 = cosTheta * sinPsi;
  416. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  417. var m12 = -sinPhi * cosPsi + cosPhi * sinTheta * sinPsi;
  418. var m20 = -sinTheta;
  419. var m21 = sinPhi * cosTheta;
  420. var m22 = cosPhi * cosTheta;
  421. if (!defined.defined(result)) {
  422. return new Matrix3(m00, m01, m02,
  423. m10, m11, m12,
  424. m20, m21, m22);
  425. }
  426. result[0] = m00;
  427. result[1] = m10;
  428. result[2] = m20;
  429. result[3] = m01;
  430. result[4] = m11;
  431. result[5] = m21;
  432. result[6] = m02;
  433. result[7] = m12;
  434. result[8] = m22;
  435. return result;
  436. };
  437. /**
  438. * Computes a Matrix3 instance representing a non-uniform scale.
  439. *
  440. * @param {Cartesian3} scale The x, y, and z scale factors.
  441. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  442. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  443. *
  444. * @example
  445. * // Creates
  446. * // [7.0, 0.0, 0.0]
  447. * // [0.0, 8.0, 0.0]
  448. * // [0.0, 0.0, 9.0]
  449. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  450. */
  451. Matrix3.fromScale = function(scale, result) {
  452. //>>includeStart('debug', pragmas.debug);
  453. Check.Check.typeOf.object('scale', scale);
  454. //>>includeEnd('debug');
  455. if (!defined.defined(result)) {
  456. return new Matrix3(
  457. scale.x, 0.0, 0.0,
  458. 0.0, scale.y, 0.0,
  459. 0.0, 0.0, scale.z);
  460. }
  461. result[0] = scale.x;
  462. result[1] = 0.0;
  463. result[2] = 0.0;
  464. result[3] = 0.0;
  465. result[4] = scale.y;
  466. result[5] = 0.0;
  467. result[6] = 0.0;
  468. result[7] = 0.0;
  469. result[8] = scale.z;
  470. return result;
  471. };
  472. /**
  473. * Computes a Matrix3 instance representing a uniform scale.
  474. *
  475. * @param {Number} scale The uniform scale factor.
  476. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  477. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  478. *
  479. * @example
  480. * // Creates
  481. * // [2.0, 0.0, 0.0]
  482. * // [0.0, 2.0, 0.0]
  483. * // [0.0, 0.0, 2.0]
  484. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  485. */
  486. Matrix3.fromUniformScale = function(scale, result) {
  487. //>>includeStart('debug', pragmas.debug);
  488. Check.Check.typeOf.number('scale', scale);
  489. //>>includeEnd('debug');
  490. if (!defined.defined(result)) {
  491. return new Matrix3(
  492. scale, 0.0, 0.0,
  493. 0.0, scale, 0.0,
  494. 0.0, 0.0, scale);
  495. }
  496. result[0] = scale;
  497. result[1] = 0.0;
  498. result[2] = 0.0;
  499. result[3] = 0.0;
  500. result[4] = scale;
  501. result[5] = 0.0;
  502. result[6] = 0.0;
  503. result[7] = 0.0;
  504. result[8] = scale;
  505. return result;
  506. };
  507. /**
  508. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  509. *
  510. * @param {Cartesian3} vector the vector on the left hand side of the cross product operation.
  511. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  512. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  513. *
  514. * @example
  515. * // Creates
  516. * // [0.0, -9.0, 8.0]
  517. * // [9.0, 0.0, -7.0]
  518. * // [-8.0, 7.0, 0.0]
  519. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  520. */
  521. Matrix3.fromCrossProduct = function(vector, result) {
  522. //>>includeStart('debug', pragmas.debug);
  523. Check.Check.typeOf.object('vector', vector);
  524. //>>includeEnd('debug');
  525. if (!defined.defined(result)) {
  526. return new Matrix3(
  527. 0.0, -vector.z, vector.y,
  528. vector.z, 0.0, -vector.x,
  529. -vector.y, vector.x, 0.0);
  530. }
  531. result[0] = 0.0;
  532. result[1] = vector.z;
  533. result[2] = -vector.y;
  534. result[3] = -vector.z;
  535. result[4] = 0.0;
  536. result[5] = vector.x;
  537. result[6] = vector.y;
  538. result[7] = -vector.x;
  539. result[8] = 0.0;
  540. return result;
  541. };
  542. /**
  543. * Creates a rotation matrix around the x-axis.
  544. *
  545. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  546. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  547. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  548. *
  549. * @example
  550. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  551. * var p = new Cesium.Cartesian3(5, 6, 7);
  552. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  553. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  554. */
  555. Matrix3.fromRotationX = function(angle, result) {
  556. //>>includeStart('debug', pragmas.debug);
  557. Check.Check.typeOf.number('angle', angle);
  558. //>>includeEnd('debug');
  559. var cosAngle = Math.cos(angle);
  560. var sinAngle = Math.sin(angle);
  561. if (!defined.defined(result)) {
  562. return new Matrix3(
  563. 1.0, 0.0, 0.0,
  564. 0.0, cosAngle, -sinAngle,
  565. 0.0, sinAngle, cosAngle);
  566. }
  567. result[0] = 1.0;
  568. result[1] = 0.0;
  569. result[2] = 0.0;
  570. result[3] = 0.0;
  571. result[4] = cosAngle;
  572. result[5] = sinAngle;
  573. result[6] = 0.0;
  574. result[7] = -sinAngle;
  575. result[8] = cosAngle;
  576. return result;
  577. };
  578. /**
  579. * Creates a rotation matrix around the y-axis.
  580. *
  581. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  582. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  583. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  584. *
  585. * @example
  586. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  587. * var p = new Cesium.Cartesian3(5, 6, 7);
  588. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  589. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  590. */
  591. Matrix3.fromRotationY = function(angle, result) {
  592. //>>includeStart('debug', pragmas.debug);
  593. Check.Check.typeOf.number('angle', angle);
  594. //>>includeEnd('debug');
  595. var cosAngle = Math.cos(angle);
  596. var sinAngle = Math.sin(angle);
  597. if (!defined.defined(result)) {
  598. return new Matrix3(
  599. cosAngle, 0.0, sinAngle,
  600. 0.0, 1.0, 0.0,
  601. -sinAngle, 0.0, cosAngle);
  602. }
  603. result[0] = cosAngle;
  604. result[1] = 0.0;
  605. result[2] = -sinAngle;
  606. result[3] = 0.0;
  607. result[4] = 1.0;
  608. result[5] = 0.0;
  609. result[6] = sinAngle;
  610. result[7] = 0.0;
  611. result[8] = cosAngle;
  612. return result;
  613. };
  614. /**
  615. * Creates a rotation matrix around the z-axis.
  616. *
  617. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  618. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  619. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  620. *
  621. * @example
  622. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  623. * var p = new Cesium.Cartesian3(5, 6, 7);
  624. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  625. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  626. */
  627. Matrix3.fromRotationZ = function(angle, result) {
  628. //>>includeStart('debug', pragmas.debug);
  629. Check.Check.typeOf.number('angle', angle);
  630. //>>includeEnd('debug');
  631. var cosAngle = Math.cos(angle);
  632. var sinAngle = Math.sin(angle);
  633. if (!defined.defined(result)) {
  634. return new Matrix3(
  635. cosAngle, -sinAngle, 0.0,
  636. sinAngle, cosAngle, 0.0,
  637. 0.0, 0.0, 1.0);
  638. }
  639. result[0] = cosAngle;
  640. result[1] = sinAngle;
  641. result[2] = 0.0;
  642. result[3] = -sinAngle;
  643. result[4] = cosAngle;
  644. result[5] = 0.0;
  645. result[6] = 0.0;
  646. result[7] = 0.0;
  647. result[8] = 1.0;
  648. return result;
  649. };
  650. /**
  651. * Creates an Array from the provided Matrix3 instance.
  652. * The array will be in column-major order.
  653. *
  654. * @param {Matrix3} matrix The matrix to use..
  655. * @param {Number[]} [result] The Array onto which to store the result.
  656. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  657. */
  658. Matrix3.toArray = function(matrix, result) {
  659. //>>includeStart('debug', pragmas.debug);
  660. Check.Check.typeOf.object('matrix', matrix);
  661. //>>includeEnd('debug');
  662. if (!defined.defined(result)) {
  663. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  664. }
  665. result[0] = matrix[0];
  666. result[1] = matrix[1];
  667. result[2] = matrix[2];
  668. result[3] = matrix[3];
  669. result[4] = matrix[4];
  670. result[5] = matrix[5];
  671. result[6] = matrix[6];
  672. result[7] = matrix[7];
  673. result[8] = matrix[8];
  674. return result;
  675. };
  676. /**
  677. * Computes the array index of the element at the provided row and column.
  678. *
  679. * @param {Number} row The zero-based index of the row.
  680. * @param {Number} column The zero-based index of the column.
  681. * @returns {Number} The index of the element at the provided row and column.
  682. *
  683. * @exception {DeveloperError} row must be 0, 1, or 2.
  684. * @exception {DeveloperError} column must be 0, 1, or 2.
  685. *
  686. * @example
  687. * var myMatrix = new Cesium.Matrix3();
  688. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  689. * var column1Row0 = myMatrix[column1Row0Index]
  690. * myMatrix[column1Row0Index] = 10.0;
  691. */
  692. Matrix3.getElementIndex = function(column, row) {
  693. //>>includeStart('debug', pragmas.debug);
  694. Check.Check.typeOf.number.greaterThanOrEquals('row', row, 0);
  695. Check.Check.typeOf.number.lessThanOrEquals('row', row, 2);
  696. Check.Check.typeOf.number.greaterThanOrEquals('column', column, 0);
  697. Check.Check.typeOf.number.lessThanOrEquals('column', column, 2);
  698. //>>includeEnd('debug');
  699. return column * 3 + row;
  700. };
  701. /**
  702. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  703. *
  704. * @param {Matrix3} matrix The matrix to use.
  705. * @param {Number} index The zero-based index of the column to retrieve.
  706. * @param {Cartesian3} result The object onto which to store the result.
  707. * @returns {Cartesian3} The modified result parameter.
  708. *
  709. * @exception {DeveloperError} index must be 0, 1, or 2.
  710. */
  711. Matrix3.getColumn = function(matrix, index, result) {
  712. //>>includeStart('debug', pragmas.debug);
  713. Check.Check.typeOf.object('matrix', matrix);
  714. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  715. Check.Check.typeOf.number.lessThanOrEquals('index', index, 2);
  716. Check.Check.typeOf.object('result', result);
  717. //>>includeEnd('debug');
  718. var startIndex = index * 3;
  719. var x = matrix[startIndex];
  720. var y = matrix[startIndex + 1];
  721. var z = matrix[startIndex + 2];
  722. result.x = x;
  723. result.y = y;
  724. result.z = z;
  725. return result;
  726. };
  727. /**
  728. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  729. *
  730. * @param {Matrix3} matrix The matrix to use.
  731. * @param {Number} index The zero-based index of the column to set.
  732. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  733. * @param {Matrix3} result The object onto which to store the result.
  734. * @returns {Matrix3} The modified result parameter.
  735. *
  736. * @exception {DeveloperError} index must be 0, 1, or 2.
  737. */
  738. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  739. //>>includeStart('debug', pragmas.debug);
  740. Check.Check.typeOf.object('matrix', matrix);
  741. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  742. Check.Check.typeOf.number.lessThanOrEquals('index', index, 2);
  743. Check.Check.typeOf.object('cartesian', cartesian);
  744. Check.Check.typeOf.object('result', result);
  745. //>>includeEnd('debug');
  746. result = Matrix3.clone(matrix, result);
  747. var startIndex = index * 3;
  748. result[startIndex] = cartesian.x;
  749. result[startIndex + 1] = cartesian.y;
  750. result[startIndex + 2] = cartesian.z;
  751. return result;
  752. };
  753. /**
  754. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  755. *
  756. * @param {Matrix3} matrix The matrix to use.
  757. * @param {Number} index The zero-based index of the row to retrieve.
  758. * @param {Cartesian3} result The object onto which to store the result.
  759. * @returns {Cartesian3} The modified result parameter.
  760. *
  761. * @exception {DeveloperError} index must be 0, 1, or 2.
  762. */
  763. Matrix3.getRow = function(matrix, index, result) {
  764. //>>includeStart('debug', pragmas.debug);
  765. Check.Check.typeOf.object('matrix', matrix);
  766. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  767. Check.Check.typeOf.number.lessThanOrEquals('index', index, 2);
  768. Check.Check.typeOf.object('result', result);
  769. //>>includeEnd('debug');
  770. var x = matrix[index];
  771. var y = matrix[index + 3];
  772. var z = matrix[index + 6];
  773. result.x = x;
  774. result.y = y;
  775. result.z = z;
  776. return result;
  777. };
  778. /**
  779. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  780. *
  781. * @param {Matrix3} matrix The matrix to use.
  782. * @param {Number} index The zero-based index of the row to set.
  783. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  784. * @param {Matrix3} result The object onto which to store the result.
  785. * @returns {Matrix3} The modified result parameter.
  786. *
  787. * @exception {DeveloperError} index must be 0, 1, or 2.
  788. */
  789. Matrix3.setRow = function(matrix, index, cartesian, result) {
  790. //>>includeStart('debug', pragmas.debug);
  791. Check.Check.typeOf.object('matrix', matrix);
  792. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  793. Check.Check.typeOf.number.lessThanOrEquals('index', index, 2);
  794. Check.Check.typeOf.object('cartesian', cartesian);
  795. Check.Check.typeOf.object('result', result);
  796. //>>includeEnd('debug');
  797. result = Matrix3.clone(matrix, result);
  798. result[index] = cartesian.x;
  799. result[index + 3] = cartesian.y;
  800. result[index + 6] = cartesian.z;
  801. return result;
  802. };
  803. var scratchColumn = new Cartesian2.Cartesian3();
  804. /**
  805. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  806. *
  807. * @param {Matrix3} matrix The matrix.
  808. * @param {Cartesian3} result The object onto which to store the result.
  809. * @returns {Cartesian3} The modified result parameter.
  810. */
  811. Matrix3.getScale = function(matrix, result) {
  812. //>>includeStart('debug', pragmas.debug);
  813. Check.Check.typeOf.object('matrix', matrix);
  814. Check.Check.typeOf.object('result', result);
  815. //>>includeEnd('debug');
  816. result.x = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  817. result.y = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  818. result.z = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  819. return result;
  820. };
  821. var scratchScale = new Cartesian2.Cartesian3();
  822. /**
  823. * Computes the maximum scale assuming the matrix is an affine transformation.
  824. * The maximum scale is the maximum length of the column vectors.
  825. *
  826. * @param {Matrix3} matrix The matrix.
  827. * @returns {Number} The maximum scale.
  828. */
  829. Matrix3.getMaximumScale = function(matrix) {
  830. Matrix3.getScale(matrix, scratchScale);
  831. return Cartesian2.Cartesian3.maximumComponent(scratchScale);
  832. };
  833. /**
  834. * Computes the product of two matrices.
  835. *
  836. * @param {Matrix3} left The first matrix.
  837. * @param {Matrix3} right The second matrix.
  838. * @param {Matrix3} result The object onto which to store the result.
  839. * @returns {Matrix3} The modified result parameter.
  840. */
  841. Matrix3.multiply = function(left, right, result) {
  842. //>>includeStart('debug', pragmas.debug);
  843. Check.Check.typeOf.object('left', left);
  844. Check.Check.typeOf.object('right', right);
  845. Check.Check.typeOf.object('result', result);
  846. //>>includeEnd('debug');
  847. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  848. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  849. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  850. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  851. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  852. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  853. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  854. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  855. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  856. result[0] = column0Row0;
  857. result[1] = column0Row1;
  858. result[2] = column0Row2;
  859. result[3] = column1Row0;
  860. result[4] = column1Row1;
  861. result[5] = column1Row2;
  862. result[6] = column2Row0;
  863. result[7] = column2Row1;
  864. result[8] = column2Row2;
  865. return result;
  866. };
  867. /**
  868. * Computes the sum of two matrices.
  869. *
  870. * @param {Matrix3} left The first matrix.
  871. * @param {Matrix3} right The second matrix.
  872. * @param {Matrix3} result The object onto which to store the result.
  873. * @returns {Matrix3} The modified result parameter.
  874. */
  875. Matrix3.add = function(left, right, result) {
  876. //>>includeStart('debug', pragmas.debug);
  877. Check.Check.typeOf.object('left', left);
  878. Check.Check.typeOf.object('right', right);
  879. Check.Check.typeOf.object('result', result);
  880. //>>includeEnd('debug');
  881. result[0] = left[0] + right[0];
  882. result[1] = left[1] + right[1];
  883. result[2] = left[2] + right[2];
  884. result[3] = left[3] + right[3];
  885. result[4] = left[4] + right[4];
  886. result[5] = left[5] + right[5];
  887. result[6] = left[6] + right[6];
  888. result[7] = left[7] + right[7];
  889. result[8] = left[8] + right[8];
  890. return result;
  891. };
  892. /**
  893. * Computes the difference 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.subtract = 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. result[0] = left[0] - right[0];
  907. result[1] = left[1] - right[1];
  908. result[2] = left[2] - right[2];
  909. result[3] = left[3] - right[3];
  910. result[4] = left[4] - right[4];
  911. result[5] = left[5] - right[5];
  912. result[6] = left[6] - right[6];
  913. result[7] = left[7] - right[7];
  914. result[8] = left[8] - right[8];
  915. return result;
  916. };
  917. /**
  918. * Computes the product of a matrix and a column vector.
  919. *
  920. * @param {Matrix3} matrix The matrix.
  921. * @param {Cartesian3} cartesian The column.
  922. * @param {Cartesian3} result The object onto which to store the result.
  923. * @returns {Cartesian3} The modified result parameter.
  924. */
  925. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  926. //>>includeStart('debug', pragmas.debug);
  927. Check.Check.typeOf.object('matrix', matrix);
  928. Check.Check.typeOf.object('cartesian', cartesian);
  929. Check.Check.typeOf.object('result', result);
  930. //>>includeEnd('debug');
  931. var vX = cartesian.x;
  932. var vY = cartesian.y;
  933. var vZ = cartesian.z;
  934. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  935. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  936. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  937. result.x = x;
  938. result.y = y;
  939. result.z = z;
  940. return result;
  941. };
  942. /**
  943. * Computes the product of a matrix and a scalar.
  944. *
  945. * @param {Matrix3} matrix The matrix.
  946. * @param {Number} scalar The number to multiply by.
  947. * @param {Matrix3} result The object onto which to store the result.
  948. * @returns {Matrix3} The modified result parameter.
  949. */
  950. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  951. //>>includeStart('debug', pragmas.debug);
  952. Check.Check.typeOf.object('matrix', matrix);
  953. Check.Check.typeOf.number('scalar', scalar);
  954. Check.Check.typeOf.object('result', result);
  955. //>>includeEnd('debug');
  956. result[0] = matrix[0] * scalar;
  957. result[1] = matrix[1] * scalar;
  958. result[2] = matrix[2] * scalar;
  959. result[3] = matrix[3] * scalar;
  960. result[4] = matrix[4] * scalar;
  961. result[5] = matrix[5] * scalar;
  962. result[6] = matrix[6] * scalar;
  963. result[7] = matrix[7] * scalar;
  964. result[8] = matrix[8] * scalar;
  965. return result;
  966. };
  967. /**
  968. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  969. *
  970. * @param {Matrix3} matrix The matrix on the left-hand side.
  971. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  972. * @param {Matrix3} result The object onto which to store the result.
  973. * @returns {Matrix3} The modified result parameter.
  974. *
  975. *
  976. * @example
  977. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  978. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  979. *
  980. * @see Matrix3.fromScale
  981. * @see Matrix3.multiplyByUniformScale
  982. */
  983. Matrix3.multiplyByScale = function(matrix, scale, result) {
  984. //>>includeStart('debug', pragmas.debug);
  985. Check.Check.typeOf.object('matrix', matrix);
  986. Check.Check.typeOf.object('scale', scale);
  987. Check.Check.typeOf.object('result', result);
  988. //>>includeEnd('debug');
  989. result[0] = matrix[0] * scale.x;
  990. result[1] = matrix[1] * scale.x;
  991. result[2] = matrix[2] * scale.x;
  992. result[3] = matrix[3] * scale.y;
  993. result[4] = matrix[4] * scale.y;
  994. result[5] = matrix[5] * scale.y;
  995. result[6] = matrix[6] * scale.z;
  996. result[7] = matrix[7] * scale.z;
  997. result[8] = matrix[8] * scale.z;
  998. return result;
  999. };
  1000. /**
  1001. * Creates a negated copy of the provided matrix.
  1002. *
  1003. * @param {Matrix3} matrix The matrix to negate.
  1004. * @param {Matrix3} result The object onto which to store the result.
  1005. * @returns {Matrix3} The modified result parameter.
  1006. */
  1007. Matrix3.negate = function(matrix, result) {
  1008. //>>includeStart('debug', pragmas.debug);
  1009. Check.Check.typeOf.object('matrix', matrix);
  1010. Check.Check.typeOf.object('result', result);
  1011. //>>includeEnd('debug');
  1012. result[0] = -matrix[0];
  1013. result[1] = -matrix[1];
  1014. result[2] = -matrix[2];
  1015. result[3] = -matrix[3];
  1016. result[4] = -matrix[4];
  1017. result[5] = -matrix[5];
  1018. result[6] = -matrix[6];
  1019. result[7] = -matrix[7];
  1020. result[8] = -matrix[8];
  1021. return result;
  1022. };
  1023. /**
  1024. * Computes the transpose of the provided matrix.
  1025. *
  1026. * @param {Matrix3} matrix The matrix to transpose.
  1027. * @param {Matrix3} result The object onto which to store the result.
  1028. * @returns {Matrix3} The modified result parameter.
  1029. */
  1030. Matrix3.transpose = function(matrix, result) {
  1031. //>>includeStart('debug', pragmas.debug);
  1032. Check.Check.typeOf.object('matrix', matrix);
  1033. Check.Check.typeOf.object('result', result);
  1034. //>>includeEnd('debug');
  1035. var column0Row0 = matrix[0];
  1036. var column0Row1 = matrix[3];
  1037. var column0Row2 = matrix[6];
  1038. var column1Row0 = matrix[1];
  1039. var column1Row1 = matrix[4];
  1040. var column1Row2 = matrix[7];
  1041. var column2Row0 = matrix[2];
  1042. var column2Row1 = matrix[5];
  1043. var column2Row2 = matrix[8];
  1044. result[0] = column0Row0;
  1045. result[1] = column0Row1;
  1046. result[2] = column0Row2;
  1047. result[3] = column1Row0;
  1048. result[4] = column1Row1;
  1049. result[5] = column1Row2;
  1050. result[6] = column2Row0;
  1051. result[7] = column2Row1;
  1052. result[8] = column2Row2;
  1053. return result;
  1054. };
  1055. var UNIT = new Cartesian2.Cartesian3(1, 1, 1);
  1056. /**
  1057. * Extracts the rotation assuming the matrix is an affine transformation.
  1058. *
  1059. * @param {Matrix3} matrix The matrix.
  1060. * @param {Matrix3} result The object onto which to store the result.
  1061. * @returns {Matrix3} The modified result parameter
  1062. */
  1063. Matrix3.getRotation = function(matrix, result) {
  1064. //>>includeStart('debug', pragmas.debug);
  1065. Check.Check.typeOf.object('matrix', matrix);
  1066. Check.Check.typeOf.object('result', result);
  1067. //>>includeEnd('debug');
  1068. var inverseScale = Cartesian2.Cartesian3.divideComponents(UNIT, Matrix3.getScale(matrix, scratchScale), scratchScale);
  1069. result = Matrix3.multiplyByScale(matrix, inverseScale, result);
  1070. return result;
  1071. };
  1072. function computeFrobeniusNorm(matrix) {
  1073. var norm = 0.0;
  1074. for (var i = 0; i < 9; ++i) {
  1075. var temp = matrix[i];
  1076. norm += temp * temp;
  1077. }
  1078. return Math.sqrt(norm);
  1079. }
  1080. var rowVal = [1, 0, 0];
  1081. var colVal = [2, 2, 1];
  1082. function offDiagonalFrobeniusNorm(matrix) {
  1083. // Computes the "off-diagonal" Frobenius norm.
  1084. // Assumes matrix is symmetric.
  1085. var norm = 0.0;
  1086. for (var i = 0; i < 3; ++i) {
  1087. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  1088. norm += 2.0 * temp * temp;
  1089. }
  1090. return Math.sqrt(norm);
  1091. }
  1092. function shurDecomposition(matrix, result) {
  1093. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  1094. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  1095. //
  1096. // The routine takes a matrix, which is assumed to be symmetric, and
  1097. // finds the largest off-diagonal term, and then creates
  1098. // a matrix (result) which can be used to help reduce it
  1099. var tolerance = _Math.CesiumMath.EPSILON15;
  1100. var maxDiagonal = 0.0;
  1101. var rotAxis = 1;
  1102. // find pivot (rotAxis) based on max diagonal of matrix
  1103. for (var i = 0; i < 3; ++i) {
  1104. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  1105. if (temp > maxDiagonal) {
  1106. rotAxis = i;
  1107. maxDiagonal = temp;
  1108. }
  1109. }
  1110. var c = 1.0;
  1111. var s = 0.0;
  1112. var p = rowVal[rotAxis];
  1113. var q = colVal[rotAxis];
  1114. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  1115. var qq = matrix[Matrix3.getElementIndex(q, q)];
  1116. var pp = matrix[Matrix3.getElementIndex(p, p)];
  1117. var qp = matrix[Matrix3.getElementIndex(q, p)];
  1118. var tau = (qq - pp) / 2.0 / qp;
  1119. var t;
  1120. if (tau < 0.0) {
  1121. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  1122. } else {
  1123. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  1124. }
  1125. c = 1.0 / Math.sqrt(1.0 + t * t);
  1126. s = t * c;
  1127. }
  1128. result = Matrix3.clone(Matrix3.IDENTITY, result);
  1129. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  1130. result[Matrix3.getElementIndex(q, p)] = s;
  1131. result[Matrix3.getElementIndex(p, q)] = -s;
  1132. return result;
  1133. }
  1134. var jMatrix = new Matrix3();
  1135. var jMatrixTranspose = new Matrix3();
  1136. /**
  1137. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  1138. * <p>
  1139. * Returns a diagonal matrix and unitary matrix such that:
  1140. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  1141. * </p>
  1142. * <p>
  1143. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  1144. * of the unitary matrix are the corresponding eigenvectors.
  1145. * </p>
  1146. *
  1147. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  1148. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  1149. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  1150. *
  1151. * @example
  1152. * var a = //... symetric matrix
  1153. * var result = {
  1154. * unitary : new Cesium.Matrix3(),
  1155. * diagonal : new Cesium.Matrix3()
  1156. * };
  1157. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  1158. *
  1159. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  1160. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  1161. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  1162. *
  1163. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  1164. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  1165. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  1166. */
  1167. Matrix3.computeEigenDecomposition = function(matrix, result) {
  1168. //>>includeStart('debug', pragmas.debug);
  1169. Check.Check.typeOf.object('matrix', matrix);
  1170. //>>includeEnd('debug');
  1171. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  1172. // section 8.4.3 The Classical Jacobi Algorithm
  1173. var tolerance = _Math.CesiumMath.EPSILON20;
  1174. var maxSweeps = 10;
  1175. var count = 0;
  1176. var sweep = 0;
  1177. if (!defined.defined(result)) {
  1178. result = {};
  1179. }
  1180. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  1181. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  1182. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  1183. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  1184. shurDecomposition(diagMatrix, jMatrix);
  1185. Matrix3.transpose(jMatrix, jMatrixTranspose);
  1186. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  1187. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  1188. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  1189. if (++count > 2) {
  1190. ++sweep;
  1191. count = 0;
  1192. }
  1193. }
  1194. return result;
  1195. };
  1196. /**
  1197. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  1198. *
  1199. * @param {Matrix3} matrix The matrix with signed elements.
  1200. * @param {Matrix3} result The object onto which to store the result.
  1201. * @returns {Matrix3} The modified result parameter.
  1202. */
  1203. Matrix3.abs = function(matrix, result) {
  1204. //>>includeStart('debug', pragmas.debug);
  1205. Check.Check.typeOf.object('matrix', matrix);
  1206. Check.Check.typeOf.object('result', result);
  1207. //>>includeEnd('debug');
  1208. result[0] = Math.abs(matrix[0]);
  1209. result[1] = Math.abs(matrix[1]);
  1210. result[2] = Math.abs(matrix[2]);
  1211. result[3] = Math.abs(matrix[3]);
  1212. result[4] = Math.abs(matrix[4]);
  1213. result[5] = Math.abs(matrix[5]);
  1214. result[6] = Math.abs(matrix[6]);
  1215. result[7] = Math.abs(matrix[7]);
  1216. result[8] = Math.abs(matrix[8]);
  1217. return result;
  1218. };
  1219. /**
  1220. * Computes the determinant of the provided matrix.
  1221. *
  1222. * @param {Matrix3} matrix The matrix to use.
  1223. * @returns {Number} The value of the determinant of the matrix.
  1224. */
  1225. Matrix3.determinant = function(matrix) {
  1226. //>>includeStart('debug', pragmas.debug);
  1227. Check.Check.typeOf.object('matrix', matrix);
  1228. //>>includeEnd('debug');
  1229. var m11 = matrix[0];
  1230. var m21 = matrix[3];
  1231. var m31 = matrix[6];
  1232. var m12 = matrix[1];
  1233. var m22 = matrix[4];
  1234. var m32 = matrix[7];
  1235. var m13 = matrix[2];
  1236. var m23 = matrix[5];
  1237. var m33 = matrix[8];
  1238. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  1239. };
  1240. /**
  1241. * Computes the inverse of the provided matrix.
  1242. *
  1243. * @param {Matrix3} matrix The matrix to invert.
  1244. * @param {Matrix3} result The object onto which to store the result.
  1245. * @returns {Matrix3} The modified result parameter.
  1246. *
  1247. * @exception {DeveloperError} matrix is not invertible.
  1248. */
  1249. Matrix3.inverse = function(matrix, result) {
  1250. //>>includeStart('debug', pragmas.debug);
  1251. Check.Check.typeOf.object('matrix', matrix);
  1252. Check.Check.typeOf.object('result', result);
  1253. //>>includeEnd('debug');
  1254. var m11 = matrix[0];
  1255. var m21 = matrix[1];
  1256. var m31 = matrix[2];
  1257. var m12 = matrix[3];
  1258. var m22 = matrix[4];
  1259. var m32 = matrix[5];
  1260. var m13 = matrix[6];
  1261. var m23 = matrix[7];
  1262. var m33 = matrix[8];
  1263. var determinant = Matrix3.determinant(matrix);
  1264. //>>includeStart('debug', pragmas.debug);
  1265. if (Math.abs(determinant) <= _Math.CesiumMath.EPSILON15) {
  1266. throw new Check.DeveloperError('matrix is not invertible');
  1267. }
  1268. //>>includeEnd('debug');
  1269. result[0] = m22 * m33 - m23 * m32;
  1270. result[1] = m23 * m31 - m21 * m33;
  1271. result[2] = m21 * m32 - m22 * m31;
  1272. result[3] = m13 * m32 - m12 * m33;
  1273. result[4] = m11 * m33 - m13 * m31;
  1274. result[5] = m12 * m31 - m11 * m32;
  1275. result[6] = m12 * m23 - m13 * m22;
  1276. result[7] = m13 * m21 - m11 * m23;
  1277. result[8] = m11 * m22 - m12 * m21;
  1278. var scale = 1.0 / determinant;
  1279. return Matrix3.multiplyByScalar(result, scale, result);
  1280. };
  1281. /**
  1282. * Compares the provided matrices componentwise and returns
  1283. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1284. *
  1285. * @param {Matrix3} [left] The first matrix.
  1286. * @param {Matrix3} [right] The second matrix.
  1287. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1288. */
  1289. Matrix3.equals = function(left, right) {
  1290. return (left === right) ||
  1291. (defined.defined(left) &&
  1292. defined.defined(right) &&
  1293. left[0] === right[0] &&
  1294. left[1] === right[1] &&
  1295. left[2] === right[2] &&
  1296. left[3] === right[3] &&
  1297. left[4] === right[4] &&
  1298. left[5] === right[5] &&
  1299. left[6] === right[6] &&
  1300. left[7] === right[7] &&
  1301. left[8] === right[8]);
  1302. };
  1303. /**
  1304. * Compares the provided matrices componentwise and returns
  1305. * <code>true</code> if they are within the provided epsilon,
  1306. * <code>false</code> otherwise.
  1307. *
  1308. * @param {Matrix3} [left] The first matrix.
  1309. * @param {Matrix3} [right] The second matrix.
  1310. * @param {Number} epsilon The epsilon to use for equality testing.
  1311. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  1312. */
  1313. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  1314. //>>includeStart('debug', pragmas.debug);
  1315. Check.Check.typeOf.number('epsilon', epsilon);
  1316. //>>includeEnd('debug');
  1317. return (left === right) ||
  1318. (defined.defined(left) &&
  1319. defined.defined(right) &&
  1320. Math.abs(left[0] - right[0]) <= epsilon &&
  1321. Math.abs(left[1] - right[1]) <= epsilon &&
  1322. Math.abs(left[2] - right[2]) <= epsilon &&
  1323. Math.abs(left[3] - right[3]) <= epsilon &&
  1324. Math.abs(left[4] - right[4]) <= epsilon &&
  1325. Math.abs(left[5] - right[5]) <= epsilon &&
  1326. Math.abs(left[6] - right[6]) <= epsilon &&
  1327. Math.abs(left[7] - right[7]) <= epsilon &&
  1328. Math.abs(left[8] - right[8]) <= epsilon);
  1329. };
  1330. /**
  1331. * An immutable Matrix3 instance initialized to the identity matrix.
  1332. *
  1333. * @type {Matrix3}
  1334. * @constant
  1335. */
  1336. Matrix3.IDENTITY = freezeObject.freezeObject(new Matrix3(1.0, 0.0, 0.0,
  1337. 0.0, 1.0, 0.0,
  1338. 0.0, 0.0, 1.0));
  1339. /**
  1340. * An immutable Matrix3 instance initialized to the zero matrix.
  1341. *
  1342. * @type {Matrix3}
  1343. * @constant
  1344. */
  1345. Matrix3.ZERO = freezeObject.freezeObject(new Matrix3(0.0, 0.0, 0.0,
  1346. 0.0, 0.0, 0.0,
  1347. 0.0, 0.0, 0.0));
  1348. /**
  1349. * The index into Matrix3 for column 0, row 0.
  1350. *
  1351. * @type {Number}
  1352. * @constant
  1353. */
  1354. Matrix3.COLUMN0ROW0 = 0;
  1355. /**
  1356. * The index into Matrix3 for column 0, row 1.
  1357. *
  1358. * @type {Number}
  1359. * @constant
  1360. */
  1361. Matrix3.COLUMN0ROW1 = 1;
  1362. /**
  1363. * The index into Matrix3 for column 0, row 2.
  1364. *
  1365. * @type {Number}
  1366. * @constant
  1367. */
  1368. Matrix3.COLUMN0ROW2 = 2;
  1369. /**
  1370. * The index into Matrix3 for column 1, row 0.
  1371. *
  1372. * @type {Number}
  1373. * @constant
  1374. */
  1375. Matrix3.COLUMN1ROW0 = 3;
  1376. /**
  1377. * The index into Matrix3 for column 1, row 1.
  1378. *
  1379. * @type {Number}
  1380. * @constant
  1381. */
  1382. Matrix3.COLUMN1ROW1 = 4;
  1383. /**
  1384. * The index into Matrix3 for column 1, row 2.
  1385. *
  1386. * @type {Number}
  1387. * @constant
  1388. */
  1389. Matrix3.COLUMN1ROW2 = 5;
  1390. /**
  1391. * The index into Matrix3 for column 2, row 0.
  1392. *
  1393. * @type {Number}
  1394. * @constant
  1395. */
  1396. Matrix3.COLUMN2ROW0 = 6;
  1397. /**
  1398. * The index into Matrix3 for column 2, row 1.
  1399. *
  1400. * @type {Number}
  1401. * @constant
  1402. */
  1403. Matrix3.COLUMN2ROW1 = 7;
  1404. /**
  1405. * The index into Matrix3 for column 2, row 2.
  1406. *
  1407. * @type {Number}
  1408. * @constant
  1409. */
  1410. Matrix3.COLUMN2ROW2 = 8;
  1411. defineProperties.defineProperties(Matrix3.prototype, {
  1412. /**
  1413. * Gets the number of items in the collection.
  1414. * @memberof Matrix3.prototype
  1415. *
  1416. * @type {Number}
  1417. */
  1418. length : {
  1419. get : function() {
  1420. return Matrix3.packedLength;
  1421. }
  1422. }
  1423. });
  1424. /**
  1425. * Duplicates the provided Matrix3 instance.
  1426. *
  1427. * @param {Matrix3} [result] The object onto which to store the result.
  1428. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  1429. */
  1430. Matrix3.prototype.clone = function(result) {
  1431. return Matrix3.clone(this, result);
  1432. };
  1433. /**
  1434. * Compares this matrix to the provided matrix componentwise and returns
  1435. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1436. *
  1437. * @param {Matrix3} [right] The right hand side matrix.
  1438. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  1439. */
  1440. Matrix3.prototype.equals = function(right) {
  1441. return Matrix3.equals(this, right);
  1442. };
  1443. /**
  1444. * @private
  1445. */
  1446. Matrix3.equalsArray = function(matrix, array, offset) {
  1447. return matrix[0] === array[offset] &&
  1448. matrix[1] === array[offset + 1] &&
  1449. matrix[2] === array[offset + 2] &&
  1450. matrix[3] === array[offset + 3] &&
  1451. matrix[4] === array[offset + 4] &&
  1452. matrix[5] === array[offset + 5] &&
  1453. matrix[6] === array[offset + 6] &&
  1454. matrix[7] === array[offset + 7] &&
  1455. matrix[8] === array[offset + 8];
  1456. };
  1457. /**
  1458. * Compares this matrix to the provided matrix componentwise and returns
  1459. * <code>true</code> if they are within the provided epsilon,
  1460. * <code>false</code> otherwise.
  1461. *
  1462. * @param {Matrix3} [right] The right hand side matrix.
  1463. * @param {Number} epsilon The epsilon to use for equality testing.
  1464. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  1465. */
  1466. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  1467. return Matrix3.equalsEpsilon(this, right, epsilon);
  1468. };
  1469. /**
  1470. * Creates a string representing this Matrix with each row being
  1471. * on a separate line and in the format '(column0, column1, column2)'.
  1472. *
  1473. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  1474. */
  1475. Matrix3.prototype.toString = function() {
  1476. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  1477. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  1478. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  1479. };
  1480. /**
  1481. * A 4D Cartesian point.
  1482. * @alias Cartesian4
  1483. * @constructor
  1484. *
  1485. * @param {Number} [x=0.0] The X component.
  1486. * @param {Number} [y=0.0] The Y component.
  1487. * @param {Number} [z=0.0] The Z component.
  1488. * @param {Number} [w=0.0] The W component.
  1489. *
  1490. * @see Cartesian2
  1491. * @see Cartesian3
  1492. * @see Packable
  1493. */
  1494. function Cartesian4(x, y, z, w) {
  1495. /**
  1496. * The X component.
  1497. * @type {Number}
  1498. * @default 0.0
  1499. */
  1500. this.x = defaultValue.defaultValue(x, 0.0);
  1501. /**
  1502. * The Y component.
  1503. * @type {Number}
  1504. * @default 0.0
  1505. */
  1506. this.y = defaultValue.defaultValue(y, 0.0);
  1507. /**
  1508. * The Z component.
  1509. * @type {Number}
  1510. * @default 0.0
  1511. */
  1512. this.z = defaultValue.defaultValue(z, 0.0);
  1513. /**
  1514. * The W component.
  1515. * @type {Number}
  1516. * @default 0.0
  1517. */
  1518. this.w = defaultValue.defaultValue(w, 0.0);
  1519. }
  1520. /**
  1521. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  1522. *
  1523. * @param {Number} x The x coordinate.
  1524. * @param {Number} y The y coordinate.
  1525. * @param {Number} z The z coordinate.
  1526. * @param {Number} w The w coordinate.
  1527. * @param {Cartesian4} [result] The object onto which to store the result.
  1528. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1529. */
  1530. Cartesian4.fromElements = function(x, y, z, w, result) {
  1531. if (!defined.defined(result)) {
  1532. return new Cartesian4(x, y, z, w);
  1533. }
  1534. result.x = x;
  1535. result.y = y;
  1536. result.z = z;
  1537. result.w = w;
  1538. return result;
  1539. };
  1540. /**
  1541. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  1542. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  1543. *
  1544. * @param {Color} color The source color.
  1545. * @param {Cartesian4} [result] The object onto which to store the result.
  1546. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1547. */
  1548. Cartesian4.fromColor = function(color, result) {
  1549. //>>includeStart('debug', pragmas.debug);
  1550. Check.Check.typeOf.object('color', color);
  1551. //>>includeEnd('debug');
  1552. if (!defined.defined(result)) {
  1553. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  1554. }
  1555. result.x = color.red;
  1556. result.y = color.green;
  1557. result.z = color.blue;
  1558. result.w = color.alpha;
  1559. return result;
  1560. };
  1561. /**
  1562. * Duplicates a Cartesian4 instance.
  1563. *
  1564. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  1565. * @param {Cartesian4} [result] The object onto which to store the result.
  1566. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  1567. */
  1568. Cartesian4.clone = function(cartesian, result) {
  1569. if (!defined.defined(cartesian)) {
  1570. return undefined;
  1571. }
  1572. if (!defined.defined(result)) {
  1573. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  1574. }
  1575. result.x = cartesian.x;
  1576. result.y = cartesian.y;
  1577. result.z = cartesian.z;
  1578. result.w = cartesian.w;
  1579. return result;
  1580. };
  1581. /**
  1582. * The number of elements used to pack the object into an array.
  1583. * @type {Number}
  1584. */
  1585. Cartesian4.packedLength = 4;
  1586. /**
  1587. * Stores the provided instance into the provided array.
  1588. *
  1589. * @param {Cartesian4} value The value to pack.
  1590. * @param {Number[]} array The array to pack into.
  1591. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  1592. *
  1593. * @returns {Number[]} The array that was packed into
  1594. */
  1595. Cartesian4.pack = function(value, array, startingIndex) {
  1596. //>>includeStart('debug', pragmas.debug);
  1597. Check.Check.typeOf.object('value', value);
  1598. Check.Check.defined('array', array);
  1599. //>>includeEnd('debug');
  1600. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  1601. array[startingIndex++] = value.x;
  1602. array[startingIndex++] = value.y;
  1603. array[startingIndex++] = value.z;
  1604. array[startingIndex] = value.w;
  1605. return array;
  1606. };
  1607. /**
  1608. * Retrieves an instance from a packed array.
  1609. *
  1610. * @param {Number[]} array The packed array.
  1611. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  1612. * @param {Cartesian4} [result] The object into which to store the result.
  1613. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1614. */
  1615. Cartesian4.unpack = function(array, startingIndex, result) {
  1616. //>>includeStart('debug', pragmas.debug);
  1617. Check.Check.defined('array', array);
  1618. //>>includeEnd('debug');
  1619. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  1620. if (!defined.defined(result)) {
  1621. result = new Cartesian4();
  1622. }
  1623. result.x = array[startingIndex++];
  1624. result.y = array[startingIndex++];
  1625. result.z = array[startingIndex++];
  1626. result.w = array[startingIndex];
  1627. return result;
  1628. };
  1629. /**
  1630. * Flattens an array of Cartesian4s into and array of components.
  1631. *
  1632. * @param {Cartesian4[]} array The array of cartesians to pack.
  1633. * @param {Number[]} [result] The array onto which to store the result.
  1634. * @returns {Number[]} The packed array.
  1635. */
  1636. Cartesian4.packArray = function(array, result) {
  1637. //>>includeStart('debug', pragmas.debug);
  1638. Check.Check.defined('array', array);
  1639. //>>includeEnd('debug');
  1640. var length = array.length;
  1641. if (!defined.defined(result)) {
  1642. result = new Array(length * 4);
  1643. } else {
  1644. result.length = length * 4;
  1645. }
  1646. for (var i = 0; i < length; ++i) {
  1647. Cartesian4.pack(array[i], result, i * 4);
  1648. }
  1649. return result;
  1650. };
  1651. /**
  1652. * Unpacks an array of cartesian components into and array of Cartesian4s.
  1653. *
  1654. * @param {Number[]} array The array of components to unpack.
  1655. * @param {Cartesian4[]} [result] The array onto which to store the result.
  1656. * @returns {Cartesian4[]} The unpacked array.
  1657. */
  1658. Cartesian4.unpackArray = function(array, result) {
  1659. //>>includeStart('debug', pragmas.debug);
  1660. Check.Check.defined('array', array);
  1661. //>>includeEnd('debug');
  1662. var length = array.length;
  1663. if (!defined.defined(result)) {
  1664. result = new Array(length / 4);
  1665. } else {
  1666. result.length = length / 4;
  1667. }
  1668. for (var i = 0; i < length; i += 4) {
  1669. var index = i / 4;
  1670. result[index] = Cartesian4.unpack(array, i, result[index]);
  1671. }
  1672. return result;
  1673. };
  1674. /**
  1675. * Creates a Cartesian4 from four consecutive elements in an array.
  1676. * @function
  1677. *
  1678. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  1679. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  1680. * @param {Cartesian4} [result] The object onto which to store the result.
  1681. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  1682. *
  1683. * @example
  1684. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  1685. * var v = [1.0, 2.0, 3.0, 4.0];
  1686. * var p = Cesium.Cartesian4.fromArray(v);
  1687. *
  1688. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  1689. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  1690. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  1691. */
  1692. Cartesian4.fromArray = Cartesian4.unpack;
  1693. /**
  1694. * Computes the value of the maximum component for the supplied Cartesian.
  1695. *
  1696. * @param {Cartesian4} cartesian The cartesian to use.
  1697. * @returns {Number} The value of the maximum component.
  1698. */
  1699. Cartesian4.maximumComponent = function(cartesian) {
  1700. //>>includeStart('debug', pragmas.debug);
  1701. Check.Check.typeOf.object('cartesian', cartesian);
  1702. //>>includeEnd('debug');
  1703. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  1704. };
  1705. /**
  1706. * Computes the value of the minimum component for the supplied Cartesian.
  1707. *
  1708. * @param {Cartesian4} cartesian The cartesian to use.
  1709. * @returns {Number} The value of the minimum component.
  1710. */
  1711. Cartesian4.minimumComponent = function(cartesian) {
  1712. //>>includeStart('debug', pragmas.debug);
  1713. Check.Check.typeOf.object('cartesian', cartesian);
  1714. //>>includeEnd('debug');
  1715. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  1716. };
  1717. /**
  1718. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  1719. *
  1720. * @param {Cartesian4} first A cartesian to compare.
  1721. * @param {Cartesian4} second A cartesian to compare.
  1722. * @param {Cartesian4} result The object into which to store the result.
  1723. * @returns {Cartesian4} A cartesian with the minimum components.
  1724. */
  1725. Cartesian4.minimumByComponent = function(first, second, result) {
  1726. //>>includeStart('debug', pragmas.debug);
  1727. Check.Check.typeOf.object('first', first);
  1728. Check.Check.typeOf.object('second', second);
  1729. Check.Check.typeOf.object('result', result);
  1730. //>>includeEnd('debug');
  1731. result.x = Math.min(first.x, second.x);
  1732. result.y = Math.min(first.y, second.y);
  1733. result.z = Math.min(first.z, second.z);
  1734. result.w = Math.min(first.w, second.w);
  1735. return result;
  1736. };
  1737. /**
  1738. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  1739. *
  1740. * @param {Cartesian4} first A cartesian to compare.
  1741. * @param {Cartesian4} second A cartesian to compare.
  1742. * @param {Cartesian4} result The object into which to store the result.
  1743. * @returns {Cartesian4} A cartesian with the maximum components.
  1744. */
  1745. Cartesian4.maximumByComponent = function(first, second, result) {
  1746. //>>includeStart('debug', pragmas.debug);
  1747. Check.Check.typeOf.object('first', first);
  1748. Check.Check.typeOf.object('second', second);
  1749. Check.Check.typeOf.object('result', result);
  1750. //>>includeEnd('debug');
  1751. result.x = Math.max(first.x, second.x);
  1752. result.y = Math.max(first.y, second.y);
  1753. result.z = Math.max(first.z, second.z);
  1754. result.w = Math.max(first.w, second.w);
  1755. return result;
  1756. };
  1757. /**
  1758. * Computes the provided Cartesian's squared magnitude.
  1759. *
  1760. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  1761. * @returns {Number} The squared magnitude.
  1762. */
  1763. Cartesian4.magnitudeSquared = function(cartesian) {
  1764. //>>includeStart('debug', pragmas.debug);
  1765. Check.Check.typeOf.object('cartesian', cartesian);
  1766. //>>includeEnd('debug');
  1767. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  1768. };
  1769. /**
  1770. * Computes the Cartesian's magnitude (length).
  1771. *
  1772. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  1773. * @returns {Number} The magnitude.
  1774. */
  1775. Cartesian4.magnitude = function(cartesian) {
  1776. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  1777. };
  1778. var distanceScratch = new Cartesian4();
  1779. /**
  1780. * Computes the 4-space distance between two points.
  1781. *
  1782. * @param {Cartesian4} left The first point to compute the distance from.
  1783. * @param {Cartesian4} right The second point to compute the distance to.
  1784. * @returns {Number} The distance between two points.
  1785. *
  1786. * @example
  1787. * // Returns 1.0
  1788. * var d = Cesium.Cartesian4.distance(
  1789. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  1790. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  1791. */
  1792. Cartesian4.distance = function(left, right) {
  1793. //>>includeStart('debug', pragmas.debug);
  1794. Check.Check.typeOf.object('left', left);
  1795. Check.Check.typeOf.object('right', right);
  1796. //>>includeEnd('debug');
  1797. Cartesian4.subtract(left, right, distanceScratch);
  1798. return Cartesian4.magnitude(distanceScratch);
  1799. };
  1800. /**
  1801. * Computes the squared distance between two points. Comparing squared distances
  1802. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  1803. *
  1804. * @param {Cartesian4} left The first point to compute the distance from.
  1805. * @param {Cartesian4} right The second point to compute the distance to.
  1806. * @returns {Number} The distance between two points.
  1807. *
  1808. * @example
  1809. * // Returns 4.0, not 2.0
  1810. * var d = Cesium.Cartesian4.distance(
  1811. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  1812. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  1813. */
  1814. Cartesian4.distanceSquared = function(left, right) {
  1815. //>>includeStart('debug', pragmas.debug);
  1816. Check.Check.typeOf.object('left', left);
  1817. Check.Check.typeOf.object('right', right);
  1818. //>>includeEnd('debug');
  1819. Cartesian4.subtract(left, right, distanceScratch);
  1820. return Cartesian4.magnitudeSquared(distanceScratch);
  1821. };
  1822. /**
  1823. * Computes the normalized form of the supplied Cartesian.
  1824. *
  1825. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  1826. * @param {Cartesian4} result The object onto which to store the result.
  1827. * @returns {Cartesian4} The modified result parameter.
  1828. */
  1829. Cartesian4.normalize = function(cartesian, result) {
  1830. //>>includeStart('debug', pragmas.debug);
  1831. Check.Check.typeOf.object('cartesian', cartesian);
  1832. Check.Check.typeOf.object('result', result);
  1833. //>>includeEnd('debug');
  1834. var magnitude = Cartesian4.magnitude(cartesian);
  1835. result.x = cartesian.x / magnitude;
  1836. result.y = cartesian.y / magnitude;
  1837. result.z = cartesian.z / magnitude;
  1838. result.w = cartesian.w / magnitude;
  1839. //>>includeStart('debug', pragmas.debug);
  1840. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  1841. throw new Check.DeveloperError('normalized result is not a number');
  1842. }
  1843. //>>includeEnd('debug');
  1844. return result;
  1845. };
  1846. /**
  1847. * Computes the dot (scalar) product of two Cartesians.
  1848. *
  1849. * @param {Cartesian4} left The first Cartesian.
  1850. * @param {Cartesian4} right The second Cartesian.
  1851. * @returns {Number} The dot product.
  1852. */
  1853. Cartesian4.dot = function(left, right) {
  1854. //>>includeStart('debug', pragmas.debug);
  1855. Check.Check.typeOf.object('left', left);
  1856. Check.Check.typeOf.object('right', right);
  1857. //>>includeEnd('debug');
  1858. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  1859. };
  1860. /**
  1861. * Computes the componentwise product of two Cartesians.
  1862. *
  1863. * @param {Cartesian4} left The first Cartesian.
  1864. * @param {Cartesian4} right The second Cartesian.
  1865. * @param {Cartesian4} result The object onto which to store the result.
  1866. * @returns {Cartesian4} The modified result parameter.
  1867. */
  1868. Cartesian4.multiplyComponents = function(left, right, result) {
  1869. //>>includeStart('debug', pragmas.debug);
  1870. Check.Check.typeOf.object('left', left);
  1871. Check.Check.typeOf.object('right', right);
  1872. Check.Check.typeOf.object('result', result);
  1873. //>>includeEnd('debug');
  1874. result.x = left.x * right.x;
  1875. result.y = left.y * right.y;
  1876. result.z = left.z * right.z;
  1877. result.w = left.w * right.w;
  1878. return result;
  1879. };
  1880. /**
  1881. * Computes the componentwise quotient of two Cartesians.
  1882. *
  1883. * @param {Cartesian4} left The first Cartesian.
  1884. * @param {Cartesian4} right The second Cartesian.
  1885. * @param {Cartesian4} result The object onto which to store the result.
  1886. * @returns {Cartesian4} The modified result parameter.
  1887. */
  1888. Cartesian4.divideComponents = function(left, right, result) {
  1889. //>>includeStart('debug', pragmas.debug);
  1890. Check.Check.typeOf.object('left', left);
  1891. Check.Check.typeOf.object('right', right);
  1892. Check.Check.typeOf.object('result', result);
  1893. //>>includeEnd('debug');
  1894. result.x = left.x / right.x;
  1895. result.y = left.y / right.y;
  1896. result.z = left.z / right.z;
  1897. result.w = left.w / right.w;
  1898. return result;
  1899. };
  1900. /**
  1901. * Computes the componentwise sum of two Cartesians.
  1902. *
  1903. * @param {Cartesian4} left The first Cartesian.
  1904. * @param {Cartesian4} right The second Cartesian.
  1905. * @param {Cartesian4} result The object onto which to store the result.
  1906. * @returns {Cartesian4} The modified result parameter.
  1907. */
  1908. Cartesian4.add = function(left, right, result) {
  1909. //>>includeStart('debug', pragmas.debug);
  1910. Check.Check.typeOf.object('left', left);
  1911. Check.Check.typeOf.object('right', right);
  1912. Check.Check.typeOf.object('result', result);
  1913. //>>includeEnd('debug');
  1914. result.x = left.x + right.x;
  1915. result.y = left.y + right.y;
  1916. result.z = left.z + right.z;
  1917. result.w = left.w + right.w;
  1918. return result;
  1919. };
  1920. /**
  1921. * Computes the componentwise difference of two Cartesians.
  1922. *
  1923. * @param {Cartesian4} left The first Cartesian.
  1924. * @param {Cartesian4} right The second Cartesian.
  1925. * @param {Cartesian4} result The object onto which to store the result.
  1926. * @returns {Cartesian4} The modified result parameter.
  1927. */
  1928. Cartesian4.subtract = function(left, right, result) {
  1929. //>>includeStart('debug', pragmas.debug);
  1930. Check.Check.typeOf.object('left', left);
  1931. Check.Check.typeOf.object('right', right);
  1932. Check.Check.typeOf.object('result', result);
  1933. //>>includeEnd('debug');
  1934. result.x = left.x - right.x;
  1935. result.y = left.y - right.y;
  1936. result.z = left.z - right.z;
  1937. result.w = left.w - right.w;
  1938. return result;
  1939. };
  1940. /**
  1941. * Multiplies the provided Cartesian componentwise by the provided scalar.
  1942. *
  1943. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  1944. * @param {Number} scalar The scalar to multiply with.
  1945. * @param {Cartesian4} result The object onto which to store the result.
  1946. * @returns {Cartesian4} The modified result parameter.
  1947. */
  1948. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  1949. //>>includeStart('debug', pragmas.debug);
  1950. Check.Check.typeOf.object('cartesian', cartesian);
  1951. Check.Check.typeOf.number('scalar', scalar);
  1952. Check.Check.typeOf.object('result', result);
  1953. //>>includeEnd('debug');
  1954. result.x = cartesian.x * scalar;
  1955. result.y = cartesian.y * scalar;
  1956. result.z = cartesian.z * scalar;
  1957. result.w = cartesian.w * scalar;
  1958. return result;
  1959. };
  1960. /**
  1961. * Divides the provided Cartesian componentwise by the provided scalar.
  1962. *
  1963. * @param {Cartesian4} cartesian The Cartesian to be divided.
  1964. * @param {Number} scalar The scalar to divide by.
  1965. * @param {Cartesian4} result The object onto which to store the result.
  1966. * @returns {Cartesian4} The modified result parameter.
  1967. */
  1968. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  1969. //>>includeStart('debug', pragmas.debug);
  1970. Check.Check.typeOf.object('cartesian', cartesian);
  1971. Check.Check.typeOf.number('scalar', scalar);
  1972. Check.Check.typeOf.object('result', result);
  1973. //>>includeEnd('debug');
  1974. result.x = cartesian.x / scalar;
  1975. result.y = cartesian.y / scalar;
  1976. result.z = cartesian.z / scalar;
  1977. result.w = cartesian.w / scalar;
  1978. return result;
  1979. };
  1980. /**
  1981. * Negates the provided Cartesian.
  1982. *
  1983. * @param {Cartesian4} cartesian The Cartesian to be negated.
  1984. * @param {Cartesian4} result The object onto which to store the result.
  1985. * @returns {Cartesian4} The modified result parameter.
  1986. */
  1987. Cartesian4.negate = function(cartesian, result) {
  1988. //>>includeStart('debug', pragmas.debug);
  1989. Check.Check.typeOf.object('cartesian', cartesian);
  1990. Check.Check.typeOf.object('result', result);
  1991. //>>includeEnd('debug');
  1992. result.x = -cartesian.x;
  1993. result.y = -cartesian.y;
  1994. result.z = -cartesian.z;
  1995. result.w = -cartesian.w;
  1996. return result;
  1997. };
  1998. /**
  1999. * Computes the absolute value of the provided Cartesian.
  2000. *
  2001. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  2002. * @param {Cartesian4} result The object onto which to store the result.
  2003. * @returns {Cartesian4} The modified result parameter.
  2004. */
  2005. Cartesian4.abs = function(cartesian, result) {
  2006. //>>includeStart('debug', pragmas.debug);
  2007. Check.Check.typeOf.object('cartesian', cartesian);
  2008. Check.Check.typeOf.object('result', result);
  2009. //>>includeEnd('debug');
  2010. result.x = Math.abs(cartesian.x);
  2011. result.y = Math.abs(cartesian.y);
  2012. result.z = Math.abs(cartesian.z);
  2013. result.w = Math.abs(cartesian.w);
  2014. return result;
  2015. };
  2016. var lerpScratch = new Cartesian4();
  2017. /**
  2018. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  2019. *
  2020. * @param {Cartesian4} start The value corresponding to t at 0.0.
  2021. * @param {Cartesian4}end The value corresponding to t at 1.0.
  2022. * @param {Number} t The point along t at which to interpolate.
  2023. * @param {Cartesian4} result The object onto which to store the result.
  2024. * @returns {Cartesian4} The modified result parameter.
  2025. */
  2026. Cartesian4.lerp = function(start, end, t, result) {
  2027. //>>includeStart('debug', pragmas.debug);
  2028. Check.Check.typeOf.object('start', start);
  2029. Check.Check.typeOf.object('end', end);
  2030. Check.Check.typeOf.number('t', t);
  2031. Check.Check.typeOf.object('result', result);
  2032. //>>includeEnd('debug');
  2033. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  2034. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  2035. return Cartesian4.add(lerpScratch, result, result);
  2036. };
  2037. var mostOrthogonalAxisScratch = new Cartesian4();
  2038. /**
  2039. * Returns the axis that is most orthogonal to the provided Cartesian.
  2040. *
  2041. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  2042. * @param {Cartesian4} result The object onto which to store the result.
  2043. * @returns {Cartesian4} The most orthogonal axis.
  2044. */
  2045. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  2046. //>>includeStart('debug', pragmas.debug);
  2047. Check.Check.typeOf.object('cartesian', cartesian);
  2048. Check.Check.typeOf.object('result', result);
  2049. //>>includeEnd('debug');
  2050. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  2051. Cartesian4.abs(f, f);
  2052. if (f.x <= f.y) {
  2053. if (f.x <= f.z) {
  2054. if (f.x <= f.w) {
  2055. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  2056. } else {
  2057. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2058. }
  2059. } else if (f.z <= f.w) {
  2060. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  2061. } else {
  2062. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2063. }
  2064. } else if (f.y <= f.z) {
  2065. if (f.y <= f.w) {
  2066. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  2067. } else {
  2068. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2069. }
  2070. } else if (f.z <= f.w) {
  2071. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  2072. } else {
  2073. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  2074. }
  2075. return result;
  2076. };
  2077. /**
  2078. * Compares the provided Cartesians componentwise and returns
  2079. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2080. *
  2081. * @param {Cartesian4} [left] The first Cartesian.
  2082. * @param {Cartesian4} [right] The second Cartesian.
  2083. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2084. */
  2085. Cartesian4.equals = function(left, right) {
  2086. return (left === right) ||
  2087. ((defined.defined(left)) &&
  2088. (defined.defined(right)) &&
  2089. (left.x === right.x) &&
  2090. (left.y === right.y) &&
  2091. (left.z === right.z) &&
  2092. (left.w === right.w));
  2093. };
  2094. /**
  2095. * @private
  2096. */
  2097. Cartesian4.equalsArray = function(cartesian, array, offset) {
  2098. return cartesian.x === array[offset] &&
  2099. cartesian.y === array[offset + 1] &&
  2100. cartesian.z === array[offset + 2] &&
  2101. cartesian.w === array[offset + 3];
  2102. };
  2103. /**
  2104. * Compares the provided Cartesians componentwise and returns
  2105. * <code>true</code> if they pass an absolute or relative tolerance test,
  2106. * <code>false</code> otherwise.
  2107. *
  2108. * @param {Cartesian4} [left] The first Cartesian.
  2109. * @param {Cartesian4} [right] The second Cartesian.
  2110. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2111. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2112. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2113. */
  2114. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  2115. return (left === right) ||
  2116. (defined.defined(left) &&
  2117. defined.defined(right) &&
  2118. _Math.CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  2119. _Math.CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  2120. _Math.CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  2121. _Math.CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  2122. };
  2123. /**
  2124. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  2125. *
  2126. * @type {Cartesian4}
  2127. * @constant
  2128. */
  2129. Cartesian4.ZERO = freezeObject.freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  2130. /**
  2131. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  2132. *
  2133. * @type {Cartesian4}
  2134. * @constant
  2135. */
  2136. Cartesian4.UNIT_X = freezeObject.freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  2137. /**
  2138. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  2139. *
  2140. * @type {Cartesian4}
  2141. * @constant
  2142. */
  2143. Cartesian4.UNIT_Y = freezeObject.freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  2144. /**
  2145. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  2146. *
  2147. * @type {Cartesian4}
  2148. * @constant
  2149. */
  2150. Cartesian4.UNIT_Z = freezeObject.freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  2151. /**
  2152. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  2153. *
  2154. * @type {Cartesian4}
  2155. * @constant
  2156. */
  2157. Cartesian4.UNIT_W = freezeObject.freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  2158. /**
  2159. * Duplicates this Cartesian4 instance.
  2160. *
  2161. * @param {Cartesian4} [result] The object onto which to store the result.
  2162. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  2163. */
  2164. Cartesian4.prototype.clone = function(result) {
  2165. return Cartesian4.clone(this, result);
  2166. };
  2167. /**
  2168. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2169. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2170. *
  2171. * @param {Cartesian4} [right] The right hand side Cartesian.
  2172. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  2173. */
  2174. Cartesian4.prototype.equals = function(right) {
  2175. return Cartesian4.equals(this, right);
  2176. };
  2177. /**
  2178. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2179. * <code>true</code> if they pass an absolute or relative tolerance test,
  2180. * <code>false</code> otherwise.
  2181. *
  2182. * @param {Cartesian4} [right] The right hand side Cartesian.
  2183. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2184. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2185. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  2186. */
  2187. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  2188. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  2189. };
  2190. /**
  2191. * Creates a string representing this Cartesian in the format '(x, y, z, w)'.
  2192. *
  2193. * @returns {String} A string representing the provided Cartesian in the format '(x, y, z, w)'.
  2194. */
  2195. Cartesian4.prototype.toString = function() {
  2196. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  2197. };
  2198. var scratchFloatArray = new Float32Array(1);
  2199. var SHIFT_LEFT_8 = 256.0;
  2200. var SHIFT_LEFT_16 = 65536.0;
  2201. var SHIFT_LEFT_24 = 16777216.0;
  2202. var SHIFT_RIGHT_8 = 1.0 / SHIFT_LEFT_8;
  2203. var SHIFT_RIGHT_16 = 1.0 / SHIFT_LEFT_16;
  2204. var SHIFT_RIGHT_24 = 1.0 / SHIFT_LEFT_24;
  2205. var BIAS = 38.0;
  2206. /**
  2207. * Packs an arbitrary floating point value to 4 values representable using uint8.
  2208. *
  2209. * @param {Number} value A floating point number
  2210. * @param {Cartesian4} [result] The Cartesian4 that will contain the packed float.
  2211. * @returns {Cartesian4} A Cartesian4 representing the float packed to values in x, y, z, and w.
  2212. */
  2213. Cartesian4.packFloat = function(value, result) {
  2214. //>>includeStart('debug', pragmas.debug);
  2215. Check.Check.typeOf.number('value', value);
  2216. //>>includeEnd('debug');
  2217. if (!defined.defined(result)) {
  2218. result = new Cartesian4();
  2219. }
  2220. // Force the value to 32 bit precision
  2221. scratchFloatArray[0] = value;
  2222. value = scratchFloatArray[0];
  2223. if (value === 0.0) {
  2224. return Cartesian4.clone(Cartesian4.ZERO, result);
  2225. }
  2226. var sign = value < 0.0 ? 1.0 : 0.0;
  2227. var exponent;
  2228. if (!isFinite(value)) {
  2229. value = 0.1;
  2230. exponent = BIAS;
  2231. } else {
  2232. value = Math.abs(value);
  2233. exponent = Math.floor(_Math.CesiumMath.logBase(value, 10)) + 1.0;
  2234. value = value / Math.pow(10.0, exponent);
  2235. }
  2236. var temp = value * SHIFT_LEFT_8;
  2237. result.x = Math.floor(temp);
  2238. temp = (temp - result.x) * SHIFT_LEFT_8;
  2239. result.y = Math.floor(temp);
  2240. temp = (temp - result.y) * SHIFT_LEFT_8;
  2241. result.z = Math.floor(temp);
  2242. result.w = (exponent + BIAS) * 2.0 + sign;
  2243. return result;
  2244. };
  2245. /**
  2246. * Unpacks a float packed using Cartesian4.packFloat.
  2247. *
  2248. * @param {Cartesian4} packedFloat A Cartesian4 containing a float packed to 4 values representable using uint8.
  2249. * @returns {Number} The unpacked float.
  2250. * @private
  2251. */
  2252. Cartesian4.unpackFloat = function(packedFloat) {
  2253. //>>includeStart('debug', pragmas.debug);
  2254. Check.Check.typeOf.object('packedFloat', packedFloat);
  2255. //>>includeEnd('debug');
  2256. var temp = packedFloat.w / 2.0;
  2257. var exponent = Math.floor(temp);
  2258. var sign = (temp - exponent) * 2.0;
  2259. exponent = exponent - BIAS;
  2260. sign = sign * 2.0 - 1.0;
  2261. sign = -sign;
  2262. if (exponent >= BIAS) {
  2263. return sign < 0.0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
  2264. }
  2265. var unpacked = sign * packedFloat.x * SHIFT_RIGHT_8;
  2266. unpacked += sign * packedFloat.y * SHIFT_RIGHT_16;
  2267. unpacked += sign * packedFloat.z * SHIFT_RIGHT_24;
  2268. return unpacked * Math.pow(10.0, exponent);
  2269. };
  2270. var warnings = {};
  2271. /**
  2272. * Logs a one time message to the console. Use this function instead of
  2273. * <code>console.log</code> directly since this does not log duplicate messages
  2274. * unless it is called from multiple workers.
  2275. *
  2276. * @exports oneTimeWarning
  2277. *
  2278. * @param {String} identifier The unique identifier for this warning.
  2279. * @param {String} [message=identifier] The message to log to the console.
  2280. *
  2281. * @example
  2282. * for(var i=0;i<foo.length;++i) {
  2283. * if (!defined(foo[i].bar)) {
  2284. * // Something that can be recovered from but may happen a lot
  2285. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  2286. * foo[i].bar = 0;
  2287. * // ...
  2288. * }
  2289. * }
  2290. *
  2291. * @private
  2292. */
  2293. function oneTimeWarning(identifier, message) {
  2294. //>>includeStart('debug', pragmas.debug);
  2295. if (!defined.defined(identifier)) {
  2296. throw new Check.DeveloperError('identifier is required.');
  2297. }
  2298. //>>includeEnd('debug');
  2299. if (!defined.defined(warnings[identifier])) {
  2300. warnings[identifier] = true;
  2301. console.warn(defaultValue.defaultValue(message, identifier));
  2302. }
  2303. }
  2304. oneTimeWarning.geometryOutlines = 'Entity geometry outlines are unsupported on terrain. Outlines will be disabled. To enable outlines, disable geometry terrain clamping by explicitly setting height to 0.';
  2305. oneTimeWarning.geometryZIndex = 'Entity geometry with zIndex are unsupported when height or extrudedHeight are defined. zIndex will be ignored';
  2306. oneTimeWarning.geometryHeightReference = 'Entity corridor, ellipse, polygon or rectangle with heightReference must also have a defined height. heightReference will be ignored';
  2307. oneTimeWarning.geometryExtrudedHeightReference = 'Entity corridor, ellipse, polygon or rectangle with extrudedHeightReference must also have a defined extrudedHeight. extrudedHeightReference will be ignored';
  2308. /**
  2309. * Logs a deprecation message to the console. Use this function instead of
  2310. * <code>console.log</code> directly since this does not log duplicate messages
  2311. * unless it is called from multiple workers.
  2312. *
  2313. * @exports deprecationWarning
  2314. *
  2315. * @param {String} identifier The unique identifier for this deprecated API.
  2316. * @param {String} message The message to log to the console.
  2317. *
  2318. * @example
  2319. * // Deprecated function or class
  2320. * function Foo() {
  2321. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  2322. * // ...
  2323. * }
  2324. *
  2325. * // Deprecated function
  2326. * Bar.prototype.func = function() {
  2327. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  2328. * // ...
  2329. * };
  2330. *
  2331. * // Deprecated property
  2332. * defineProperties(Bar.prototype, {
  2333. * prop : {
  2334. * get : function() {
  2335. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  2336. * // ...
  2337. * },
  2338. * set : function(value) {
  2339. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  2340. * // ...
  2341. * }
  2342. * }
  2343. * });
  2344. *
  2345. * @private
  2346. */
  2347. function deprecationWarning(identifier, message) {
  2348. //>>includeStart('debug', pragmas.debug);
  2349. if (!defined.defined(identifier) || !defined.defined(message)) {
  2350. throw new Check.DeveloperError('identifier and message are required.');
  2351. }
  2352. //>>includeEnd('debug');
  2353. oneTimeWarning(identifier, message);
  2354. }
  2355. /**
  2356. * A 4x4 matrix, indexable as a column-major order array.
  2357. * Constructor parameters are in row-major order for code readability.
  2358. * @alias Matrix4
  2359. * @constructor
  2360. *
  2361. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  2362. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  2363. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  2364. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  2365. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  2366. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  2367. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  2368. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  2369. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  2370. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  2371. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  2372. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  2373. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  2374. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  2375. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  2376. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  2377. *
  2378. * @see Matrix4.fromColumnMajorArray
  2379. * @see Matrix4.fromRowMajorArray
  2380. * @see Matrix4.fromRotationTranslation
  2381. * @see Matrix4.fromTranslationRotationScale
  2382. * @see Matrix4.fromTranslationQuaternionRotationScale
  2383. * @see Matrix4.fromTranslation
  2384. * @see Matrix4.fromScale
  2385. * @see Matrix4.fromUniformScale
  2386. * @see Matrix4.fromCamera
  2387. * @see Matrix4.computePerspectiveFieldOfView
  2388. * @see Matrix4.computeOrthographicOffCenter
  2389. * @see Matrix4.computePerspectiveOffCenter
  2390. * @see Matrix4.computeInfinitePerspectiveOffCenter
  2391. * @see Matrix4.computeViewportTransformation
  2392. * @see Matrix4.computeView
  2393. * @see Matrix2
  2394. * @see Matrix3
  2395. * @see Packable
  2396. */
  2397. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  2398. column0Row1, column1Row1, column2Row1, column3Row1,
  2399. column0Row2, column1Row2, column2Row2, column3Row2,
  2400. column0Row3, column1Row3, column2Row3, column3Row3) {
  2401. this[0] = defaultValue.defaultValue(column0Row0, 0.0);
  2402. this[1] = defaultValue.defaultValue(column0Row1, 0.0);
  2403. this[2] = defaultValue.defaultValue(column0Row2, 0.0);
  2404. this[3] = defaultValue.defaultValue(column0Row3, 0.0);
  2405. this[4] = defaultValue.defaultValue(column1Row0, 0.0);
  2406. this[5] = defaultValue.defaultValue(column1Row1, 0.0);
  2407. this[6] = defaultValue.defaultValue(column1Row2, 0.0);
  2408. this[7] = defaultValue.defaultValue(column1Row3, 0.0);
  2409. this[8] = defaultValue.defaultValue(column2Row0, 0.0);
  2410. this[9] = defaultValue.defaultValue(column2Row1, 0.0);
  2411. this[10] = defaultValue.defaultValue(column2Row2, 0.0);
  2412. this[11] = defaultValue.defaultValue(column2Row3, 0.0);
  2413. this[12] = defaultValue.defaultValue(column3Row0, 0.0);
  2414. this[13] = defaultValue.defaultValue(column3Row1, 0.0);
  2415. this[14] = defaultValue.defaultValue(column3Row2, 0.0);
  2416. this[15] = defaultValue.defaultValue(column3Row3, 0.0);
  2417. }
  2418. /**
  2419. * The number of elements used to pack the object into an array.
  2420. * @type {Number}
  2421. */
  2422. Matrix4.packedLength = 16;
  2423. /**
  2424. * Stores the provided instance into the provided array.
  2425. *
  2426. * @param {Matrix4} value The value to pack.
  2427. * @param {Number[]} array The array to pack into.
  2428. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2429. *
  2430. * @returns {Number[]} The array that was packed into
  2431. */
  2432. Matrix4.pack = function(value, array, startingIndex) {
  2433. //>>includeStart('debug', pragmas.debug);
  2434. Check.Check.typeOf.object('value', value);
  2435. Check.Check.defined('array', array);
  2436. //>>includeEnd('debug');
  2437. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  2438. array[startingIndex++] = value[0];
  2439. array[startingIndex++] = value[1];
  2440. array[startingIndex++] = value[2];
  2441. array[startingIndex++] = value[3];
  2442. array[startingIndex++] = value[4];
  2443. array[startingIndex++] = value[5];
  2444. array[startingIndex++] = value[6];
  2445. array[startingIndex++] = value[7];
  2446. array[startingIndex++] = value[8];
  2447. array[startingIndex++] = value[9];
  2448. array[startingIndex++] = value[10];
  2449. array[startingIndex++] = value[11];
  2450. array[startingIndex++] = value[12];
  2451. array[startingIndex++] = value[13];
  2452. array[startingIndex++] = value[14];
  2453. array[startingIndex] = value[15];
  2454. return array;
  2455. };
  2456. /**
  2457. * Retrieves an instance from a packed array.
  2458. *
  2459. * @param {Number[]} array The packed array.
  2460. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2461. * @param {Matrix4} [result] The object into which to store the result.
  2462. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  2463. */
  2464. Matrix4.unpack = function(array, startingIndex, result) {
  2465. //>>includeStart('debug', pragmas.debug);
  2466. Check.Check.defined('array', array);
  2467. //>>includeEnd('debug');
  2468. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  2469. if (!defined.defined(result)) {
  2470. result = new Matrix4();
  2471. }
  2472. result[0] = array[startingIndex++];
  2473. result[1] = array[startingIndex++];
  2474. result[2] = array[startingIndex++];
  2475. result[3] = array[startingIndex++];
  2476. result[4] = array[startingIndex++];
  2477. result[5] = array[startingIndex++];
  2478. result[6] = array[startingIndex++];
  2479. result[7] = array[startingIndex++];
  2480. result[8] = array[startingIndex++];
  2481. result[9] = array[startingIndex++];
  2482. result[10] = array[startingIndex++];
  2483. result[11] = array[startingIndex++];
  2484. result[12] = array[startingIndex++];
  2485. result[13] = array[startingIndex++];
  2486. result[14] = array[startingIndex++];
  2487. result[15] = array[startingIndex];
  2488. return result;
  2489. };
  2490. /**
  2491. * Duplicates a Matrix4 instance.
  2492. *
  2493. * @param {Matrix4} matrix The matrix to duplicate.
  2494. * @param {Matrix4} [result] The object onto which to store the result.
  2495. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  2496. */
  2497. Matrix4.clone = function(matrix, result) {
  2498. if (!defined.defined(matrix)) {
  2499. return undefined;
  2500. }
  2501. if (!defined.defined(result)) {
  2502. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  2503. matrix[1], matrix[5], matrix[9], matrix[13],
  2504. matrix[2], matrix[6], matrix[10], matrix[14],
  2505. matrix[3], matrix[7], matrix[11], matrix[15]);
  2506. }
  2507. result[0] = matrix[0];
  2508. result[1] = matrix[1];
  2509. result[2] = matrix[2];
  2510. result[3] = matrix[3];
  2511. result[4] = matrix[4];
  2512. result[5] = matrix[5];
  2513. result[6] = matrix[6];
  2514. result[7] = matrix[7];
  2515. result[8] = matrix[8];
  2516. result[9] = matrix[9];
  2517. result[10] = matrix[10];
  2518. result[11] = matrix[11];
  2519. result[12] = matrix[12];
  2520. result[13] = matrix[13];
  2521. result[14] = matrix[14];
  2522. result[15] = matrix[15];
  2523. return result;
  2524. };
  2525. /**
  2526. * Creates a Matrix4 from 16 consecutive elements in an array.
  2527. * @function
  2528. *
  2529. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  2530. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  2531. * @param {Matrix4} [result] The object onto which to store the result.
  2532. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  2533. *
  2534. * @example
  2535. * // Create the Matrix4:
  2536. * // [1.0, 2.0, 3.0, 4.0]
  2537. * // [1.0, 2.0, 3.0, 4.0]
  2538. * // [1.0, 2.0, 3.0, 4.0]
  2539. * // [1.0, 2.0, 3.0, 4.0]
  2540. *
  2541. * 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];
  2542. * var m = Cesium.Matrix4.fromArray(v);
  2543. *
  2544. * // Create same Matrix4 with using an offset into an array
  2545. * 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];
  2546. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  2547. */
  2548. Matrix4.fromArray = Matrix4.unpack;
  2549. /**
  2550. * Computes a Matrix4 instance from a column-major order array.
  2551. *
  2552. * @param {Number[]} values The column-major order array.
  2553. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2554. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2555. */
  2556. Matrix4.fromColumnMajorArray = function(values, result) {
  2557. //>>includeStart('debug', pragmas.debug);
  2558. Check.Check.defined('values', values);
  2559. //>>includeEnd('debug');
  2560. return Matrix4.clone(values, result);
  2561. };
  2562. /**
  2563. * Computes a Matrix4 instance from a row-major order array.
  2564. * The resulting matrix will be in column-major order.
  2565. *
  2566. * @param {Number[]} values The row-major order array.
  2567. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2568. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2569. */
  2570. Matrix4.fromRowMajorArray = function(values, result) {
  2571. //>>includeStart('debug', pragmas.debug);
  2572. Check.Check.defined('values', values);
  2573. //>>includeEnd('debug');
  2574. if (!defined.defined(result)) {
  2575. return new Matrix4(values[0], values[1], values[2], values[3],
  2576. values[4], values[5], values[6], values[7],
  2577. values[8], values[9], values[10], values[11],
  2578. values[12], values[13], values[14], values[15]);
  2579. }
  2580. result[0] = values[0];
  2581. result[1] = values[4];
  2582. result[2] = values[8];
  2583. result[3] = values[12];
  2584. result[4] = values[1];
  2585. result[5] = values[5];
  2586. result[6] = values[9];
  2587. result[7] = values[13];
  2588. result[8] = values[2];
  2589. result[9] = values[6];
  2590. result[10] = values[10];
  2591. result[11] = values[14];
  2592. result[12] = values[3];
  2593. result[13] = values[7];
  2594. result[14] = values[11];
  2595. result[15] = values[15];
  2596. return result;
  2597. };
  2598. /**
  2599. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  2600. * and a Cartesian3 representing the translation.
  2601. *
  2602. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  2603. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  2604. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2605. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2606. */
  2607. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  2608. //>>includeStart('debug', pragmas.debug);
  2609. Check.Check.typeOf.object('rotation', rotation);
  2610. //>>includeEnd('debug');
  2611. translation = defaultValue.defaultValue(translation, Cartesian2.Cartesian3.ZERO);
  2612. if (!defined.defined(result)) {
  2613. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  2614. rotation[1], rotation[4], rotation[7], translation.y,
  2615. rotation[2], rotation[5], rotation[8], translation.z,
  2616. 0.0, 0.0, 0.0, 1.0);
  2617. }
  2618. result[0] = rotation[0];
  2619. result[1] = rotation[1];
  2620. result[2] = rotation[2];
  2621. result[3] = 0.0;
  2622. result[4] = rotation[3];
  2623. result[5] = rotation[4];
  2624. result[6] = rotation[5];
  2625. result[7] = 0.0;
  2626. result[8] = rotation[6];
  2627. result[9] = rotation[7];
  2628. result[10] = rotation[8];
  2629. result[11] = 0.0;
  2630. result[12] = translation.x;
  2631. result[13] = translation.y;
  2632. result[14] = translation.z;
  2633. result[15] = 1.0;
  2634. return result;
  2635. };
  2636. /**
  2637. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  2638. * representation with the rotation represented as a quaternion.
  2639. *
  2640. * @param {Cartesian3} translation The translation transformation.
  2641. * @param {Quaternion} rotation The rotation transformation.
  2642. * @param {Cartesian3} scale The non-uniform scale transformation.
  2643. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2644. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2645. *
  2646. * @example
  2647. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  2648. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  2649. * Cesium.Quaternion.IDENTITY, // rotation
  2650. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  2651. * result);
  2652. */
  2653. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  2654. //>>includeStart('debug', pragmas.debug);
  2655. Check.Check.typeOf.object('translation', translation);
  2656. Check.Check.typeOf.object('rotation', rotation);
  2657. Check.Check.typeOf.object('scale', scale);
  2658. //>>includeEnd('debug');
  2659. if (!defined.defined(result)) {
  2660. result = new Matrix4();
  2661. }
  2662. var scaleX = scale.x;
  2663. var scaleY = scale.y;
  2664. var scaleZ = scale.z;
  2665. var x2 = rotation.x * rotation.x;
  2666. var xy = rotation.x * rotation.y;
  2667. var xz = rotation.x * rotation.z;
  2668. var xw = rotation.x * rotation.w;
  2669. var y2 = rotation.y * rotation.y;
  2670. var yz = rotation.y * rotation.z;
  2671. var yw = rotation.y * rotation.w;
  2672. var z2 = rotation.z * rotation.z;
  2673. var zw = rotation.z * rotation.w;
  2674. var w2 = rotation.w * rotation.w;
  2675. var m00 = x2 - y2 - z2 + w2;
  2676. var m01 = 2.0 * (xy - zw);
  2677. var m02 = 2.0 * (xz + yw);
  2678. var m10 = 2.0 * (xy + zw);
  2679. var m11 = -x2 + y2 - z2 + w2;
  2680. var m12 = 2.0 * (yz - xw);
  2681. var m20 = 2.0 * (xz - yw);
  2682. var m21 = 2.0 * (yz + xw);
  2683. var m22 = -x2 - y2 + z2 + w2;
  2684. result[0] = m00 * scaleX;
  2685. result[1] = m10 * scaleX;
  2686. result[2] = m20 * scaleX;
  2687. result[3] = 0.0;
  2688. result[4] = m01 * scaleY;
  2689. result[5] = m11 * scaleY;
  2690. result[6] = m21 * scaleY;
  2691. result[7] = 0.0;
  2692. result[8] = m02 * scaleZ;
  2693. result[9] = m12 * scaleZ;
  2694. result[10] = m22 * scaleZ;
  2695. result[11] = 0.0;
  2696. result[12] = translation.x;
  2697. result[13] = translation.y;
  2698. result[14] = translation.z;
  2699. result[15] = 1.0;
  2700. return result;
  2701. };
  2702. /**
  2703. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  2704. *
  2705. * @param {TranslationRotationScale} translationRotationScale The instance.
  2706. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2707. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2708. */
  2709. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  2710. //>>includeStart('debug', pragmas.debug);
  2711. Check.Check.typeOf.object('translationRotationScale', translationRotationScale);
  2712. //>>includeEnd('debug');
  2713. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  2714. };
  2715. /**
  2716. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  2717. *
  2718. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  2719. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2720. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2721. *
  2722. * @see Matrix4.multiplyByTranslation
  2723. */
  2724. Matrix4.fromTranslation = function(translation, result) {
  2725. //>>includeStart('debug', pragmas.debug);
  2726. Check.Check.typeOf.object('translation', translation);
  2727. //>>includeEnd('debug');
  2728. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  2729. };
  2730. /**
  2731. * Computes a Matrix4 instance representing a non-uniform scale.
  2732. *
  2733. * @param {Cartesian3} scale The x, y, and z scale factors.
  2734. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2735. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2736. *
  2737. * @example
  2738. * // Creates
  2739. * // [7.0, 0.0, 0.0, 0.0]
  2740. * // [0.0, 8.0, 0.0, 0.0]
  2741. * // [0.0, 0.0, 9.0, 0.0]
  2742. * // [0.0, 0.0, 0.0, 1.0]
  2743. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  2744. */
  2745. Matrix4.fromScale = function(scale, result) {
  2746. //>>includeStart('debug', pragmas.debug);
  2747. Check.Check.typeOf.object('scale', scale);
  2748. //>>includeEnd('debug');
  2749. if (!defined.defined(result)) {
  2750. return new Matrix4(
  2751. scale.x, 0.0, 0.0, 0.0,
  2752. 0.0, scale.y, 0.0, 0.0,
  2753. 0.0, 0.0, scale.z, 0.0,
  2754. 0.0, 0.0, 0.0, 1.0);
  2755. }
  2756. result[0] = scale.x;
  2757. result[1] = 0.0;
  2758. result[2] = 0.0;
  2759. result[3] = 0.0;
  2760. result[4] = 0.0;
  2761. result[5] = scale.y;
  2762. result[6] = 0.0;
  2763. result[7] = 0.0;
  2764. result[8] = 0.0;
  2765. result[9] = 0.0;
  2766. result[10] = scale.z;
  2767. result[11] = 0.0;
  2768. result[12] = 0.0;
  2769. result[13] = 0.0;
  2770. result[14] = 0.0;
  2771. result[15] = 1.0;
  2772. return result;
  2773. };
  2774. /**
  2775. * Computes a Matrix4 instance representing a uniform scale.
  2776. *
  2777. * @param {Number} scale The uniform scale factor.
  2778. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2779. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2780. *
  2781. * @example
  2782. * // Creates
  2783. * // [2.0, 0.0, 0.0, 0.0]
  2784. * // [0.0, 2.0, 0.0, 0.0]
  2785. * // [0.0, 0.0, 2.0, 0.0]
  2786. * // [0.0, 0.0, 0.0, 1.0]
  2787. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  2788. */
  2789. Matrix4.fromUniformScale = function(scale, result) {
  2790. //>>includeStart('debug', pragmas.debug);
  2791. Check.Check.typeOf.number('scale', scale);
  2792. //>>includeEnd('debug');
  2793. if (!defined.defined(result)) {
  2794. return new Matrix4(scale, 0.0, 0.0, 0.0,
  2795. 0.0, scale, 0.0, 0.0,
  2796. 0.0, 0.0, scale, 0.0,
  2797. 0.0, 0.0, 0.0, 1.0);
  2798. }
  2799. result[0] = scale;
  2800. result[1] = 0.0;
  2801. result[2] = 0.0;
  2802. result[3] = 0.0;
  2803. result[4] = 0.0;
  2804. result[5] = scale;
  2805. result[6] = 0.0;
  2806. result[7] = 0.0;
  2807. result[8] = 0.0;
  2808. result[9] = 0.0;
  2809. result[10] = scale;
  2810. result[11] = 0.0;
  2811. result[12] = 0.0;
  2812. result[13] = 0.0;
  2813. result[14] = 0.0;
  2814. result[15] = 1.0;
  2815. return result;
  2816. };
  2817. var fromCameraF = new Cartesian2.Cartesian3();
  2818. var fromCameraR = new Cartesian2.Cartesian3();
  2819. var fromCameraU = new Cartesian2.Cartesian3();
  2820. /**
  2821. * Computes a Matrix4 instance from a Camera.
  2822. *
  2823. * @param {Camera} camera The camera to use.
  2824. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  2825. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  2826. */
  2827. Matrix4.fromCamera = function(camera, result) {
  2828. //>>includeStart('debug', pragmas.debug);
  2829. Check.Check.typeOf.object('camera', camera);
  2830. //>>includeEnd('debug');
  2831. var position = camera.position;
  2832. var direction = camera.direction;
  2833. var up = camera.up;
  2834. //>>includeStart('debug', pragmas.debug);
  2835. Check.Check.typeOf.object('camera.position', position);
  2836. Check.Check.typeOf.object('camera.direction', direction);
  2837. Check.Check.typeOf.object('camera.up', up);
  2838. //>>includeEnd('debug');
  2839. Cartesian2.Cartesian3.normalize(direction, fromCameraF);
  2840. Cartesian2.Cartesian3.normalize(Cartesian2.Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  2841. Cartesian2.Cartesian3.normalize(Cartesian2.Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  2842. var sX = fromCameraR.x;
  2843. var sY = fromCameraR.y;
  2844. var sZ = fromCameraR.z;
  2845. var fX = fromCameraF.x;
  2846. var fY = fromCameraF.y;
  2847. var fZ = fromCameraF.z;
  2848. var uX = fromCameraU.x;
  2849. var uY = fromCameraU.y;
  2850. var uZ = fromCameraU.z;
  2851. var positionX = position.x;
  2852. var positionY = position.y;
  2853. var positionZ = position.z;
  2854. var t0 = sX * -positionX + sY * -positionY + sZ * -positionZ;
  2855. var t1 = uX * -positionX + uY * -positionY + uZ * -positionZ;
  2856. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  2857. // The code below this comment is an optimized
  2858. // version of the commented lines.
  2859. // Rather that create two matrices and then multiply,
  2860. // we just bake in the multiplcation as part of creation.
  2861. // var rotation = new Matrix4(
  2862. // sX, sY, sZ, 0.0,
  2863. // uX, uY, uZ, 0.0,
  2864. // -fX, -fY, -fZ, 0.0,
  2865. // 0.0, 0.0, 0.0, 1.0);
  2866. // var translation = new Matrix4(
  2867. // 1.0, 0.0, 0.0, -position.x,
  2868. // 0.0, 1.0, 0.0, -position.y,
  2869. // 0.0, 0.0, 1.0, -position.z,
  2870. // 0.0, 0.0, 0.0, 1.0);
  2871. // return rotation.multiply(translation);
  2872. if (!defined.defined(result)) {
  2873. return new Matrix4(
  2874. sX, sY, sZ, t0,
  2875. uX, uY, uZ, t1,
  2876. -fX, -fY, -fZ, t2,
  2877. 0.0, 0.0, 0.0, 1.0);
  2878. }
  2879. result[0] = sX;
  2880. result[1] = uX;
  2881. result[2] = -fX;
  2882. result[3] = 0.0;
  2883. result[4] = sY;
  2884. result[5] = uY;
  2885. result[6] = -fY;
  2886. result[7] = 0.0;
  2887. result[8] = sZ;
  2888. result[9] = uZ;
  2889. result[10] = -fZ;
  2890. result[11] = 0.0;
  2891. result[12] = t0;
  2892. result[13] = t1;
  2893. result[14] = t2;
  2894. result[15] = 1.0;
  2895. return result;
  2896. };
  2897. /**
  2898. * Computes a Matrix4 instance representing a perspective transformation matrix.
  2899. *
  2900. * @param {Number} fovY The field of view along the Y axis in radians.
  2901. * @param {Number} aspectRatio The aspect ratio.
  2902. * @param {Number} near The distance to the near plane in meters.
  2903. * @param {Number} far The distance to the far plane in meters.
  2904. * @param {Matrix4} result The object in which the result will be stored.
  2905. * @returns {Matrix4} The modified result parameter.
  2906. *
  2907. * @exception {DeveloperError} fovY must be in (0, PI].
  2908. * @exception {DeveloperError} aspectRatio must be greater than zero.
  2909. * @exception {DeveloperError} near must be greater than zero.
  2910. * @exception {DeveloperError} far must be greater than zero.
  2911. */
  2912. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  2913. //>>includeStart('debug', pragmas.debug);
  2914. Check.Check.typeOf.number.greaterThan('fovY', fovY, 0.0);
  2915. Check.Check.typeOf.number.lessThan('fovY', fovY, Math.PI);
  2916. Check.Check.typeOf.number.greaterThan('near', near, 0.0);
  2917. Check.Check.typeOf.number.greaterThan('far', far, 0.0);
  2918. Check.Check.typeOf.object('result', result);
  2919. //>>includeEnd('debug');
  2920. var bottom = Math.tan(fovY * 0.5);
  2921. var column1Row1 = 1.0 / bottom;
  2922. var column0Row0 = column1Row1 / aspectRatio;
  2923. var column2Row2 = (far + near) / (near - far);
  2924. var column3Row2 = (2.0 * far * near) / (near - far);
  2925. result[0] = column0Row0;
  2926. result[1] = 0.0;
  2927. result[2] = 0.0;
  2928. result[3] = 0.0;
  2929. result[4] = 0.0;
  2930. result[5] = column1Row1;
  2931. result[6] = 0.0;
  2932. result[7] = 0.0;
  2933. result[8] = 0.0;
  2934. result[9] = 0.0;
  2935. result[10] = column2Row2;
  2936. result[11] = -1.0;
  2937. result[12] = 0.0;
  2938. result[13] = 0.0;
  2939. result[14] = column3Row2;
  2940. result[15] = 0.0;
  2941. return result;
  2942. };
  2943. /**
  2944. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  2945. *
  2946. * @param {Number} left The number of meters to the left of the camera that will be in view.
  2947. * @param {Number} right The number of meters to the right of the camera that will be in view.
  2948. * @param {Number} bottom The number of meters below of the camera that will be in view.
  2949. * @param {Number} top The number of meters above of the camera that will be in view.
  2950. * @param {Number} near The distance to the near plane in meters.
  2951. * @param {Number} far The distance to the far plane in meters.
  2952. * @param {Matrix4} result The object in which the result will be stored.
  2953. * @returns {Matrix4} The modified result parameter.
  2954. */
  2955. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  2956. //>>includeStart('debug', pragmas.debug);
  2957. Check.Check.typeOf.number('left', left);
  2958. Check.Check.typeOf.number('right', right);
  2959. Check.Check.typeOf.number('bottom', bottom);
  2960. Check.Check.typeOf.number('top', top);
  2961. Check.Check.typeOf.number('near', near);
  2962. Check.Check.typeOf.number('far', far);
  2963. Check.Check.typeOf.object('result', result);
  2964. //>>includeEnd('debug');
  2965. var a = 1.0 / (right - left);
  2966. var b = 1.0 / (top - bottom);
  2967. var c = 1.0 / (far - near);
  2968. var tx = -(right + left) * a;
  2969. var ty = -(top + bottom) * b;
  2970. var tz = -(far + near) * c;
  2971. a *= 2.0;
  2972. b *= 2.0;
  2973. c *= -2.0;
  2974. result[0] = a;
  2975. result[1] = 0.0;
  2976. result[2] = 0.0;
  2977. result[3] = 0.0;
  2978. result[4] = 0.0;
  2979. result[5] = b;
  2980. result[6] = 0.0;
  2981. result[7] = 0.0;
  2982. result[8] = 0.0;
  2983. result[9] = 0.0;
  2984. result[10] = c;
  2985. result[11] = 0.0;
  2986. result[12] = tx;
  2987. result[13] = ty;
  2988. result[14] = tz;
  2989. result[15] = 1.0;
  2990. return result;
  2991. };
  2992. /**
  2993. * Computes a Matrix4 instance representing an off center perspective transformation.
  2994. *
  2995. * @param {Number} left The number of meters to the left of the camera that will be in view.
  2996. * @param {Number} right The number of meters to the right of the camera that will be in view.
  2997. * @param {Number} bottom The number of meters below of the camera that will be in view.
  2998. * @param {Number} top The number of meters above of the camera that will be in view.
  2999. * @param {Number} near The distance to the near plane in meters.
  3000. * @param {Number} far The distance to the far plane in meters.
  3001. * @param {Matrix4} result The object in which the result will be stored.
  3002. * @returns {Matrix4} The modified result parameter.
  3003. */
  3004. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  3005. //>>includeStart('debug', pragmas.debug);
  3006. Check.Check.typeOf.number('left', left);
  3007. Check.Check.typeOf.number('right', right);
  3008. Check.Check.typeOf.number('bottom', bottom);
  3009. Check.Check.typeOf.number('top', top);
  3010. Check.Check.typeOf.number('near', near);
  3011. Check.Check.typeOf.number('far', far);
  3012. Check.Check.typeOf.object('result', result);
  3013. //>>includeEnd('debug');
  3014. var column0Row0 = 2.0 * near / (right - left);
  3015. var column1Row1 = 2.0 * near / (top - bottom);
  3016. var column2Row0 = (right + left) / (right - left);
  3017. var column2Row1 = (top + bottom) / (top - bottom);
  3018. var column2Row2 = -(far + near) / (far - near);
  3019. var column2Row3 = -1.0;
  3020. var column3Row2 = -2.0 * far * near / (far - near);
  3021. result[0] = column0Row0;
  3022. result[1] = 0.0;
  3023. result[2] = 0.0;
  3024. result[3] = 0.0;
  3025. result[4] = 0.0;
  3026. result[5] = column1Row1;
  3027. result[6] = 0.0;
  3028. result[7] = 0.0;
  3029. result[8] = column2Row0;
  3030. result[9] = column2Row1;
  3031. result[10] = column2Row2;
  3032. result[11] = column2Row3;
  3033. result[12] = 0.0;
  3034. result[13] = 0.0;
  3035. result[14] = column3Row2;
  3036. result[15] = 0.0;
  3037. return result;
  3038. };
  3039. /**
  3040. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  3041. *
  3042. * @param {Number} left The number of meters to the left of the camera that will be in view.
  3043. * @param {Number} right The number of meters to the right of the camera that will be in view.
  3044. * @param {Number} bottom The number of meters below of the camera that will be in view.
  3045. * @param {Number} top The number of meters above of the camera that will be in view.
  3046. * @param {Number} near The distance to the near plane in meters.
  3047. * @param {Matrix4} result The object in which the result will be stored.
  3048. * @returns {Matrix4} The modified result parameter.
  3049. */
  3050. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  3051. //>>includeStart('debug', pragmas.debug);
  3052. Check.Check.typeOf.number('left', left);
  3053. Check.Check.typeOf.number('right', right);
  3054. Check.Check.typeOf.number('bottom', bottom);
  3055. Check.Check.typeOf.number('top', top);
  3056. Check.Check.typeOf.number('near', near);
  3057. Check.Check.typeOf.object('result', result);
  3058. //>>includeEnd('debug');
  3059. var column0Row0 = 2.0 * near / (right - left);
  3060. var column1Row1 = 2.0 * near / (top - bottom);
  3061. var column2Row0 = (right + left) / (right - left);
  3062. var column2Row1 = (top + bottom) / (top - bottom);
  3063. var column2Row2 = -1.0;
  3064. var column2Row3 = -1.0;
  3065. var column3Row2 = -2.0 * near;
  3066. result[0] = column0Row0;
  3067. result[1] = 0.0;
  3068. result[2] = 0.0;
  3069. result[3] = 0.0;
  3070. result[4] = 0.0;
  3071. result[5] = column1Row1;
  3072. result[6] = 0.0;
  3073. result[7] = 0.0;
  3074. result[8] = column2Row0;
  3075. result[9] = column2Row1;
  3076. result[10] = column2Row2;
  3077. result[11] = column2Row3;
  3078. result[12] = 0.0;
  3079. result[13] = 0.0;
  3080. result[14] = column3Row2;
  3081. result[15] = 0.0;
  3082. return result;
  3083. };
  3084. /**
  3085. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  3086. *
  3087. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  3088. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  3089. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  3090. * @param {Matrix4} result The object in which the result will be stored.
  3091. * @returns {Matrix4} The modified result parameter.
  3092. *
  3093. * @example
  3094. * // Create viewport transformation using an explicit viewport and depth range.
  3095. * var m = Cesium.Matrix4.computeViewportTransformation({
  3096. * x : 0.0,
  3097. * y : 0.0,
  3098. * width : 1024.0,
  3099. * height : 768.0
  3100. * }, 0.0, 1.0, new Cesium.Matrix4());
  3101. */
  3102. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  3103. //>>includeStart('debug', pragmas.debug);
  3104. Check.Check.typeOf.object('result', result);
  3105. //>>includeEnd('debug');
  3106. viewport = defaultValue.defaultValue(viewport, defaultValue.defaultValue.EMPTY_OBJECT);
  3107. var x = defaultValue.defaultValue(viewport.x, 0.0);
  3108. var y = defaultValue.defaultValue(viewport.y, 0.0);
  3109. var width = defaultValue.defaultValue(viewport.width, 0.0);
  3110. var height = defaultValue.defaultValue(viewport.height, 0.0);
  3111. nearDepthRange = defaultValue.defaultValue(nearDepthRange, 0.0);
  3112. farDepthRange = defaultValue.defaultValue(farDepthRange, 1.0);
  3113. var halfWidth = width * 0.5;
  3114. var halfHeight = height * 0.5;
  3115. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  3116. var column0Row0 = halfWidth;
  3117. var column1Row1 = halfHeight;
  3118. var column2Row2 = halfDepth;
  3119. var column3Row0 = x + halfWidth;
  3120. var column3Row1 = y + halfHeight;
  3121. var column3Row2 = nearDepthRange + halfDepth;
  3122. var column3Row3 = 1.0;
  3123. result[0] = column0Row0;
  3124. result[1] = 0.0;
  3125. result[2] = 0.0;
  3126. result[3] = 0.0;
  3127. result[4] = 0.0;
  3128. result[5] = column1Row1;
  3129. result[6] = 0.0;
  3130. result[7] = 0.0;
  3131. result[8] = 0.0;
  3132. result[9] = 0.0;
  3133. result[10] = column2Row2;
  3134. result[11] = 0.0;
  3135. result[12] = column3Row0;
  3136. result[13] = column3Row1;
  3137. result[14] = column3Row2;
  3138. result[15] = column3Row3;
  3139. return result;
  3140. };
  3141. /**
  3142. * Computes a Matrix4 instance that transforms from world space to view space.
  3143. *
  3144. * @param {Cartesian3} position The position of the camera.
  3145. * @param {Cartesian3} direction The forward direction.
  3146. * @param {Cartesian3} up The up direction.
  3147. * @param {Cartesian3} right The right direction.
  3148. * @param {Matrix4} result The object in which the result will be stored.
  3149. * @returns {Matrix4} The modified result parameter.
  3150. */
  3151. Matrix4.computeView = function(position, direction, up, right, result) {
  3152. //>>includeStart('debug', pragmas.debug);
  3153. Check.Check.typeOf.object('position', position);
  3154. Check.Check.typeOf.object('direction', direction);
  3155. Check.Check.typeOf.object('up', up);
  3156. Check.Check.typeOf.object('right', right);
  3157. Check.Check.typeOf.object('result', result);
  3158. //>>includeEnd('debug');
  3159. result[0] = right.x;
  3160. result[1] = up.x;
  3161. result[2] = -direction.x;
  3162. result[3] = 0.0;
  3163. result[4] = right.y;
  3164. result[5] = up.y;
  3165. result[6] = -direction.y;
  3166. result[7] = 0.0;
  3167. result[8] = right.z;
  3168. result[9] = up.z;
  3169. result[10] = -direction.z;
  3170. result[11] = 0.0;
  3171. result[12] = -Cartesian2.Cartesian3.dot(right, position);
  3172. result[13] = -Cartesian2.Cartesian3.dot(up, position);
  3173. result[14] = Cartesian2.Cartesian3.dot(direction, position);
  3174. result[15] = 1.0;
  3175. return result;
  3176. };
  3177. /**
  3178. * Computes an Array from the provided Matrix4 instance.
  3179. * The array will be in column-major order.
  3180. *
  3181. * @param {Matrix4} matrix The matrix to use..
  3182. * @param {Number[]} [result] The Array onto which to store the result.
  3183. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  3184. *
  3185. * @example
  3186. * //create an array from an instance of Matrix4
  3187. * // m = [10.0, 14.0, 18.0, 22.0]
  3188. * // [11.0, 15.0, 19.0, 23.0]
  3189. * // [12.0, 16.0, 20.0, 24.0]
  3190. * // [13.0, 17.0, 21.0, 25.0]
  3191. * var a = Cesium.Matrix4.toArray(m);
  3192. *
  3193. * // m remains the same
  3194. * //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]
  3195. */
  3196. Matrix4.toArray = function(matrix, result) {
  3197. //>>includeStart('debug', pragmas.debug);
  3198. Check.Check.typeOf.object('matrix', matrix);
  3199. //>>includeEnd('debug');
  3200. if (!defined.defined(result)) {
  3201. return [matrix[0], matrix[1], matrix[2], matrix[3],
  3202. matrix[4], matrix[5], matrix[6], matrix[7],
  3203. matrix[8], matrix[9], matrix[10], matrix[11],
  3204. matrix[12], matrix[13], matrix[14], matrix[15]];
  3205. }
  3206. result[0] = matrix[0];
  3207. result[1] = matrix[1];
  3208. result[2] = matrix[2];
  3209. result[3] = matrix[3];
  3210. result[4] = matrix[4];
  3211. result[5] = matrix[5];
  3212. result[6] = matrix[6];
  3213. result[7] = matrix[7];
  3214. result[8] = matrix[8];
  3215. result[9] = matrix[9];
  3216. result[10] = matrix[10];
  3217. result[11] = matrix[11];
  3218. result[12] = matrix[12];
  3219. result[13] = matrix[13];
  3220. result[14] = matrix[14];
  3221. result[15] = matrix[15];
  3222. return result;
  3223. };
  3224. /**
  3225. * Computes the array index of the element at the provided row and column.
  3226. *
  3227. * @param {Number} row The zero-based index of the row.
  3228. * @param {Number} column The zero-based index of the column.
  3229. * @returns {Number} The index of the element at the provided row and column.
  3230. *
  3231. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  3232. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  3233. *
  3234. * @example
  3235. * var myMatrix = new Cesium.Matrix4();
  3236. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  3237. * var column1Row0 = myMatrix[column1Row0Index];
  3238. * myMatrix[column1Row0Index] = 10.0;
  3239. */
  3240. Matrix4.getElementIndex = function(column, row) {
  3241. //>>includeStart('debug', pragmas.debug);
  3242. Check.Check.typeOf.number.greaterThanOrEquals('row', row, 0);
  3243. Check.Check.typeOf.number.lessThanOrEquals('row', row, 3);
  3244. Check.Check.typeOf.number.greaterThanOrEquals('column', column, 0);
  3245. Check.Check.typeOf.number.lessThanOrEquals('column', column, 3);
  3246. //>>includeEnd('debug');
  3247. return column * 4 + row;
  3248. };
  3249. /**
  3250. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  3251. *
  3252. * @param {Matrix4} matrix The matrix to use.
  3253. * @param {Number} index The zero-based index of the column to retrieve.
  3254. * @param {Cartesian4} result The object onto which to store the result.
  3255. * @returns {Cartesian4} The modified result parameter.
  3256. *
  3257. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3258. *
  3259. * @example
  3260. * //returns a Cartesian4 instance with values from the specified column
  3261. * // m = [10.0, 11.0, 12.0, 13.0]
  3262. * // [14.0, 15.0, 16.0, 17.0]
  3263. * // [18.0, 19.0, 20.0, 21.0]
  3264. * // [22.0, 23.0, 24.0, 25.0]
  3265. *
  3266. * //Example 1: Creates an instance of Cartesian
  3267. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  3268. *
  3269. * @example
  3270. * //Example 2: Sets values for Cartesian instance
  3271. * var a = new Cesium.Cartesian4();
  3272. * Cesium.Matrix4.getColumn(m, 2, a);
  3273. *
  3274. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  3275. */
  3276. Matrix4.getColumn = function(matrix, index, result) {
  3277. //>>includeStart('debug', pragmas.debug);
  3278. Check.Check.typeOf.object('matrix', matrix);
  3279. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  3280. Check.Check.typeOf.number.lessThanOrEquals('index', index, 3);
  3281. Check.Check.typeOf.object('result', result);
  3282. //>>includeEnd('debug');
  3283. var startIndex = index * 4;
  3284. var x = matrix[startIndex];
  3285. var y = matrix[startIndex + 1];
  3286. var z = matrix[startIndex + 2];
  3287. var w = matrix[startIndex + 3];
  3288. result.x = x;
  3289. result.y = y;
  3290. result.z = z;
  3291. result.w = w;
  3292. return result;
  3293. };
  3294. /**
  3295. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  3296. *
  3297. * @param {Matrix4} matrix The matrix to use.
  3298. * @param {Number} index The zero-based index of the column to set.
  3299. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  3300. * @param {Matrix4} result The object onto which to store the result.
  3301. * @returns {Matrix4} The modified result parameter.
  3302. *
  3303. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3304. *
  3305. * @example
  3306. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  3307. * // m = [10.0, 11.0, 12.0, 13.0]
  3308. * // [14.0, 15.0, 16.0, 17.0]
  3309. * // [18.0, 19.0, 20.0, 21.0]
  3310. * // [22.0, 23.0, 24.0, 25.0]
  3311. *
  3312. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  3313. *
  3314. * // m remains the same
  3315. * // a = [10.0, 11.0, 99.0, 13.0]
  3316. * // [14.0, 15.0, 98.0, 17.0]
  3317. * // [18.0, 19.0, 97.0, 21.0]
  3318. * // [22.0, 23.0, 96.0, 25.0]
  3319. */
  3320. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  3321. //>>includeStart('debug', pragmas.debug);
  3322. Check.Check.typeOf.object('matrix', matrix);
  3323. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  3324. Check.Check.typeOf.number.lessThanOrEquals('index', index, 3);
  3325. Check.Check.typeOf.object('cartesian', cartesian);
  3326. Check.Check.typeOf.object('result', result);
  3327. //>>includeEnd('debug');
  3328. result = Matrix4.clone(matrix, result);
  3329. var startIndex = index * 4;
  3330. result[startIndex] = cartesian.x;
  3331. result[startIndex + 1] = cartesian.y;
  3332. result[startIndex + 2] = cartesian.z;
  3333. result[startIndex + 3] = cartesian.w;
  3334. return result;
  3335. };
  3336. /**
  3337. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  3338. * matrix with the provided translation. This assumes the matrix is an affine transformation
  3339. *
  3340. * @param {Matrix4} matrix The matrix to use.
  3341. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  3342. * @param {Matrix4} result The object onto which to store the result.
  3343. * @returns {Matrix4} The modified result parameter.
  3344. */
  3345. Matrix4.setTranslation = function(matrix, translation, result) {
  3346. //>>includeStart('debug', pragmas.debug);
  3347. Check.Check.typeOf.object('matrix', matrix);
  3348. Check.Check.typeOf.object('translation', translation);
  3349. Check.Check.typeOf.object('result', result);
  3350. //>>includeEnd('debug');
  3351. result[0] = matrix[0];
  3352. result[1] = matrix[1];
  3353. result[2] = matrix[2];
  3354. result[3] = matrix[3];
  3355. result[4] = matrix[4];
  3356. result[5] = matrix[5];
  3357. result[6] = matrix[6];
  3358. result[7] = matrix[7];
  3359. result[8] = matrix[8];
  3360. result[9] = matrix[9];
  3361. result[10] = matrix[10];
  3362. result[11] = matrix[11];
  3363. result[12] = translation.x;
  3364. result[13] = translation.y;
  3365. result[14] = translation.z;
  3366. result[15] = matrix[15];
  3367. return result;
  3368. };
  3369. var scaleScratch = new Cartesian2.Cartesian3();
  3370. /**
  3371. * Computes a new matrix that replaces the scale with the provided scale. This assumes the matrix is an affine transformation
  3372. *
  3373. * @param {Matrix4} matrix The matrix to use.
  3374. * @param {Cartesian3} scale The scale that replaces the scale of the provided matrix.
  3375. * @param {Matrix4} result The object onto which to store the result.
  3376. * @returns {Matrix4} The modified result parameter.
  3377. */
  3378. Matrix4.setScale = function(matrix, scale, result) {
  3379. //>>includeStart('debug', pragmas.debug);
  3380. Check.Check.typeOf.object('matrix', matrix);
  3381. Check.Check.typeOf.object('scale', scale);
  3382. Check.Check.typeOf.object('result', result);
  3383. //>>includeEnd('debug');
  3384. var existingScale = Matrix4.getScale(matrix, scaleScratch);
  3385. var newScale = Cartesian2.Cartesian3.divideComponents(scale, existingScale, scaleScratch);
  3386. return Matrix4.multiplyByScale(matrix, newScale, result);
  3387. };
  3388. /**
  3389. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  3390. *
  3391. * @param {Matrix4} matrix The matrix to use.
  3392. * @param {Number} index The zero-based index of the row to retrieve.
  3393. * @param {Cartesian4} result The object onto which to store the result.
  3394. * @returns {Cartesian4} The modified result parameter.
  3395. *
  3396. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3397. *
  3398. * @example
  3399. * //returns a Cartesian4 instance with values from the specified column
  3400. * // m = [10.0, 11.0, 12.0, 13.0]
  3401. * // [14.0, 15.0, 16.0, 17.0]
  3402. * // [18.0, 19.0, 20.0, 21.0]
  3403. * // [22.0, 23.0, 24.0, 25.0]
  3404. *
  3405. * //Example 1: Returns an instance of Cartesian
  3406. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  3407. *
  3408. * @example
  3409. * //Example 2: Sets values for a Cartesian instance
  3410. * var a = new Cesium.Cartesian4();
  3411. * Cesium.Matrix4.getRow(m, 2, a);
  3412. *
  3413. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  3414. */
  3415. Matrix4.getRow = function(matrix, index, result) {
  3416. //>>includeStart('debug', pragmas.debug);
  3417. Check.Check.typeOf.object('matrix', matrix);
  3418. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  3419. Check.Check.typeOf.number.lessThanOrEquals('index', index, 3);
  3420. Check.Check.typeOf.object('result', result);
  3421. //>>includeEnd('debug');
  3422. var x = matrix[index];
  3423. var y = matrix[index + 4];
  3424. var z = matrix[index + 8];
  3425. var w = matrix[index + 12];
  3426. result.x = x;
  3427. result.y = y;
  3428. result.z = z;
  3429. result.w = w;
  3430. return result;
  3431. };
  3432. /**
  3433. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  3434. *
  3435. * @param {Matrix4} matrix The matrix to use.
  3436. * @param {Number} index The zero-based index of the row to set.
  3437. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  3438. * @param {Matrix4} result The object onto which to store the result.
  3439. * @returns {Matrix4} The modified result parameter.
  3440. *
  3441. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  3442. *
  3443. * @example
  3444. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  3445. * // m = [10.0, 11.0, 12.0, 13.0]
  3446. * // [14.0, 15.0, 16.0, 17.0]
  3447. * // [18.0, 19.0, 20.0, 21.0]
  3448. * // [22.0, 23.0, 24.0, 25.0]
  3449. *
  3450. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  3451. *
  3452. * // m remains the same
  3453. * // a = [10.0, 11.0, 12.0, 13.0]
  3454. * // [14.0, 15.0, 16.0, 17.0]
  3455. * // [99.0, 98.0, 97.0, 96.0]
  3456. * // [22.0, 23.0, 24.0, 25.0]
  3457. */
  3458. Matrix4.setRow = function(matrix, index, cartesian, result) {
  3459. //>>includeStart('debug', pragmas.debug);
  3460. Check.Check.typeOf.object('matrix', matrix);
  3461. Check.Check.typeOf.number.greaterThanOrEquals('index', index, 0);
  3462. Check.Check.typeOf.number.lessThanOrEquals('index', index, 3);
  3463. Check.Check.typeOf.object('cartesian', cartesian);
  3464. Check.Check.typeOf.object('result', result);
  3465. //>>includeEnd('debug');
  3466. result = Matrix4.clone(matrix, result);
  3467. result[index] = cartesian.x;
  3468. result[index + 4] = cartesian.y;
  3469. result[index + 8] = cartesian.z;
  3470. result[index + 12] = cartesian.w;
  3471. return result;
  3472. };
  3473. var scratchColumn$1 = new Cartesian2.Cartesian3();
  3474. /**
  3475. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  3476. *
  3477. * @param {Matrix4} matrix The matrix.
  3478. * @param {Cartesian3} result The object onto which to store the result.
  3479. * @returns {Cartesian3} The modified result parameter
  3480. */
  3481. Matrix4.getScale = function(matrix, result) {
  3482. //>>includeStart('debug', pragmas.debug);
  3483. Check.Check.typeOf.object('matrix', matrix);
  3484. Check.Check.typeOf.object('result', result);
  3485. //>>includeEnd('debug');
  3486. result.x = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn$1));
  3487. result.y = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn$1));
  3488. result.z = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn$1));
  3489. return result;
  3490. };
  3491. var scratchScale$1 = new Cartesian2.Cartesian3();
  3492. /**
  3493. * Computes the maximum scale assuming the matrix is an affine transformation.
  3494. * The maximum scale is the maximum length of the column vectors in the upper-left
  3495. * 3x3 matrix.
  3496. *
  3497. * @param {Matrix4} matrix The matrix.
  3498. * @returns {Number} The maximum scale.
  3499. */
  3500. Matrix4.getMaximumScale = function(matrix) {
  3501. Matrix4.getScale(matrix, scratchScale$1);
  3502. return Cartesian2.Cartesian3.maximumComponent(scratchScale$1);
  3503. };
  3504. /**
  3505. * Computes the product of two matrices.
  3506. *
  3507. * @param {Matrix4} left The first matrix.
  3508. * @param {Matrix4} right The second matrix.
  3509. * @param {Matrix4} result The object onto which to store the result.
  3510. * @returns {Matrix4} The modified result parameter.
  3511. */
  3512. Matrix4.multiply = function(left, right, result) {
  3513. //>>includeStart('debug', pragmas.debug);
  3514. Check.Check.typeOf.object('left', left);
  3515. Check.Check.typeOf.object('right', right);
  3516. Check.Check.typeOf.object('result', result);
  3517. //>>includeEnd('debug');
  3518. var left0 = left[0];
  3519. var left1 = left[1];
  3520. var left2 = left[2];
  3521. var left3 = left[3];
  3522. var left4 = left[4];
  3523. var left5 = left[5];
  3524. var left6 = left[6];
  3525. var left7 = left[7];
  3526. var left8 = left[8];
  3527. var left9 = left[9];
  3528. var left10 = left[10];
  3529. var left11 = left[11];
  3530. var left12 = left[12];
  3531. var left13 = left[13];
  3532. var left14 = left[14];
  3533. var left15 = left[15];
  3534. var right0 = right[0];
  3535. var right1 = right[1];
  3536. var right2 = right[2];
  3537. var right3 = right[3];
  3538. var right4 = right[4];
  3539. var right5 = right[5];
  3540. var right6 = right[6];
  3541. var right7 = right[7];
  3542. var right8 = right[8];
  3543. var right9 = right[9];
  3544. var right10 = right[10];
  3545. var right11 = right[11];
  3546. var right12 = right[12];
  3547. var right13 = right[13];
  3548. var right14 = right[14];
  3549. var right15 = right[15];
  3550. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  3551. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  3552. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  3553. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  3554. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  3555. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  3556. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  3557. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  3558. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  3559. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  3560. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  3561. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  3562. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  3563. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  3564. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  3565. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  3566. result[0] = column0Row0;
  3567. result[1] = column0Row1;
  3568. result[2] = column0Row2;
  3569. result[3] = column0Row3;
  3570. result[4] = column1Row0;
  3571. result[5] = column1Row1;
  3572. result[6] = column1Row2;
  3573. result[7] = column1Row3;
  3574. result[8] = column2Row0;
  3575. result[9] = column2Row1;
  3576. result[10] = column2Row2;
  3577. result[11] = column2Row3;
  3578. result[12] = column3Row0;
  3579. result[13] = column3Row1;
  3580. result[14] = column3Row2;
  3581. result[15] = column3Row3;
  3582. return result;
  3583. };
  3584. /**
  3585. * Computes the sum of two matrices.
  3586. *
  3587. * @param {Matrix4} left The first matrix.
  3588. * @param {Matrix4} right The second matrix.
  3589. * @param {Matrix4} result The object onto which to store the result.
  3590. * @returns {Matrix4} The modified result parameter.
  3591. */
  3592. Matrix4.add = function(left, right, result) {
  3593. //>>includeStart('debug', pragmas.debug);
  3594. Check.Check.typeOf.object('left', left);
  3595. Check.Check.typeOf.object('right', right);
  3596. Check.Check.typeOf.object('result', result);
  3597. //>>includeEnd('debug');
  3598. result[0] = left[0] + right[0];
  3599. result[1] = left[1] + right[1];
  3600. result[2] = left[2] + right[2];
  3601. result[3] = left[3] + right[3];
  3602. result[4] = left[4] + right[4];
  3603. result[5] = left[5] + right[5];
  3604. result[6] = left[6] + right[6];
  3605. result[7] = left[7] + right[7];
  3606. result[8] = left[8] + right[8];
  3607. result[9] = left[9] + right[9];
  3608. result[10] = left[10] + right[10];
  3609. result[11] = left[11] + right[11];
  3610. result[12] = left[12] + right[12];
  3611. result[13] = left[13] + right[13];
  3612. result[14] = left[14] + right[14];
  3613. result[15] = left[15] + right[15];
  3614. return result;
  3615. };
  3616. /**
  3617. * Computes the difference of two matrices.
  3618. *
  3619. * @param {Matrix4} left The first matrix.
  3620. * @param {Matrix4} right The second matrix.
  3621. * @param {Matrix4} result The object onto which to store the result.
  3622. * @returns {Matrix4} The modified result parameter.
  3623. */
  3624. Matrix4.subtract = function(left, right, result) {
  3625. //>>includeStart('debug', pragmas.debug);
  3626. Check.Check.typeOf.object('left', left);
  3627. Check.Check.typeOf.object('right', right);
  3628. Check.Check.typeOf.object('result', result);
  3629. //>>includeEnd('debug');
  3630. result[0] = left[0] - right[0];
  3631. result[1] = left[1] - right[1];
  3632. result[2] = left[2] - right[2];
  3633. result[3] = left[3] - right[3];
  3634. result[4] = left[4] - right[4];
  3635. result[5] = left[5] - right[5];
  3636. result[6] = left[6] - right[6];
  3637. result[7] = left[7] - right[7];
  3638. result[8] = left[8] - right[8];
  3639. result[9] = left[9] - right[9];
  3640. result[10] = left[10] - right[10];
  3641. result[11] = left[11] - right[11];
  3642. result[12] = left[12] - right[12];
  3643. result[13] = left[13] - right[13];
  3644. result[14] = left[14] - right[14];
  3645. result[15] = left[15] - right[15];
  3646. return result;
  3647. };
  3648. /**
  3649. * Computes the product of two matrices assuming the matrices are
  3650. * affine transformation matrices, where the upper left 3x3 elements
  3651. * are a rotation matrix, and the upper three elements in the fourth
  3652. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  3653. * The matrix is not verified to be in the proper form.
  3654. * This method is faster than computing the product for general 4x4
  3655. * matrices using {@link Matrix4.multiply}.
  3656. *
  3657. * @param {Matrix4} left The first matrix.
  3658. * @param {Matrix4} right The second matrix.
  3659. * @param {Matrix4} result The object onto which to store the result.
  3660. * @returns {Matrix4} The modified result parameter.
  3661. *
  3662. * @example
  3663. * 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);
  3664. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  3665. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  3666. */
  3667. Matrix4.multiplyTransformation = function(left, right, result) {
  3668. //>>includeStart('debug', pragmas.debug);
  3669. Check.Check.typeOf.object('left', left);
  3670. Check.Check.typeOf.object('right', right);
  3671. Check.Check.typeOf.object('result', result);
  3672. //>>includeEnd('debug');
  3673. var left0 = left[0];
  3674. var left1 = left[1];
  3675. var left2 = left[2];
  3676. var left4 = left[4];
  3677. var left5 = left[5];
  3678. var left6 = left[6];
  3679. var left8 = left[8];
  3680. var left9 = left[9];
  3681. var left10 = left[10];
  3682. var left12 = left[12];
  3683. var left13 = left[13];
  3684. var left14 = left[14];
  3685. var right0 = right[0];
  3686. var right1 = right[1];
  3687. var right2 = right[2];
  3688. var right4 = right[4];
  3689. var right5 = right[5];
  3690. var right6 = right[6];
  3691. var right8 = right[8];
  3692. var right9 = right[9];
  3693. var right10 = right[10];
  3694. var right12 = right[12];
  3695. var right13 = right[13];
  3696. var right14 = right[14];
  3697. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  3698. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  3699. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  3700. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  3701. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  3702. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  3703. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  3704. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  3705. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  3706. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  3707. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  3708. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  3709. result[0] = column0Row0;
  3710. result[1] = column0Row1;
  3711. result[2] = column0Row2;
  3712. result[3] = 0.0;
  3713. result[4] = column1Row0;
  3714. result[5] = column1Row1;
  3715. result[6] = column1Row2;
  3716. result[7] = 0.0;
  3717. result[8] = column2Row0;
  3718. result[9] = column2Row1;
  3719. result[10] = column2Row2;
  3720. result[11] = 0.0;
  3721. result[12] = column3Row0;
  3722. result[13] = column3Row1;
  3723. result[14] = column3Row2;
  3724. result[15] = 1.0;
  3725. return result;
  3726. };
  3727. /**
  3728. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  3729. * by a 3x3 rotation matrix. This is an optimization
  3730. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  3731. *
  3732. * @param {Matrix4} matrix The matrix on the left-hand side.
  3733. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  3734. * @param {Matrix4} result The object onto which to store the result.
  3735. * @returns {Matrix4} The modified result parameter.
  3736. *
  3737. * @example
  3738. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  3739. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  3740. */
  3741. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  3742. //>>includeStart('debug', pragmas.debug);
  3743. Check.Check.typeOf.object('matrix', matrix);
  3744. Check.Check.typeOf.object('rotation', rotation);
  3745. Check.Check.typeOf.object('result', result);
  3746. //>>includeEnd('debug');
  3747. var left0 = matrix[0];
  3748. var left1 = matrix[1];
  3749. var left2 = matrix[2];
  3750. var left4 = matrix[4];
  3751. var left5 = matrix[5];
  3752. var left6 = matrix[6];
  3753. var left8 = matrix[8];
  3754. var left9 = matrix[9];
  3755. var left10 = matrix[10];
  3756. var right0 = rotation[0];
  3757. var right1 = rotation[1];
  3758. var right2 = rotation[2];
  3759. var right4 = rotation[3];
  3760. var right5 = rotation[4];
  3761. var right6 = rotation[5];
  3762. var right8 = rotation[6];
  3763. var right9 = rotation[7];
  3764. var right10 = rotation[8];
  3765. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  3766. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  3767. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  3768. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  3769. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  3770. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  3771. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  3772. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  3773. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  3774. result[0] = column0Row0;
  3775. result[1] = column0Row1;
  3776. result[2] = column0Row2;
  3777. result[3] = 0.0;
  3778. result[4] = column1Row0;
  3779. result[5] = column1Row1;
  3780. result[6] = column1Row2;
  3781. result[7] = 0.0;
  3782. result[8] = column2Row0;
  3783. result[9] = column2Row1;
  3784. result[10] = column2Row2;
  3785. result[11] = 0.0;
  3786. result[12] = matrix[12];
  3787. result[13] = matrix[13];
  3788. result[14] = matrix[14];
  3789. result[15] = matrix[15];
  3790. return result;
  3791. };
  3792. /**
  3793. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  3794. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  3795. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  3796. *
  3797. * @param {Matrix4} matrix The matrix on the left-hand side.
  3798. * @param {Cartesian3} translation The translation on the right-hand side.
  3799. * @param {Matrix4} result The object onto which to store the result.
  3800. * @returns {Matrix4} The modified result parameter.
  3801. *
  3802. * @example
  3803. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  3804. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  3805. */
  3806. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  3807. //>>includeStart('debug', pragmas.debug);
  3808. Check.Check.typeOf.object('matrix', matrix);
  3809. Check.Check.typeOf.object('translation', translation);
  3810. Check.Check.typeOf.object('result', result);
  3811. //>>includeEnd('debug');
  3812. var x = translation.x;
  3813. var y = translation.y;
  3814. var z = translation.z;
  3815. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  3816. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  3817. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  3818. result[0] = matrix[0];
  3819. result[1] = matrix[1];
  3820. result[2] = matrix[2];
  3821. result[3] = matrix[3];
  3822. result[4] = matrix[4];
  3823. result[5] = matrix[5];
  3824. result[6] = matrix[6];
  3825. result[7] = matrix[7];
  3826. result[8] = matrix[8];
  3827. result[9] = matrix[9];
  3828. result[10] = matrix[10];
  3829. result[11] = matrix[11];
  3830. result[12] = tx;
  3831. result[13] = ty;
  3832. result[14] = tz;
  3833. result[15] = matrix[15];
  3834. return result;
  3835. };
  3836. var uniformScaleScratch = new Cartesian2.Cartesian3();
  3837. /**
  3838. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  3839. * by an implicit uniform scale matrix. This is an optimization
  3840. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  3841. * <code>m</code> must be an affine matrix.
  3842. * This function performs fewer allocations and arithmetic operations.
  3843. *
  3844. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  3845. * @param {Number} scale The uniform scale on the right-hand side.
  3846. * @param {Matrix4} result The object onto which to store the result.
  3847. * @returns {Matrix4} The modified result parameter.
  3848. *
  3849. *
  3850. * @example
  3851. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  3852. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  3853. *
  3854. * @see Matrix4.fromUniformScale
  3855. * @see Matrix4.multiplyByScale
  3856. */
  3857. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  3858. //>>includeStart('debug', pragmas.debug);
  3859. Check.Check.typeOf.object('matrix', matrix);
  3860. Check.Check.typeOf.number('scale', scale);
  3861. Check.Check.typeOf.object('result', result);
  3862. //>>includeEnd('debug');
  3863. uniformScaleScratch.x = scale;
  3864. uniformScaleScratch.y = scale;
  3865. uniformScaleScratch.z = scale;
  3866. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  3867. };
  3868. /**
  3869. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  3870. * by an implicit non-uniform scale matrix. This is an optimization
  3871. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  3872. * <code>m</code> must be an affine matrix.
  3873. * This function performs fewer allocations and arithmetic operations.
  3874. *
  3875. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  3876. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  3877. * @param {Matrix4} result The object onto which to store the result.
  3878. * @returns {Matrix4} The modified result parameter.
  3879. *
  3880. *
  3881. * @example
  3882. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  3883. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  3884. *
  3885. * @see Matrix4.fromScale
  3886. * @see Matrix4.multiplyByUniformScale
  3887. */
  3888. Matrix4.multiplyByScale = function(matrix, scale, result) {
  3889. //>>includeStart('debug', pragmas.debug);
  3890. Check.Check.typeOf.object('matrix', matrix);
  3891. Check.Check.typeOf.object('scale', scale);
  3892. Check.Check.typeOf.object('result', result);
  3893. //>>includeEnd('debug');
  3894. var scaleX = scale.x;
  3895. var scaleY = scale.y;
  3896. var scaleZ = scale.z;
  3897. // Faster than Cartesian3.equals
  3898. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  3899. return Matrix4.clone(matrix, result);
  3900. }
  3901. result[0] = scaleX * matrix[0];
  3902. result[1] = scaleX * matrix[1];
  3903. result[2] = scaleX * matrix[2];
  3904. result[3] = 0.0;
  3905. result[4] = scaleY * matrix[4];
  3906. result[5] = scaleY * matrix[5];
  3907. result[6] = scaleY * matrix[6];
  3908. result[7] = 0.0;
  3909. result[8] = scaleZ * matrix[8];
  3910. result[9] = scaleZ * matrix[9];
  3911. result[10] = scaleZ * matrix[10];
  3912. result[11] = 0.0;
  3913. result[12] = matrix[12];
  3914. result[13] = matrix[13];
  3915. result[14] = matrix[14];
  3916. result[15] = 1.0;
  3917. return result;
  3918. };
  3919. /**
  3920. * Computes the product of a matrix and a column vector.
  3921. *
  3922. * @param {Matrix4} matrix The matrix.
  3923. * @param {Cartesian4} cartesian The vector.
  3924. * @param {Cartesian4} result The object onto which to store the result.
  3925. * @returns {Cartesian4} The modified result parameter.
  3926. */
  3927. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  3928. //>>includeStart('debug', pragmas.debug);
  3929. Check.Check.typeOf.object('matrix', matrix);
  3930. Check.Check.typeOf.object('cartesian', cartesian);
  3931. Check.Check.typeOf.object('result', result);
  3932. //>>includeEnd('debug');
  3933. var vX = cartesian.x;
  3934. var vY = cartesian.y;
  3935. var vZ = cartesian.z;
  3936. var vW = cartesian.w;
  3937. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  3938. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  3939. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  3940. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  3941. result.x = x;
  3942. result.y = y;
  3943. result.z = z;
  3944. result.w = w;
  3945. return result;
  3946. };
  3947. /**
  3948. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  3949. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  3950. *
  3951. * @param {Matrix4} matrix The matrix.
  3952. * @param {Cartesian3} cartesian The point.
  3953. * @param {Cartesian3} result The object onto which to store the result.
  3954. * @returns {Cartesian3} The modified result parameter.
  3955. *
  3956. * @example
  3957. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  3958. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  3959. * // A shortcut for
  3960. * // Cartesian3 p = ...
  3961. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  3962. */
  3963. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  3964. //>>includeStart('debug', pragmas.debug);
  3965. Check.Check.typeOf.object('matrix', matrix);
  3966. Check.Check.typeOf.object('cartesian', cartesian);
  3967. Check.Check.typeOf.object('result', result);
  3968. //>>includeEnd('debug');
  3969. var vX = cartesian.x;
  3970. var vY = cartesian.y;
  3971. var vZ = cartesian.z;
  3972. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  3973. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  3974. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  3975. result.x = x;
  3976. result.y = y;
  3977. result.z = z;
  3978. return result;
  3979. };
  3980. /**
  3981. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  3982. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  3983. *
  3984. * @param {Matrix4} matrix The matrix.
  3985. * @param {Cartesian3} cartesian The point.
  3986. * @param {Cartesian3} result The object onto which to store the result.
  3987. * @returns {Cartesian3} The modified result parameter.
  3988. *
  3989. * @example
  3990. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  3991. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  3992. */
  3993. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  3994. //>>includeStart('debug', pragmas.debug);
  3995. Check.Check.typeOf.object('matrix', matrix);
  3996. Check.Check.typeOf.object('cartesian', cartesian);
  3997. Check.Check.typeOf.object('result', result);
  3998. //>>includeEnd('debug');
  3999. var vX = cartesian.x;
  4000. var vY = cartesian.y;
  4001. var vZ = cartesian.z;
  4002. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  4003. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  4004. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  4005. result.x = x;
  4006. result.y = y;
  4007. result.z = z;
  4008. return result;
  4009. };
  4010. /**
  4011. * Computes the product of a matrix and a scalar.
  4012. *
  4013. * @param {Matrix4} matrix The matrix.
  4014. * @param {Number} scalar The number to multiply by.
  4015. * @param {Matrix4} result The object onto which to store the result.
  4016. * @returns {Matrix4} The modified result parameter.
  4017. *
  4018. * @example
  4019. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  4020. * // m = [10.0, 11.0, 12.0, 13.0]
  4021. * // [14.0, 15.0, 16.0, 17.0]
  4022. * // [18.0, 19.0, 20.0, 21.0]
  4023. * // [22.0, 23.0, 24.0, 25.0]
  4024. *
  4025. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  4026. *
  4027. * // m remains the same
  4028. * // a = [-20.0, -22.0, -24.0, -26.0]
  4029. * // [-28.0, -30.0, -32.0, -34.0]
  4030. * // [-36.0, -38.0, -40.0, -42.0]
  4031. * // [-44.0, -46.0, -48.0, -50.0]
  4032. */
  4033. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  4034. //>>includeStart('debug', pragmas.debug);
  4035. Check.Check.typeOf.object('matrix', matrix);
  4036. Check.Check.typeOf.number('scalar', scalar);
  4037. Check.Check.typeOf.object('result', result);
  4038. //>>includeEnd('debug');
  4039. result[0] = matrix[0] * scalar;
  4040. result[1] = matrix[1] * scalar;
  4041. result[2] = matrix[2] * scalar;
  4042. result[3] = matrix[3] * scalar;
  4043. result[4] = matrix[4] * scalar;
  4044. result[5] = matrix[5] * scalar;
  4045. result[6] = matrix[6] * scalar;
  4046. result[7] = matrix[7] * scalar;
  4047. result[8] = matrix[8] * scalar;
  4048. result[9] = matrix[9] * scalar;
  4049. result[10] = matrix[10] * scalar;
  4050. result[11] = matrix[11] * scalar;
  4051. result[12] = matrix[12] * scalar;
  4052. result[13] = matrix[13] * scalar;
  4053. result[14] = matrix[14] * scalar;
  4054. result[15] = matrix[15] * scalar;
  4055. return result;
  4056. };
  4057. /**
  4058. * Computes a negated copy of the provided matrix.
  4059. *
  4060. * @param {Matrix4} matrix The matrix to negate.
  4061. * @param {Matrix4} result The object onto which to store the result.
  4062. * @returns {Matrix4} The modified result parameter.
  4063. *
  4064. * @example
  4065. * //create a new Matrix4 instance which is a negation of a Matrix4
  4066. * // m = [10.0, 11.0, 12.0, 13.0]
  4067. * // [14.0, 15.0, 16.0, 17.0]
  4068. * // [18.0, 19.0, 20.0, 21.0]
  4069. * // [22.0, 23.0, 24.0, 25.0]
  4070. *
  4071. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  4072. *
  4073. * // m remains the same
  4074. * // a = [-10.0, -11.0, -12.0, -13.0]
  4075. * // [-14.0, -15.0, -16.0, -17.0]
  4076. * // [-18.0, -19.0, -20.0, -21.0]
  4077. * // [-22.0, -23.0, -24.0, -25.0]
  4078. */
  4079. Matrix4.negate = function(matrix, result) {
  4080. //>>includeStart('debug', pragmas.debug);
  4081. Check.Check.typeOf.object('matrix', matrix);
  4082. Check.Check.typeOf.object('result', result);
  4083. //>>includeEnd('debug');
  4084. result[0] = -matrix[0];
  4085. result[1] = -matrix[1];
  4086. result[2] = -matrix[2];
  4087. result[3] = -matrix[3];
  4088. result[4] = -matrix[4];
  4089. result[5] = -matrix[5];
  4090. result[6] = -matrix[6];
  4091. result[7] = -matrix[7];
  4092. result[8] = -matrix[8];
  4093. result[9] = -matrix[9];
  4094. result[10] = -matrix[10];
  4095. result[11] = -matrix[11];
  4096. result[12] = -matrix[12];
  4097. result[13] = -matrix[13];
  4098. result[14] = -matrix[14];
  4099. result[15] = -matrix[15];
  4100. return result;
  4101. };
  4102. /**
  4103. * Computes the transpose of the provided matrix.
  4104. *
  4105. * @param {Matrix4} matrix The matrix to transpose.
  4106. * @param {Matrix4} result The object onto which to store the result.
  4107. * @returns {Matrix4} The modified result parameter.
  4108. *
  4109. * @example
  4110. * //returns transpose of a Matrix4
  4111. * // m = [10.0, 11.0, 12.0, 13.0]
  4112. * // [14.0, 15.0, 16.0, 17.0]
  4113. * // [18.0, 19.0, 20.0, 21.0]
  4114. * // [22.0, 23.0, 24.0, 25.0]
  4115. *
  4116. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  4117. *
  4118. * // m remains the same
  4119. * // a = [10.0, 14.0, 18.0, 22.0]
  4120. * // [11.0, 15.0, 19.0, 23.0]
  4121. * // [12.0, 16.0, 20.0, 24.0]
  4122. * // [13.0, 17.0, 21.0, 25.0]
  4123. */
  4124. Matrix4.transpose = function(matrix, result) {
  4125. //>>includeStart('debug', pragmas.debug);
  4126. Check.Check.typeOf.object('matrix', matrix);
  4127. Check.Check.typeOf.object('result', result);
  4128. //>>includeEnd('debug');
  4129. var matrix1 = matrix[1];
  4130. var matrix2 = matrix[2];
  4131. var matrix3 = matrix[3];
  4132. var matrix6 = matrix[6];
  4133. var matrix7 = matrix[7];
  4134. var matrix11 = matrix[11];
  4135. result[0] = matrix[0];
  4136. result[1] = matrix[4];
  4137. result[2] = matrix[8];
  4138. result[3] = matrix[12];
  4139. result[4] = matrix1;
  4140. result[5] = matrix[5];
  4141. result[6] = matrix[9];
  4142. result[7] = matrix[13];
  4143. result[8] = matrix2;
  4144. result[9] = matrix6;
  4145. result[10] = matrix[10];
  4146. result[11] = matrix[14];
  4147. result[12] = matrix3;
  4148. result[13] = matrix7;
  4149. result[14] = matrix11;
  4150. result[15] = matrix[15];
  4151. return result;
  4152. };
  4153. /**
  4154. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  4155. *
  4156. * @param {Matrix4} matrix The matrix with signed elements.
  4157. * @param {Matrix4} result The object onto which to store the result.
  4158. * @returns {Matrix4} The modified result parameter.
  4159. */
  4160. Matrix4.abs = function(matrix, result) {
  4161. //>>includeStart('debug', pragmas.debug);
  4162. Check.Check.typeOf.object('matrix', matrix);
  4163. Check.Check.typeOf.object('result', result);
  4164. //>>includeEnd('debug');
  4165. result[0] = Math.abs(matrix[0]);
  4166. result[1] = Math.abs(matrix[1]);
  4167. result[2] = Math.abs(matrix[2]);
  4168. result[3] = Math.abs(matrix[3]);
  4169. result[4] = Math.abs(matrix[4]);
  4170. result[5] = Math.abs(matrix[5]);
  4171. result[6] = Math.abs(matrix[6]);
  4172. result[7] = Math.abs(matrix[7]);
  4173. result[8] = Math.abs(matrix[8]);
  4174. result[9] = Math.abs(matrix[9]);
  4175. result[10] = Math.abs(matrix[10]);
  4176. result[11] = Math.abs(matrix[11]);
  4177. result[12] = Math.abs(matrix[12]);
  4178. result[13] = Math.abs(matrix[13]);
  4179. result[14] = Math.abs(matrix[14]);
  4180. result[15] = Math.abs(matrix[15]);
  4181. return result;
  4182. };
  4183. /**
  4184. * Compares the provided matrices componentwise and returns
  4185. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4186. *
  4187. * @param {Matrix4} [left] The first matrix.
  4188. * @param {Matrix4} [right] The second matrix.
  4189. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  4190. *
  4191. * @example
  4192. * //compares two Matrix4 instances
  4193. *
  4194. * // a = [10.0, 14.0, 18.0, 22.0]
  4195. * // [11.0, 15.0, 19.0, 23.0]
  4196. * // [12.0, 16.0, 20.0, 24.0]
  4197. * // [13.0, 17.0, 21.0, 25.0]
  4198. *
  4199. * // b = [10.0, 14.0, 18.0, 22.0]
  4200. * // [11.0, 15.0, 19.0, 23.0]
  4201. * // [12.0, 16.0, 20.0, 24.0]
  4202. * // [13.0, 17.0, 21.0, 25.0]
  4203. *
  4204. * if(Cesium.Matrix4.equals(a,b)) {
  4205. * console.log("Both matrices are equal");
  4206. * } else {
  4207. * console.log("They are not equal");
  4208. * }
  4209. *
  4210. * //Prints "Both matrices are equal" on the console
  4211. */
  4212. Matrix4.equals = function(left, right) {
  4213. // Given that most matrices will be transformation matrices, the elements
  4214. // are tested in order such that the test is likely to fail as early
  4215. // as possible. I _think_ this is just as friendly to the L1 cache
  4216. // as testing in index order. It is certainty faster in practice.
  4217. return (left === right) ||
  4218. (defined.defined(left) &&
  4219. defined.defined(right) &&
  4220. // Translation
  4221. left[12] === right[12] &&
  4222. left[13] === right[13] &&
  4223. left[14] === right[14] &&
  4224. // Rotation/scale
  4225. left[0] === right[0] &&
  4226. left[1] === right[1] &&
  4227. left[2] === right[2] &&
  4228. left[4] === right[4] &&
  4229. left[5] === right[5] &&
  4230. left[6] === right[6] &&
  4231. left[8] === right[8] &&
  4232. left[9] === right[9] &&
  4233. left[10] === right[10] &&
  4234. // Bottom row
  4235. left[3] === right[3] &&
  4236. left[7] === right[7] &&
  4237. left[11] === right[11] &&
  4238. left[15] === right[15]);
  4239. };
  4240. /**
  4241. * Compares the provided matrices componentwise and returns
  4242. * <code>true</code> if they are within the provided epsilon,
  4243. * <code>false</code> otherwise.
  4244. *
  4245. * @param {Matrix4} [left] The first matrix.
  4246. * @param {Matrix4} [right] The second matrix.
  4247. * @param {Number} epsilon The epsilon to use for equality testing.
  4248. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  4249. *
  4250. * @example
  4251. * //compares two Matrix4 instances
  4252. *
  4253. * // a = [10.5, 14.5, 18.5, 22.5]
  4254. * // [11.5, 15.5, 19.5, 23.5]
  4255. * // [12.5, 16.5, 20.5, 24.5]
  4256. * // [13.5, 17.5, 21.5, 25.5]
  4257. *
  4258. * // b = [10.0, 14.0, 18.0, 22.0]
  4259. * // [11.0, 15.0, 19.0, 23.0]
  4260. * // [12.0, 16.0, 20.0, 24.0]
  4261. * // [13.0, 17.0, 21.0, 25.0]
  4262. *
  4263. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  4264. * console.log("Difference between both the matrices is less than 0.1");
  4265. * } else {
  4266. * console.log("Difference between both the matrices is not less than 0.1");
  4267. * }
  4268. *
  4269. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  4270. */
  4271. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  4272. //>>includeStart('debug', pragmas.debug);
  4273. Check.Check.typeOf.number('epsilon', epsilon);
  4274. //>>includeEnd('debug');
  4275. return (left === right) ||
  4276. (defined.defined(left) &&
  4277. defined.defined(right) &&
  4278. Math.abs(left[0] - right[0]) <= epsilon &&
  4279. Math.abs(left[1] - right[1]) <= epsilon &&
  4280. Math.abs(left[2] - right[2]) <= epsilon &&
  4281. Math.abs(left[3] - right[3]) <= epsilon &&
  4282. Math.abs(left[4] - right[4]) <= epsilon &&
  4283. Math.abs(left[5] - right[5]) <= epsilon &&
  4284. Math.abs(left[6] - right[6]) <= epsilon &&
  4285. Math.abs(left[7] - right[7]) <= epsilon &&
  4286. Math.abs(left[8] - right[8]) <= epsilon &&
  4287. Math.abs(left[9] - right[9]) <= epsilon &&
  4288. Math.abs(left[10] - right[10]) <= epsilon &&
  4289. Math.abs(left[11] - right[11]) <= epsilon &&
  4290. Math.abs(left[12] - right[12]) <= epsilon &&
  4291. Math.abs(left[13] - right[13]) <= epsilon &&
  4292. Math.abs(left[14] - right[14]) <= epsilon &&
  4293. Math.abs(left[15] - right[15]) <= epsilon);
  4294. };
  4295. /**
  4296. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  4297. *
  4298. * @param {Matrix4} matrix The matrix to use.
  4299. * @param {Cartesian3} result The object onto which to store the result.
  4300. * @returns {Cartesian3} The modified result parameter.
  4301. */
  4302. Matrix4.getTranslation = function(matrix, result) {
  4303. //>>includeStart('debug', pragmas.debug);
  4304. Check.Check.typeOf.object('matrix', matrix);
  4305. Check.Check.typeOf.object('result', result);
  4306. //>>includeEnd('debug');
  4307. result.x = matrix[12];
  4308. result.y = matrix[13];
  4309. result.z = matrix[14];
  4310. return result;
  4311. };
  4312. /**
  4313. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is an affine transformation matrix.
  4314. *
  4315. * @param {Matrix4} matrix The matrix to use.
  4316. * @param {Matrix3} result The object onto which to store the result.
  4317. * @returns {Matrix3} The modified result parameter.
  4318. *
  4319. * @deprecated moved to Matrix4.getMatrix3
  4320. */
  4321. Matrix4.getRotation = function(matrix, result) {
  4322. deprecationWarning('Matrix4.getRotation', 'Matrix4.getRotation is deprecated and will be removed in Cesium 1.65. Use Matrix4.getMatrix3 instead.');
  4323. return Matrix4.getMatrix3(matrix, result);
  4324. };
  4325. /**
  4326. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is an affine transformation matrix.
  4327. *
  4328. * @param {Matrix4} matrix The matrix to use.
  4329. * @param {Matrix3} result The object onto which to store the result.
  4330. * @returns {Matrix3} The modified result parameter.
  4331. *
  4332. * @example
  4333. * // returns a Matrix3 instance from a Matrix4 instance
  4334. *
  4335. * // m = [10.0, 14.0, 18.0, 22.0]
  4336. * // [11.0, 15.0, 19.0, 23.0]
  4337. * // [12.0, 16.0, 20.0, 24.0]
  4338. * // [13.0, 17.0, 21.0, 25.0]
  4339. *
  4340. * var b = new Cesium.Matrix3();
  4341. * Cesium.Matrix4.getMatrix3(m,b);
  4342. *
  4343. * // b = [10.0, 14.0, 18.0]
  4344. * // [11.0, 15.0, 19.0]
  4345. * // [12.0, 16.0, 20.0]
  4346. */
  4347. Matrix4.getMatrix3 = function(matrix, result) {
  4348. //>>includeStart('debug', pragmas.debug);
  4349. Check.Check.typeOf.object('matrix', matrix);
  4350. Check.Check.typeOf.object('result', result);
  4351. //>>includeEnd('debug');
  4352. result[0] = matrix[0];
  4353. result[1] = matrix[1];
  4354. result[2] = matrix[2];
  4355. result[3] = matrix[4];
  4356. result[4] = matrix[5];
  4357. result[5] = matrix[6];
  4358. result[6] = matrix[8];
  4359. result[7] = matrix[9];
  4360. result[8] = matrix[10];
  4361. return result;
  4362. };
  4363. var scratchInverseRotation = new Matrix3();
  4364. var scratchMatrix3Zero = new Matrix3();
  4365. var scratchBottomRow = new Cartesian4();
  4366. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  4367. /**
  4368. * Computes the inverse of the provided matrix using Cramers Rule.
  4369. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  4370. * If the matrix is an affine transformation matrix, it is more efficient
  4371. * to invert it with {@link Matrix4.inverseTransformation}.
  4372. *
  4373. * @param {Matrix4} matrix The matrix to invert.
  4374. * @param {Matrix4} result The object onto which to store the result.
  4375. * @returns {Matrix4} The modified result parameter.
  4376. *
  4377. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  4378. */
  4379. Matrix4.inverse = function(matrix, result) {
  4380. //>>includeStart('debug', pragmas.debug);
  4381. Check.Check.typeOf.object('matrix', matrix);
  4382. Check.Check.typeOf.object('result', result);
  4383. //>>includeEnd('debug');
  4384. //
  4385. // Ported from:
  4386. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  4387. //
  4388. var src0 = matrix[0];
  4389. var src1 = matrix[4];
  4390. var src2 = matrix[8];
  4391. var src3 = matrix[12];
  4392. var src4 = matrix[1];
  4393. var src5 = matrix[5];
  4394. var src6 = matrix[9];
  4395. var src7 = matrix[13];
  4396. var src8 = matrix[2];
  4397. var src9 = matrix[6];
  4398. var src10 = matrix[10];
  4399. var src11 = matrix[14];
  4400. var src12 = matrix[3];
  4401. var src13 = matrix[7];
  4402. var src14 = matrix[11];
  4403. var src15 = matrix[15];
  4404. // calculate pairs for first 8 elements (cofactors)
  4405. var tmp0 = src10 * src15;
  4406. var tmp1 = src11 * src14;
  4407. var tmp2 = src9 * src15;
  4408. var tmp3 = src11 * src13;
  4409. var tmp4 = src9 * src14;
  4410. var tmp5 = src10 * src13;
  4411. var tmp6 = src8 * src15;
  4412. var tmp7 = src11 * src12;
  4413. var tmp8 = src8 * src14;
  4414. var tmp9 = src10 * src12;
  4415. var tmp10 = src8 * src13;
  4416. var tmp11 = src9 * src12;
  4417. // calculate first 8 elements (cofactors)
  4418. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  4419. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  4420. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  4421. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  4422. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  4423. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  4424. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  4425. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  4426. // calculate pairs for second 8 elements (cofactors)
  4427. tmp0 = src2 * src7;
  4428. tmp1 = src3 * src6;
  4429. tmp2 = src1 * src7;
  4430. tmp3 = src3 * src5;
  4431. tmp4 = src1 * src6;
  4432. tmp5 = src2 * src5;
  4433. tmp6 = src0 * src7;
  4434. tmp7 = src3 * src4;
  4435. tmp8 = src0 * src6;
  4436. tmp9 = src2 * src4;
  4437. tmp10 = src0 * src5;
  4438. tmp11 = src1 * src4;
  4439. // calculate second 8 elements (cofactors)
  4440. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  4441. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  4442. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  4443. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  4444. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  4445. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  4446. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  4447. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  4448. // calculate determinant
  4449. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  4450. if (Math.abs(det) < _Math.CesiumMath.EPSILON21) {
  4451. // Special case for a zero scale matrix that can occur, for example,
  4452. // when a model's node has a [0, 0, 0] scale.
  4453. if (Matrix3.equalsEpsilon(Matrix4.getMatrix3(matrix, scratchInverseRotation), scratchMatrix3Zero, _Math.CesiumMath.EPSILON7) &&
  4454. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  4455. result[0] = 0.0;
  4456. result[1] = 0.0;
  4457. result[2] = 0.0;
  4458. result[3] = 0.0;
  4459. result[4] = 0.0;
  4460. result[5] = 0.0;
  4461. result[6] = 0.0;
  4462. result[7] = 0.0;
  4463. result[8] = 0.0;
  4464. result[9] = 0.0;
  4465. result[10] = 0.0;
  4466. result[11] = 0.0;
  4467. result[12] = -matrix[12];
  4468. result[13] = -matrix[13];
  4469. result[14] = -matrix[14];
  4470. result[15] = 1.0;
  4471. return result;
  4472. }
  4473. throw new RuntimeError.RuntimeError('matrix is not invertible because its determinate is zero.');
  4474. }
  4475. // calculate matrix inverse
  4476. det = 1.0 / det;
  4477. result[0] = dst0 * det;
  4478. result[1] = dst1 * det;
  4479. result[2] = dst2 * det;
  4480. result[3] = dst3 * det;
  4481. result[4] = dst4 * det;
  4482. result[5] = dst5 * det;
  4483. result[6] = dst6 * det;
  4484. result[7] = dst7 * det;
  4485. result[8] = dst8 * det;
  4486. result[9] = dst9 * det;
  4487. result[10] = dst10 * det;
  4488. result[11] = dst11 * det;
  4489. result[12] = dst12 * det;
  4490. result[13] = dst13 * det;
  4491. result[14] = dst14 * det;
  4492. result[15] = dst15 * det;
  4493. return result;
  4494. };
  4495. /**
  4496. * Computes the inverse of the provided matrix assuming it is
  4497. * an affine transformation matrix, where the upper left 3x3 elements
  4498. * are a rotation matrix, and the upper three elements in the fourth
  4499. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  4500. * The matrix is not verified to be in the proper form.
  4501. * This method is faster than computing the inverse for a general 4x4
  4502. * matrix using {@link Matrix4.inverse}.
  4503. *
  4504. * @param {Matrix4} matrix The matrix to invert.
  4505. * @param {Matrix4} result The object onto which to store the result.
  4506. * @returns {Matrix4} The modified result parameter.
  4507. */
  4508. Matrix4.inverseTransformation = function(matrix, result) {
  4509. //>>includeStart('debug', pragmas.debug);
  4510. Check.Check.typeOf.object('matrix', matrix);
  4511. Check.Check.typeOf.object('result', result);
  4512. //>>includeEnd('debug');
  4513. //This function is an optimized version of the below 4 lines.
  4514. //var rT = Matrix3.transpose(Matrix4.getMatrix3(matrix));
  4515. //var rTN = Matrix3.negate(rT);
  4516. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  4517. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  4518. var matrix0 = matrix[0];
  4519. var matrix1 = matrix[1];
  4520. var matrix2 = matrix[2];
  4521. var matrix4 = matrix[4];
  4522. var matrix5 = matrix[5];
  4523. var matrix6 = matrix[6];
  4524. var matrix8 = matrix[8];
  4525. var matrix9 = matrix[9];
  4526. var matrix10 = matrix[10];
  4527. var vX = matrix[12];
  4528. var vY = matrix[13];
  4529. var vZ = matrix[14];
  4530. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  4531. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  4532. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  4533. result[0] = matrix0;
  4534. result[1] = matrix4;
  4535. result[2] = matrix8;
  4536. result[3] = 0.0;
  4537. result[4] = matrix1;
  4538. result[5] = matrix5;
  4539. result[6] = matrix9;
  4540. result[7] = 0.0;
  4541. result[8] = matrix2;
  4542. result[9] = matrix6;
  4543. result[10] = matrix10;
  4544. result[11] = 0.0;
  4545. result[12] = x;
  4546. result[13] = y;
  4547. result[14] = z;
  4548. result[15] = 1.0;
  4549. return result;
  4550. };
  4551. /**
  4552. * An immutable Matrix4 instance initialized to the identity matrix.
  4553. *
  4554. * @type {Matrix4}
  4555. * @constant
  4556. */
  4557. Matrix4.IDENTITY = freezeObject.freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  4558. 0.0, 1.0, 0.0, 0.0,
  4559. 0.0, 0.0, 1.0, 0.0,
  4560. 0.0, 0.0, 0.0, 1.0));
  4561. /**
  4562. * An immutable Matrix4 instance initialized to the zero matrix.
  4563. *
  4564. * @type {Matrix4}
  4565. * @constant
  4566. */
  4567. Matrix4.ZERO = freezeObject.freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  4568. 0.0, 0.0, 0.0, 0.0,
  4569. 0.0, 0.0, 0.0, 0.0,
  4570. 0.0, 0.0, 0.0, 0.0));
  4571. /**
  4572. * The index into Matrix4 for column 0, row 0.
  4573. *
  4574. * @type {Number}
  4575. * @constant
  4576. */
  4577. Matrix4.COLUMN0ROW0 = 0;
  4578. /**
  4579. * The index into Matrix4 for column 0, row 1.
  4580. *
  4581. * @type {Number}
  4582. * @constant
  4583. */
  4584. Matrix4.COLUMN0ROW1 = 1;
  4585. /**
  4586. * The index into Matrix4 for column 0, row 2.
  4587. *
  4588. * @type {Number}
  4589. * @constant
  4590. */
  4591. Matrix4.COLUMN0ROW2 = 2;
  4592. /**
  4593. * The index into Matrix4 for column 0, row 3.
  4594. *
  4595. * @type {Number}
  4596. * @constant
  4597. */
  4598. Matrix4.COLUMN0ROW3 = 3;
  4599. /**
  4600. * The index into Matrix4 for column 1, row 0.
  4601. *
  4602. * @type {Number}
  4603. * @constant
  4604. */
  4605. Matrix4.COLUMN1ROW0 = 4;
  4606. /**
  4607. * The index into Matrix4 for column 1, row 1.
  4608. *
  4609. * @type {Number}
  4610. * @constant
  4611. */
  4612. Matrix4.COLUMN1ROW1 = 5;
  4613. /**
  4614. * The index into Matrix4 for column 1, row 2.
  4615. *
  4616. * @type {Number}
  4617. * @constant
  4618. */
  4619. Matrix4.COLUMN1ROW2 = 6;
  4620. /**
  4621. * The index into Matrix4 for column 1, row 3.
  4622. *
  4623. * @type {Number}
  4624. * @constant
  4625. */
  4626. Matrix4.COLUMN1ROW3 = 7;
  4627. /**
  4628. * The index into Matrix4 for column 2, row 0.
  4629. *
  4630. * @type {Number}
  4631. * @constant
  4632. */
  4633. Matrix4.COLUMN2ROW0 = 8;
  4634. /**
  4635. * The index into Matrix4 for column 2, row 1.
  4636. *
  4637. * @type {Number}
  4638. * @constant
  4639. */
  4640. Matrix4.COLUMN2ROW1 = 9;
  4641. /**
  4642. * The index into Matrix4 for column 2, row 2.
  4643. *
  4644. * @type {Number}
  4645. * @constant
  4646. */
  4647. Matrix4.COLUMN2ROW2 = 10;
  4648. /**
  4649. * The index into Matrix4 for column 2, row 3.
  4650. *
  4651. * @type {Number}
  4652. * @constant
  4653. */
  4654. Matrix4.COLUMN2ROW3 = 11;
  4655. /**
  4656. * The index into Matrix4 for column 3, row 0.
  4657. *
  4658. * @type {Number}
  4659. * @constant
  4660. */
  4661. Matrix4.COLUMN3ROW0 = 12;
  4662. /**
  4663. * The index into Matrix4 for column 3, row 1.
  4664. *
  4665. * @type {Number}
  4666. * @constant
  4667. */
  4668. Matrix4.COLUMN3ROW1 = 13;
  4669. /**
  4670. * The index into Matrix4 for column 3, row 2.
  4671. *
  4672. * @type {Number}
  4673. * @constant
  4674. */
  4675. Matrix4.COLUMN3ROW2 = 14;
  4676. /**
  4677. * The index into Matrix4 for column 3, row 3.
  4678. *
  4679. * @type {Number}
  4680. * @constant
  4681. */
  4682. Matrix4.COLUMN3ROW3 = 15;
  4683. defineProperties.defineProperties(Matrix4.prototype, {
  4684. /**
  4685. * Gets the number of items in the collection.
  4686. * @memberof Matrix4.prototype
  4687. *
  4688. * @type {Number}
  4689. */
  4690. length : {
  4691. get : function() {
  4692. return Matrix4.packedLength;
  4693. }
  4694. }
  4695. });
  4696. /**
  4697. * Duplicates the provided Matrix4 instance.
  4698. *
  4699. * @param {Matrix4} [result] The object onto which to store the result.
  4700. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  4701. */
  4702. Matrix4.prototype.clone = function(result) {
  4703. return Matrix4.clone(this, result);
  4704. };
  4705. /**
  4706. * Compares this matrix to the provided matrix componentwise and returns
  4707. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4708. *
  4709. * @param {Matrix4} [right] The right hand side matrix.
  4710. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  4711. */
  4712. Matrix4.prototype.equals = function(right) {
  4713. return Matrix4.equals(this, right);
  4714. };
  4715. /**
  4716. * @private
  4717. */
  4718. Matrix4.equalsArray = function(matrix, array, offset) {
  4719. return matrix[0] === array[offset] &&
  4720. matrix[1] === array[offset + 1] &&
  4721. matrix[2] === array[offset + 2] &&
  4722. matrix[3] === array[offset + 3] &&
  4723. matrix[4] === array[offset + 4] &&
  4724. matrix[5] === array[offset + 5] &&
  4725. matrix[6] === array[offset + 6] &&
  4726. matrix[7] === array[offset + 7] &&
  4727. matrix[8] === array[offset + 8] &&
  4728. matrix[9] === array[offset + 9] &&
  4729. matrix[10] === array[offset + 10] &&
  4730. matrix[11] === array[offset + 11] &&
  4731. matrix[12] === array[offset + 12] &&
  4732. matrix[13] === array[offset + 13] &&
  4733. matrix[14] === array[offset + 14] &&
  4734. matrix[15] === array[offset + 15];
  4735. };
  4736. /**
  4737. * Compares this matrix to the provided matrix componentwise and returns
  4738. * <code>true</code> if they are within the provided epsilon,
  4739. * <code>false</code> otherwise.
  4740. *
  4741. * @param {Matrix4} [right] The right hand side matrix.
  4742. * @param {Number} epsilon The epsilon to use for equality testing.
  4743. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  4744. */
  4745. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  4746. return Matrix4.equalsEpsilon(this, right, epsilon);
  4747. };
  4748. /**
  4749. * Computes a string representing this Matrix with each row being
  4750. * on a separate line and in the format '(column0, column1, column2, column3)'.
  4751. *
  4752. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  4753. */
  4754. Matrix4.prototype.toString = function() {
  4755. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] + ')\n' +
  4756. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] + ')\n' +
  4757. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] + ')\n' +
  4758. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] + ')';
  4759. };
  4760. /**
  4761. * A bounding sphere with a center and a radius.
  4762. * @alias BoundingSphere
  4763. * @constructor
  4764. *
  4765. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  4766. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  4767. *
  4768. * @see AxisAlignedBoundingBox
  4769. * @see BoundingRectangle
  4770. * @see Packable
  4771. */
  4772. function BoundingSphere(center, radius) {
  4773. /**
  4774. * The center point of the sphere.
  4775. * @type {Cartesian3}
  4776. * @default {@link Cartesian3.ZERO}
  4777. */
  4778. this.center = Cartesian2.Cartesian3.clone(defaultValue.defaultValue(center, Cartesian2.Cartesian3.ZERO));
  4779. /**
  4780. * The radius of the sphere.
  4781. * @type {Number}
  4782. * @default 0.0
  4783. */
  4784. this.radius = defaultValue.defaultValue(radius, 0.0);
  4785. }
  4786. var fromPointsXMin = new Cartesian2.Cartesian3();
  4787. var fromPointsYMin = new Cartesian2.Cartesian3();
  4788. var fromPointsZMin = new Cartesian2.Cartesian3();
  4789. var fromPointsXMax = new Cartesian2.Cartesian3();
  4790. var fromPointsYMax = new Cartesian2.Cartesian3();
  4791. var fromPointsZMax = new Cartesian2.Cartesian3();
  4792. var fromPointsCurrentPos = new Cartesian2.Cartesian3();
  4793. var fromPointsScratch = new Cartesian2.Cartesian3();
  4794. var fromPointsRitterCenter = new Cartesian2.Cartesian3();
  4795. var fromPointsMinBoxPt = new Cartesian2.Cartesian3();
  4796. var fromPointsMaxBoxPt = new Cartesian2.Cartesian3();
  4797. var fromPointsNaiveCenterScratch = new Cartesian2.Cartesian3();
  4798. var volumeConstant = (4.0 / 3.0) * _Math.CesiumMath.PI;
  4799. /**
  4800. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  4801. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  4802. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  4803. *
  4804. * @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.
  4805. * @param {BoundingSphere} [result] The object onto which to store the result.
  4806. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  4807. *
  4808. * @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
  4809. */
  4810. BoundingSphere.fromPoints = function(positions, result) {
  4811. if (!defined.defined(result)) {
  4812. result = new BoundingSphere();
  4813. }
  4814. if (!defined.defined(positions) || positions.length === 0) {
  4815. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  4816. result.radius = 0.0;
  4817. return result;
  4818. }
  4819. var currentPos = Cartesian2.Cartesian3.clone(positions[0], fromPointsCurrentPos);
  4820. var xMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMin);
  4821. var yMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMin);
  4822. var zMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMin);
  4823. var xMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMax);
  4824. var yMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMax);
  4825. var zMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMax);
  4826. var numPositions = positions.length;
  4827. var i;
  4828. for (i = 1; i < numPositions; i++) {
  4829. Cartesian2.Cartesian3.clone(positions[i], currentPos);
  4830. var x = currentPos.x;
  4831. var y = currentPos.y;
  4832. var z = currentPos.z;
  4833. // Store points containing the the smallest and largest components
  4834. if (x < xMin.x) {
  4835. Cartesian2.Cartesian3.clone(currentPos, xMin);
  4836. }
  4837. if (x > xMax.x) {
  4838. Cartesian2.Cartesian3.clone(currentPos, xMax);
  4839. }
  4840. if (y < yMin.y) {
  4841. Cartesian2.Cartesian3.clone(currentPos, yMin);
  4842. }
  4843. if (y > yMax.y) {
  4844. Cartesian2.Cartesian3.clone(currentPos, yMax);
  4845. }
  4846. if (z < zMin.z) {
  4847. Cartesian2.Cartesian3.clone(currentPos, zMin);
  4848. }
  4849. if (z > zMax.z) {
  4850. Cartesian2.Cartesian3.clone(currentPos, zMax);
  4851. }
  4852. }
  4853. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  4854. var xSpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  4855. var ySpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  4856. var zSpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  4857. // Set the diameter endpoints to the largest span.
  4858. var diameter1 = xMin;
  4859. var diameter2 = xMax;
  4860. var maxSpan = xSpan;
  4861. if (ySpan > maxSpan) {
  4862. maxSpan = ySpan;
  4863. diameter1 = yMin;
  4864. diameter2 = yMax;
  4865. }
  4866. if (zSpan > maxSpan) {
  4867. maxSpan = zSpan;
  4868. diameter1 = zMin;
  4869. diameter2 = zMax;
  4870. }
  4871. // Calculate the center of the initial sphere found by Ritter's algorithm
  4872. var ritterCenter = fromPointsRitterCenter;
  4873. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  4874. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  4875. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  4876. // Calculate the radius of the initial sphere found by Ritter's algorithm
  4877. var radiusSquared = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  4878. var ritterRadius = Math.sqrt(radiusSquared);
  4879. // Find the center of the sphere found using the Naive method.
  4880. var minBoxPt = fromPointsMinBoxPt;
  4881. minBoxPt.x = xMin.x;
  4882. minBoxPt.y = yMin.y;
  4883. minBoxPt.z = zMin.z;
  4884. var maxBoxPt = fromPointsMaxBoxPt;
  4885. maxBoxPt.x = xMax.x;
  4886. maxBoxPt.y = yMax.y;
  4887. maxBoxPt.z = zMax.z;
  4888. var naiveCenter = Cartesian2.Cartesian3.midpoint(minBoxPt, maxBoxPt, fromPointsNaiveCenterScratch);
  4889. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  4890. var naiveRadius = 0;
  4891. for (i = 0; i < numPositions; i++) {
  4892. Cartesian2.Cartesian3.clone(positions[i], currentPos);
  4893. // Find the furthest point from the naive center to calculate the naive radius.
  4894. var r = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  4895. if (r > naiveRadius) {
  4896. naiveRadius = r;
  4897. }
  4898. // Make adjustments to the Ritter Sphere to include all points.
  4899. var oldCenterToPointSquared = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  4900. if (oldCenterToPointSquared > radiusSquared) {
  4901. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  4902. // Calculate new radius to include the point that lies outside
  4903. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  4904. radiusSquared = ritterRadius * ritterRadius;
  4905. // Calculate center of new Ritter sphere
  4906. var oldToNew = oldCenterToPoint - ritterRadius;
  4907. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  4908. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  4909. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  4910. }
  4911. }
  4912. if (ritterRadius < naiveRadius) {
  4913. Cartesian2.Cartesian3.clone(ritterCenter, result.center);
  4914. result.radius = ritterRadius;
  4915. } else {
  4916. Cartesian2.Cartesian3.clone(naiveCenter, result.center);
  4917. result.radius = naiveRadius;
  4918. }
  4919. return result;
  4920. };
  4921. var defaultProjection = new GeographicProjection();
  4922. var fromRectangle2DLowerLeft = new Cartesian2.Cartesian3();
  4923. var fromRectangle2DUpperRight = new Cartesian2.Cartesian3();
  4924. var fromRectangle2DSouthwest = new Cartesian2.Cartographic();
  4925. var fromRectangle2DNortheast = new Cartesian2.Cartographic();
  4926. /**
  4927. * Computes a bounding sphere from a rectangle projected in 2D.
  4928. *
  4929. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  4930. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  4931. * @param {BoundingSphere} [result] The object onto which to store the result.
  4932. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  4933. */
  4934. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  4935. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  4936. };
  4937. /**
  4938. * Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
  4939. * object's minimum and maximum heights over the rectangle.
  4940. *
  4941. * @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
  4942. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  4943. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  4944. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  4945. * @param {BoundingSphere} [result] The object onto which to store the result.
  4946. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  4947. */
  4948. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  4949. if (!defined.defined(result)) {
  4950. result = new BoundingSphere();
  4951. }
  4952. if (!defined.defined(rectangle)) {
  4953. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  4954. result.radius = 0.0;
  4955. return result;
  4956. }
  4957. projection = defaultValue.defaultValue(projection, defaultProjection);
  4958. Cartesian2.Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  4959. fromRectangle2DSouthwest.height = minimumHeight;
  4960. Cartesian2.Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  4961. fromRectangle2DNortheast.height = maximumHeight;
  4962. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  4963. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  4964. var width = upperRight.x - lowerLeft.x;
  4965. var height = upperRight.y - lowerLeft.y;
  4966. var elevation = upperRight.z - lowerLeft.z;
  4967. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  4968. var center = result.center;
  4969. center.x = lowerLeft.x + width * 0.5;
  4970. center.y = lowerLeft.y + height * 0.5;
  4971. center.z = lowerLeft.z + elevation * 0.5;
  4972. return result;
  4973. };
  4974. var fromRectangle3DScratch = [];
  4975. /**
  4976. * Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
  4977. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  4978. *
  4979. * @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
  4980. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  4981. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  4982. * @param {BoundingSphere} [result] The object onto which to store the result.
  4983. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  4984. */
  4985. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  4986. ellipsoid = defaultValue.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  4987. surfaceHeight = defaultValue.defaultValue(surfaceHeight, 0.0);
  4988. if (!defined.defined(result)) {
  4989. result = new BoundingSphere();
  4990. }
  4991. if (!defined.defined(rectangle)) {
  4992. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  4993. result.radius = 0.0;
  4994. return result;
  4995. }
  4996. var positions = Cartesian2.Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  4997. return BoundingSphere.fromPoints(positions, result);
  4998. };
  4999. /**
  5000. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  5001. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  5002. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  5003. * ensure a tight fit.
  5004. *
  5005. * @param {Number[]} [positions] An array of points that the bounding sphere will enclose. Each point
  5006. * is formed from three elements in the array in the order X, Y, Z.
  5007. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  5008. * origin of the coordinate system. This is useful when the positions are to be used for
  5009. * relative-to-center (RTC) rendering.
  5010. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  5011. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  5012. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  5013. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  5014. * the stride is 5, however, two array elements are skipped and the next position begins at array
  5015. * index 5.
  5016. * @param {BoundingSphere} [result] The object onto which to store the result.
  5017. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5018. *
  5019. * @example
  5020. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  5021. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  5022. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  5023. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  5024. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  5025. * 4.0, 5.0, 6.0, 0.1, 0.2,
  5026. * 7.0, 8.0, 9.0, 0.1, 0.2];
  5027. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  5028. *
  5029. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  5030. */
  5031. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  5032. if (!defined.defined(result)) {
  5033. result = new BoundingSphere();
  5034. }
  5035. if (!defined.defined(positions) || positions.length === 0) {
  5036. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5037. result.radius = 0.0;
  5038. return result;
  5039. }
  5040. center = defaultValue.defaultValue(center, Cartesian2.Cartesian3.ZERO);
  5041. stride = defaultValue.defaultValue(stride, 3);
  5042. //>>includeStart('debug', pragmas.debug);
  5043. Check.Check.typeOf.number.greaterThanOrEquals('stride', stride, 3);
  5044. //>>includeEnd('debug');
  5045. var currentPos = fromPointsCurrentPos;
  5046. currentPos.x = positions[0] + center.x;
  5047. currentPos.y = positions[1] + center.y;
  5048. currentPos.z = positions[2] + center.z;
  5049. var xMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMin);
  5050. var yMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMin);
  5051. var zMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMin);
  5052. var xMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMax);
  5053. var yMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMax);
  5054. var zMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMax);
  5055. var numElements = positions.length;
  5056. var i;
  5057. for (i = 0; i < numElements; i += stride) {
  5058. var x = positions[i] + center.x;
  5059. var y = positions[i + 1] + center.y;
  5060. var z = positions[i + 2] + center.z;
  5061. currentPos.x = x;
  5062. currentPos.y = y;
  5063. currentPos.z = z;
  5064. // Store points containing the the smallest and largest components
  5065. if (x < xMin.x) {
  5066. Cartesian2.Cartesian3.clone(currentPos, xMin);
  5067. }
  5068. if (x > xMax.x) {
  5069. Cartesian2.Cartesian3.clone(currentPos, xMax);
  5070. }
  5071. if (y < yMin.y) {
  5072. Cartesian2.Cartesian3.clone(currentPos, yMin);
  5073. }
  5074. if (y > yMax.y) {
  5075. Cartesian2.Cartesian3.clone(currentPos, yMax);
  5076. }
  5077. if (z < zMin.z) {
  5078. Cartesian2.Cartesian3.clone(currentPos, zMin);
  5079. }
  5080. if (z > zMax.z) {
  5081. Cartesian2.Cartesian3.clone(currentPos, zMax);
  5082. }
  5083. }
  5084. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  5085. var xSpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  5086. var ySpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  5087. var zSpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  5088. // Set the diameter endpoints to the largest span.
  5089. var diameter1 = xMin;
  5090. var diameter2 = xMax;
  5091. var maxSpan = xSpan;
  5092. if (ySpan > maxSpan) {
  5093. maxSpan = ySpan;
  5094. diameter1 = yMin;
  5095. diameter2 = yMax;
  5096. }
  5097. if (zSpan > maxSpan) {
  5098. maxSpan = zSpan;
  5099. diameter1 = zMin;
  5100. diameter2 = zMax;
  5101. }
  5102. // Calculate the center of the initial sphere found by Ritter's algorithm
  5103. var ritterCenter = fromPointsRitterCenter;
  5104. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  5105. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  5106. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  5107. // Calculate the radius of the initial sphere found by Ritter's algorithm
  5108. var radiusSquared = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  5109. var ritterRadius = Math.sqrt(radiusSquared);
  5110. // Find the center of the sphere found using the Naive method.
  5111. var minBoxPt = fromPointsMinBoxPt;
  5112. minBoxPt.x = xMin.x;
  5113. minBoxPt.y = yMin.y;
  5114. minBoxPt.z = zMin.z;
  5115. var maxBoxPt = fromPointsMaxBoxPt;
  5116. maxBoxPt.x = xMax.x;
  5117. maxBoxPt.y = yMax.y;
  5118. maxBoxPt.z = zMax.z;
  5119. var naiveCenter = Cartesian2.Cartesian3.midpoint(minBoxPt, maxBoxPt, fromPointsNaiveCenterScratch);
  5120. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  5121. var naiveRadius = 0;
  5122. for (i = 0; i < numElements; i += stride) {
  5123. currentPos.x = positions[i] + center.x;
  5124. currentPos.y = positions[i + 1] + center.y;
  5125. currentPos.z = positions[i + 2] + center.z;
  5126. // Find the furthest point from the naive center to calculate the naive radius.
  5127. var r = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  5128. if (r > naiveRadius) {
  5129. naiveRadius = r;
  5130. }
  5131. // Make adjustments to the Ritter Sphere to include all points.
  5132. var oldCenterToPointSquared = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  5133. if (oldCenterToPointSquared > radiusSquared) {
  5134. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  5135. // Calculate new radius to include the point that lies outside
  5136. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  5137. radiusSquared = ritterRadius * ritterRadius;
  5138. // Calculate center of new Ritter sphere
  5139. var oldToNew = oldCenterToPoint - ritterRadius;
  5140. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  5141. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  5142. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  5143. }
  5144. }
  5145. if (ritterRadius < naiveRadius) {
  5146. Cartesian2.Cartesian3.clone(ritterCenter, result.center);
  5147. result.radius = ritterRadius;
  5148. } else {
  5149. Cartesian2.Cartesian3.clone(naiveCenter, result.center);
  5150. result.radius = naiveRadius;
  5151. }
  5152. return result;
  5153. };
  5154. /**
  5155. * Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
  5156. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  5157. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  5158. * ensure a tight fit.
  5159. *
  5160. * @param {Number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  5161. * is formed from three elements in the array in the order X, Y, Z.
  5162. * @param {Number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  5163. * is formed from three elements in the array in the order X, Y, Z.
  5164. * @param {BoundingSphere} [result] The object onto which to store the result.
  5165. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5166. *
  5167. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  5168. */
  5169. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  5170. if (!defined.defined(result)) {
  5171. result = new BoundingSphere();
  5172. }
  5173. if (!defined.defined(positionsHigh) || !defined.defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  5174. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5175. result.radius = 0.0;
  5176. return result;
  5177. }
  5178. var currentPos = fromPointsCurrentPos;
  5179. currentPos.x = positionsHigh[0] + positionsLow[0];
  5180. currentPos.y = positionsHigh[1] + positionsLow[1];
  5181. currentPos.z = positionsHigh[2] + positionsLow[2];
  5182. var xMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMin);
  5183. var yMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMin);
  5184. var zMin = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMin);
  5185. var xMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsXMax);
  5186. var yMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsYMax);
  5187. var zMax = Cartesian2.Cartesian3.clone(currentPos, fromPointsZMax);
  5188. var numElements = positionsHigh.length;
  5189. var i;
  5190. for (i = 0; i < numElements; i += 3) {
  5191. var x = positionsHigh[i] + positionsLow[i];
  5192. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  5193. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  5194. currentPos.x = x;
  5195. currentPos.y = y;
  5196. currentPos.z = z;
  5197. // Store points containing the the smallest and largest components
  5198. if (x < xMin.x) {
  5199. Cartesian2.Cartesian3.clone(currentPos, xMin);
  5200. }
  5201. if (x > xMax.x) {
  5202. Cartesian2.Cartesian3.clone(currentPos, xMax);
  5203. }
  5204. if (y < yMin.y) {
  5205. Cartesian2.Cartesian3.clone(currentPos, yMin);
  5206. }
  5207. if (y > yMax.y) {
  5208. Cartesian2.Cartesian3.clone(currentPos, yMax);
  5209. }
  5210. if (z < zMin.z) {
  5211. Cartesian2.Cartesian3.clone(currentPos, zMin);
  5212. }
  5213. if (z > zMax.z) {
  5214. Cartesian2.Cartesian3.clone(currentPos, zMax);
  5215. }
  5216. }
  5217. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  5218. var xSpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  5219. var ySpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  5220. var zSpan = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  5221. // Set the diameter endpoints to the largest span.
  5222. var diameter1 = xMin;
  5223. var diameter2 = xMax;
  5224. var maxSpan = xSpan;
  5225. if (ySpan > maxSpan) {
  5226. maxSpan = ySpan;
  5227. diameter1 = yMin;
  5228. diameter2 = yMax;
  5229. }
  5230. if (zSpan > maxSpan) {
  5231. maxSpan = zSpan;
  5232. diameter1 = zMin;
  5233. diameter2 = zMax;
  5234. }
  5235. // Calculate the center of the initial sphere found by Ritter's algorithm
  5236. var ritterCenter = fromPointsRitterCenter;
  5237. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  5238. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  5239. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  5240. // Calculate the radius of the initial sphere found by Ritter's algorithm
  5241. var radiusSquared = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  5242. var ritterRadius = Math.sqrt(radiusSquared);
  5243. // Find the center of the sphere found using the Naive method.
  5244. var minBoxPt = fromPointsMinBoxPt;
  5245. minBoxPt.x = xMin.x;
  5246. minBoxPt.y = yMin.y;
  5247. minBoxPt.z = zMin.z;
  5248. var maxBoxPt = fromPointsMaxBoxPt;
  5249. maxBoxPt.x = xMax.x;
  5250. maxBoxPt.y = yMax.y;
  5251. maxBoxPt.z = zMax.z;
  5252. var naiveCenter = Cartesian2.Cartesian3.midpoint(minBoxPt, maxBoxPt, fromPointsNaiveCenterScratch);
  5253. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  5254. var naiveRadius = 0;
  5255. for (i = 0; i < numElements; i += 3) {
  5256. currentPos.x = positionsHigh[i] + positionsLow[i];
  5257. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  5258. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  5259. // Find the furthest point from the naive center to calculate the naive radius.
  5260. var r = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  5261. if (r > naiveRadius) {
  5262. naiveRadius = r;
  5263. }
  5264. // Make adjustments to the Ritter Sphere to include all points.
  5265. var oldCenterToPointSquared = Cartesian2.Cartesian3.magnitudeSquared(Cartesian2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  5266. if (oldCenterToPointSquared > radiusSquared) {
  5267. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  5268. // Calculate new radius to include the point that lies outside
  5269. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  5270. radiusSquared = ritterRadius * ritterRadius;
  5271. // Calculate center of new Ritter sphere
  5272. var oldToNew = oldCenterToPoint - ritterRadius;
  5273. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  5274. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  5275. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  5276. }
  5277. }
  5278. if (ritterRadius < naiveRadius) {
  5279. Cartesian2.Cartesian3.clone(ritterCenter, result.center);
  5280. result.radius = ritterRadius;
  5281. } else {
  5282. Cartesian2.Cartesian3.clone(naiveCenter, result.center);
  5283. result.radius = naiveRadius;
  5284. }
  5285. return result;
  5286. };
  5287. /**
  5288. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  5289. * tighly and fully encompases the box.
  5290. *
  5291. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  5292. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  5293. * @param {BoundingSphere} [result] The object onto which to store the result.
  5294. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5295. *
  5296. * @example
  5297. * // Create a bounding sphere around the unit cube
  5298. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  5299. */
  5300. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  5301. //>>includeStart('debug', pragmas.debug);
  5302. Check.Check.typeOf.object('corner', corner);
  5303. Check.Check.typeOf.object('oppositeCorner', oppositeCorner);
  5304. //>>includeEnd('debug');
  5305. if (!defined.defined(result)) {
  5306. result = new BoundingSphere();
  5307. }
  5308. var center = Cartesian2.Cartesian3.midpoint(corner, oppositeCorner, result.center);
  5309. result.radius = Cartesian2.Cartesian3.distance(center, oppositeCorner);
  5310. return result;
  5311. };
  5312. /**
  5313. * Creates a bounding sphere encompassing an ellipsoid.
  5314. *
  5315. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  5316. * @param {BoundingSphere} [result] The object onto which to store the result.
  5317. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5318. *
  5319. * @example
  5320. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  5321. */
  5322. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  5323. //>>includeStart('debug', pragmas.debug);
  5324. Check.Check.typeOf.object('ellipsoid', ellipsoid);
  5325. //>>includeEnd('debug');
  5326. if (!defined.defined(result)) {
  5327. result = new BoundingSphere();
  5328. }
  5329. Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5330. result.radius = ellipsoid.maximumRadius;
  5331. return result;
  5332. };
  5333. var fromBoundingSpheresScratch = new Cartesian2.Cartesian3();
  5334. /**
  5335. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  5336. *
  5337. * @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
  5338. * @param {BoundingSphere} [result] The object onto which to store the result.
  5339. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5340. */
  5341. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  5342. if (!defined.defined(result)) {
  5343. result = new BoundingSphere();
  5344. }
  5345. if (!defined.defined(boundingSpheres) || boundingSpheres.length === 0) {
  5346. result.center = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.ZERO, result.center);
  5347. result.radius = 0.0;
  5348. return result;
  5349. }
  5350. var length = boundingSpheres.length;
  5351. if (length === 1) {
  5352. return BoundingSphere.clone(boundingSpheres[0], result);
  5353. }
  5354. if (length === 2) {
  5355. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  5356. }
  5357. var positions = [];
  5358. var i;
  5359. for (i = 0; i < length; i++) {
  5360. positions.push(boundingSpheres[i].center);
  5361. }
  5362. result = BoundingSphere.fromPoints(positions, result);
  5363. var center = result.center;
  5364. var radius = result.radius;
  5365. for (i = 0; i < length; i++) {
  5366. var tmp = boundingSpheres[i];
  5367. radius = Math.max(radius, Cartesian2.Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  5368. }
  5369. result.radius = radius;
  5370. return result;
  5371. };
  5372. var fromOrientedBoundingBoxScratchU = new Cartesian2.Cartesian3();
  5373. var fromOrientedBoundingBoxScratchV = new Cartesian2.Cartesian3();
  5374. var fromOrientedBoundingBoxScratchW = new Cartesian2.Cartesian3();
  5375. /**
  5376. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  5377. *
  5378. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  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.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  5383. //>>includeStart('debug', pragmas.debug);
  5384. Check.Check.defined('orientedBoundingBox', orientedBoundingBox);
  5385. //>>includeEnd('debug');
  5386. if (!defined.defined(result)) {
  5387. result = new BoundingSphere();
  5388. }
  5389. var halfAxes = orientedBoundingBox.halfAxes;
  5390. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  5391. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  5392. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  5393. Cartesian2.Cartesian3.add(u, v, u);
  5394. Cartesian2.Cartesian3.add(u, w, u);
  5395. result.center = Cartesian2.Cartesian3.clone(orientedBoundingBox.center, result.center);
  5396. result.radius = Cartesian2.Cartesian3.magnitude(u);
  5397. return result;
  5398. };
  5399. /**
  5400. * Duplicates a BoundingSphere instance.
  5401. *
  5402. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  5403. * @param {BoundingSphere} [result] The object onto which to store the result.
  5404. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  5405. */
  5406. BoundingSphere.clone = function(sphere, result) {
  5407. if (!defined.defined(sphere)) {
  5408. return undefined;
  5409. }
  5410. if (!defined.defined(result)) {
  5411. return new BoundingSphere(sphere.center, sphere.radius);
  5412. }
  5413. result.center = Cartesian2.Cartesian3.clone(sphere.center, result.center);
  5414. result.radius = sphere.radius;
  5415. return result;
  5416. };
  5417. /**
  5418. * The number of elements used to pack the object into an array.
  5419. * @type {Number}
  5420. */
  5421. BoundingSphere.packedLength = 4;
  5422. /**
  5423. * Stores the provided instance into the provided array.
  5424. *
  5425. * @param {BoundingSphere} value The value to pack.
  5426. * @param {Number[]} array The array to pack into.
  5427. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5428. *
  5429. * @returns {Number[]} The array that was packed into
  5430. */
  5431. BoundingSphere.pack = function(value, array, startingIndex) {
  5432. //>>includeStart('debug', pragmas.debug);
  5433. Check.Check.typeOf.object('value', value);
  5434. Check.Check.defined('array', array);
  5435. //>>includeEnd('debug');
  5436. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  5437. var center = value.center;
  5438. array[startingIndex++] = center.x;
  5439. array[startingIndex++] = center.y;
  5440. array[startingIndex++] = center.z;
  5441. array[startingIndex] = value.radius;
  5442. return array;
  5443. };
  5444. /**
  5445. * Retrieves an instance from a packed array.
  5446. *
  5447. * @param {Number[]} array The packed array.
  5448. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5449. * @param {BoundingSphere} [result] The object into which to store the result.
  5450. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  5451. */
  5452. BoundingSphere.unpack = function(array, startingIndex, result) {
  5453. //>>includeStart('debug', pragmas.debug);
  5454. Check.Check.defined('array', array);
  5455. //>>includeEnd('debug');
  5456. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  5457. if (!defined.defined(result)) {
  5458. result = new BoundingSphere();
  5459. }
  5460. var center = result.center;
  5461. center.x = array[startingIndex++];
  5462. center.y = array[startingIndex++];
  5463. center.z = array[startingIndex++];
  5464. result.radius = array[startingIndex];
  5465. return result;
  5466. };
  5467. var unionScratch = new Cartesian2.Cartesian3();
  5468. var unionScratchCenter = new Cartesian2.Cartesian3();
  5469. /**
  5470. * Computes a bounding sphere that contains both the left and right bounding spheres.
  5471. *
  5472. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  5473. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  5474. * @param {BoundingSphere} [result] The object onto which to store the result.
  5475. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5476. */
  5477. BoundingSphere.union = function(left, right, result) {
  5478. //>>includeStart('debug', pragmas.debug);
  5479. Check.Check.typeOf.object('left', left);
  5480. Check.Check.typeOf.object('right', right);
  5481. //>>includeEnd('debug');
  5482. if (!defined.defined(result)) {
  5483. result = new BoundingSphere();
  5484. }
  5485. var leftCenter = left.center;
  5486. var leftRadius = left.radius;
  5487. var rightCenter = right.center;
  5488. var rightRadius = right.radius;
  5489. var toRightCenter = Cartesian2.Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  5490. var centerSeparation = Cartesian2.Cartesian3.magnitude(toRightCenter);
  5491. if (leftRadius >= (centerSeparation + rightRadius)) {
  5492. // Left sphere wins.
  5493. left.clone(result);
  5494. return result;
  5495. }
  5496. if (rightRadius >= (centerSeparation + leftRadius)) {
  5497. // Right sphere wins.
  5498. right.clone(result);
  5499. return result;
  5500. }
  5501. // There are two tangent points, one on far side of each sphere.
  5502. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  5503. // Compute the center point halfway between the two tangent points.
  5504. var center = Cartesian2.Cartesian3.multiplyByScalar(toRightCenter,
  5505. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  5506. Cartesian2.Cartesian3.add(center, leftCenter, center);
  5507. Cartesian2.Cartesian3.clone(center, result.center);
  5508. result.radius = halfDistanceBetweenTangentPoints;
  5509. return result;
  5510. };
  5511. var expandScratch = new Cartesian2.Cartesian3();
  5512. /**
  5513. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  5514. *
  5515. * @param {BoundingSphere} sphere A sphere to expand.
  5516. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  5517. * @param {BoundingSphere} [result] The object onto which to store the result.
  5518. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5519. */
  5520. BoundingSphere.expand = function(sphere, point, result) {
  5521. //>>includeStart('debug', pragmas.debug);
  5522. Check.Check.typeOf.object('sphere', sphere);
  5523. Check.Check.typeOf.object('point', point);
  5524. //>>includeEnd('debug');
  5525. result = BoundingSphere.clone(sphere, result);
  5526. var radius = Cartesian2.Cartesian3.magnitude(Cartesian2.Cartesian3.subtract(point, result.center, expandScratch));
  5527. if (radius > result.radius) {
  5528. result.radius = radius;
  5529. }
  5530. return result;
  5531. };
  5532. /**
  5533. * Determines which side of a plane a sphere is located.
  5534. *
  5535. * @param {BoundingSphere} sphere The bounding sphere to test.
  5536. * @param {Plane} plane The plane to test against.
  5537. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  5538. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  5539. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  5540. * intersects the plane.
  5541. */
  5542. BoundingSphere.intersectPlane = function(sphere, plane) {
  5543. //>>includeStart('debug', pragmas.debug);
  5544. Check.Check.typeOf.object('sphere', sphere);
  5545. Check.Check.typeOf.object('plane', plane);
  5546. //>>includeEnd('debug');
  5547. var center = sphere.center;
  5548. var radius = sphere.radius;
  5549. var normal = plane.normal;
  5550. var distanceToPlane = Cartesian2.Cartesian3.dot(normal, center) + plane.distance;
  5551. if (distanceToPlane < -radius) {
  5552. // The center point is negative side of the plane normal
  5553. return Intersect$1.OUTSIDE;
  5554. } else if (distanceToPlane < radius) {
  5555. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  5556. return Intersect$1.INTERSECTING;
  5557. }
  5558. return Intersect$1.INSIDE;
  5559. };
  5560. /**
  5561. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  5562. *
  5563. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  5564. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  5565. * @param {BoundingSphere} [result] The object onto which to store the result.
  5566. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5567. */
  5568. BoundingSphere.transform = function(sphere, transform, result) {
  5569. //>>includeStart('debug', pragmas.debug);
  5570. Check.Check.typeOf.object('sphere', sphere);
  5571. Check.Check.typeOf.object('transform', transform);
  5572. //>>includeEnd('debug');
  5573. if (!defined.defined(result)) {
  5574. result = new BoundingSphere();
  5575. }
  5576. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  5577. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  5578. return result;
  5579. };
  5580. var distanceSquaredToScratch = new Cartesian2.Cartesian3();
  5581. /**
  5582. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  5583. *
  5584. * @param {BoundingSphere} sphere The sphere.
  5585. * @param {Cartesian3} cartesian The point
  5586. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  5587. *
  5588. * @example
  5589. * // Sort bounding spheres from back to front
  5590. * spheres.sort(function(a, b) {
  5591. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  5592. * });
  5593. */
  5594. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  5595. //>>includeStart('debug', pragmas.debug);
  5596. Check.Check.typeOf.object('sphere', sphere);
  5597. Check.Check.typeOf.object('cartesian', cartesian);
  5598. //>>includeEnd('debug');
  5599. var diff = Cartesian2.Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  5600. return Cartesian2.Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  5601. };
  5602. /**
  5603. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  5604. * The transformation matrix is not verified to have a uniform scale of 1.
  5605. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  5606. *
  5607. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  5608. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  5609. * @param {BoundingSphere} [result] The object onto which to store the result.
  5610. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5611. *
  5612. * @example
  5613. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  5614. * var boundingSphere = new Cesium.BoundingSphere();
  5615. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  5616. */
  5617. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  5618. //>>includeStart('debug', pragmas.debug);
  5619. Check.Check.typeOf.object('sphere', sphere);
  5620. Check.Check.typeOf.object('transform', transform);
  5621. //>>includeEnd('debug');
  5622. if (!defined.defined(result)) {
  5623. result = new BoundingSphere();
  5624. }
  5625. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  5626. result.radius = sphere.radius;
  5627. return result;
  5628. };
  5629. var scratchCartesian3 = new Cartesian2.Cartesian3();
  5630. /**
  5631. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  5632. * plus/minus the radius of the bounding sphere.
  5633. * <br>
  5634. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  5635. * closest and farthest planes from position that intersect the bounding sphere.
  5636. *
  5637. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  5638. * @param {Cartesian3} position The position to calculate the distance from.
  5639. * @param {Cartesian3} direction The direction from position.
  5640. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  5641. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  5642. */
  5643. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  5644. //>>includeStart('debug', pragmas.debug);
  5645. Check.Check.typeOf.object('sphere', sphere);
  5646. Check.Check.typeOf.object('position', position);
  5647. Check.Check.typeOf.object('direction', direction);
  5648. //>>includeEnd('debug');
  5649. if (!defined.defined(result)) {
  5650. result = new Interval();
  5651. }
  5652. var toCenter = Cartesian2.Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  5653. var mag = Cartesian2.Cartesian3.dot(direction, toCenter);
  5654. result.start = mag - sphere.radius;
  5655. result.stop = mag + sphere.radius;
  5656. return result;
  5657. };
  5658. var projectTo2DNormalScratch = new Cartesian2.Cartesian3();
  5659. var projectTo2DEastScratch = new Cartesian2.Cartesian3();
  5660. var projectTo2DNorthScratch = new Cartesian2.Cartesian3();
  5661. var projectTo2DWestScratch = new Cartesian2.Cartesian3();
  5662. var projectTo2DSouthScratch = new Cartesian2.Cartesian3();
  5663. var projectTo2DCartographicScratch = new Cartesian2.Cartographic();
  5664. var projectTo2DPositionsScratch = new Array(8);
  5665. for (var n = 0; n < 8; ++n) {
  5666. projectTo2DPositionsScratch[n] = new Cartesian2.Cartesian3();
  5667. }
  5668. var projectTo2DProjection = new GeographicProjection();
  5669. /**
  5670. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  5671. *
  5672. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  5673. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  5674. * @param {BoundingSphere} [result] The object onto which to store the result.
  5675. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5676. */
  5677. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  5678. //>>includeStart('debug', pragmas.debug);
  5679. Check.Check.typeOf.object('sphere', sphere);
  5680. //>>includeEnd('debug');
  5681. projection = defaultValue.defaultValue(projection, projectTo2DProjection);
  5682. var ellipsoid = projection.ellipsoid;
  5683. var center = sphere.center;
  5684. var radius = sphere.radius;
  5685. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  5686. var east = Cartesian2.Cartesian3.cross(Cartesian2.Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  5687. Cartesian2.Cartesian3.normalize(east, east);
  5688. var north = Cartesian2.Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  5689. Cartesian2.Cartesian3.normalize(north, north);
  5690. Cartesian2.Cartesian3.multiplyByScalar(normal, radius, normal);
  5691. Cartesian2.Cartesian3.multiplyByScalar(north, radius, north);
  5692. Cartesian2.Cartesian3.multiplyByScalar(east, radius, east);
  5693. var south = Cartesian2.Cartesian3.negate(north, projectTo2DSouthScratch);
  5694. var west = Cartesian2.Cartesian3.negate(east, projectTo2DWestScratch);
  5695. var positions = projectTo2DPositionsScratch;
  5696. // top NE corner
  5697. var corner = positions[0];
  5698. Cartesian2.Cartesian3.add(normal, north, corner);
  5699. Cartesian2.Cartesian3.add(corner, east, corner);
  5700. // top NW corner
  5701. corner = positions[1];
  5702. Cartesian2.Cartesian3.add(normal, north, corner);
  5703. Cartesian2.Cartesian3.add(corner, west, corner);
  5704. // top SW corner
  5705. corner = positions[2];
  5706. Cartesian2.Cartesian3.add(normal, south, corner);
  5707. Cartesian2.Cartesian3.add(corner, west, corner);
  5708. // top SE corner
  5709. corner = positions[3];
  5710. Cartesian2.Cartesian3.add(normal, south, corner);
  5711. Cartesian2.Cartesian3.add(corner, east, corner);
  5712. Cartesian2.Cartesian3.negate(normal, normal);
  5713. // bottom NE corner
  5714. corner = positions[4];
  5715. Cartesian2.Cartesian3.add(normal, north, corner);
  5716. Cartesian2.Cartesian3.add(corner, east, corner);
  5717. // bottom NW corner
  5718. corner = positions[5];
  5719. Cartesian2.Cartesian3.add(normal, north, corner);
  5720. Cartesian2.Cartesian3.add(corner, west, corner);
  5721. // bottom SW corner
  5722. corner = positions[6];
  5723. Cartesian2.Cartesian3.add(normal, south, corner);
  5724. Cartesian2.Cartesian3.add(corner, west, corner);
  5725. // bottom SE corner
  5726. corner = positions[7];
  5727. Cartesian2.Cartesian3.add(normal, south, corner);
  5728. Cartesian2.Cartesian3.add(corner, east, corner);
  5729. var length = positions.length;
  5730. for (var i = 0; i < length; ++i) {
  5731. var position = positions[i];
  5732. Cartesian2.Cartesian3.add(center, position, position);
  5733. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  5734. projection.project(cartographic, position);
  5735. }
  5736. result = BoundingSphere.fromPoints(positions, result);
  5737. // swizzle center components
  5738. center = result.center;
  5739. var x = center.x;
  5740. var y = center.y;
  5741. var z = center.z;
  5742. center.x = z;
  5743. center.y = x;
  5744. center.z = y;
  5745. return result;
  5746. };
  5747. /**
  5748. * Determines whether or not a sphere is hidden from view by the occluder.
  5749. *
  5750. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  5751. * @param {Occluder} occluder The occluder.
  5752. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  5753. */
  5754. BoundingSphere.isOccluded = function(sphere, occluder) {
  5755. //>>includeStart('debug', pragmas.debug);
  5756. Check.Check.typeOf.object('sphere', sphere);
  5757. Check.Check.typeOf.object('occluder', occluder);
  5758. //>>includeEnd('debug');
  5759. return !occluder.isBoundingSphereVisible(sphere);
  5760. };
  5761. /**
  5762. * Compares the provided BoundingSphere componentwise and returns
  5763. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5764. *
  5765. * @param {BoundingSphere} [left] The first BoundingSphere.
  5766. * @param {BoundingSphere} [right] The second BoundingSphere.
  5767. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5768. */
  5769. BoundingSphere.equals = function(left, right) {
  5770. return (left === right) ||
  5771. ((defined.defined(left)) &&
  5772. (defined.defined(right)) &&
  5773. Cartesian2.Cartesian3.equals(left.center, right.center) &&
  5774. left.radius === right.radius);
  5775. };
  5776. /**
  5777. * Determines which side of a plane the sphere is located.
  5778. *
  5779. * @param {Plane} plane The plane to test against.
  5780. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  5781. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  5782. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  5783. * intersects the plane.
  5784. */
  5785. BoundingSphere.prototype.intersectPlane = function(plane) {
  5786. return BoundingSphere.intersectPlane(this, plane);
  5787. };
  5788. /**
  5789. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  5790. *
  5791. * @param {Cartesian3} cartesian The point
  5792. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  5793. *
  5794. * @example
  5795. * // Sort bounding spheres from back to front
  5796. * spheres.sort(function(a, b) {
  5797. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  5798. * });
  5799. */
  5800. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  5801. return BoundingSphere.distanceSquaredTo(this, cartesian);
  5802. };
  5803. /**
  5804. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  5805. * plus/minus the radius of the bounding sphere.
  5806. * <br>
  5807. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  5808. * closest and farthest planes from position that intersect the bounding sphere.
  5809. *
  5810. * @param {Cartesian3} position The position to calculate the distance from.
  5811. * @param {Cartesian3} direction The direction from position.
  5812. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  5813. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  5814. */
  5815. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  5816. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  5817. };
  5818. /**
  5819. * Determines whether or not a sphere is hidden from view by the occluder.
  5820. *
  5821. * @param {Occluder} occluder The occluder.
  5822. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  5823. */
  5824. BoundingSphere.prototype.isOccluded = function(occluder) {
  5825. return BoundingSphere.isOccluded(this, occluder);
  5826. };
  5827. /**
  5828. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  5829. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5830. *
  5831. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  5832. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5833. */
  5834. BoundingSphere.prototype.equals = function(right) {
  5835. return BoundingSphere.equals(this, right);
  5836. };
  5837. /**
  5838. * Duplicates this BoundingSphere instance.
  5839. *
  5840. * @param {BoundingSphere} [result] The object onto which to store the result.
  5841. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  5842. */
  5843. BoundingSphere.prototype.clone = function(result) {
  5844. return BoundingSphere.clone(this, result);
  5845. };
  5846. /**
  5847. * Computes the radius of the BoundingSphere.
  5848. * @returns {Number} The radius of the BoundingSphere.
  5849. */
  5850. BoundingSphere.prototype.volume = function() {
  5851. var radius = this.radius;
  5852. return volumeConstant * radius * radius * radius;
  5853. };
  5854. var _supportsFullscreen;
  5855. var _names = {
  5856. requestFullscreen : undefined,
  5857. exitFullscreen : undefined,
  5858. fullscreenEnabled : undefined,
  5859. fullscreenElement : undefined,
  5860. fullscreenchange : undefined,
  5861. fullscreenerror : undefined
  5862. };
  5863. /**
  5864. * Browser-independent functions for working with the standard fullscreen API.
  5865. *
  5866. * @exports Fullscreen
  5867. * @namespace
  5868. *
  5869. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  5870. */
  5871. var Fullscreen = {};
  5872. defineProperties.defineProperties(Fullscreen, {
  5873. /**
  5874. * The element that is currently fullscreen, if any. To simply check if the
  5875. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  5876. * @memberof Fullscreen
  5877. * @type {Object}
  5878. * @readonly
  5879. */
  5880. element : {
  5881. get : function() {
  5882. if (!Fullscreen.supportsFullscreen()) {
  5883. return undefined;
  5884. }
  5885. return document[_names.fullscreenElement];
  5886. }
  5887. },
  5888. /**
  5889. * The name of the event on the document that is fired when fullscreen is
  5890. * entered or exited. This event name is intended for use with addEventListener.
  5891. * In your event handler, to determine if the browser is in fullscreen mode or not,
  5892. * use {@link Fullscreen#fullscreen}.
  5893. * @memberof Fullscreen
  5894. * @type {String}
  5895. * @readonly
  5896. */
  5897. changeEventName : {
  5898. get : function() {
  5899. if (!Fullscreen.supportsFullscreen()) {
  5900. return undefined;
  5901. }
  5902. return _names.fullscreenchange;
  5903. }
  5904. },
  5905. /**
  5906. * The name of the event that is fired when a fullscreen error
  5907. * occurs. This event name is intended for use with addEventListener.
  5908. * @memberof Fullscreen
  5909. * @type {String}
  5910. * @readonly
  5911. */
  5912. errorEventName : {
  5913. get : function() {
  5914. if (!Fullscreen.supportsFullscreen()) {
  5915. return undefined;
  5916. }
  5917. return _names.fullscreenerror;
  5918. }
  5919. },
  5920. /**
  5921. * Determine whether the browser will allow an element to be made fullscreen, or not.
  5922. * For example, by default, iframes cannot go fullscreen unless the containing page
  5923. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  5924. * @memberof Fullscreen
  5925. * @type {Boolean}
  5926. * @readonly
  5927. */
  5928. enabled : {
  5929. get : function() {
  5930. if (!Fullscreen.supportsFullscreen()) {
  5931. return undefined;
  5932. }
  5933. return document[_names.fullscreenEnabled];
  5934. }
  5935. },
  5936. /**
  5937. * Determines if the browser is currently in fullscreen mode.
  5938. * @memberof Fullscreen
  5939. * @type {Boolean}
  5940. * @readonly
  5941. */
  5942. fullscreen : {
  5943. get : function() {
  5944. if (!Fullscreen.supportsFullscreen()) {
  5945. return undefined;
  5946. }
  5947. return Fullscreen.element !== null;
  5948. }
  5949. }
  5950. });
  5951. /**
  5952. * Detects whether the browser supports the standard fullscreen API.
  5953. *
  5954. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  5955. * <code>false</code> otherwise.
  5956. */
  5957. Fullscreen.supportsFullscreen = function() {
  5958. if (defined.defined(_supportsFullscreen)) {
  5959. return _supportsFullscreen;
  5960. }
  5961. _supportsFullscreen = false;
  5962. var body = document.body;
  5963. if (typeof body.requestFullscreen === 'function') {
  5964. // go with the unprefixed, standard set of names
  5965. _names.requestFullscreen = 'requestFullscreen';
  5966. _names.exitFullscreen = 'exitFullscreen';
  5967. _names.fullscreenEnabled = 'fullscreenEnabled';
  5968. _names.fullscreenElement = 'fullscreenElement';
  5969. _names.fullscreenchange = 'fullscreenchange';
  5970. _names.fullscreenerror = 'fullscreenerror';
  5971. _supportsFullscreen = true;
  5972. return _supportsFullscreen;
  5973. }
  5974. //check for the correct combination of prefix plus the various names that browsers use
  5975. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  5976. var name;
  5977. for (var i = 0, len = prefixes.length; i < len; ++i) {
  5978. var prefix = prefixes[i];
  5979. // casing of Fullscreen differs across browsers
  5980. name = prefix + 'RequestFullscreen';
  5981. if (typeof body[name] === 'function') {
  5982. _names.requestFullscreen = name;
  5983. _supportsFullscreen = true;
  5984. } else {
  5985. name = prefix + 'RequestFullScreen';
  5986. if (typeof body[name] === 'function') {
  5987. _names.requestFullscreen = name;
  5988. _supportsFullscreen = true;
  5989. }
  5990. }
  5991. // disagreement about whether it's "exit" as per spec, or "cancel"
  5992. name = prefix + 'ExitFullscreen';
  5993. if (typeof document[name] === 'function') {
  5994. _names.exitFullscreen = name;
  5995. } else {
  5996. name = prefix + 'CancelFullScreen';
  5997. if (typeof document[name] === 'function') {
  5998. _names.exitFullscreen = name;
  5999. }
  6000. }
  6001. // casing of Fullscreen differs across browsers
  6002. name = prefix + 'FullscreenEnabled';
  6003. if (document[name] !== undefined) {
  6004. _names.fullscreenEnabled = name;
  6005. } else {
  6006. name = prefix + 'FullScreenEnabled';
  6007. if (document[name] !== undefined) {
  6008. _names.fullscreenEnabled = name;
  6009. }
  6010. }
  6011. // casing of Fullscreen differs across browsers
  6012. name = prefix + 'FullscreenElement';
  6013. if (document[name] !== undefined) {
  6014. _names.fullscreenElement = name;
  6015. } else {
  6016. name = prefix + 'FullScreenElement';
  6017. if (document[name] !== undefined) {
  6018. _names.fullscreenElement = name;
  6019. }
  6020. }
  6021. // thankfully, event names are all lowercase per spec
  6022. name = prefix + 'fullscreenchange';
  6023. // event names do not have 'on' in the front, but the property on the document does
  6024. if (document['on' + name] !== undefined) {
  6025. //except on IE
  6026. if (prefix === 'ms') {
  6027. name = 'MSFullscreenChange';
  6028. }
  6029. _names.fullscreenchange = name;
  6030. }
  6031. name = prefix + 'fullscreenerror';
  6032. if (document['on' + name] !== undefined) {
  6033. //except on IE
  6034. if (prefix === 'ms') {
  6035. name = 'MSFullscreenError';
  6036. }
  6037. _names.fullscreenerror = name;
  6038. }
  6039. }
  6040. return _supportsFullscreen;
  6041. };
  6042. /**
  6043. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  6044. * If fullscreen mode is not supported by the browser, does nothing.
  6045. *
  6046. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  6047. * @param {HMDVRDevice} [vrDevice] The VR device.
  6048. *
  6049. * @example
  6050. * // Put the entire page into fullscreen.
  6051. * Cesium.Fullscreen.requestFullscreen(document.body)
  6052. *
  6053. * // Place only the Cesium canvas into fullscreen.
  6054. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  6055. */
  6056. Fullscreen.requestFullscreen = function(element, vrDevice) {
  6057. if (!Fullscreen.supportsFullscreen()) {
  6058. return;
  6059. }
  6060. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  6061. };
  6062. /**
  6063. * Asynchronously exits fullscreen mode. If the browser is not currently
  6064. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  6065. */
  6066. Fullscreen.exitFullscreen = function() {
  6067. if (!Fullscreen.supportsFullscreen()) {
  6068. return;
  6069. }
  6070. document[_names.exitFullscreen]();
  6071. };
  6072. //For unit tests
  6073. Fullscreen._names = _names;
  6074. /*global CanvasPixelArray*/
  6075. var theNavigator;
  6076. if (typeof navigator !== 'undefined') {
  6077. theNavigator = navigator;
  6078. } else {
  6079. theNavigator = {};
  6080. }
  6081. function extractVersion(versionString) {
  6082. var parts = versionString.split('.');
  6083. for (var i = 0, len = parts.length; i < len; ++i) {
  6084. parts[i] = parseInt(parts[i], 10);
  6085. }
  6086. return parts;
  6087. }
  6088. var isChromeResult;
  6089. var chromeVersionResult;
  6090. function isChrome() {
  6091. if (!defined.defined(isChromeResult)) {
  6092. isChromeResult = false;
  6093. // Edge contains Chrome in the user agent too
  6094. if (!isEdge()) {
  6095. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  6096. if (fields !== null) {
  6097. isChromeResult = true;
  6098. chromeVersionResult = extractVersion(fields[1]);
  6099. }
  6100. }
  6101. }
  6102. return isChromeResult;
  6103. }
  6104. function chromeVersion() {
  6105. return isChrome() && chromeVersionResult;
  6106. }
  6107. var isSafariResult;
  6108. var safariVersionResult;
  6109. function isSafari() {
  6110. if (!defined.defined(isSafariResult)) {
  6111. isSafariResult = false;
  6112. // Chrome and Edge contain Safari in the user agent too
  6113. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  6114. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  6115. if (fields !== null) {
  6116. isSafariResult = true;
  6117. safariVersionResult = extractVersion(fields[1]);
  6118. }
  6119. }
  6120. }
  6121. return isSafariResult;
  6122. }
  6123. function safariVersion() {
  6124. return isSafari() && safariVersionResult;
  6125. }
  6126. var isWebkitResult;
  6127. var webkitVersionResult;
  6128. function isWebkit() {
  6129. if (!defined.defined(isWebkitResult)) {
  6130. isWebkitResult = false;
  6131. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  6132. if (fields !== null) {
  6133. isWebkitResult = true;
  6134. webkitVersionResult = extractVersion(fields[1]);
  6135. webkitVersionResult.isNightly = !!fields[2];
  6136. }
  6137. }
  6138. return isWebkitResult;
  6139. }
  6140. function webkitVersion() {
  6141. return isWebkit() && webkitVersionResult;
  6142. }
  6143. var isInternetExplorerResult;
  6144. var internetExplorerVersionResult;
  6145. function isInternetExplorer() {
  6146. if (!defined.defined(isInternetExplorerResult)) {
  6147. isInternetExplorerResult = false;
  6148. var fields;
  6149. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  6150. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  6151. if (fields !== null) {
  6152. isInternetExplorerResult = true;
  6153. internetExplorerVersionResult = extractVersion(fields[1]);
  6154. }
  6155. } else if (theNavigator.appName === 'Netscape') {
  6156. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  6157. if (fields !== null) {
  6158. isInternetExplorerResult = true;
  6159. internetExplorerVersionResult = extractVersion(fields[1]);
  6160. }
  6161. }
  6162. }
  6163. return isInternetExplorerResult;
  6164. }
  6165. function internetExplorerVersion() {
  6166. return isInternetExplorer() && internetExplorerVersionResult;
  6167. }
  6168. var isEdgeResult;
  6169. var edgeVersionResult;
  6170. function isEdge() {
  6171. if (!defined.defined(isEdgeResult)) {
  6172. isEdgeResult = false;
  6173. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  6174. if (fields !== null) {
  6175. isEdgeResult = true;
  6176. edgeVersionResult = extractVersion(fields[1]);
  6177. }
  6178. }
  6179. return isEdgeResult;
  6180. }
  6181. function edgeVersion() {
  6182. return isEdge() && edgeVersionResult;
  6183. }
  6184. var isFirefoxResult;
  6185. var firefoxVersionResult;
  6186. function isFirefox() {
  6187. if (!defined.defined(isFirefoxResult)) {
  6188. isFirefoxResult = false;
  6189. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  6190. if (fields !== null) {
  6191. isFirefoxResult = true;
  6192. firefoxVersionResult = extractVersion(fields[1]);
  6193. }
  6194. }
  6195. return isFirefoxResult;
  6196. }
  6197. var isWindowsResult;
  6198. function isWindows() {
  6199. if (!defined.defined(isWindowsResult)) {
  6200. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  6201. }
  6202. return isWindowsResult;
  6203. }
  6204. function firefoxVersion() {
  6205. return isFirefox() && firefoxVersionResult;
  6206. }
  6207. var hasPointerEvents;
  6208. function supportsPointerEvents() {
  6209. if (!defined.defined(hasPointerEvents)) {
  6210. //While navigator.pointerEnabled is deprecated in the W3C specification
  6211. //we still need to use it if it exists in order to support browsers
  6212. //that rely on it, such as the Windows WebBrowser control which defines
  6213. //PointerEvent but sets navigator.pointerEnabled to false.
  6214. //Firefox disabled because of https://github.com/AnalyticalGraphicsInc/cesium/issues/6372
  6215. hasPointerEvents = !isFirefox() && typeof PointerEvent !== 'undefined' && (!defined.defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  6216. }
  6217. return hasPointerEvents;
  6218. }
  6219. var imageRenderingValueResult;
  6220. var supportsImageRenderingPixelatedResult;
  6221. function supportsImageRenderingPixelated() {
  6222. if (!defined.defined(supportsImageRenderingPixelatedResult)) {
  6223. var canvas = document.createElement('canvas');
  6224. canvas.setAttribute('style',
  6225. 'image-rendering: -moz-crisp-edges;' +
  6226. 'image-rendering: pixelated;');
  6227. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  6228. var tmp = canvas.style.imageRendering;
  6229. supportsImageRenderingPixelatedResult = defined.defined(tmp) && tmp !== '';
  6230. if (supportsImageRenderingPixelatedResult) {
  6231. imageRenderingValueResult = tmp;
  6232. }
  6233. }
  6234. return supportsImageRenderingPixelatedResult;
  6235. }
  6236. function imageRenderingValue() {
  6237. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  6238. }
  6239. function supportsWebP() {
  6240. //>>includeStart('debug', pragmas.debug);
  6241. if (!supportsWebP.initialized) {
  6242. throw new Check.DeveloperError('You must call FeatureDetection.supportsWebP.initialize and wait for the promise to resolve before calling FeatureDetection.supportsWebP');
  6243. }
  6244. //>>includeEnd('debug');
  6245. return supportsWebP._result;
  6246. }
  6247. supportsWebP._promise = undefined;
  6248. supportsWebP._result = undefined;
  6249. supportsWebP.initialize = function() {
  6250. // From https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp
  6251. if (defined.defined(supportsWebP._promise)) {
  6252. return supportsWebP._promise;
  6253. }
  6254. var supportsWebPDeferred = when.when.defer();
  6255. supportsWebP._promise = supportsWebPDeferred.promise;
  6256. if (isEdge()) {
  6257. // Edge's WebP support with WebGL is incomplete.
  6258. // See bug report: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/19221241/
  6259. supportsWebP._result = false;
  6260. supportsWebPDeferred.resolve(supportsWebP._result);
  6261. return supportsWebPDeferred.promise;
  6262. }
  6263. var image = new Image();
  6264. image.onload = function () {
  6265. supportsWebP._result = (image.width > 0) && (image.height > 0);
  6266. supportsWebPDeferred.resolve(supportsWebP._result);
  6267. };
  6268. image.onerror = function () {
  6269. supportsWebP._result = false;
  6270. supportsWebPDeferred.resolve(supportsWebP._result);
  6271. };
  6272. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  6273. return supportsWebPDeferred.promise;
  6274. };
  6275. defineProperties.defineProperties(supportsWebP, {
  6276. initialized: {
  6277. get: function() {
  6278. return defined.defined(supportsWebP._result);
  6279. }
  6280. }
  6281. });
  6282. var typedArrayTypes = [];
  6283. if (typeof ArrayBuffer !== 'undefined') {
  6284. typedArrayTypes.push(Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array);
  6285. if (typeof Uint8ClampedArray !== 'undefined') {
  6286. typedArrayTypes.push(Uint8ClampedArray);
  6287. }
  6288. if (typeof CanvasPixelArray !== 'undefined') {
  6289. typedArrayTypes.push(CanvasPixelArray);
  6290. }
  6291. }
  6292. /**
  6293. * A set of functions to detect whether the current browser supports
  6294. * various features.
  6295. *
  6296. * @exports FeatureDetection
  6297. */
  6298. var FeatureDetection = {
  6299. isChrome : isChrome,
  6300. chromeVersion : chromeVersion,
  6301. isSafari : isSafari,
  6302. safariVersion : safariVersion,
  6303. isWebkit : isWebkit,
  6304. webkitVersion : webkitVersion,
  6305. isInternetExplorer : isInternetExplorer,
  6306. internetExplorerVersion : internetExplorerVersion,
  6307. isEdge : isEdge,
  6308. edgeVersion : edgeVersion,
  6309. isFirefox : isFirefox,
  6310. firefoxVersion : firefoxVersion,
  6311. isWindows : isWindows,
  6312. hardwareConcurrency : defaultValue.defaultValue(theNavigator.hardwareConcurrency, 3),
  6313. supportsPointerEvents : supportsPointerEvents,
  6314. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  6315. supportsWebP: supportsWebP,
  6316. imageRenderingValue: imageRenderingValue,
  6317. typedArrayTypes: typedArrayTypes
  6318. };
  6319. /**
  6320. * Detects whether the current browser supports the full screen standard.
  6321. *
  6322. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  6323. *
  6324. * @see Fullscreen
  6325. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  6326. */
  6327. FeatureDetection.supportsFullscreen = function() {
  6328. return Fullscreen.supportsFullscreen();
  6329. };
  6330. /**
  6331. * Detects whether the current browser supports typed arrays.
  6332. *
  6333. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  6334. *
  6335. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  6336. */
  6337. FeatureDetection.supportsTypedArrays = function() {
  6338. return typeof ArrayBuffer !== 'undefined';
  6339. };
  6340. /**
  6341. * Detects whether the current browser supports Web Workers.
  6342. *
  6343. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  6344. *
  6345. * @see {@link http://www.w3.org/TR/workers/}
  6346. */
  6347. FeatureDetection.supportsWebWorkers = function() {
  6348. return typeof Worker !== 'undefined';
  6349. };
  6350. /**
  6351. * Detects whether the current browser supports Web Assembly.
  6352. *
  6353. * @returns {Boolean} true if the browsers supports Web Assembly, false if not.
  6354. *
  6355. * @see {@link https://developer.mozilla.org/en-US/docs/WebAssembly}
  6356. */
  6357. FeatureDetection.supportsWebAssembly = function() {
  6358. return typeof WebAssembly !== 'undefined' && !FeatureDetection.isEdge();
  6359. };
  6360. /**
  6361. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  6362. * @alias Quaternion
  6363. * @constructor
  6364. *
  6365. * @param {Number} [x=0.0] The X component.
  6366. * @param {Number} [y=0.0] The Y component.
  6367. * @param {Number} [z=0.0] The Z component.
  6368. * @param {Number} [w=0.0] The W component.
  6369. *
  6370. * @see PackableForInterpolation
  6371. */
  6372. function Quaternion(x, y, z, w) {
  6373. /**
  6374. * The X component.
  6375. * @type {Number}
  6376. * @default 0.0
  6377. */
  6378. this.x = defaultValue.defaultValue(x, 0.0);
  6379. /**
  6380. * The Y component.
  6381. * @type {Number}
  6382. * @default 0.0
  6383. */
  6384. this.y = defaultValue.defaultValue(y, 0.0);
  6385. /**
  6386. * The Z component.
  6387. * @type {Number}
  6388. * @default 0.0
  6389. */
  6390. this.z = defaultValue.defaultValue(z, 0.0);
  6391. /**
  6392. * The W component.
  6393. * @type {Number}
  6394. * @default 0.0
  6395. */
  6396. this.w = defaultValue.defaultValue(w, 0.0);
  6397. }
  6398. var fromAxisAngleScratch = new Cartesian2.Cartesian3();
  6399. /**
  6400. * Computes a quaternion representing a rotation around an axis.
  6401. *
  6402. * @param {Cartesian3} axis The axis of rotation.
  6403. * @param {Number} angle The angle in radians to rotate around the axis.
  6404. * @param {Quaternion} [result] The object onto which to store the result.
  6405. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  6406. */
  6407. Quaternion.fromAxisAngle = function(axis, angle, result) {
  6408. //>>includeStart('debug', pragmas.debug);
  6409. Check.Check.typeOf.object('axis', axis);
  6410. Check.Check.typeOf.number('angle', angle);
  6411. //>>includeEnd('debug');
  6412. var halfAngle = angle / 2.0;
  6413. var s = Math.sin(halfAngle);
  6414. fromAxisAngleScratch = Cartesian2.Cartesian3.normalize(axis, fromAxisAngleScratch);
  6415. var x = fromAxisAngleScratch.x * s;
  6416. var y = fromAxisAngleScratch.y * s;
  6417. var z = fromAxisAngleScratch.z * s;
  6418. var w = Math.cos(halfAngle);
  6419. if (!defined.defined(result)) {
  6420. return new Quaternion(x, y, z, w);
  6421. }
  6422. result.x = x;
  6423. result.y = y;
  6424. result.z = z;
  6425. result.w = w;
  6426. return result;
  6427. };
  6428. var fromRotationMatrixNext = [1, 2, 0];
  6429. var fromRotationMatrixQuat = new Array(3);
  6430. /**
  6431. * Computes a Quaternion from the provided Matrix3 instance.
  6432. *
  6433. * @param {Matrix3} matrix The rotation matrix.
  6434. * @param {Quaternion} [result] The object onto which to store the result.
  6435. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  6436. *
  6437. * @see Matrix3.fromQuaternion
  6438. */
  6439. Quaternion.fromRotationMatrix = function(matrix, result) {
  6440. //>>includeStart('debug', pragmas.debug);
  6441. Check.Check.typeOf.object('matrix', matrix);
  6442. //>>includeEnd('debug');
  6443. var root;
  6444. var x;
  6445. var y;
  6446. var z;
  6447. var w;
  6448. var m00 = matrix[Matrix3.COLUMN0ROW0];
  6449. var m11 = matrix[Matrix3.COLUMN1ROW1];
  6450. var m22 = matrix[Matrix3.COLUMN2ROW2];
  6451. var trace = m00 + m11 + m22;
  6452. if (trace > 0.0) {
  6453. // |w| > 1/2, may as well choose w > 1/2
  6454. root = Math.sqrt(trace + 1.0); // 2w
  6455. w = 0.5 * root;
  6456. root = 0.5 / root; // 1/(4w)
  6457. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  6458. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  6459. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  6460. } else {
  6461. // |w| <= 1/2
  6462. var next = fromRotationMatrixNext;
  6463. var i = 0;
  6464. if (m11 > m00) {
  6465. i = 1;
  6466. }
  6467. if (m22 > m00 && m22 > m11) {
  6468. i = 2;
  6469. }
  6470. var j = next[i];
  6471. var k = next[j];
  6472. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  6473. var quat = fromRotationMatrixQuat;
  6474. quat[i] = 0.5 * root;
  6475. root = 0.5 / root;
  6476. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  6477. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  6478. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  6479. x = -quat[0];
  6480. y = -quat[1];
  6481. z = -quat[2];
  6482. }
  6483. if (!defined.defined(result)) {
  6484. return new Quaternion(x, y, z, w);
  6485. }
  6486. result.x = x;
  6487. result.y = y;
  6488. result.z = z;
  6489. result.w = w;
  6490. return result;
  6491. };
  6492. var scratchHPRQuaternion = new Quaternion();
  6493. var scratchHeadingQuaternion = new Quaternion();
  6494. var scratchPitchQuaternion = new Quaternion();
  6495. var scratchRollQuaternion = new Quaternion();
  6496. /**
  6497. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  6498. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  6499. * the positive x axis.
  6500. *
  6501. * @param {HeadingPitchRoll} headingPitchRoll The rotation expressed as a heading, pitch and roll.
  6502. * @param {Quaternion} [result] The object onto which to store the result.
  6503. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  6504. */
  6505. Quaternion.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  6506. //>>includeStart('debug', pragmas.debug);
  6507. Check.Check.typeOf.object('headingPitchRoll', headingPitchRoll);
  6508. //>>includeEnd('debug');
  6509. scratchRollQuaternion = Quaternion.fromAxisAngle(Cartesian2.Cartesian3.UNIT_X, headingPitchRoll.roll, scratchHPRQuaternion);
  6510. scratchPitchQuaternion = Quaternion.fromAxisAngle(Cartesian2.Cartesian3.UNIT_Y, -headingPitchRoll.pitch, result);
  6511. result = Quaternion.multiply(scratchPitchQuaternion, scratchRollQuaternion, scratchPitchQuaternion);
  6512. scratchHeadingQuaternion = Quaternion.fromAxisAngle(Cartesian2.Cartesian3.UNIT_Z, -headingPitchRoll.heading, scratchHPRQuaternion);
  6513. return Quaternion.multiply(scratchHeadingQuaternion, result, result);
  6514. };
  6515. var sampledQuaternionAxis = new Cartesian2.Cartesian3();
  6516. var sampledQuaternionRotation = new Cartesian2.Cartesian3();
  6517. var sampledQuaternionTempQuaternion = new Quaternion();
  6518. var sampledQuaternionQuaternion0 = new Quaternion();
  6519. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  6520. /**
  6521. * The number of elements used to pack the object into an array.
  6522. * @type {Number}
  6523. */
  6524. Quaternion.packedLength = 4;
  6525. /**
  6526. * Stores the provided instance into the provided array.
  6527. *
  6528. * @param {Quaternion} value The value to pack.
  6529. * @param {Number[]} array The array to pack into.
  6530. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  6531. *
  6532. * @returns {Number[]} The array that was packed into
  6533. */
  6534. Quaternion.pack = function(value, array, startingIndex) {
  6535. //>>includeStart('debug', pragmas.debug);
  6536. Check.Check.typeOf.object('value', value);
  6537. Check.Check.defined('array', array);
  6538. //>>includeEnd('debug');
  6539. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  6540. array[startingIndex++] = value.x;
  6541. array[startingIndex++] = value.y;
  6542. array[startingIndex++] = value.z;
  6543. array[startingIndex] = value.w;
  6544. return array;
  6545. };
  6546. /**
  6547. * Retrieves an instance from a packed array.
  6548. *
  6549. * @param {Number[]} array The packed array.
  6550. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  6551. * @param {Quaternion} [result] The object into which to store the result.
  6552. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  6553. */
  6554. Quaternion.unpack = function(array, startingIndex, result) {
  6555. //>>includeStart('debug', pragmas.debug);
  6556. Check.Check.defined('array', array);
  6557. //>>includeEnd('debug');
  6558. startingIndex = defaultValue.defaultValue(startingIndex, 0);
  6559. if (!defined.defined(result)) {
  6560. result = new Quaternion();
  6561. }
  6562. result.x = array[startingIndex];
  6563. result.y = array[startingIndex + 1];
  6564. result.z = array[startingIndex + 2];
  6565. result.w = array[startingIndex + 3];
  6566. return result;
  6567. };
  6568. /**
  6569. * The number of elements used to store the object into an array in its interpolatable form.
  6570. * @type {Number}
  6571. */
  6572. Quaternion.packedInterpolationLength = 3;
  6573. /**
  6574. * Converts a packed array into a form suitable for interpolation.
  6575. *
  6576. * @param {Number[]} packedArray The packed array.
  6577. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  6578. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  6579. * @param {Number[]} result The object into which to store the result.
  6580. */
  6581. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  6582. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  6583. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  6584. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  6585. var offset = i * 3;
  6586. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  6587. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  6588. if (sampledQuaternionTempQuaternion.w < 0) {
  6589. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  6590. }
  6591. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  6592. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  6593. result[offset] = sampledQuaternionAxis.x * angle;
  6594. result[offset + 1] = sampledQuaternionAxis.y * angle;
  6595. result[offset + 2] = sampledQuaternionAxis.z * angle;
  6596. }
  6597. };
  6598. /**
  6599. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  6600. *
  6601. * @param {Number[]} array The array previously packed for interpolation.
  6602. * @param {Number[]} sourceArray The original packed array.
  6603. * @param {Number} [firstIndex=0] The firstIndex used to convert the array.
  6604. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  6605. * @param {Quaternion} [result] The object into which to store the result.
  6606. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  6607. */
  6608. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  6609. if (!defined.defined(result)) {
  6610. result = new Quaternion();
  6611. }
  6612. Cartesian2.Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  6613. var magnitude = Cartesian2.Cartesian3.magnitude(sampledQuaternionRotation);
  6614. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  6615. if (magnitude === 0) {
  6616. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  6617. } else {
  6618. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  6619. }
  6620. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  6621. };
  6622. /**
  6623. * Duplicates a Quaternion instance.
  6624. *
  6625. * @param {Quaternion} quaternion The quaternion to duplicate.
  6626. * @param {Quaternion} [result] The object onto which to store the result.
  6627. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  6628. */
  6629. Quaternion.clone = function(quaternion, result) {
  6630. if (!defined.defined(quaternion)) {
  6631. return undefined;
  6632. }
  6633. if (!defined.defined(result)) {
  6634. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  6635. }
  6636. result.x = quaternion.x;
  6637. result.y = quaternion.y;
  6638. result.z = quaternion.z;
  6639. result.w = quaternion.w;
  6640. return result;
  6641. };
  6642. /**
  6643. * Computes the conjugate of the provided quaternion.
  6644. *
  6645. * @param {Quaternion} quaternion The quaternion to conjugate.
  6646. * @param {Quaternion} result The object onto which to store the result.
  6647. * @returns {Quaternion} The modified result parameter.
  6648. */
  6649. Quaternion.conjugate = function(quaternion, result) {
  6650. //>>includeStart('debug', pragmas.debug);
  6651. Check.Check.typeOf.object('quaternion', quaternion);
  6652. Check.Check.typeOf.object('result', result);
  6653. //>>includeEnd('debug');
  6654. result.x = -quaternion.x;
  6655. result.y = -quaternion.y;
  6656. result.z = -quaternion.z;
  6657. result.w = quaternion.w;
  6658. return result;
  6659. };
  6660. /**
  6661. * Computes magnitude squared for the provided quaternion.
  6662. *
  6663. * @param {Quaternion} quaternion The quaternion to conjugate.
  6664. * @returns {Number} The magnitude squared.
  6665. */
  6666. Quaternion.magnitudeSquared = function(quaternion) {
  6667. //>>includeStart('debug', pragmas.debug);
  6668. Check.Check.typeOf.object('quaternion', quaternion);
  6669. //>>includeEnd('debug');
  6670. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  6671. };
  6672. /**
  6673. * Computes magnitude for the provided quaternion.
  6674. *
  6675. * @param {Quaternion} quaternion The quaternion to conjugate.
  6676. * @returns {Number} The magnitude.
  6677. */
  6678. Quaternion.magnitude = function(quaternion) {
  6679. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  6680. };
  6681. /**
  6682. * Computes the normalized form of the provided quaternion.
  6683. *
  6684. * @param {Quaternion} quaternion The quaternion to normalize.
  6685. * @param {Quaternion} result The object onto which to store the result.
  6686. * @returns {Quaternion} The modified result parameter.
  6687. */
  6688. Quaternion.normalize = function(quaternion, result) {
  6689. //>>includeStart('debug', pragmas.debug);
  6690. Check.Check.typeOf.object('result', result);
  6691. //>>includeEnd('debug');
  6692. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  6693. var x = quaternion.x * inverseMagnitude;
  6694. var y = quaternion.y * inverseMagnitude;
  6695. var z = quaternion.z * inverseMagnitude;
  6696. var w = quaternion.w * inverseMagnitude;
  6697. result.x = x;
  6698. result.y = y;
  6699. result.z = z;
  6700. result.w = w;
  6701. return result;
  6702. };
  6703. /**
  6704. * Computes the inverse of the provided quaternion.
  6705. *
  6706. * @param {Quaternion} quaternion The quaternion to normalize.
  6707. * @param {Quaternion} result The object onto which to store the result.
  6708. * @returns {Quaternion} The modified result parameter.
  6709. */
  6710. Quaternion.inverse = function(quaternion, result) {
  6711. //>>includeStart('debug', pragmas.debug);
  6712. Check.Check.typeOf.object('result', result);
  6713. //>>includeEnd('debug');
  6714. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  6715. result = Quaternion.conjugate(quaternion, result);
  6716. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  6717. };
  6718. /**
  6719. * Computes the componentwise sum of two quaternions.
  6720. *
  6721. * @param {Quaternion} left The first quaternion.
  6722. * @param {Quaternion} right The second quaternion.
  6723. * @param {Quaternion} result The object onto which to store the result.
  6724. * @returns {Quaternion} The modified result parameter.
  6725. */
  6726. Quaternion.add = function(left, right, result) {
  6727. //>>includeStart('debug', pragmas.debug);
  6728. Check.Check.typeOf.object('left', left);
  6729. Check.Check.typeOf.object('right', right);
  6730. Check.Check.typeOf.object('result', result);
  6731. //>>includeEnd('debug');
  6732. result.x = left.x + right.x;
  6733. result.y = left.y + right.y;
  6734. result.z = left.z + right.z;
  6735. result.w = left.w + right.w;
  6736. return result;
  6737. };
  6738. /**
  6739. * Computes the componentwise difference of two quaternions.
  6740. *
  6741. * @param {Quaternion} left The first quaternion.
  6742. * @param {Quaternion} right The second quaternion.
  6743. * @param {Quaternion} result The object onto which to store the result.
  6744. * @returns {Quaternion} The modified result parameter.
  6745. */
  6746. Quaternion.subtract = function(left, right, result) {
  6747. //>>includeStart('debug', pragmas.debug);
  6748. Check.Check.typeOf.object('left', left);
  6749. Check.Check.typeOf.object('right', right);
  6750. Check.Check.typeOf.object('result', result);
  6751. //>>includeEnd('debug');
  6752. result.x = left.x - right.x;
  6753. result.y = left.y - right.y;
  6754. result.z = left.z - right.z;
  6755. result.w = left.w - right.w;
  6756. return result;
  6757. };
  6758. /**
  6759. * Negates the provided quaternion.
  6760. *
  6761. * @param {Quaternion} quaternion The quaternion to be negated.
  6762. * @param {Quaternion} result The object onto which to store the result.
  6763. * @returns {Quaternion} The modified result parameter.
  6764. */
  6765. Quaternion.negate = function(quaternion, result) {
  6766. //>>includeStart('debug', pragmas.debug);
  6767. Check.Check.typeOf.object('quaternion', quaternion);
  6768. Check.Check.typeOf.object('result', result);
  6769. //>>includeEnd('debug');
  6770. result.x = -quaternion.x;
  6771. result.y = -quaternion.y;
  6772. result.z = -quaternion.z;
  6773. result.w = -quaternion.w;
  6774. return result;
  6775. };
  6776. /**
  6777. * Computes the dot (scalar) product of two quaternions.
  6778. *
  6779. * @param {Quaternion} left The first quaternion.
  6780. * @param {Quaternion} right The second quaternion.
  6781. * @returns {Number} The dot product.
  6782. */
  6783. Quaternion.dot = function(left, right) {
  6784. //>>includeStart('debug', pragmas.debug);
  6785. Check.Check.typeOf.object('left', left);
  6786. Check.Check.typeOf.object('right', right);
  6787. //>>includeEnd('debug');
  6788. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  6789. };
  6790. /**
  6791. * Computes the product of two quaternions.
  6792. *
  6793. * @param {Quaternion} left The first quaternion.
  6794. * @param {Quaternion} right The second quaternion.
  6795. * @param {Quaternion} result The object onto which to store the result.
  6796. * @returns {Quaternion} The modified result parameter.
  6797. */
  6798. Quaternion.multiply = function(left, right, result) {
  6799. //>>includeStart('debug', pragmas.debug);
  6800. Check.Check.typeOf.object('left', left);
  6801. Check.Check.typeOf.object('right', right);
  6802. Check.Check.typeOf.object('result', result);
  6803. //>>includeEnd('debug');
  6804. var leftX = left.x;
  6805. var leftY = left.y;
  6806. var leftZ = left.z;
  6807. var leftW = left.w;
  6808. var rightX = right.x;
  6809. var rightY = right.y;
  6810. var rightZ = right.z;
  6811. var rightW = right.w;
  6812. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  6813. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  6814. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  6815. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  6816. result.x = x;
  6817. result.y = y;
  6818. result.z = z;
  6819. result.w = w;
  6820. return result;
  6821. };
  6822. /**
  6823. * Multiplies the provided quaternion componentwise by the provided scalar.
  6824. *
  6825. * @param {Quaternion} quaternion The quaternion to be scaled.
  6826. * @param {Number} scalar The scalar to multiply with.
  6827. * @param {Quaternion} result The object onto which to store the result.
  6828. * @returns {Quaternion} The modified result parameter.
  6829. */
  6830. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  6831. //>>includeStart('debug', pragmas.debug);
  6832. Check.Check.typeOf.object('quaternion', quaternion);
  6833. Check.Check.typeOf.number('scalar', scalar);
  6834. Check.Check.typeOf.object('result', result);
  6835. //>>includeEnd('debug');
  6836. result.x = quaternion.x * scalar;
  6837. result.y = quaternion.y * scalar;
  6838. result.z = quaternion.z * scalar;
  6839. result.w = quaternion.w * scalar;
  6840. return result;
  6841. };
  6842. /**
  6843. * Divides the provided quaternion componentwise by the provided scalar.
  6844. *
  6845. * @param {Quaternion} quaternion The quaternion to be divided.
  6846. * @param {Number} scalar The scalar to divide by.
  6847. * @param {Quaternion} result The object onto which to store the result.
  6848. * @returns {Quaternion} The modified result parameter.
  6849. */
  6850. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  6851. //>>includeStart('debug', pragmas.debug);
  6852. Check.Check.typeOf.object('quaternion', quaternion);
  6853. Check.Check.typeOf.number('scalar', scalar);
  6854. Check.Check.typeOf.object('result', result);
  6855. //>>includeEnd('debug');
  6856. result.x = quaternion.x / scalar;
  6857. result.y = quaternion.y / scalar;
  6858. result.z = quaternion.z / scalar;
  6859. result.w = quaternion.w / scalar;
  6860. return result;
  6861. };
  6862. /**
  6863. * Computes the axis of rotation of the provided quaternion.
  6864. *
  6865. * @param {Quaternion} quaternion The quaternion to use.
  6866. * @param {Cartesian3} result The object onto which to store the result.
  6867. * @returns {Cartesian3} The modified result parameter.
  6868. */
  6869. Quaternion.computeAxis = function(quaternion, result) {
  6870. //>>includeStart('debug', pragmas.debug);
  6871. Check.Check.typeOf.object('quaternion', quaternion);
  6872. Check.Check.typeOf.object('result', result);
  6873. //>>includeEnd('debug');
  6874. var w = quaternion.w;
  6875. if (Math.abs(w - 1.0) < _Math.CesiumMath.EPSILON6) {
  6876. result.x = result.y = result.z = 0;
  6877. return result;
  6878. }
  6879. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  6880. result.x = quaternion.x * scalar;
  6881. result.y = quaternion.y * scalar;
  6882. result.z = quaternion.z * scalar;
  6883. return result;
  6884. };
  6885. /**
  6886. * Computes the angle of rotation of the provided quaternion.
  6887. *
  6888. * @param {Quaternion} quaternion The quaternion to use.
  6889. * @returns {Number} The angle of rotation.
  6890. */
  6891. Quaternion.computeAngle = function(quaternion) {
  6892. //>>includeStart('debug', pragmas.debug);
  6893. Check.Check.typeOf.object('quaternion', quaternion);
  6894. //>>includeEnd('debug');
  6895. if (Math.abs(quaternion.w - 1.0) < _Math.CesiumMath.EPSILON6) {
  6896. return 0.0;
  6897. }
  6898. return 2.0 * Math.acos(quaternion.w);
  6899. };
  6900. var lerpScratch$1 = new Quaternion();
  6901. /**
  6902. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  6903. *
  6904. * @param {Quaternion} start The value corresponding to t at 0.0.
  6905. * @param {Quaternion} end The value corresponding to t at 1.0.
  6906. * @param {Number} t The point along t at which to interpolate.
  6907. * @param {Quaternion} result The object onto which to store the result.
  6908. * @returns {Quaternion} The modified result parameter.
  6909. */
  6910. Quaternion.lerp = function(start, end, t, result) {
  6911. //>>includeStart('debug', pragmas.debug);
  6912. Check.Check.typeOf.object('start', start);
  6913. Check.Check.typeOf.object('end', end);
  6914. Check.Check.typeOf.number('t', t);
  6915. Check.Check.typeOf.object('result', result);
  6916. //>>includeEnd('debug');
  6917. lerpScratch$1 = Quaternion.multiplyByScalar(end, t, lerpScratch$1);
  6918. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  6919. return Quaternion.add(lerpScratch$1, result, result);
  6920. };
  6921. var slerpEndNegated = new Quaternion();
  6922. var slerpScaledP = new Quaternion();
  6923. var slerpScaledR = new Quaternion();
  6924. /**
  6925. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  6926. *
  6927. * @param {Quaternion} start The value corresponding to t at 0.0.
  6928. * @param {Quaternion} end The value corresponding to t at 1.0.
  6929. * @param {Number} t The point along t at which to interpolate.
  6930. * @param {Quaternion} result The object onto which to store the result.
  6931. * @returns {Quaternion} The modified result parameter.
  6932. *
  6933. * @see Quaternion#fastSlerp
  6934. */
  6935. Quaternion.slerp = function(start, end, t, result) {
  6936. //>>includeStart('debug', pragmas.debug);
  6937. Check.Check.typeOf.object('start', start);
  6938. Check.Check.typeOf.object('end', end);
  6939. Check.Check.typeOf.number('t', t);
  6940. Check.Check.typeOf.object('result', result);
  6941. //>>includeEnd('debug');
  6942. var dot = Quaternion.dot(start, end);
  6943. // The angle between start must be acute. Since q and -q represent
  6944. // the same rotation, negate q to get the acute angle.
  6945. var r = end;
  6946. if (dot < 0.0) {
  6947. dot = -dot;
  6948. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  6949. }
  6950. // dot > 0, as the dot product approaches 1, the angle between the
  6951. // quaternions vanishes. use linear interpolation.
  6952. if (1.0 - dot < _Math.CesiumMath.EPSILON6) {
  6953. return Quaternion.lerp(start, r, t, result);
  6954. }
  6955. var theta = Math.acos(dot);
  6956. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  6957. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  6958. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  6959. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  6960. };
  6961. /**
  6962. * The logarithmic quaternion function.
  6963. *
  6964. * @param {Quaternion} quaternion The unit quaternion.
  6965. * @param {Cartesian3} result The object onto which to store the result.
  6966. * @returns {Cartesian3} The modified result parameter.
  6967. */
  6968. Quaternion.log = function(quaternion, result) {
  6969. //>>includeStart('debug', pragmas.debug);
  6970. Check.Check.typeOf.object('quaternion', quaternion);
  6971. Check.Check.typeOf.object('result', result);
  6972. //>>includeEnd('debug');
  6973. var theta = _Math.CesiumMath.acosClamped(quaternion.w);
  6974. var thetaOverSinTheta = 0.0;
  6975. if (theta !== 0.0) {
  6976. thetaOverSinTheta = theta / Math.sin(theta);
  6977. }
  6978. return Cartesian2.Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  6979. };
  6980. /**
  6981. * The exponential quaternion function.
  6982. *
  6983. * @param {Cartesian3} cartesian The cartesian.
  6984. * @param {Quaternion} result The object onto which to store the result.
  6985. * @returns {Quaternion} The modified result parameter.
  6986. */
  6987. Quaternion.exp = function(cartesian, result) {
  6988. //>>includeStart('debug', pragmas.debug);
  6989. Check.Check.typeOf.object('cartesian', cartesian);
  6990. Check.Check.typeOf.object('result', result);
  6991. //>>includeEnd('debug');
  6992. var theta = Cartesian2.Cartesian3.magnitude(cartesian);
  6993. var sinThetaOverTheta = 0.0;
  6994. if (theta !== 0.0) {
  6995. sinThetaOverTheta = Math.sin(theta) / theta;
  6996. }
  6997. result.x = cartesian.x * sinThetaOverTheta;
  6998. result.y = cartesian.y * sinThetaOverTheta;
  6999. result.z = cartesian.z * sinThetaOverTheta;
  7000. result.w = Math.cos(theta);
  7001. return result;
  7002. };
  7003. var squadScratchCartesian0 = new Cartesian2.Cartesian3();
  7004. var squadScratchCartesian1 = new Cartesian2.Cartesian3();
  7005. var squadScratchQuaternion0 = new Quaternion();
  7006. var squadScratchQuaternion1 = new Quaternion();
  7007. /**
  7008. * Computes an inner quadrangle point.
  7009. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  7010. *
  7011. * @param {Quaternion} q0 The first quaternion.
  7012. * @param {Quaternion} q1 The second quaternion.
  7013. * @param {Quaternion} q2 The third quaternion.
  7014. * @param {Quaternion} result The object onto which to store the result.
  7015. * @returns {Quaternion} The modified result parameter.
  7016. *
  7017. * @see Quaternion#squad
  7018. */
  7019. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  7020. //>>includeStart('debug', pragmas.debug);
  7021. Check.Check.typeOf.object('q0', q0);
  7022. Check.Check.typeOf.object('q1', q1);
  7023. Check.Check.typeOf.object('q2', q2);
  7024. Check.Check.typeOf.object('result', result);
  7025. //>>includeEnd('debug');
  7026. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  7027. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  7028. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  7029. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  7030. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  7031. Cartesian2.Cartesian3.add(cart0, cart1, cart0);
  7032. Cartesian2.Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  7033. Cartesian2.Cartesian3.negate(cart0, cart0);
  7034. Quaternion.exp(cart0, squadScratchQuaternion0);
  7035. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  7036. };
  7037. /**
  7038. * Computes the spherical quadrangle interpolation between quaternions.
  7039. *
  7040. * @param {Quaternion} q0 The first quaternion.
  7041. * @param {Quaternion} q1 The second quaternion.
  7042. * @param {Quaternion} s0 The first inner quadrangle.
  7043. * @param {Quaternion} s1 The second inner quadrangle.
  7044. * @param {Number} t The time in [0,1] used to interpolate.
  7045. * @param {Quaternion} result The object onto which to store the result.
  7046. * @returns {Quaternion} The modified result parameter.
  7047. *
  7048. *
  7049. * @example
  7050. * // 1. compute the squad interpolation between two quaternions on a curve
  7051. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  7052. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  7053. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  7054. *
  7055. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  7056. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  7057. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  7058. *
  7059. * @see Quaternion#computeInnerQuadrangle
  7060. */
  7061. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  7062. //>>includeStart('debug', pragmas.debug);
  7063. Check.Check.typeOf.object('q0', q0);
  7064. Check.Check.typeOf.object('q1', q1);
  7065. Check.Check.typeOf.object('s0', s0);
  7066. Check.Check.typeOf.object('s1', s1);
  7067. Check.Check.typeOf.number('t', t);
  7068. Check.Check.typeOf.object('result', result);
  7069. //>>includeEnd('debug');
  7070. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  7071. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  7072. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  7073. };
  7074. var fastSlerpScratchQuaternion = new Quaternion();
  7075. var opmu = 1.90110745351730037;
  7076. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7077. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7078. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7079. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  7080. for (var i = 0; i < 7; ++i) {
  7081. var s = i + 1.0;
  7082. var t = 2.0 * s + 1.0;
  7083. u[i] = 1.0 / (s * t);
  7084. v[i] = s / t;
  7085. }
  7086. u[7] = opmu / (8.0 * 17.0);
  7087. v[7] = opmu * 8.0 / 17.0;
  7088. /**
  7089. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  7090. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  7091. *
  7092. * @param {Quaternion} start The value corresponding to t at 0.0.
  7093. * @param {Quaternion} end The value corresponding to t at 1.0.
  7094. * @param {Number} t The point along t at which to interpolate.
  7095. * @param {Quaternion} result The object onto which to store the result.
  7096. * @returns {Quaternion} The modified result parameter.
  7097. *
  7098. * @see Quaternion#slerp
  7099. */
  7100. Quaternion.fastSlerp = function(start, end, t, result) {
  7101. //>>includeStart('debug', pragmas.debug);
  7102. Check.Check.typeOf.object('start', start);
  7103. Check.Check.typeOf.object('end', end);
  7104. Check.Check.typeOf.number('t', t);
  7105. Check.Check.typeOf.object('result', result);
  7106. //>>includeEnd('debug');
  7107. var x = Quaternion.dot(start, end);
  7108. var sign;
  7109. if (x >= 0) {
  7110. sign = 1.0;
  7111. } else {
  7112. sign = -1.0;
  7113. x = -x;
  7114. }
  7115. var xm1 = x - 1.0;
  7116. var d = 1.0 - t;
  7117. var sqrT = t * t;
  7118. var sqrD = d * d;
  7119. for (var i = 7; i >= 0; --i) {
  7120. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  7121. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  7122. }
  7123. var cT = sign * t * (
  7124. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  7125. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  7126. var cD = d * (
  7127. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  7128. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  7129. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  7130. Quaternion.multiplyByScalar(end, cT, result);
  7131. return Quaternion.add(temp, result, result);
  7132. };
  7133. /**
  7134. * Computes the spherical quadrangle interpolation between quaternions.
  7135. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  7136. *
  7137. * @param {Quaternion} q0 The first quaternion.
  7138. * @param {Quaternion} q1 The second quaternion.
  7139. * @param {Quaternion} s0 The first inner quadrangle.
  7140. * @param {Quaternion} s1 The second inner quadrangle.
  7141. * @param {Number} t The time in [0,1] used to interpolate.
  7142. * @param {Quaternion} result The object onto which to store the result.
  7143. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  7144. *
  7145. * @see Quaternion#squad
  7146. */
  7147. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  7148. //>>includeStart('debug', pragmas.debug);
  7149. Check.Check.typeOf.object('q0', q0);
  7150. Check.Check.typeOf.object('q1', q1);
  7151. Check.Check.typeOf.object('s0', s0);
  7152. Check.Check.typeOf.object('s1', s1);
  7153. Check.Check.typeOf.number('t', t);
  7154. Check.Check.typeOf.object('result', result);
  7155. //>>includeEnd('debug');
  7156. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  7157. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  7158. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  7159. };
  7160. /**
  7161. * Compares the provided quaternions componentwise and returns
  7162. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7163. *
  7164. * @param {Quaternion} [left] The first quaternion.
  7165. * @param {Quaternion} [right] The second quaternion.
  7166. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7167. */
  7168. Quaternion.equals = function(left, right) {
  7169. return (left === right) ||
  7170. ((defined.defined(left)) &&
  7171. (defined.defined(right)) &&
  7172. (left.x === right.x) &&
  7173. (left.y === right.y) &&
  7174. (left.z === right.z) &&
  7175. (left.w === right.w));
  7176. };
  7177. /**
  7178. * Compares the provided quaternions componentwise and returns
  7179. * <code>true</code> if they are within the provided epsilon,
  7180. * <code>false</code> otherwise.
  7181. *
  7182. * @param {Quaternion} [left] The first quaternion.
  7183. * @param {Quaternion} [right] The second quaternion.
  7184. * @param {Number} epsilon The epsilon to use for equality testing.
  7185. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7186. */
  7187. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  7188. //>>includeStart('debug', pragmas.debug);
  7189. Check.Check.typeOf.number('epsilon', epsilon);
  7190. //>>includeEnd('debug');
  7191. return (left === right) ||
  7192. ((defined.defined(left)) &&
  7193. (defined.defined(right)) &&
  7194. (Math.abs(left.x - right.x) <= epsilon) &&
  7195. (Math.abs(left.y - right.y) <= epsilon) &&
  7196. (Math.abs(left.z - right.z) <= epsilon) &&
  7197. (Math.abs(left.w - right.w) <= epsilon));
  7198. };
  7199. /**
  7200. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  7201. *
  7202. * @type {Quaternion}
  7203. * @constant
  7204. */
  7205. Quaternion.ZERO = freezeObject.freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  7206. /**
  7207. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  7208. *
  7209. * @type {Quaternion}
  7210. * @constant
  7211. */
  7212. Quaternion.IDENTITY = freezeObject.freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  7213. /**
  7214. * Duplicates this Quaternion instance.
  7215. *
  7216. * @param {Quaternion} [result] The object onto which to store the result.
  7217. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  7218. */
  7219. Quaternion.prototype.clone = function(result) {
  7220. return Quaternion.clone(this, result);
  7221. };
  7222. /**
  7223. * Compares this and the provided quaternion componentwise and returns
  7224. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7225. *
  7226. * @param {Quaternion} [right] The right hand side quaternion.
  7227. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7228. */
  7229. Quaternion.prototype.equals = function(right) {
  7230. return Quaternion.equals(this, right);
  7231. };
  7232. /**
  7233. * Compares this and the provided quaternion componentwise and returns
  7234. * <code>true</code> if they are within the provided epsilon,
  7235. * <code>false</code> otherwise.
  7236. *
  7237. * @param {Quaternion} [right] The right hand side quaternion.
  7238. * @param {Number} epsilon The epsilon to use for equality testing.
  7239. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7240. */
  7241. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  7242. return Quaternion.equalsEpsilon(this, right, epsilon);
  7243. };
  7244. /**
  7245. * Returns a string representing this quaternion in the format (x, y, z, w).
  7246. *
  7247. * @returns {String} A string representing this Quaternion.
  7248. */
  7249. Quaternion.prototype.toString = function() {
  7250. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  7251. };
  7252. /**
  7253. * Finds an item in a sorted array.
  7254. *
  7255. * @exports binarySearch
  7256. * @param {Array} array The sorted array to search.
  7257. * @param {*} itemToFind The item to find in the array.
  7258. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  7259. * elements in the array.
  7260. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  7261. * does not exist, the return value is a negative number which is the bitwise complement (~)
  7262. * of the index before which the itemToFind should be inserted in order to maintain the
  7263. * sorted order of the array.
  7264. *
  7265. * @example
  7266. * // Create a comparator function to search through an array of numbers.
  7267. * function comparator(a, b) {
  7268. * return a - b;
  7269. * };
  7270. * var numbers = [0, 2, 4, 6, 8];
  7271. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  7272. */
  7273. function binarySearch(array, itemToFind, comparator) {
  7274. //>>includeStart('debug', pragmas.debug);
  7275. Check.Check.defined('array', array);
  7276. Check.Check.defined('itemToFind', itemToFind);
  7277. Check.Check.defined('comparator', comparator);
  7278. //>>includeEnd('debug');
  7279. var low = 0;
  7280. var high = array.length - 1;
  7281. var i;
  7282. var comparison;
  7283. while (low <= high) {
  7284. i = ~~((low + high) / 2);
  7285. comparison = comparator(array[i], itemToFind);
  7286. if (comparison < 0) {
  7287. low = i + 1;
  7288. continue;
  7289. }
  7290. if (comparison > 0) {
  7291. high = i - 1;
  7292. continue;
  7293. }
  7294. return i;
  7295. }
  7296. return ~(high + 1);
  7297. }
  7298. /**
  7299. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  7300. *
  7301. * @alias EarthOrientationParametersSample
  7302. * @constructor
  7303. *
  7304. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  7305. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  7306. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  7307. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  7308. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  7309. *
  7310. * @private
  7311. */
  7312. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  7313. /**
  7314. * The pole wander about the X axis, in radians.
  7315. * @type {Number}
  7316. */
  7317. this.xPoleWander = xPoleWander;
  7318. /**
  7319. * The pole wander about the Y axis, in radians.
  7320. * @type {Number}
  7321. */
  7322. this.yPoleWander = yPoleWander;
  7323. /**
  7324. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  7325. * @type {Number}
  7326. */
  7327. this.xPoleOffset = xPoleOffset;
  7328. /**
  7329. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  7330. * @type {Number}
  7331. */
  7332. this.yPoleOffset = yPoleOffset;
  7333. /**
  7334. * The difference in time standards, UT1 - UTC, in seconds.
  7335. * @type {Number}
  7336. */
  7337. this.ut1MinusUtc = ut1MinusUtc;
  7338. }
  7339. /**
  7340. @license
  7341. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  7342. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  7343. php.js is copyright 2012 Kevin van Zonneveld.
  7344. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  7345. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  7346. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  7347. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  7348. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  7349. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  7350. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  7351. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  7352. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  7353. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  7354. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  7355. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  7356. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  7357. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  7358. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  7359. (http://geekfg.blogspot.com), Andrea Giammarchi
  7360. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  7361. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  7362. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  7363. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  7364. Marc Palau, Martin
  7365. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  7366. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  7367. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  7368. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  7369. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  7370. Ariede (http://caioariede.com), Robin, Kankrelune
  7371. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  7372. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  7373. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  7374. David, Aman Gupta, Michael White, Public Domain
  7375. (http://www.json.org/json2.js), Steven Levithan
  7376. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  7377. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  7378. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  7379. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  7380. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  7381. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  7382. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  7383. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  7384. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  7385. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  7386. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  7387. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  7388. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  7389. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  7390. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  7391. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  7392. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  7393. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  7394. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  7395. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  7396. (http://yass.meetcweb.com), Peter-Paul Koch
  7397. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  7398. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  7399. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  7400. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  7401. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  7402. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  7403. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  7404. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  7405. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  7406. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  7407. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  7408. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  7409. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  7410. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  7411. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  7412. (http://www.premasolutions.com/), Philippe Jausions
  7413. (http://pear.php.net/user/jausions), Aidan Lister
  7414. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  7415. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  7416. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  7417. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  7418. (http://www.pedrotainha.com), James, Arnout Kazemier
  7419. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  7420. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  7421. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  7422. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  7423. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  7424. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  7425. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  7426. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  7427. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  7428. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  7429. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  7430. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  7431. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  7432. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  7433. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  7434. (http://benblume.co.uk/), DtTvB
  7435. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  7436. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  7437. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  7438. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  7439. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  7440. Bryan
  7441. Licensed under the MIT (MIT-LICENSE.txt) license.
  7442. Permission is hereby granted, free of charge, to any person obtaining a
  7443. copy of this software and associated documentation files (the
  7444. "Software"), to deal in the Software without restriction, including
  7445. without limitation the rights to use, copy, modify, merge, publish,
  7446. distribute, sublicense, and/or sell copies of the Software, and to
  7447. permit persons to whom the Software is furnished to do so, subject to
  7448. the following conditions:
  7449. The above copyright notice and this permission notice shall be included
  7450. in all copies or substantial portions of the Software.
  7451. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7452. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7453. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  7454. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  7455. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  7456. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  7457. OTHER DEALINGS IN THE SOFTWARE.
  7458. */
  7459. function sprintf () {
  7460. // http://kevin.vanzonneveld.net
  7461. // + original by: Ash Searle (http://hexmen.com/blog/)
  7462. // + namespaced by: Michael White (http://getsprink.com)
  7463. // + tweaked by: Jack
  7464. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  7465. // + input by: Paulo Freitas
  7466. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  7467. // + input by: Brett Zamir (http://brett-zamir.me)
  7468. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  7469. // + improved by: Dj
  7470. // + improved by: Allidylls
  7471. // * example 1: sprintf("%01.2f", 123.1);
  7472. // * returns 1: 123.10
  7473. // * example 2: sprintf("[%10s]", 'monkey');
  7474. // * returns 2: '[ monkey]'
  7475. // * example 3: sprintf("[%'#10s]", 'monkey');
  7476. // * returns 3: '[####monkey]'
  7477. // * example 4: sprintf("%d", 123456789012345);
  7478. // * returns 4: '123456789012345'
  7479. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  7480. var a = arguments,
  7481. i = 0,
  7482. format = a[i++];
  7483. // pad()
  7484. var pad = function (str, len, chr, leftJustify) {
  7485. if (!chr) {
  7486. chr = ' ';
  7487. }
  7488. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  7489. return leftJustify ? str + padding : padding + str;
  7490. };
  7491. // justify()
  7492. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  7493. var diff = minWidth - value.length;
  7494. if (diff > 0) {
  7495. if (leftJustify || !zeroPad) {
  7496. value = pad(value, minWidth, customPadChar, leftJustify);
  7497. } else {
  7498. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  7499. }
  7500. }
  7501. return value;
  7502. };
  7503. // formatBaseX()
  7504. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  7505. // Note: casts negative numbers to positive ones
  7506. var number = value >>> 0;
  7507. prefix = prefix && number && {
  7508. '2': '0b',
  7509. '8': '0',
  7510. '16': '0x'
  7511. }[base] || '';
  7512. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  7513. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  7514. };
  7515. // formatString()
  7516. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  7517. if (precision != null) {
  7518. value = value.slice(0, precision);
  7519. }
  7520. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  7521. };
  7522. // doFormat()
  7523. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  7524. var number;
  7525. var prefix;
  7526. var method;
  7527. var textTransform;
  7528. var value;
  7529. if (substring == '%%') {
  7530. return '%';
  7531. }
  7532. // parse flags
  7533. var leftJustify = false,
  7534. positivePrefix = '',
  7535. zeroPad = false,
  7536. prefixBaseX = false,
  7537. customPadChar = ' ';
  7538. var flagsl = flags.length;
  7539. for (var j = 0; flags && j < flagsl; j++) {
  7540. switch (flags.charAt(j)) {
  7541. case ' ':
  7542. positivePrefix = ' ';
  7543. break;
  7544. case '+':
  7545. positivePrefix = '+';
  7546. break;
  7547. case '-':
  7548. leftJustify = true;
  7549. break;
  7550. case "'":
  7551. customPadChar = flags.charAt(j + 1);
  7552. break;
  7553. case '0':
  7554. zeroPad = true;
  7555. break;
  7556. case '#':
  7557. prefixBaseX = true;
  7558. break;
  7559. }
  7560. }
  7561. // parameters may be null, undefined, empty-string or real valued
  7562. // we want to ignore null, undefined and empty-string values
  7563. if (!minWidth) {
  7564. minWidth = 0;
  7565. } else if (minWidth == '*') {
  7566. minWidth = +a[i++];
  7567. } else if (minWidth.charAt(0) == '*') {
  7568. minWidth = +a[minWidth.slice(1, -1)];
  7569. } else {
  7570. minWidth = +minWidth;
  7571. }
  7572. // Note: undocumented perl feature:
  7573. if (minWidth < 0) {
  7574. minWidth = -minWidth;
  7575. leftJustify = true;
  7576. }
  7577. if (!isFinite(minWidth)) {
  7578. throw new Error('sprintf: (minimum-)width must be finite');
  7579. }
  7580. if (!precision) {
  7581. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  7582. } else if (precision == '*') {
  7583. precision = +a[i++];
  7584. } else if (precision.charAt(0) == '*') {
  7585. precision = +a[precision.slice(1, -1)];
  7586. } else {
  7587. precision = +precision;
  7588. }
  7589. // grab value using valueIndex if required?
  7590. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  7591. switch (type) {
  7592. case 's':
  7593. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  7594. case 'c':
  7595. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  7596. case 'b':
  7597. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  7598. case 'o':
  7599. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  7600. case 'x':
  7601. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  7602. case 'X':
  7603. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  7604. case 'u':
  7605. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  7606. case 'i':
  7607. case 'd':
  7608. number = +value || 0;
  7609. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  7610. prefix = number < 0 ? '-' : positivePrefix;
  7611. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  7612. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  7613. case 'e':
  7614. case 'E':
  7615. case 'f': // Should handle locales (as per setlocale)
  7616. case 'F':
  7617. case 'g':
  7618. case 'G':
  7619. number = +value;
  7620. prefix = number < 0 ? '-' : positivePrefix;
  7621. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  7622. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  7623. value = prefix + Math.abs(number)[method](precision);
  7624. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  7625. default:
  7626. return substring;
  7627. }
  7628. };
  7629. return format.replace(regex, doFormat);
  7630. }
  7631. /**
  7632. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  7633. * In addition to submillisecond precision, this object can also represent leap seconds.
  7634. * @alias GregorianDate
  7635. * @constructor
  7636. *
  7637. * @see JulianDate#toGregorianDate
  7638. */
  7639. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  7640. /**
  7641. * Gets or sets the year as a whole number.
  7642. * @type {Number}
  7643. */
  7644. this.year = year;
  7645. /**
  7646. * Gets or sets the month as a whole number with range [1, 12].
  7647. * @type {Number}
  7648. */
  7649. this.month = month;
  7650. /**
  7651. * Gets or sets the day of the month as a whole number starting at 1.
  7652. * @type {Number}
  7653. */
  7654. this.day = day;
  7655. /**
  7656. * Gets or sets the hour as a whole number with range [0, 23].
  7657. * @type {Number}
  7658. */
  7659. this.hour = hour;
  7660. /**
  7661. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  7662. * @type {Number}
  7663. */
  7664. this.minute = minute;
  7665. /**
  7666. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  7667. * @type {Number}
  7668. */
  7669. this.second = second;
  7670. /**
  7671. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  7672. * @type {Number}
  7673. */
  7674. this.millisecond = millisecond;
  7675. /**
  7676. * Gets or sets whether this time is during a leap second.
  7677. * @type {Boolean}
  7678. */
  7679. this.isLeapSecond = isLeapSecond;
  7680. }
  7681. /**
  7682. * Determines if a given date is a leap year.
  7683. *
  7684. * @exports isLeapYear
  7685. *
  7686. * @param {Number} year The year to be tested.
  7687. * @returns {Boolean} True if <code>year</code> is a leap year.
  7688. *
  7689. * @example
  7690. * var leapYear = Cesium.isLeapYear(2000); // true
  7691. */
  7692. function isLeapYear(year) {
  7693. //>>includeStart('debug', pragmas.debug);
  7694. if (year === null || isNaN(year)) {
  7695. throw new Check.DeveloperError('year is required and must be a number.');
  7696. }
  7697. //>>includeEnd('debug');
  7698. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  7699. }
  7700. /**
  7701. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  7702. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  7703. * @alias LeapSecond
  7704. * @constructor
  7705. *
  7706. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  7707. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  7708. */
  7709. function LeapSecond(date, offset) {
  7710. /**
  7711. * Gets or sets the date at which this leap second occurs.
  7712. * @type {JulianDate}
  7713. */
  7714. this.julianDate = date;
  7715. /**
  7716. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  7717. * of this leap second.
  7718. * @type {Number}
  7719. */
  7720. this.offset = offset;
  7721. }
  7722. /**
  7723. * Constants for time conversions like those done by {@link JulianDate}.
  7724. *
  7725. * @exports TimeConstants
  7726. *
  7727. * @see JulianDate
  7728. *
  7729. * @private
  7730. */
  7731. var TimeConstants = {
  7732. /**
  7733. * The number of seconds in one millisecond: <code>0.001</code>
  7734. * @type {Number}
  7735. * @constant
  7736. */
  7737. SECONDS_PER_MILLISECOND : 0.001,
  7738. /**
  7739. * The number of seconds in one minute: <code>60</code>.
  7740. * @type {Number}
  7741. * @constant
  7742. */
  7743. SECONDS_PER_MINUTE : 60.0,
  7744. /**
  7745. * The number of minutes in one hour: <code>60</code>.
  7746. * @type {Number}
  7747. * @constant
  7748. */
  7749. MINUTES_PER_HOUR : 60.0,
  7750. /**
  7751. * The number of hours in one day: <code>24</code>.
  7752. * @type {Number}
  7753. * @constant
  7754. */
  7755. HOURS_PER_DAY : 24.0,
  7756. /**
  7757. * The number of seconds in one hour: <code>3600</code>.
  7758. * @type {Number}
  7759. * @constant
  7760. */
  7761. SECONDS_PER_HOUR : 3600.0,
  7762. /**
  7763. * The number of minutes in one day: <code>1440</code>.
  7764. * @type {Number}
  7765. * @constant
  7766. */
  7767. MINUTES_PER_DAY : 1440.0,
  7768. /**
  7769. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  7770. * @type {Number}
  7771. * @constant
  7772. */
  7773. SECONDS_PER_DAY : 86400.0,
  7774. /**
  7775. * The number of days in one Julian century: <code>36525</code>.
  7776. * @type {Number}
  7777. * @constant
  7778. */
  7779. DAYS_PER_JULIAN_CENTURY : 36525.0,
  7780. /**
  7781. * One trillionth of a second.
  7782. * @type {Number}
  7783. * @constant
  7784. */
  7785. PICOSECOND : 0.000000001,
  7786. /**
  7787. * The number of days to subtract from a Julian date to determine the
  7788. * modified Julian date, which gives the number of days since midnight
  7789. * on November 17, 1858.
  7790. * @type {Number}
  7791. * @constant
  7792. */
  7793. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  7794. };
  7795. var TimeConstants$1 = freezeObject.freezeObject(TimeConstants);
  7796. /**
  7797. * Provides the type of time standards which JulianDate can take as input.
  7798. *
  7799. * @exports TimeStandard
  7800. *
  7801. * @see JulianDate
  7802. */
  7803. var TimeStandard = {
  7804. /**
  7805. * Represents the coordinated Universal Time (UTC) time standard.
  7806. *
  7807. * UTC is related to TAI according to the relationship
  7808. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  7809. * seconds which have been introduced as of the time in TAI.
  7810. *
  7811. * @type {Number}
  7812. * @constant
  7813. */
  7814. UTC : 0,
  7815. /**
  7816. * Represents the International Atomic Time (TAI) time standard.
  7817. * TAI is the principal time standard to which the other time standards are related.
  7818. *
  7819. * @type {Number}
  7820. * @constant
  7821. */
  7822. TAI : 1
  7823. };
  7824. var TimeStandard$1 = freezeObject.freezeObject(TimeStandard);
  7825. var gregorianDateScratch = new GregorianDate();
  7826. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  7827. var daysInLeapFeburary = 29;
  7828. function compareLeapSecondDates(leapSecond, dateToFind) {
  7829. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  7830. }
  7831. // we don't really need a leap second instance, anything with a julianDate property will do
  7832. var binarySearchScratchLeapSecond = new LeapSecond();
  7833. function convertUtcToTai(julianDate) {
  7834. //Even though julianDate is in UTC, we'll treat it as TAI and
  7835. //search the leap second table for it.
  7836. binarySearchScratchLeapSecond.julianDate = julianDate;
  7837. var leapSeconds = JulianDate.leapSeconds;
  7838. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  7839. if (index < 0) {
  7840. index = ~index;
  7841. }
  7842. if (index >= leapSeconds.length) {
  7843. index = leapSeconds.length - 1;
  7844. }
  7845. var offset = leapSeconds[index].offset;
  7846. if (index > 0) {
  7847. //Now we have the index of the closest leap second that comes on or after our UTC time.
  7848. //However, if the difference between the UTC date being converted and the TAI
  7849. //defined leap second is greater than the offset, we are off by one and need to use
  7850. //the previous leap second.
  7851. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  7852. if (difference > offset) {
  7853. index--;
  7854. offset = leapSeconds[index].offset;
  7855. }
  7856. }
  7857. JulianDate.addSeconds(julianDate, offset, julianDate);
  7858. }
  7859. function convertTaiToUtc(julianDate, result) {
  7860. binarySearchScratchLeapSecond.julianDate = julianDate;
  7861. var leapSeconds = JulianDate.leapSeconds;
  7862. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  7863. if (index < 0) {
  7864. index = ~index;
  7865. }
  7866. //All times before our first leap second get the first offset.
  7867. if (index === 0) {
  7868. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  7869. }
  7870. //All times after our leap second get the last offset.
  7871. if (index >= leapSeconds.length) {
  7872. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  7873. }
  7874. //Compute the difference between the found leap second and the time we are converting.
  7875. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  7876. if (difference === 0) {
  7877. //The date is in our leap second table.
  7878. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  7879. }
  7880. if (difference <= 1.0) {
  7881. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  7882. return undefined;
  7883. }
  7884. //The time is in between two leap seconds, index is the leap second after the date
  7885. //we're converting, so we subtract one to get the correct LeapSecond instance.
  7886. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  7887. }
  7888. function setComponents(wholeDays, secondsOfDay, julianDate) {
  7889. var extraDays = (secondsOfDay / TimeConstants$1.SECONDS_PER_DAY) | 0;
  7890. wholeDays += extraDays;
  7891. secondsOfDay -= TimeConstants$1.SECONDS_PER_DAY * extraDays;
  7892. if (secondsOfDay < 0) {
  7893. wholeDays--;
  7894. secondsOfDay += TimeConstants$1.SECONDS_PER_DAY;
  7895. }
  7896. julianDate.dayNumber = wholeDays;
  7897. julianDate.secondsOfDay = secondsOfDay;
  7898. return julianDate;
  7899. }
  7900. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  7901. // Algorithm from page 604 of the Explanatory Supplement to the
  7902. // Astronomical Almanac (Seidelmann 1992).
  7903. var a = ((month - 14) / 12) | 0;
  7904. var b = year + 4800 + a;
  7905. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  7906. // JulianDates are noon-based
  7907. hour = hour - 12;
  7908. if (hour < 0) {
  7909. hour += 24;
  7910. }
  7911. var secondsOfDay = second + ((hour * TimeConstants$1.SECONDS_PER_HOUR) + (minute * TimeConstants$1.SECONDS_PER_MINUTE) + (millisecond * TimeConstants$1.SECONDS_PER_MILLISECOND));
  7912. if (secondsOfDay >= 43200.0) {
  7913. dayNumber -= 1;
  7914. }
  7915. return [dayNumber, secondsOfDay];
  7916. }
  7917. //Regular expressions used for ISO8601 date parsing.
  7918. //YYYY
  7919. var matchCalendarYear = /^(\d{4})$/;
  7920. //YYYY-MM (YYYYMM is invalid)
  7921. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  7922. //YYYY-DDD or YYYYDDD
  7923. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  7924. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  7925. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  7926. //YYYY-MM-DD or YYYYMMDD
  7927. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  7928. // Match utc offset
  7929. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  7930. // Match hours HH or HH.xxxxx
  7931. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  7932. // Match hours/minutes HH:MM HHMM.xxxxx
  7933. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  7934. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  7935. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  7936. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  7937. /**
  7938. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  7939. * For increased precision, this class stores the whole number part of the date and the seconds
  7940. * part of the date in separate components. In order to be safe for arithmetic and represent
  7941. * leap seconds, the date is always stored in the International Atomic Time standard
  7942. * {@link TimeStandard.TAI}.
  7943. * @alias JulianDate
  7944. * @constructor
  7945. *
  7946. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  7947. * @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.
  7948. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  7949. */
  7950. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  7951. /**
  7952. * Gets or sets the number of whole days.
  7953. * @type {Number}
  7954. */
  7955. this.dayNumber = undefined;
  7956. /**
  7957. * Gets or sets the number of seconds into the current day.
  7958. * @type {Number}
  7959. */
  7960. this.secondsOfDay = undefined;
  7961. julianDayNumber = defaultValue.defaultValue(julianDayNumber, 0.0);
  7962. secondsOfDay = defaultValue.defaultValue(secondsOfDay, 0.0);
  7963. timeStandard = defaultValue.defaultValue(timeStandard, TimeStandard$1.UTC);
  7964. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  7965. var wholeDays = julianDayNumber | 0;
  7966. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants$1.SECONDS_PER_DAY;
  7967. setComponents(wholeDays, secondsOfDay, this);
  7968. if (timeStandard === TimeStandard$1.UTC) {
  7969. convertUtcToTai(this);
  7970. }
  7971. }
  7972. /**
  7973. * Creates a new instance from a GregorianDate.
  7974. *
  7975. * @param {GregorianDate} date A GregorianDate.
  7976. * @param {JulianDate} [result] An existing instance to use for the result.
  7977. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  7978. *
  7979. * @exception {DeveloperError} date must be a valid GregorianDate.
  7980. */
  7981. JulianDate.fromGregorianDate = function(date, result) {
  7982. //>>includeStart('debug', pragmas.debug);
  7983. if (!(date instanceof GregorianDate)) {
  7984. throw new Check.DeveloperError('date must be a valid GregorianDate.');
  7985. }
  7986. //>>includeEnd('debug');
  7987. var components = computeJulianDateComponents(date.year, date.month, date.day, date.hour, date.minute, date.second, date.millisecond);
  7988. if (!defined.defined(result)) {
  7989. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  7990. }
  7991. setComponents(components[0], components[1], result);
  7992. convertUtcToTai(result);
  7993. return result;
  7994. };
  7995. /**
  7996. * Creates a new instance from a JavaScript Date.
  7997. *
  7998. * @param {Date} date A JavaScript Date.
  7999. * @param {JulianDate} [result] An existing instance to use for the result.
  8000. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8001. *
  8002. * @exception {DeveloperError} date must be a valid JavaScript Date.
  8003. */
  8004. JulianDate.fromDate = function(date, result) {
  8005. //>>includeStart('debug', pragmas.debug);
  8006. if (!(date instanceof Date) || isNaN(date.getTime())) {
  8007. throw new Check.DeveloperError('date must be a valid JavaScript Date.');
  8008. }
  8009. //>>includeEnd('debug');
  8010. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  8011. if (!defined.defined(result)) {
  8012. return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  8013. }
  8014. setComponents(components[0], components[1], result);
  8015. convertUtcToTai(result);
  8016. return result;
  8017. };
  8018. /**
  8019. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  8020. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  8021. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  8022. *
  8023. * @param {String} iso8601String An ISO 8601 date.
  8024. * @param {JulianDate} [result] An existing instance to use for the result.
  8025. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8026. *
  8027. * @exception {DeveloperError} Invalid ISO 8601 date.
  8028. */
  8029. JulianDate.fromIso8601 = function(iso8601String, result) {
  8030. //>>includeStart('debug', pragmas.debug);
  8031. if (typeof iso8601String !== 'string') {
  8032. throw new Check.DeveloperError(iso8601ErrorMessage);
  8033. }
  8034. //>>includeEnd('debug');
  8035. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  8036. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  8037. iso8601String = iso8601String.replace(',', '.');
  8038. //Split the string into its date and time components, denoted by a mandatory T
  8039. var tokens = iso8601String.split('T');
  8040. var year;
  8041. var month = 1;
  8042. var day = 1;
  8043. var hour = 0;
  8044. var minute = 0;
  8045. var second = 0;
  8046. var millisecond = 0;
  8047. //Lacking a time is okay, but a missing date is illegal.
  8048. var date = tokens[0];
  8049. var time = tokens[1];
  8050. var tmp;
  8051. var inLeapYear;
  8052. //>>includeStart('debug', pragmas.debug);
  8053. if (!defined.defined(date)) {
  8054. throw new Check.DeveloperError(iso8601ErrorMessage);
  8055. }
  8056. var dashCount;
  8057. //>>includeEnd('debug');
  8058. //First match the date against possible regular expressions.
  8059. tokens = date.match(matchCalendarDate);
  8060. if (tokens !== null) {
  8061. //>>includeStart('debug', pragmas.debug);
  8062. dashCount = date.split('-').length - 1;
  8063. if (dashCount > 0 && dashCount !== 2) {
  8064. throw new Check.DeveloperError(iso8601ErrorMessage);
  8065. }
  8066. //>>includeEnd('debug');
  8067. year = +tokens[1];
  8068. month = +tokens[2];
  8069. day = +tokens[3];
  8070. } else {
  8071. tokens = date.match(matchCalendarMonth);
  8072. if (tokens !== null) {
  8073. year = +tokens[1];
  8074. month = +tokens[2];
  8075. } else {
  8076. tokens = date.match(matchCalendarYear);
  8077. if (tokens !== null) {
  8078. year = +tokens[1];
  8079. } else {
  8080. //Not a year/month/day so it must be an ordinal date.
  8081. var dayOfYear;
  8082. tokens = date.match(matchOrdinalDate);
  8083. if (tokens !== null) {
  8084. year = +tokens[1];
  8085. dayOfYear = +tokens[2];
  8086. inLeapYear = isLeapYear(year);
  8087. //This validation is only applicable for this format.
  8088. //>>includeStart('debug', pragmas.debug);
  8089. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  8090. throw new Check.DeveloperError(iso8601ErrorMessage);
  8091. }
  8092. //>>includeEnd('debug')
  8093. } else {
  8094. tokens = date.match(matchWeekDate);
  8095. if (tokens !== null) {
  8096. //ISO week date to ordinal date from
  8097. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  8098. year = +tokens[1];
  8099. var weekNumber = +tokens[2];
  8100. var dayOfWeek = +tokens[3] || 0;
  8101. //>>includeStart('debug', pragmas.debug);
  8102. dashCount = date.split('-').length - 1;
  8103. if (dashCount > 0 &&
  8104. ((!defined.defined(tokens[3]) && dashCount !== 1) ||
  8105. (defined.defined(tokens[3]) && dashCount !== 2))) {
  8106. throw new Check.DeveloperError(iso8601ErrorMessage);
  8107. }
  8108. //>>includeEnd('debug')
  8109. var january4 = new Date(Date.UTC(year, 0, 4));
  8110. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  8111. } else {
  8112. //None of our regular expressions succeeded in parsing the date properly.
  8113. //>>includeStart('debug', pragmas.debug);
  8114. throw new Check.DeveloperError(iso8601ErrorMessage);
  8115. //>>includeEnd('debug')
  8116. }
  8117. }
  8118. //Split an ordinal date into month/day.
  8119. tmp = new Date(Date.UTC(year, 0, 1));
  8120. tmp.setUTCDate(dayOfYear);
  8121. month = tmp.getUTCMonth() + 1;
  8122. day = tmp.getUTCDate();
  8123. }
  8124. }
  8125. }
  8126. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  8127. inLeapYear = isLeapYear(year);
  8128. //>>includeStart('debug', pragmas.debug);
  8129. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  8130. throw new Check.DeveloperError(iso8601ErrorMessage);
  8131. }
  8132. //>>includeEnd('debug')
  8133. //Now move onto the time string, which is much simpler.
  8134. //If no time is specified, it is considered the beginning of the day, UTC to match Javascript's implementation.
  8135. var offsetIndex;
  8136. if (defined.defined(time)) {
  8137. tokens = time.match(matchHoursMinutesSeconds);
  8138. if (tokens !== null) {
  8139. //>>includeStart('debug', pragmas.debug);
  8140. dashCount = time.split(':').length - 1;
  8141. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  8142. throw new Check.DeveloperError(iso8601ErrorMessage);
  8143. }
  8144. //>>includeEnd('debug')
  8145. hour = +tokens[1];
  8146. minute = +tokens[2];
  8147. second = +tokens[3];
  8148. millisecond = +(tokens[4] || 0) * 1000.0;
  8149. offsetIndex = 5;
  8150. } else {
  8151. tokens = time.match(matchHoursMinutes);
  8152. if (tokens !== null) {
  8153. //>>includeStart('debug', pragmas.debug);
  8154. dashCount = time.split(':').length - 1;
  8155. if (dashCount > 2) {
  8156. throw new Check.DeveloperError(iso8601ErrorMessage);
  8157. }
  8158. //>>includeEnd('debug')
  8159. hour = +tokens[1];
  8160. minute = +tokens[2];
  8161. second = +(tokens[3] || 0) * 60.0;
  8162. offsetIndex = 4;
  8163. } else {
  8164. tokens = time.match(matchHours);
  8165. if (tokens !== null) {
  8166. hour = +tokens[1];
  8167. minute = +(tokens[2] || 0) * 60.0;
  8168. offsetIndex = 3;
  8169. } else {
  8170. //>>includeStart('debug', pragmas.debug);
  8171. throw new Check.DeveloperError(iso8601ErrorMessage);
  8172. //>>includeEnd('debug')
  8173. }
  8174. }
  8175. }
  8176. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  8177. //>>includeStart('debug', pragmas.debug);
  8178. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  8179. throw new Check.DeveloperError(iso8601ErrorMessage);
  8180. }
  8181. //>>includeEnd('debug');
  8182. //Check the UTC offset value, if no value exists, use local time
  8183. //a Z indicates UTC, + or - are offsets.
  8184. var offset = tokens[offsetIndex];
  8185. var offsetHours = +(tokens[offsetIndex + 1]);
  8186. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  8187. switch (offset) {
  8188. case '+':
  8189. hour = hour - offsetHours;
  8190. minute = minute - offsetMinutes;
  8191. break;
  8192. case '-':
  8193. hour = hour + offsetHours;
  8194. minute = minute + offsetMinutes;
  8195. break;
  8196. case 'Z':
  8197. break;
  8198. default:
  8199. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  8200. break;
  8201. }
  8202. }
  8203. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  8204. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  8205. //Then we add it back in after converting to TAI.
  8206. var isLeapSecond = second === 60;
  8207. if (isLeapSecond) {
  8208. second--;
  8209. }
  8210. //Even if we successfully parsed the string into its components, after applying UTC offset or
  8211. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  8212. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  8213. while (minute >= 60) {
  8214. minute -= 60;
  8215. hour++;
  8216. }
  8217. while (hour >= 24) {
  8218. hour -= 24;
  8219. day++;
  8220. }
  8221. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  8222. while (day > tmp) {
  8223. day -= tmp;
  8224. month++;
  8225. if (month > 12) {
  8226. month -= 12;
  8227. year++;
  8228. }
  8229. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  8230. }
  8231. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  8232. while (minute < 0) {
  8233. minute += 60;
  8234. hour--;
  8235. }
  8236. while (hour < 0) {
  8237. hour += 24;
  8238. day--;
  8239. }
  8240. while (day < 1) {
  8241. month--;
  8242. if (month < 1) {
  8243. month += 12;
  8244. year--;
  8245. }
  8246. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  8247. day += tmp;
  8248. }
  8249. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  8250. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  8251. if (!defined.defined(result)) {
  8252. result = new JulianDate(components[0], components[1], TimeStandard$1.UTC);
  8253. } else {
  8254. setComponents(components[0], components[1], result);
  8255. convertUtcToTai(result);
  8256. }
  8257. //If we were on a leap second, add it back.
  8258. if (isLeapSecond) {
  8259. JulianDate.addSeconds(result, 1, result);
  8260. }
  8261. return result;
  8262. };
  8263. /**
  8264. * Creates a new instance that represents the current system time.
  8265. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  8266. *
  8267. * @param {JulianDate} [result] An existing instance to use for the result.
  8268. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8269. */
  8270. JulianDate.now = function(result) {
  8271. return JulianDate.fromDate(new Date(), result);
  8272. };
  8273. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard$1.TAI);
  8274. /**
  8275. * Creates a {@link GregorianDate} from the provided instance.
  8276. *
  8277. * @param {JulianDate} julianDate The date to be converted.
  8278. * @param {GregorianDate} [result] An existing instance to use for the result.
  8279. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  8280. */
  8281. JulianDate.toGregorianDate = function(julianDate, result) {
  8282. //>>includeStart('debug', pragmas.debug);
  8283. if (!defined.defined(julianDate)) {
  8284. throw new Check.DeveloperError('julianDate is required.');
  8285. }
  8286. //>>includeEnd('debug');
  8287. var isLeapSecond = false;
  8288. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  8289. if (!defined.defined(thisUtc)) {
  8290. //Conversion to UTC will fail if we are during a leap second.
  8291. //If that's the case, subtract a second and convert again.
  8292. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  8293. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  8294. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  8295. isLeapSecond = true;
  8296. }
  8297. var julianDayNumber = thisUtc.dayNumber;
  8298. var secondsOfDay = thisUtc.secondsOfDay;
  8299. if (secondsOfDay >= 43200.0) {
  8300. julianDayNumber += 1;
  8301. }
  8302. // Algorithm from page 604 of the Explanatory Supplement to the
  8303. // Astronomical Almanac (Seidelmann 1992).
  8304. var L = (julianDayNumber + 68569) | 0;
  8305. var N = (4 * L / 146097) | 0;
  8306. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  8307. var I = ((4000 * (L + 1)) / 1461001) | 0;
  8308. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  8309. var J = ((80 * L) / 2447) | 0;
  8310. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  8311. L = (J / 11) | 0;
  8312. var month = (J + 2 - 12 * L) | 0;
  8313. var year = (100 * (N - 49) + I + L) | 0;
  8314. var hour = (secondsOfDay / TimeConstants$1.SECONDS_PER_HOUR) | 0;
  8315. var remainingSeconds = secondsOfDay - (hour * TimeConstants$1.SECONDS_PER_HOUR);
  8316. var minute = (remainingSeconds / TimeConstants$1.SECONDS_PER_MINUTE) | 0;
  8317. remainingSeconds = remainingSeconds - (minute * TimeConstants$1.SECONDS_PER_MINUTE);
  8318. var second = remainingSeconds | 0;
  8319. var millisecond = ((remainingSeconds - second) / TimeConstants$1.SECONDS_PER_MILLISECOND);
  8320. // JulianDates are noon-based
  8321. hour += 12;
  8322. if (hour > 23) {
  8323. hour -= 24;
  8324. }
  8325. //If we were on a leap second, add it back.
  8326. if (isLeapSecond) {
  8327. second += 1;
  8328. }
  8329. if (!defined.defined(result)) {
  8330. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  8331. }
  8332. result.year = year;
  8333. result.month = month;
  8334. result.day = day;
  8335. result.hour = hour;
  8336. result.minute = minute;
  8337. result.second = second;
  8338. result.millisecond = millisecond;
  8339. result.isLeapSecond = isLeapSecond;
  8340. return result;
  8341. };
  8342. /**
  8343. * Creates a JavaScript Date from the provided instance.
  8344. * Since JavaScript dates are only accurate to the nearest millisecond and
  8345. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  8346. * If the provided JulianDate is during a leap second, the previous second is used.
  8347. *
  8348. * @param {JulianDate} julianDate The date to be converted.
  8349. * @returns {Date} A new instance representing the provided date.
  8350. */
  8351. JulianDate.toDate = function(julianDate) {
  8352. //>>includeStart('debug', pragmas.debug);
  8353. if (!defined.defined(julianDate)) {
  8354. throw new Check.DeveloperError('julianDate is required.');
  8355. }
  8356. //>>includeEnd('debug');
  8357. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  8358. var second = gDate.second;
  8359. if (gDate.isLeapSecond) {
  8360. second -= 1;
  8361. }
  8362. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  8363. };
  8364. /**
  8365. * Creates an ISO8601 representation of the provided date.
  8366. *
  8367. * @param {JulianDate} julianDate The date to be converted.
  8368. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  8369. * @returns {String} The ISO8601 representation of the provided date.
  8370. */
  8371. JulianDate.toIso8601 = function(julianDate, precision) {
  8372. //>>includeStart('debug', pragmas.debug);
  8373. if (!defined.defined(julianDate)) {
  8374. throw new Check.DeveloperError('julianDate is required.');
  8375. }
  8376. //>>includeEnd('debug');
  8377. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  8378. var year = gDate.year;
  8379. var month = gDate.month;
  8380. var day = gDate.day;
  8381. var hour = gDate.hour;
  8382. var minute = gDate.minute;
  8383. var second = gDate.second;
  8384. var millisecond = gDate.millisecond;
  8385. // special case - Iso8601.MAXIMUM_VALUE produces a string which we can't parse unless we adjust.
  8386. // 10000-01-01T00:00:00 is the same instant as 9999-12-31T24:00:00
  8387. if (year === 10000 && month === 1 && day === 1 && hour === 0 && minute === 0 && second === 0 && millisecond === 0) {
  8388. year = 9999;
  8389. month = 12;
  8390. day = 31;
  8391. hour = 24;
  8392. }
  8393. var millisecondStr;
  8394. if (!defined.defined(precision) && millisecond !== 0) {
  8395. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  8396. millisecondStr = (millisecond * 0.01).toString().replace('.', '');
  8397. return sprintf('%04d-%02d-%02dT%02d:%02d:%02d.%sZ', year, month, day, hour, minute, second, millisecondStr);
  8398. }
  8399. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  8400. if (!defined.defined(precision) || precision === 0) {
  8401. return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ', year, month, day, hour, minute, second);
  8402. }
  8403. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  8404. millisecondStr = (millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  8405. return sprintf('%04d-%02d-%02dT%02d:%02d:%02d.%sZ', year, month, day, hour, minute, second, millisecondStr);
  8406. };
  8407. /**
  8408. * Duplicates a JulianDate instance.
  8409. *
  8410. * @param {JulianDate} julianDate The date to duplicate.
  8411. * @param {JulianDate} [result] An existing instance to use for the result.
  8412. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  8413. */
  8414. JulianDate.clone = function(julianDate, result) {
  8415. if (!defined.defined(julianDate)) {
  8416. return undefined;
  8417. }
  8418. if (!defined.defined(result)) {
  8419. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard$1.TAI);
  8420. }
  8421. result.dayNumber = julianDate.dayNumber;
  8422. result.secondsOfDay = julianDate.secondsOfDay;
  8423. return result;
  8424. };
  8425. /**
  8426. * Compares two instances.
  8427. *
  8428. * @param {JulianDate} left The first instance.
  8429. * @param {JulianDate} right The second instance.
  8430. * @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.
  8431. */
  8432. JulianDate.compare = function(left, right) {
  8433. //>>includeStart('debug', pragmas.debug);
  8434. if (!defined.defined(left)) {
  8435. throw new Check.DeveloperError('left is required.');
  8436. }
  8437. if (!defined.defined(right)) {
  8438. throw new Check.DeveloperError('right is required.');
  8439. }
  8440. //>>includeEnd('debug');
  8441. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  8442. if (julianDayNumberDifference !== 0) {
  8443. return julianDayNumberDifference;
  8444. }
  8445. return left.secondsOfDay - right.secondsOfDay;
  8446. };
  8447. /**
  8448. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  8449. *
  8450. * @param {JulianDate} [left] The first instance.
  8451. * @param {JulianDate} [right] The second instance.
  8452. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  8453. */
  8454. JulianDate.equals = function(left, right) {
  8455. return (left === right) ||
  8456. (defined.defined(left) &&
  8457. defined.defined(right) &&
  8458. left.dayNumber === right.dayNumber &&
  8459. left.secondsOfDay === right.secondsOfDay);
  8460. };
  8461. /**
  8462. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  8463. * each other. That is, in order for the dates to be considered equal (and for
  8464. * this function to return <code>true</code>), the absolute value of the difference between them, in
  8465. * seconds, must be less than <code>epsilon</code>.
  8466. *
  8467. * @param {JulianDate} [left] The first instance.
  8468. * @param {JulianDate} [right] The second instance.
  8469. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  8470. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  8471. */
  8472. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  8473. //>>includeStart('debug', pragmas.debug);
  8474. if (!defined.defined(epsilon)) {
  8475. throw new Check.DeveloperError('epsilon is required.');
  8476. }
  8477. //>>includeEnd('debug');
  8478. return (left === right) ||
  8479. (defined.defined(left) &&
  8480. defined.defined(right) &&
  8481. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  8482. };
  8483. /**
  8484. * Computes the total number of whole and fractional days represented by the provided instance.
  8485. *
  8486. * @param {JulianDate} julianDate The date.
  8487. * @returns {Number} The Julian date as single floating point number.
  8488. */
  8489. JulianDate.totalDays = function(julianDate) {
  8490. //>>includeStart('debug', pragmas.debug);
  8491. if (!defined.defined(julianDate)) {
  8492. throw new Check.DeveloperError('julianDate is required.');
  8493. }
  8494. //>>includeEnd('debug');
  8495. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants$1.SECONDS_PER_DAY);
  8496. };
  8497. /**
  8498. * Computes the difference in seconds between the provided instance.
  8499. *
  8500. * @param {JulianDate} left The first instance.
  8501. * @param {JulianDate} right The second instance.
  8502. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  8503. */
  8504. JulianDate.secondsDifference = function(left, right) {
  8505. //>>includeStart('debug', pragmas.debug);
  8506. if (!defined.defined(left)) {
  8507. throw new Check.DeveloperError('left is required.');
  8508. }
  8509. if (!defined.defined(right)) {
  8510. throw new Check.DeveloperError('right is required.');
  8511. }
  8512. //>>includeEnd('debug');
  8513. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants$1.SECONDS_PER_DAY;
  8514. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  8515. };
  8516. /**
  8517. * Computes the difference in days between the provided instance.
  8518. *
  8519. * @param {JulianDate} left The first instance.
  8520. * @param {JulianDate} right The second instance.
  8521. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  8522. */
  8523. JulianDate.daysDifference = function(left, right) {
  8524. //>>includeStart('debug', pragmas.debug);
  8525. if (!defined.defined(left)) {
  8526. throw new Check.DeveloperError('left is required.');
  8527. }
  8528. if (!defined.defined(right)) {
  8529. throw new Check.DeveloperError('right is required.');
  8530. }
  8531. //>>includeEnd('debug');
  8532. var dayDifference = (left.dayNumber - right.dayNumber);
  8533. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants$1.SECONDS_PER_DAY;
  8534. return dayDifference + secondDifference;
  8535. };
  8536. /**
  8537. * Computes the number of seconds the provided instance is ahead of UTC.
  8538. *
  8539. * @param {JulianDate} julianDate The date.
  8540. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  8541. */
  8542. JulianDate.computeTaiMinusUtc = function(julianDate) {
  8543. binarySearchScratchLeapSecond.julianDate = julianDate;
  8544. var leapSeconds = JulianDate.leapSeconds;
  8545. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  8546. if (index < 0) {
  8547. index = ~index;
  8548. --index;
  8549. if (index < 0) {
  8550. index = 0;
  8551. }
  8552. }
  8553. return leapSeconds[index].offset;
  8554. };
  8555. /**
  8556. * Adds the provided number of seconds to the provided date instance.
  8557. *
  8558. * @param {JulianDate} julianDate The date.
  8559. * @param {Number} seconds The number of seconds to add or subtract.
  8560. * @param {JulianDate} result An existing instance to use for the result.
  8561. * @returns {JulianDate} The modified result parameter.
  8562. */
  8563. JulianDate.addSeconds = function(julianDate, seconds, result) {
  8564. //>>includeStart('debug', pragmas.debug);
  8565. if (!defined.defined(julianDate)) {
  8566. throw new Check.DeveloperError('julianDate is required.');
  8567. }
  8568. if (!defined.defined(seconds)) {
  8569. throw new Check.DeveloperError('seconds is required.');
  8570. }
  8571. if (!defined.defined(result)) {
  8572. throw new Check.DeveloperError('result is required.');
  8573. }
  8574. //>>includeEnd('debug');
  8575. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  8576. };
  8577. /**
  8578. * Adds the provided number of minutes to the provided date instance.
  8579. *
  8580. * @param {JulianDate} julianDate The date.
  8581. * @param {Number} minutes The number of minutes to add or subtract.
  8582. * @param {JulianDate} result An existing instance to use for the result.
  8583. * @returns {JulianDate} The modified result parameter.
  8584. */
  8585. JulianDate.addMinutes = function(julianDate, minutes, result) {
  8586. //>>includeStart('debug', pragmas.debug);
  8587. if (!defined.defined(julianDate)) {
  8588. throw new Check.DeveloperError('julianDate is required.');
  8589. }
  8590. if (!defined.defined(minutes)) {
  8591. throw new Check.DeveloperError('minutes is required.');
  8592. }
  8593. if (!defined.defined(result)) {
  8594. throw new Check.DeveloperError('result is required.');
  8595. }
  8596. //>>includeEnd('debug');
  8597. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants$1.SECONDS_PER_MINUTE);
  8598. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  8599. };
  8600. /**
  8601. * Adds the provided number of hours to the provided date instance.
  8602. *
  8603. * @param {JulianDate} julianDate The date.
  8604. * @param {Number} hours The number of hours to add or subtract.
  8605. * @param {JulianDate} result An existing instance to use for the result.
  8606. * @returns {JulianDate} The modified result parameter.
  8607. */
  8608. JulianDate.addHours = function(julianDate, hours, result) {
  8609. //>>includeStart('debug', pragmas.debug);
  8610. if (!defined.defined(julianDate)) {
  8611. throw new Check.DeveloperError('julianDate is required.');
  8612. }
  8613. if (!defined.defined(hours)) {
  8614. throw new Check.DeveloperError('hours is required.');
  8615. }
  8616. if (!defined.defined(result)) {
  8617. throw new Check.DeveloperError('result is required.');
  8618. }
  8619. //>>includeEnd('debug');
  8620. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants$1.SECONDS_PER_HOUR);
  8621. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  8622. };
  8623. /**
  8624. * Adds the provided number of days to the provided date instance.
  8625. *
  8626. * @param {JulianDate} julianDate The date.
  8627. * @param {Number} days The number of days to add or subtract.
  8628. * @param {JulianDate} result An existing instance to use for the result.
  8629. * @returns {JulianDate} The modified result parameter.
  8630. */
  8631. JulianDate.addDays = function(julianDate, days, result) {
  8632. //>>includeStart('debug', pragmas.debug);
  8633. if (!defined.defined(julianDate)) {
  8634. throw new Check.DeveloperError('julianDate is required.');
  8635. }
  8636. if (!defined.defined(days)) {
  8637. throw new Check.DeveloperError('days is required.');
  8638. }
  8639. if (!defined.defined(result)) {
  8640. throw new Check.DeveloperError('result is required.');
  8641. }
  8642. //>>includeEnd('debug');
  8643. var newJulianDayNumber = julianDate.dayNumber + days;
  8644. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  8645. };
  8646. /**
  8647. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  8648. *
  8649. * @param {JulianDate} left The first instance.
  8650. * @param {JulianDate} right The second instance.
  8651. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  8652. */
  8653. JulianDate.lessThan = function(left, right) {
  8654. return JulianDate.compare(left, right) < 0;
  8655. };
  8656. /**
  8657. * 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.
  8658. *
  8659. * @param {JulianDate} left The first instance.
  8660. * @param {JulianDate} right The second instance.
  8661. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  8662. */
  8663. JulianDate.lessThanOrEquals = function(left, right) {
  8664. return JulianDate.compare(left, right) <= 0;
  8665. };
  8666. /**
  8667. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  8668. *
  8669. * @param {JulianDate} left The first instance.
  8670. * @param {JulianDate} right The second instance.
  8671. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  8672. */
  8673. JulianDate.greaterThan = function(left, right) {
  8674. return JulianDate.compare(left, right) > 0;
  8675. };
  8676. /**
  8677. * 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.
  8678. *
  8679. * @param {JulianDate} left The first instance.
  8680. * @param {JulianDate} right The second instance.
  8681. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  8682. */
  8683. JulianDate.greaterThanOrEquals = function(left, right) {
  8684. return JulianDate.compare(left, right) >= 0;
  8685. };
  8686. /**
  8687. * Duplicates this instance.
  8688. *
  8689. * @param {JulianDate} [result] An existing instance to use for the result.
  8690. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  8691. */
  8692. JulianDate.prototype.clone = function(result) {
  8693. return JulianDate.clone(this, result);
  8694. };
  8695. /**
  8696. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  8697. *
  8698. * @param {JulianDate} [right] The second instance.
  8699. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  8700. */
  8701. JulianDate.prototype.equals = function(right) {
  8702. return JulianDate.equals(this, right);
  8703. };
  8704. /**
  8705. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  8706. * each other. That is, in order for the dates to be considered equal (and for
  8707. * this function to return <code>true</code>), the absolute value of the difference between them, in
  8708. * seconds, must be less than <code>epsilon</code>.
  8709. *
  8710. * @param {JulianDate} [right] The second instance.
  8711. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  8712. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  8713. */
  8714. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  8715. return JulianDate.equalsEpsilon(this, right, epsilon);
  8716. };
  8717. /**
  8718. * Creates a string representing this date in ISO8601 format.
  8719. *
  8720. * @returns {String} A string representing this date in ISO8601 format.
  8721. */
  8722. JulianDate.prototype.toString = function() {
  8723. return JulianDate.toIso8601(this);
  8724. };
  8725. /**
  8726. * Gets or sets the list of leap seconds used throughout Cesium.
  8727. * @memberof JulianDate
  8728. * @type {LeapSecond[]}
  8729. */
  8730. JulianDate.leapSeconds = [
  8731. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard$1.TAI), 10), // January 1, 1972 00:00:00 UTC
  8732. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard$1.TAI), 11), // July 1, 1972 00:00:00 UTC
  8733. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard$1.TAI), 12), // January 1, 1973 00:00:00 UTC
  8734. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard$1.TAI), 13), // January 1, 1974 00:00:00 UTC
  8735. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard$1.TAI), 14), // January 1, 1975 00:00:00 UTC
  8736. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard$1.TAI), 15), // January 1, 1976 00:00:00 UTC
  8737. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard$1.TAI), 16), // January 1, 1977 00:00:00 UTC
  8738. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard$1.TAI), 17), // January 1, 1978 00:00:00 UTC
  8739. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard$1.TAI), 18), // January 1, 1979 00:00:00 UTC
  8740. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard$1.TAI), 19), // January 1, 1980 00:00:00 UTC
  8741. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard$1.TAI), 20), // July 1, 1981 00:00:00 UTC
  8742. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard$1.TAI), 21), // July 1, 1982 00:00:00 UTC
  8743. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard$1.TAI), 22), // July 1, 1983 00:00:00 UTC
  8744. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard$1.TAI), 23), // July 1, 1985 00:00:00 UTC
  8745. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard$1.TAI), 24), // January 1, 1988 00:00:00 UTC
  8746. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard$1.TAI), 25), // January 1, 1990 00:00:00 UTC
  8747. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard$1.TAI), 26), // January 1, 1991 00:00:00 UTC
  8748. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard$1.TAI), 27), // July 1, 1992 00:00:00 UTC
  8749. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard$1.TAI), 28), // July 1, 1993 00:00:00 UTC
  8750. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard$1.TAI), 29), // July 1, 1994 00:00:00 UTC
  8751. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard$1.TAI), 30), // January 1, 1996 00:00:00 UTC
  8752. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard$1.TAI), 31), // July 1, 1997 00:00:00 UTC
  8753. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard$1.TAI), 32), // January 1, 1999 00:00:00 UTC
  8754. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard$1.TAI), 33), // January 1, 2006 00:00:00 UTC
  8755. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard$1.TAI), 34), // January 1, 2009 00:00:00 UTC
  8756. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard$1.TAI), 35), // July 1, 2012 00:00:00 UTC
  8757. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard$1.TAI), 36), // July 1, 2015 00:00:00 UTC
  8758. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard$1.TAI), 37) // January 1, 2017 00:00:00 UTC
  8759. ];
  8760. /**
  8761. * @license
  8762. *
  8763. * Grauw URI utilities
  8764. *
  8765. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  8766. *
  8767. * @author Laurens Holst (http://www.grauw.nl/)
  8768. *
  8769. * Copyright 2012 Laurens Holst
  8770. *
  8771. * Licensed under the Apache License, Version 2.0 (the "License");
  8772. * you may not use this file except in compliance with the License.
  8773. * You may obtain a copy of the License at
  8774. *
  8775. * http://www.apache.org/licenses/LICENSE-2.0
  8776. *
  8777. * Unless required by applicable law or agreed to in writing, software
  8778. * distributed under the License is distributed on an "AS IS" BASIS,
  8779. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8780. * See the License for the specific language governing permissions and
  8781. * limitations under the License.
  8782. *
  8783. */
  8784. /**
  8785. * Constructs a URI object.
  8786. * @constructor
  8787. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  8788. * @param {string|URI} uri A string or URI object to create the object from.
  8789. */
  8790. function URI(uri) {
  8791. if (uri instanceof URI) { // copy constructor
  8792. this.scheme = uri.scheme;
  8793. this.authority = uri.authority;
  8794. this.path = uri.path;
  8795. this.query = uri.query;
  8796. this.fragment = uri.fragment;
  8797. } else if (uri) { // uri is URI string or cast to string
  8798. var c = parseRegex.exec(uri);
  8799. this.scheme = c[1];
  8800. this.authority = c[2];
  8801. this.path = c[3];
  8802. this.query = c[4];
  8803. this.fragment = c[5];
  8804. }
  8805. }
  8806. // Initial values on the prototype
  8807. URI.prototype.scheme = null;
  8808. URI.prototype.authority = null;
  8809. URI.prototype.path = '';
  8810. URI.prototype.query = null;
  8811. URI.prototype.fragment = null;
  8812. // Regular expression from RFC 3986 appendix B
  8813. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  8814. /**
  8815. * Returns the scheme part of the URI.
  8816. * In "http://example.com:80/a/b?x#y" this is "http".
  8817. */
  8818. URI.prototype.getScheme = function() {
  8819. return this.scheme;
  8820. };
  8821. /**
  8822. * Returns the authority part of the URI.
  8823. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  8824. */
  8825. URI.prototype.getAuthority = function() {
  8826. return this.authority;
  8827. };
  8828. /**
  8829. * Returns the path part of the URI.
  8830. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  8831. * In "mailto:mike@example.com" this is "mike@example.com".
  8832. */
  8833. URI.prototype.getPath = function() {
  8834. return this.path;
  8835. };
  8836. /**
  8837. * Returns the query part of the URI.
  8838. * In "http://example.com:80/a/b?x#y" this is "x".
  8839. */
  8840. URI.prototype.getQuery = function() {
  8841. return this.query;
  8842. };
  8843. /**
  8844. * Returns the fragment part of the URI.
  8845. * In "http://example.com:80/a/b?x#y" this is "y".
  8846. */
  8847. URI.prototype.getFragment = function() {
  8848. return this.fragment;
  8849. };
  8850. /**
  8851. * Tests whether the URI is an absolute URI.
  8852. * See RFC 3986 section 4.3.
  8853. */
  8854. URI.prototype.isAbsolute = function() {
  8855. return !!this.scheme && !this.fragment;
  8856. };
  8857. ///**
  8858. //* Extensive validation of the URI against the ABNF in RFC 3986
  8859. //*/
  8860. //URI.prototype.validate
  8861. /**
  8862. * Tests whether the URI is a same-document reference.
  8863. * See RFC 3986 section 4.4.
  8864. *
  8865. * To perform more thorough comparison, you can normalise the URI objects.
  8866. */
  8867. URI.prototype.isSameDocumentAs = function(uri) {
  8868. return uri.scheme == this.scheme &&
  8869. uri.authority == this.authority &&
  8870. uri.path == this.path &&
  8871. uri.query == this.query;
  8872. };
  8873. /**
  8874. * Simple String Comparison of two URIs.
  8875. * See RFC 3986 section 6.2.1.
  8876. *
  8877. * To perform more thorough comparison, you can normalise the URI objects.
  8878. */
  8879. URI.prototype.equals = function(uri) {
  8880. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  8881. };
  8882. /**
  8883. * Normalizes the URI using syntax-based normalization.
  8884. * This includes case normalization, percent-encoding normalization and path segment normalization.
  8885. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  8886. * (Although that would not be a valid URI in the first place. See validate().)
  8887. * See RFC 3986 section 6.2.2.
  8888. */
  8889. URI.prototype.normalize = function() {
  8890. this.removeDotSegments();
  8891. if (this.scheme)
  8892. this.scheme = this.scheme.toLowerCase();
  8893. if (this.authority)
  8894. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  8895. replace(caseRegex, replaceCase);
  8896. if (this.path)
  8897. this.path = this.path.replace(caseRegex, replaceCase);
  8898. if (this.query)
  8899. this.query = this.query.replace(caseRegex, replaceCase);
  8900. if (this.fragment)
  8901. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  8902. };
  8903. var caseRegex = /%[0-9a-z]{2}/gi;
  8904. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  8905. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  8906. function replaceCase(str) {
  8907. var dec = unescape(str);
  8908. return percentRegex.test(dec) ? dec : str.toUpperCase();
  8909. }
  8910. function replaceAuthority(str, p1, p2, p3) {
  8911. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  8912. }
  8913. /**
  8914. * Resolve a relative URI (this) against a base URI.
  8915. * The base URI must be an absolute URI.
  8916. * See RFC 3986 section 5.2
  8917. */
  8918. URI.prototype.resolve = function(baseURI) {
  8919. var uri = new URI();
  8920. if (this.scheme) {
  8921. uri.scheme = this.scheme;
  8922. uri.authority = this.authority;
  8923. uri.path = this.path;
  8924. uri.query = this.query;
  8925. } else {
  8926. uri.scheme = baseURI.scheme;
  8927. if (this.authority) {
  8928. uri.authority = this.authority;
  8929. uri.path = this.path;
  8930. uri.query = this.query;
  8931. } else {
  8932. uri.authority = baseURI.authority;
  8933. if (this.path == '') {
  8934. uri.path = baseURI.path;
  8935. uri.query = this.query || baseURI.query;
  8936. } else {
  8937. if (this.path.charAt(0) == '/') {
  8938. uri.path = this.path;
  8939. uri.removeDotSegments();
  8940. } else {
  8941. if (baseURI.authority && baseURI.path == '') {
  8942. uri.path = '/' + this.path;
  8943. } else {
  8944. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  8945. }
  8946. uri.removeDotSegments();
  8947. }
  8948. uri.query = this.query;
  8949. }
  8950. }
  8951. }
  8952. uri.fragment = this.fragment;
  8953. return uri;
  8954. };
  8955. /**
  8956. * Remove dot segments from path.
  8957. * See RFC 3986 section 5.2.4
  8958. * @private
  8959. */
  8960. URI.prototype.removeDotSegments = function() {
  8961. var input = this.path.split('/'),
  8962. output = [],
  8963. segment,
  8964. absPath = input[0] == '';
  8965. if (absPath)
  8966. input.shift();
  8967. var sFirst = input[0] == '' ? input.shift() : null;
  8968. while (input.length) {
  8969. segment = input.shift();
  8970. if (segment == '..') {
  8971. output.pop();
  8972. } else if (segment != '.') {
  8973. output.push(segment);
  8974. }
  8975. }
  8976. if (segment == '.' || segment == '..')
  8977. output.push('');
  8978. if (absPath)
  8979. output.unshift('');
  8980. this.path = output.join('/');
  8981. };
  8982. // We don't like this function because it builds up a cache that is never cleared.
  8983. // /**
  8984. // * Resolves a relative URI against an absolute base URI.
  8985. // * Convenience method.
  8986. // * @param {String} uri the relative URI to resolve
  8987. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  8988. // */
  8989. // URI.resolve = function(sURI, sBaseURI) {
  8990. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  8991. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  8992. // return uri.resolve(baseURI).toString();
  8993. // };
  8994. // var cache = {};
  8995. /**
  8996. * Serialises the URI to a string.
  8997. */
  8998. URI.prototype.toString = function() {
  8999. var result = '';
  9000. if (this.scheme)
  9001. result += this.scheme + ':';
  9002. if (this.authority)
  9003. result += '//' + this.authority;
  9004. result += this.path;
  9005. if (this.query)
  9006. result += '?' + this.query;
  9007. if (this.fragment)
  9008. result += '#' + this.fragment;
  9009. return result;
  9010. };
  9011. /**
  9012. * @private
  9013. */
  9014. function appendForwardSlash(url) {
  9015. if (url.length === 0 || url[url.length - 1] !== '/') {
  9016. url = url + '/';
  9017. }
  9018. return url;
  9019. }
  9020. /**
  9021. * Clones an object, returning a new object containing the same properties.
  9022. *
  9023. * @exports clone
  9024. *
  9025. * @param {Object} object The object to clone.
  9026. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  9027. * @returns {Object} The cloned object.
  9028. */
  9029. function clone(object, deep) {
  9030. if (object === null || typeof object !== 'object') {
  9031. return object;
  9032. }
  9033. deep = defaultValue.defaultValue(deep, false);
  9034. var result = new object.constructor();
  9035. for ( var propertyName in object) {
  9036. if (object.hasOwnProperty(propertyName)) {
  9037. var value = object[propertyName];
  9038. if (deep) {
  9039. value = clone(value, deep);
  9040. }
  9041. result[propertyName] = value;
  9042. }
  9043. }
  9044. return result;
  9045. }
  9046. /**
  9047. * Merges two objects, copying their properties onto a new combined object. When two objects have the same
  9048. * property, the value of the property on the first object is used. If either object is undefined,
  9049. * it will be treated as an empty object.
  9050. *
  9051. * @example
  9052. * var object1 = {
  9053. * propOne : 1,
  9054. * propTwo : {
  9055. * value1 : 10
  9056. * }
  9057. * }
  9058. * var object2 = {
  9059. * propTwo : 2
  9060. * }
  9061. * var final = Cesium.combine(object1, object2);
  9062. *
  9063. * // final === {
  9064. * // propOne : 1,
  9065. * // propTwo : {
  9066. * // value1 : 10
  9067. * // }
  9068. * // }
  9069. *
  9070. * @param {Object} [object1] The first object to merge.
  9071. * @param {Object} [object2] The second object to merge.
  9072. * @param {Boolean} [deep=false] Perform a recursive merge.
  9073. * @returns {Object} The combined object containing all properties from both objects.
  9074. *
  9075. * @exports combine
  9076. */
  9077. function combine(object1, object2, deep) {
  9078. deep = defaultValue.defaultValue(deep, false);
  9079. var result = {};
  9080. var object1Defined = defined.defined(object1);
  9081. var object2Defined = defined.defined(object2);
  9082. var property;
  9083. var object1Value;
  9084. var object2Value;
  9085. if (object1Defined) {
  9086. for (property in object1) {
  9087. if (object1.hasOwnProperty(property)) {
  9088. object1Value = object1[property];
  9089. if (object2Defined && deep && typeof object1Value === 'object' && object2.hasOwnProperty(property)) {
  9090. object2Value = object2[property];
  9091. if (typeof object2Value === 'object') {
  9092. result[property] = combine(object1Value, object2Value, deep);
  9093. } else {
  9094. result[property] = object1Value;
  9095. }
  9096. } else {
  9097. result[property] = object1Value;
  9098. }
  9099. }
  9100. }
  9101. }
  9102. if (object2Defined) {
  9103. for (property in object2) {
  9104. if (object2.hasOwnProperty(property) && !result.hasOwnProperty(property)) {
  9105. object2Value = object2[property];
  9106. result[property] = object2Value;
  9107. }
  9108. }
  9109. }
  9110. return result;
  9111. }
  9112. /**
  9113. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  9114. * @exports getAbsoluteUri
  9115. *
  9116. * @param {String} relative The relative Uri.
  9117. * @param {String} [base] The base Uri.
  9118. * @returns {String} The absolute Uri of the given relative Uri.
  9119. *
  9120. * @example
  9121. * //absolute Uri will be "https://test.com/awesome.png";
  9122. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  9123. */
  9124. function getAbsoluteUri(relative, base) {
  9125. var documentObject;
  9126. if (typeof document !== 'undefined') {
  9127. documentObject = document;
  9128. }
  9129. return getAbsoluteUri._implementation(relative, base, documentObject);
  9130. }
  9131. getAbsoluteUri._implementation = function(relative, base, documentObject) {
  9132. //>>includeStart('debug', pragmas.debug);
  9133. if (!defined.defined(relative)) {
  9134. throw new Check.DeveloperError('relative uri is required.');
  9135. }
  9136. //>>includeEnd('debug');
  9137. if (!defined.defined(base)) {
  9138. if (typeof documentObject === 'undefined') {
  9139. return relative;
  9140. }
  9141. base = defaultValue.defaultValue(documentObject.baseURI, documentObject.location.href);
  9142. }
  9143. var baseUri = new URI(base);
  9144. var relativeUri = new URI(relative);
  9145. return relativeUri.resolve(baseUri).toString();
  9146. };
  9147. /**
  9148. * Given a URI, returns the base path of the URI.
  9149. * @exports getBaseUri
  9150. *
  9151. * @param {String} uri The Uri.
  9152. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  9153. * @returns {String} The base path of the Uri.
  9154. *
  9155. * @example
  9156. * // basePath will be "/Gallery/";
  9157. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
  9158. *
  9159. * // basePath will be "/Gallery/?value=true&example=false";
  9160. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
  9161. */
  9162. function getBaseUri(uri, includeQuery) {
  9163. //>>includeStart('debug', pragmas.debug);
  9164. if (!defined.defined(uri)) {
  9165. throw new Check.DeveloperError('uri is required.');
  9166. }
  9167. //>>includeEnd('debug');
  9168. var basePath = '';
  9169. var i = uri.lastIndexOf('/');
  9170. if (i !== -1) {
  9171. basePath = uri.substring(0, i + 1);
  9172. }
  9173. if (!includeQuery) {
  9174. return basePath;
  9175. }
  9176. uri = new URI(uri);
  9177. if (defined.defined(uri.query)) {
  9178. basePath += '?' + uri.query;
  9179. }
  9180. if (defined.defined(uri.fragment)){
  9181. basePath += '#' + uri.fragment;
  9182. }
  9183. return basePath;
  9184. }
  9185. /**
  9186. * Given a URI, returns the extension of the URI.
  9187. * @exports getExtensionFromUri
  9188. *
  9189. * @param {String} uri The Uri.
  9190. * @returns {String} The extension of the Uri.
  9191. *
  9192. * @example
  9193. * //extension will be "czml";
  9194. * var extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
  9195. */
  9196. function getExtensionFromUri(uri) {
  9197. //>>includeStart('debug', pragmas.debug);
  9198. if (!defined.defined(uri)) {
  9199. throw new Check.DeveloperError('uri is required.');
  9200. }
  9201. //>>includeEnd('debug');
  9202. var uriObject = new URI(uri);
  9203. uriObject.normalize();
  9204. var path = uriObject.path;
  9205. var index = path.lastIndexOf('/');
  9206. if (index !== -1) {
  9207. path = path.substr(index + 1);
  9208. }
  9209. index = path.lastIndexOf('.');
  9210. if (index === -1) {
  9211. path = '';
  9212. } else {
  9213. path = path.substr(index + 1);
  9214. }
  9215. return path;
  9216. }
  9217. var blobUriRegex = /^blob:/i;
  9218. /**
  9219. * Determines if the specified uri is a blob uri.
  9220. *
  9221. * @exports isBlobUri
  9222. *
  9223. * @param {String} uri The uri to test.
  9224. * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
  9225. *
  9226. * @private
  9227. */
  9228. function isBlobUri(uri) {
  9229. //>>includeStart('debug', pragmas.debug);
  9230. Check.Check.typeOf.string('uri', uri);
  9231. //>>includeEnd('debug');
  9232. return blobUriRegex.test(uri);
  9233. }
  9234. var a;
  9235. /**
  9236. * Given a URL, determine whether that URL is considered cross-origin to the current page.
  9237. *
  9238. * @private
  9239. */
  9240. function isCrossOriginUrl(url) {
  9241. if (!defined.defined(a)) {
  9242. a = document.createElement('a');
  9243. }
  9244. // copy window location into the anchor to get consistent results
  9245. // when the port is default for the protocol (e.g. 80 for HTTP)
  9246. a.href = window.location.href;
  9247. // host includes both hostname and port if the port is not standard
  9248. var host = a.host;
  9249. var protocol = a.protocol;
  9250. a.href = url;
  9251. // IE only absolutizes href on get, not set
  9252. a.href = a.href; // eslint-disable-line no-self-assign
  9253. return protocol !== a.protocol || host !== a.host;
  9254. }
  9255. var dataUriRegex = /^data:/i;
  9256. /**
  9257. * Determines if the specified uri is a data uri.
  9258. *
  9259. * @exports isDataUri
  9260. *
  9261. * @param {String} uri The uri to test.
  9262. * @returns {Boolean} true when the uri is a data uri; otherwise, false.
  9263. *
  9264. * @private
  9265. */
  9266. function isDataUri(uri) {
  9267. //>>includeStart('debug', pragmas.debug);
  9268. Check.Check.typeOf.string('uri', uri);
  9269. //>>includeEnd('debug');
  9270. return dataUriRegex.test(uri);
  9271. }
  9272. /**
  9273. * @private
  9274. */
  9275. function loadAndExecuteScript(url) {
  9276. var deferred = when.when.defer();
  9277. var script = document.createElement('script');
  9278. script.async = true;
  9279. script.src = url;
  9280. var head = document.getElementsByTagName('head')[0];
  9281. script.onload = function() {
  9282. script.onload = undefined;
  9283. head.removeChild(script);
  9284. deferred.resolve();
  9285. };
  9286. script.onerror = function(e) {
  9287. deferred.reject(e);
  9288. };
  9289. head.appendChild(script);
  9290. return deferred.promise;
  9291. }
  9292. /**
  9293. * Tests an object to see if it is an array.
  9294. * @exports isArray
  9295. *
  9296. * @param {*} value The value to test.
  9297. * @returns {Boolean} true if the value is an array, false otherwise.
  9298. */
  9299. var isArray = Array.isArray;
  9300. if (!defined.defined(isArray)) {
  9301. isArray = function(value) {
  9302. return Object.prototype.toString.call(value) === '[object Array]';
  9303. };
  9304. }
  9305. var isArray$1 = isArray;
  9306. /**
  9307. * Converts an object representing a set of name/value pairs into a query string,
  9308. * with names and values encoded properly for use in a URL. Values that are arrays
  9309. * will produce multiple values with the same name.
  9310. * @exports objectToQuery
  9311. *
  9312. * @param {Object} obj The object containing data to encode.
  9313. * @returns {String} An encoded query string.
  9314. *
  9315. *
  9316. * @example
  9317. * var str = Cesium.objectToQuery({
  9318. * key1 : 'some value',
  9319. * key2 : 'a/b',
  9320. * key3 : ['x', 'y']
  9321. * });
  9322. *
  9323. * @see queryToObject
  9324. * // str will be:
  9325. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  9326. */
  9327. function objectToQuery(obj) {
  9328. //>>includeStart('debug', pragmas.debug);
  9329. if (!defined.defined(obj)) {
  9330. throw new Check.DeveloperError('obj is required.');
  9331. }
  9332. //>>includeEnd('debug');
  9333. var result = '';
  9334. for ( var propName in obj) {
  9335. if (obj.hasOwnProperty(propName)) {
  9336. var value = obj[propName];
  9337. var part = encodeURIComponent(propName) + '=';
  9338. if (isArray$1(value)) {
  9339. for (var i = 0, len = value.length; i < len; ++i) {
  9340. result += part + encodeURIComponent(value[i]) + '&';
  9341. }
  9342. } else {
  9343. result += part + encodeURIComponent(value) + '&';
  9344. }
  9345. }
  9346. }
  9347. // trim last &
  9348. result = result.slice(0, -1);
  9349. // This function used to replace %20 with + which is more compact and readable.
  9350. // However, some servers didn't properly handle + as a space.
  9351. // https://github.com/AnalyticalGraphicsInc/cesium/issues/2192
  9352. return result;
  9353. }
  9354. /**
  9355. * Parses a query string into an object, where the keys and values of the object are the
  9356. * name/value pairs from the query string, decoded. If a name appears multiple times,
  9357. * the value in the object will be an array of values.
  9358. * @exports queryToObject
  9359. *
  9360. * @param {String} queryString The query string.
  9361. * @returns {Object} An object containing the parameters parsed from the query string.
  9362. *
  9363. *
  9364. * @example
  9365. * var obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
  9366. * // obj will be:
  9367. * // {
  9368. * // key1 : 'some value',
  9369. * // key2 : 'a/b',
  9370. * // key3 : ['x', 'y']
  9371. * // }
  9372. *
  9373. * @see objectToQuery
  9374. */
  9375. function queryToObject(queryString) {
  9376. //>>includeStart('debug', pragmas.debug);
  9377. if (!defined.defined(queryString)) {
  9378. throw new Check.DeveloperError('queryString is required.');
  9379. }
  9380. //>>includeEnd('debug');
  9381. var result = {};
  9382. if (queryString === '') {
  9383. return result;
  9384. }
  9385. var parts = queryString.replace(/\+/g, '%20').split(/[&;]/);
  9386. for (var i = 0, len = parts.length; i < len; ++i) {
  9387. var subparts = parts[i].split('=');
  9388. var name = decodeURIComponent(subparts[0]);
  9389. var value = subparts[1];
  9390. if (defined.defined(value)) {
  9391. value = decodeURIComponent(value);
  9392. } else {
  9393. value = '';
  9394. }
  9395. var resultValue = result[name];
  9396. if (typeof resultValue === 'string') {
  9397. // expand the single value to an array
  9398. result[name] = [resultValue, value];
  9399. } else if (isArray$1(resultValue)) {
  9400. resultValue.push(value);
  9401. } else {
  9402. result[name] = value;
  9403. }
  9404. }
  9405. return result;
  9406. }
  9407. /**
  9408. * State of the request.
  9409. *
  9410. * @exports RequestState
  9411. */
  9412. var RequestState = {
  9413. /**
  9414. * Initial unissued state.
  9415. *
  9416. * @type Number
  9417. * @constant
  9418. */
  9419. UNISSUED : 0,
  9420. /**
  9421. * Issued but not yet active. Will become active when open slots are available.
  9422. *
  9423. * @type Number
  9424. * @constant
  9425. */
  9426. ISSUED : 1,
  9427. /**
  9428. * Actual http request has been sent.
  9429. *
  9430. * @type Number
  9431. * @constant
  9432. */
  9433. ACTIVE : 2,
  9434. /**
  9435. * Request completed successfully.
  9436. *
  9437. * @type Number
  9438. * @constant
  9439. */
  9440. RECEIVED : 3,
  9441. /**
  9442. * Request was cancelled, either explicitly or automatically because of low priority.
  9443. *
  9444. * @type Number
  9445. * @constant
  9446. */
  9447. CANCELLED : 4,
  9448. /**
  9449. * Request failed.
  9450. *
  9451. * @type Number
  9452. * @constant
  9453. */
  9454. FAILED : 5
  9455. };
  9456. var RequestState$1 = freezeObject.freezeObject(RequestState);
  9457. /**
  9458. * An enum identifying the type of request. Used for finer grained logging and priority sorting.
  9459. *
  9460. * @exports RequestType
  9461. */
  9462. var RequestType = {
  9463. /**
  9464. * Terrain request.
  9465. *
  9466. * @type Number
  9467. * @constant
  9468. */
  9469. TERRAIN : 0,
  9470. /**
  9471. * Imagery request.
  9472. *
  9473. * @type Number
  9474. * @constant
  9475. */
  9476. IMAGERY : 1,
  9477. /**
  9478. * 3D Tiles request.
  9479. *
  9480. * @type Number
  9481. * @constant
  9482. */
  9483. TILES3D : 2,
  9484. /**
  9485. * Other request.
  9486. *
  9487. * @type Number
  9488. * @constant
  9489. */
  9490. OTHER : 3
  9491. };
  9492. var RequestType$1 = freezeObject.freezeObject(RequestType);
  9493. /**
  9494. * Stores information for making a request. In general this does not need to be constructed directly.
  9495. *
  9496. * @alias Request
  9497. * @constructor
  9498. * @namespace
  9499. * @exports Request
  9500. * @param {Object} [options] An object with the following properties:
  9501. * @param {String} [options.url] The url to request.
  9502. * @param {Request~RequestCallback} [options.requestFunction] The function that makes the actual data request.
  9503. * @param {Request~CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
  9504. * @param {Request~PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
  9505. * @param {Number} [options.priority=0.0] The initial priority of the request.
  9506. * @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.
  9507. * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
  9508. * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
  9509. */
  9510. function Request(options) {
  9511. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  9512. var throttleByServer = defaultValue.defaultValue(options.throttleByServer, false);
  9513. var throttle = defaultValue.defaultValue(options.throttle, false);
  9514. /**
  9515. * The URL to request.
  9516. *
  9517. * @type {String}
  9518. */
  9519. this.url = options.url;
  9520. /**
  9521. * The function that makes the actual data request.
  9522. *
  9523. * @type {Request~RequestCallback}
  9524. */
  9525. this.requestFunction = options.requestFunction;
  9526. /**
  9527. * The function that is called when the request is cancelled.
  9528. *
  9529. * @type {Request~CancelCallback}
  9530. */
  9531. this.cancelFunction = options.cancelFunction;
  9532. /**
  9533. * The function that is called to update the request's priority, which occurs once per frame.
  9534. *
  9535. * @type {Request~PriorityCallback}
  9536. */
  9537. this.priorityFunction = options.priorityFunction;
  9538. /**
  9539. * Priority is a unit-less value where lower values represent higher priority.
  9540. * For world-based objects, this is usually the distance from the camera.
  9541. * A request that does not have a priority function defaults to a priority of 0.
  9542. *
  9543. * If priorityFunction is defined, this value is updated every frame with the result of that call.
  9544. *
  9545. * @type {Number}
  9546. * @default 0.0
  9547. */
  9548. this.priority = defaultValue.defaultValue(options.priority, 0.0);
  9549. /**
  9550. * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
  9551. * request will be throttled and sent based on priority.
  9552. *
  9553. * @type {Boolean}
  9554. * @readonly
  9555. *
  9556. * @default false
  9557. */
  9558. this.throttle = throttle;
  9559. /**
  9560. * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
  9561. * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
  9562. * to <code>true</code> is preferable for requests going through HTTP/1 servers.
  9563. *
  9564. * @type {Boolean}
  9565. * @readonly
  9566. *
  9567. * @default false
  9568. */
  9569. this.throttleByServer = throttleByServer;
  9570. /**
  9571. * Type of request.
  9572. *
  9573. * @type {RequestType}
  9574. * @readonly
  9575. *
  9576. * @default RequestType.OTHER
  9577. */
  9578. this.type = defaultValue.defaultValue(options.type, RequestType$1.OTHER);
  9579. /**
  9580. * A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
  9581. *
  9582. * @type {String}
  9583. *
  9584. * @private
  9585. */
  9586. this.serverKey = undefined;
  9587. /**
  9588. * The current state of the request.
  9589. *
  9590. * @type {RequestState}
  9591. * @readonly
  9592. */
  9593. this.state = RequestState$1.UNISSUED;
  9594. /**
  9595. * The requests's deferred promise.
  9596. *
  9597. * @type {Object}
  9598. *
  9599. * @private
  9600. */
  9601. this.deferred = undefined;
  9602. /**
  9603. * Whether the request was explicitly cancelled.
  9604. *
  9605. * @type {Boolean}
  9606. *
  9607. * @private
  9608. */
  9609. this.cancelled = false;
  9610. }
  9611. /**
  9612. * Mark the request as cancelled.
  9613. *
  9614. * @private
  9615. */
  9616. Request.prototype.cancel = function() {
  9617. this.cancelled = true;
  9618. };
  9619. /**
  9620. * Duplicates a Request instance.
  9621. *
  9622. * @param {Request} [result] The object onto which to store the result.
  9623. *
  9624. * @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
  9625. */
  9626. Request.prototype.clone = function(result) {
  9627. if (!defined.defined(result)) {
  9628. return new Request(this);
  9629. }
  9630. result.url = this.url;
  9631. result.requestFunction = this.requestFunction;
  9632. result.cancelFunction = this.cancelFunction;
  9633. result.priorityFunction = this.priorityFunction;
  9634. result.priority = this.priority;
  9635. result.throttle = this.throttle;
  9636. result.throttleByServer = this.throttleByServer;
  9637. result.type = this.type;
  9638. result.serverKey = this.serverKey;
  9639. // These get defaulted because the cloned request hasn't been issued
  9640. result.state = this.RequestState.UNISSUED;
  9641. result.deferred = undefined;
  9642. result.cancelled = false;
  9643. return result;
  9644. };
  9645. /**
  9646. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  9647. * a dictionary.
  9648. *
  9649. * @exports parseResponseHeaders
  9650. *
  9651. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  9652. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  9653. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  9654. * is that header's value.
  9655. *
  9656. * @private
  9657. */
  9658. function parseResponseHeaders(headerString) {
  9659. var headers = {};
  9660. if (!headerString) {
  9661. return headers;
  9662. }
  9663. var headerPairs = headerString.split('\u000d\u000a');
  9664. for (var i = 0; i < headerPairs.length; ++i) {
  9665. var headerPair = headerPairs[i];
  9666. // Can't use split() here because it does the wrong thing
  9667. // if the header value has the string ": " in it.
  9668. var index = headerPair.indexOf('\u003a\u0020');
  9669. if (index > 0) {
  9670. var key = headerPair.substring(0, index);
  9671. var val = headerPair.substring(index + 2);
  9672. headers[key] = val;
  9673. }
  9674. }
  9675. return headers;
  9676. }
  9677. /**
  9678. * An event that is raised when a request encounters an error.
  9679. *
  9680. * @constructor
  9681. * @alias RequestErrorEvent
  9682. *
  9683. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  9684. * @param {Object} [response] The response included along with the error.
  9685. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  9686. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  9687. */
  9688. function RequestErrorEvent(statusCode, response, responseHeaders) {
  9689. /**
  9690. * The HTTP error status code, such as 404. If the error does not have a particular
  9691. * HTTP code, this property will be undefined.
  9692. *
  9693. * @type {Number}
  9694. */
  9695. this.statusCode = statusCode;
  9696. /**
  9697. * The response included along with the error. If the error does not include a response,
  9698. * this property will be undefined.
  9699. *
  9700. * @type {Object}
  9701. */
  9702. this.response = response;
  9703. /**
  9704. * The headers included in the response, represented as an object literal of key/value pairs.
  9705. * If the error does not include any headers, this property will be undefined.
  9706. *
  9707. * @type {Object}
  9708. */
  9709. this.responseHeaders = responseHeaders;
  9710. if (typeof this.responseHeaders === 'string') {
  9711. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  9712. }
  9713. }
  9714. /**
  9715. * Creates a string representing this RequestErrorEvent.
  9716. * @memberof RequestErrorEvent
  9717. *
  9718. * @returns {String} A string representing the provided RequestErrorEvent.
  9719. */
  9720. RequestErrorEvent.prototype.toString = function() {
  9721. var str = 'Request has failed.';
  9722. if (defined.defined(this.statusCode)) {
  9723. str += ' Status Code: ' + this.statusCode;
  9724. }
  9725. return str;
  9726. };
  9727. /**
  9728. * A generic utility class for managing subscribers for a particular event.
  9729. * This class is usually instantiated inside of a container class and
  9730. * exposed as a property for others to subscribe to.
  9731. *
  9732. * @alias Event
  9733. * @constructor
  9734. * @example
  9735. * MyObject.prototype.myListener = function(arg1, arg2) {
  9736. * this.myArg1Copy = arg1;
  9737. * this.myArg2Copy = arg2;
  9738. * }
  9739. *
  9740. * var myObjectInstance = new MyObject();
  9741. * var evt = new Cesium.Event();
  9742. * evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
  9743. * evt.raiseEvent('1', '2');
  9744. * evt.removeEventListener(MyObject.prototype.myListener);
  9745. */
  9746. function Event() {
  9747. this._listeners = [];
  9748. this._scopes = [];
  9749. this._toRemove = [];
  9750. this._insideRaiseEvent = false;
  9751. }
  9752. defineProperties.defineProperties(Event.prototype, {
  9753. /**
  9754. * The number of listeners currently subscribed to the event.
  9755. * @memberof Event.prototype
  9756. * @type {Number}
  9757. * @readonly
  9758. */
  9759. numberOfListeners : {
  9760. get : function() {
  9761. return this._listeners.length - this._toRemove.length;
  9762. }
  9763. }
  9764. });
  9765. /**
  9766. * Registers a callback function to be executed whenever the event is raised.
  9767. * An optional scope can be provided to serve as the <code>this</code> pointer
  9768. * in which the function will execute.
  9769. *
  9770. * @param {Function} listener The function to be executed when the event is raised.
  9771. * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
  9772. * pointer in which the listener function will execute.
  9773. * @returns {Event~RemoveCallback} A function that will remove this event listener when invoked.
  9774. *
  9775. * @see Event#raiseEvent
  9776. * @see Event#removeEventListener
  9777. */
  9778. Event.prototype.addEventListener = function(listener, scope) {
  9779. //>>includeStart('debug', pragmas.debug);
  9780. Check.Check.typeOf.func('listener', listener);
  9781. //>>includeEnd('debug');
  9782. this._listeners.push(listener);
  9783. this._scopes.push(scope);
  9784. var event = this;
  9785. return function() {
  9786. event.removeEventListener(listener, scope);
  9787. };
  9788. };
  9789. /**
  9790. * Unregisters a previously registered callback.
  9791. *
  9792. * @param {Function} listener The function to be unregistered.
  9793. * @param {Object} [scope] The scope that was originally passed to addEventListener.
  9794. * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> if the listener and scope are not registered with the event.
  9795. *
  9796. * @see Event#addEventListener
  9797. * @see Event#raiseEvent
  9798. */
  9799. Event.prototype.removeEventListener = function(listener, scope) {
  9800. //>>includeStart('debug', pragmas.debug);
  9801. Check.Check.typeOf.func('listener', listener);
  9802. //>>includeEnd('debug');
  9803. var listeners = this._listeners;
  9804. var scopes = this._scopes;
  9805. var index = -1;
  9806. for (var i = 0; i < listeners.length; i++) {
  9807. if (listeners[i] === listener && scopes[i] === scope) {
  9808. index = i;
  9809. break;
  9810. }
  9811. }
  9812. if (index !== -1) {
  9813. if (this._insideRaiseEvent) {
  9814. //In order to allow removing an event subscription from within
  9815. //a callback, we don't actually remove the items here. Instead
  9816. //remember the index they are at and undefined their value.
  9817. this._toRemove.push(index);
  9818. listeners[index] = undefined;
  9819. scopes[index] = undefined;
  9820. } else {
  9821. listeners.splice(index, 1);
  9822. scopes.splice(index, 1);
  9823. }
  9824. return true;
  9825. }
  9826. return false;
  9827. };
  9828. function compareNumber(a,b) {
  9829. return b - a;
  9830. }
  9831. /**
  9832. * Raises the event by calling each registered listener with all supplied arguments.
  9833. *
  9834. * @param {*} arguments This method takes any number of parameters and passes them through to the listener functions.
  9835. *
  9836. * @see Event#addEventListener
  9837. * @see Event#removeEventListener
  9838. */
  9839. Event.prototype.raiseEvent = function() {
  9840. this._insideRaiseEvent = true;
  9841. var i;
  9842. var listeners = this._listeners;
  9843. var scopes = this._scopes;
  9844. var length = listeners.length;
  9845. for (i = 0; i < length; i++) {
  9846. var listener = listeners[i];
  9847. if (defined.defined(listener)) {
  9848. listeners[i].apply(scopes[i], arguments);
  9849. }
  9850. }
  9851. //Actually remove items removed in removeEventListener.
  9852. var toRemove = this._toRemove;
  9853. length = toRemove.length;
  9854. if (length > 0) {
  9855. toRemove.sort(compareNumber);
  9856. for (i = 0; i < length; i++) {
  9857. var index = toRemove[i];
  9858. listeners.splice(index, 1);
  9859. scopes.splice(index, 1);
  9860. }
  9861. toRemove.length = 0;
  9862. }
  9863. this._insideRaiseEvent = false;
  9864. };
  9865. /**
  9866. * Array implementation of a heap.
  9867. *
  9868. * @alias Heap
  9869. * @constructor
  9870. * @private
  9871. *
  9872. * @param {Object} options Object with the following properties:
  9873. * @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.
  9874. */
  9875. function Heap(options) {
  9876. //>>includeStart('debug', pragmas.debug);
  9877. Check.Check.typeOf.object('options', options);
  9878. Check.Check.defined('options.comparator', options.comparator);
  9879. //>>includeEnd('debug');
  9880. this._comparator = options.comparator;
  9881. this._array = [];
  9882. this._length = 0;
  9883. this._maximumLength = undefined;
  9884. }
  9885. defineProperties.defineProperties(Heap.prototype, {
  9886. /**
  9887. * Gets the length of the heap.
  9888. *
  9889. * @memberof Heap.prototype
  9890. *
  9891. * @type {Number}
  9892. * @readonly
  9893. */
  9894. length : {
  9895. get : function() {
  9896. return this._length;
  9897. }
  9898. },
  9899. /**
  9900. * Gets the internal array.
  9901. *
  9902. * @memberof Heap.prototype
  9903. *
  9904. * @type {Array}
  9905. * @readonly
  9906. */
  9907. internalArray : {
  9908. get : function() {
  9909. return this._array;
  9910. }
  9911. },
  9912. /**
  9913. * Gets and sets the maximum length of the heap.
  9914. *
  9915. * @memberof Heap.prototype
  9916. *
  9917. * @type {Number}
  9918. */
  9919. maximumLength : {
  9920. get : function() {
  9921. return this._maximumLength;
  9922. },
  9923. set : function(value) {
  9924. this._maximumLength = value;
  9925. if (this._length > value && value > 0) {
  9926. this._length = value;
  9927. this._array.length = value;
  9928. }
  9929. }
  9930. },
  9931. /**
  9932. * 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.
  9933. *
  9934. * @memberof Heap.prototype
  9935. *
  9936. * @type {Heap~ComparatorCallback}
  9937. */
  9938. comparator : {
  9939. get : function() {
  9940. return this._comparator;
  9941. }
  9942. }
  9943. });
  9944. function swap(array, a, b) {
  9945. var temp = array[a];
  9946. array[a] = array[b];
  9947. array[b] = temp;
  9948. }
  9949. /**
  9950. * Resizes the internal array of the heap.
  9951. *
  9952. * @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
  9953. */
  9954. Heap.prototype.reserve = function(length) {
  9955. length = defaultValue.defaultValue(length, this._length);
  9956. this._array.length = length;
  9957. };
  9958. /**
  9959. * Update the heap so that index and all descendants satisfy the heap property.
  9960. *
  9961. * @param {Number} [index=0] The starting index to heapify from.
  9962. */
  9963. Heap.prototype.heapify = function(index) {
  9964. index = defaultValue.defaultValue(index, 0);
  9965. var length = this._length;
  9966. var comparator = this._comparator;
  9967. var array = this._array;
  9968. var candidate = -1;
  9969. var inserting = true;
  9970. while (inserting) {
  9971. var right = 2 * (index + 1);
  9972. var left = right - 1;
  9973. if (left < length && comparator(array[left], array[index]) < 0) {
  9974. candidate = left;
  9975. } else {
  9976. candidate = index;
  9977. }
  9978. if (right < length && comparator(array[right], array[candidate]) < 0) {
  9979. candidate = right;
  9980. }
  9981. if (candidate !== index) {
  9982. swap(array, candidate, index);
  9983. index = candidate;
  9984. } else {
  9985. inserting = false;
  9986. }
  9987. }
  9988. };
  9989. /**
  9990. * Resort the heap.
  9991. */
  9992. Heap.prototype.resort = function() {
  9993. var length = this._length;
  9994. for (var i = Math.ceil(length / 2); i >= 0; --i) {
  9995. this.heapify(i);
  9996. }
  9997. };
  9998. /**
  9999. * Insert an element into the heap. If the length would grow greater than maximumLength
  10000. * of the heap, extra elements are removed.
  10001. *
  10002. * @param {*} element The element to insert
  10003. *
  10004. * @return {*} The element that was removed from the heap if the heap is at full capacity.
  10005. */
  10006. Heap.prototype.insert = function(element) {
  10007. //>>includeStart('debug', pragmas.debug);
  10008. Check.Check.defined('element', element);
  10009. //>>includeEnd('debug');
  10010. var array = this._array;
  10011. var comparator = this._comparator;
  10012. var maximumLength = this._maximumLength;
  10013. var index = this._length++;
  10014. if (index < array.length) {
  10015. array[index] = element;
  10016. } else {
  10017. array.push(element);
  10018. }
  10019. while (index !== 0) {
  10020. var parent = Math.floor((index - 1) / 2);
  10021. if (comparator(array[index], array[parent]) < 0) {
  10022. swap(array, index, parent);
  10023. index = parent;
  10024. } else {
  10025. break;
  10026. }
  10027. }
  10028. var removedElement;
  10029. if (defined.defined(maximumLength) && (this._length > maximumLength)) {
  10030. removedElement = array[maximumLength];
  10031. this._length = maximumLength;
  10032. }
  10033. return removedElement;
  10034. };
  10035. /**
  10036. * Remove the element specified by index from the heap and return it.
  10037. *
  10038. * @param {Number} [index=0] The index to remove.
  10039. * @returns {*} The specified element of the heap.
  10040. */
  10041. Heap.prototype.pop = function(index) {
  10042. index = defaultValue.defaultValue(index, 0);
  10043. if (this._length === 0) {
  10044. return undefined;
  10045. }
  10046. //>>includeStart('debug', pragmas.debug);
  10047. Check.Check.typeOf.number.lessThan('index', index, this._length);
  10048. //>>includeEnd('debug');
  10049. var array = this._array;
  10050. var root = array[index];
  10051. swap(array, index, --this._length);
  10052. this.heapify(index);
  10053. return root;
  10054. };
  10055. function sortRequests(a, b) {
  10056. return a.priority - b.priority;
  10057. }
  10058. var statistics = {
  10059. numberOfAttemptedRequests : 0,
  10060. numberOfActiveRequests : 0,
  10061. numberOfCancelledRequests : 0,
  10062. numberOfCancelledActiveRequests : 0,
  10063. numberOfFailedRequests : 0,
  10064. numberOfActiveRequestsEver : 0,
  10065. lastNumberOfActiveRequests : 0
  10066. };
  10067. var priorityHeapLength = 20;
  10068. var requestHeap = new Heap({
  10069. comparator : sortRequests
  10070. });
  10071. requestHeap.maximumLength = priorityHeapLength;
  10072. requestHeap.reserve(priorityHeapLength);
  10073. var activeRequests = [];
  10074. var numberOfActiveRequestsByServer = {};
  10075. var pageUri = typeof document !== 'undefined' ? new URI(document.location.href) : new URI();
  10076. var requestCompletedEvent = new Event();
  10077. /**
  10078. * Tracks the number of active requests and prioritizes incoming requests.
  10079. *
  10080. * @exports RequestScheduler
  10081. *
  10082. * @private
  10083. */
  10084. function RequestScheduler() {
  10085. }
  10086. /**
  10087. * The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
  10088. * @type {Number}
  10089. * @default 50
  10090. */
  10091. RequestScheduler.maximumRequests = 50;
  10092. /**
  10093. * The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
  10094. * listed in requestsByServer do not observe this limit.
  10095. * @type {Number}
  10096. * @default 6
  10097. */
  10098. RequestScheduler.maximumRequestsPerServer = 6;
  10099. /**
  10100. * A per serverKey list of overrides to use for throttling instead of maximumRequestsPerServer
  10101. */
  10102. RequestScheduler.requestsByServer = {
  10103. 'api.cesium.com:443': 18,
  10104. 'assets.cesium.com:443': 18
  10105. };
  10106. /**
  10107. * Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
  10108. * @type {Boolean}
  10109. * @default true
  10110. */
  10111. RequestScheduler.throttleRequests = true;
  10112. /**
  10113. * When true, log statistics to the console every frame
  10114. * @type {Boolean}
  10115. * @default false
  10116. */
  10117. RequestScheduler.debugShowStatistics = false;
  10118. /**
  10119. * An event that's raised when a request is completed. Event handlers are passed
  10120. * the error object if the request fails.
  10121. *
  10122. * @type {Event}
  10123. * @default Event()
  10124. */
  10125. RequestScheduler.requestCompletedEvent = requestCompletedEvent;
  10126. defineProperties.defineProperties(RequestScheduler, {
  10127. /**
  10128. * Returns the statistics used by the request scheduler.
  10129. *
  10130. * @memberof RequestScheduler
  10131. *
  10132. * @type Object
  10133. * @readonly
  10134. */
  10135. statistics : {
  10136. get : function() {
  10137. return statistics;
  10138. }
  10139. },
  10140. /**
  10141. * 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.
  10142. *
  10143. * @memberof RequestScheduler
  10144. *
  10145. * @type {Number}
  10146. * @default 20
  10147. */
  10148. priorityHeapLength : {
  10149. get : function() {
  10150. return priorityHeapLength;
  10151. },
  10152. set : function(value) {
  10153. // If the new length shrinks the heap, need to cancel some of the requests.
  10154. // Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
  10155. if (value < priorityHeapLength) {
  10156. while (requestHeap.length > value) {
  10157. var request = requestHeap.pop();
  10158. cancelRequest(request);
  10159. }
  10160. }
  10161. priorityHeapLength = value;
  10162. requestHeap.maximumLength = value;
  10163. requestHeap.reserve(value);
  10164. }
  10165. }
  10166. });
  10167. function updatePriority(request) {
  10168. if (defined.defined(request.priorityFunction)) {
  10169. request.priority = request.priorityFunction();
  10170. }
  10171. }
  10172. function serverHasOpenSlots(serverKey) {
  10173. var maxRequests = defaultValue.defaultValue(RequestScheduler.requestsByServer[serverKey], RequestScheduler.maximumRequestsPerServer);
  10174. return numberOfActiveRequestsByServer[serverKey] < maxRequests;
  10175. }
  10176. function issueRequest(request) {
  10177. if (request.state === RequestState$1.UNISSUED) {
  10178. request.state = RequestState$1.ISSUED;
  10179. request.deferred = when.when.defer();
  10180. }
  10181. return request.deferred.promise;
  10182. }
  10183. function getRequestReceivedFunction(request) {
  10184. return function(results) {
  10185. if (request.state === RequestState$1.CANCELLED) {
  10186. // If the data request comes back but the request is cancelled, ignore it.
  10187. return;
  10188. }
  10189. --statistics.numberOfActiveRequests;
  10190. --numberOfActiveRequestsByServer[request.serverKey];
  10191. requestCompletedEvent.raiseEvent();
  10192. request.state = RequestState$1.RECEIVED;
  10193. request.deferred.resolve(results);
  10194. };
  10195. }
  10196. function getRequestFailedFunction(request) {
  10197. return function(error) {
  10198. if (request.state === RequestState$1.CANCELLED) {
  10199. // If the data request comes back but the request is cancelled, ignore it.
  10200. return;
  10201. }
  10202. ++statistics.numberOfFailedRequests;
  10203. --statistics.numberOfActiveRequests;
  10204. --numberOfActiveRequestsByServer[request.serverKey];
  10205. requestCompletedEvent.raiseEvent(error);
  10206. request.state = RequestState$1.FAILED;
  10207. request.deferred.reject(error);
  10208. };
  10209. }
  10210. function startRequest(request) {
  10211. var promise = issueRequest(request);
  10212. request.state = RequestState$1.ACTIVE;
  10213. activeRequests.push(request);
  10214. ++statistics.numberOfActiveRequests;
  10215. ++statistics.numberOfActiveRequestsEver;
  10216. ++numberOfActiveRequestsByServer[request.serverKey];
  10217. request.requestFunction().then(getRequestReceivedFunction(request)).otherwise(getRequestFailedFunction(request));
  10218. return promise;
  10219. }
  10220. function cancelRequest(request) {
  10221. var active = request.state === RequestState$1.ACTIVE;
  10222. request.state = RequestState$1.CANCELLED;
  10223. ++statistics.numberOfCancelledRequests;
  10224. request.deferred.reject();
  10225. if (active) {
  10226. --statistics.numberOfActiveRequests;
  10227. --numberOfActiveRequestsByServer[request.serverKey];
  10228. ++statistics.numberOfCancelledActiveRequests;
  10229. }
  10230. if (defined.defined(request.cancelFunction)) {
  10231. request.cancelFunction();
  10232. }
  10233. }
  10234. /**
  10235. * Sort requests by priority and start requests.
  10236. */
  10237. RequestScheduler.update = function() {
  10238. var i;
  10239. var request;
  10240. // Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
  10241. var removeCount = 0;
  10242. var activeLength = activeRequests.length;
  10243. for (i = 0; i < activeLength; ++i) {
  10244. request = activeRequests[i];
  10245. if (request.cancelled) {
  10246. // Request was explicitly cancelled
  10247. cancelRequest(request);
  10248. }
  10249. if (request.state !== RequestState$1.ACTIVE) {
  10250. // Request is no longer active, remove from array
  10251. ++removeCount;
  10252. continue;
  10253. }
  10254. if (removeCount > 0) {
  10255. // Shift back to fill in vacated slots from completed requests
  10256. activeRequests[i - removeCount] = request;
  10257. }
  10258. }
  10259. activeRequests.length -= removeCount;
  10260. // Update priority of issued requests and resort the heap
  10261. var issuedRequests = requestHeap.internalArray;
  10262. var issuedLength = requestHeap.length;
  10263. for (i = 0; i < issuedLength; ++i) {
  10264. updatePriority(issuedRequests[i]);
  10265. }
  10266. requestHeap.resort();
  10267. // Get the number of open slots and fill with the highest priority requests.
  10268. // Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
  10269. var openSlots = Math.max(RequestScheduler.maximumRequests - activeRequests.length, 0);
  10270. var filledSlots = 0;
  10271. while (filledSlots < openSlots && requestHeap.length > 0) {
  10272. // Loop until all open slots are filled or the heap becomes empty
  10273. request = requestHeap.pop();
  10274. if (request.cancelled) {
  10275. // Request was explicitly cancelled
  10276. cancelRequest(request);
  10277. continue;
  10278. }
  10279. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  10280. // Open slots are available, but the request is throttled by its server. Cancel and try again later.
  10281. cancelRequest(request);
  10282. continue;
  10283. }
  10284. startRequest(request);
  10285. ++filledSlots;
  10286. }
  10287. updateStatistics();
  10288. };
  10289. /**
  10290. * Get the server key from a given url.
  10291. *
  10292. * @param {String} url The url.
  10293. * @returns {String} The server key.
  10294. */
  10295. RequestScheduler.getServerKey = function(url) {
  10296. //>>includeStart('debug', pragmas.debug);
  10297. Check.Check.typeOf.string('url', url);
  10298. //>>includeEnd('debug');
  10299. var uri = new URI(url).resolve(pageUri);
  10300. uri.normalize();
  10301. var serverKey = uri.authority;
  10302. if (!/:/.test(serverKey)) {
  10303. // If the authority does not contain a port number, add port 443 for https or port 80 for http
  10304. serverKey = serverKey + ':' + (uri.scheme === 'https' ? '443' : '80');
  10305. }
  10306. var length = numberOfActiveRequestsByServer[serverKey];
  10307. if (!defined.defined(length)) {
  10308. numberOfActiveRequestsByServer[serverKey] = 0;
  10309. }
  10310. return serverKey;
  10311. };
  10312. /**
  10313. * Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
  10314. * queued and sorted by priority before being sent.
  10315. *
  10316. * @param {Request} request The request object.
  10317. *
  10318. * @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
  10319. */
  10320. RequestScheduler.request = function(request) {
  10321. //>>includeStart('debug', pragmas.debug);
  10322. Check.Check.typeOf.object('request', request);
  10323. Check.Check.typeOf.string('request.url', request.url);
  10324. Check.Check.typeOf.func('request.requestFunction', request.requestFunction);
  10325. //>>includeEnd('debug');
  10326. if (isDataUri(request.url) || isBlobUri(request.url)) {
  10327. requestCompletedEvent.raiseEvent();
  10328. request.state = RequestState$1.RECEIVED;
  10329. return request.requestFunction();
  10330. }
  10331. ++statistics.numberOfAttemptedRequests;
  10332. if (!defined.defined(request.serverKey)) {
  10333. request.serverKey = RequestScheduler.getServerKey(request.url);
  10334. }
  10335. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  10336. // Server is saturated. Try again later.
  10337. return undefined;
  10338. }
  10339. if (!RequestScheduler.throttleRequests || !request.throttle) {
  10340. return startRequest(request);
  10341. }
  10342. if (activeRequests.length >= RequestScheduler.maximumRequests) {
  10343. // Active requests are saturated. Try again later.
  10344. return undefined;
  10345. }
  10346. // Insert into the priority heap and see if a request was bumped off. If this request is the lowest
  10347. // priority it will be returned.
  10348. updatePriority(request);
  10349. var removedRequest = requestHeap.insert(request);
  10350. if (defined.defined(removedRequest)) {
  10351. if (removedRequest === request) {
  10352. // Request does not have high enough priority to be issued
  10353. return undefined;
  10354. }
  10355. // A previously issued request has been bumped off the priority heap, so cancel it
  10356. cancelRequest(removedRequest);
  10357. }
  10358. return issueRequest(request);
  10359. };
  10360. function updateStatistics() {
  10361. if (!RequestScheduler.debugShowStatistics) {
  10362. return;
  10363. }
  10364. if (statistics.numberOfActiveRequests === 0 && statistics.lastNumberOfActiveRequests > 0) {
  10365. if (statistics.numberOfAttemptedRequests > 0) {
  10366. console.log('Number of attempted requests: ' + statistics.numberOfAttemptedRequests);
  10367. statistics.numberOfAttemptedRequests = 0;
  10368. }
  10369. if (statistics.numberOfCancelledRequests > 0) {
  10370. console.log('Number of cancelled requests: ' + statistics.numberOfCancelledRequests);
  10371. statistics.numberOfCancelledRequests = 0;
  10372. }
  10373. if (statistics.numberOfCancelledActiveRequests > 0) {
  10374. console.log('Number of cancelled active requests: ' + statistics.numberOfCancelledActiveRequests);
  10375. statistics.numberOfCancelledActiveRequests = 0;
  10376. }
  10377. if (statistics.numberOfFailedRequests > 0) {
  10378. console.log('Number of failed requests: ' + statistics.numberOfFailedRequests);
  10379. statistics.numberOfFailedRequests = 0;
  10380. }
  10381. }
  10382. statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
  10383. }
  10384. /**
  10385. * For testing only. Clears any requests that may not have completed from previous tests.
  10386. *
  10387. * @private
  10388. */
  10389. RequestScheduler.clearForSpecs = function() {
  10390. while (requestHeap.length > 0) {
  10391. var request = requestHeap.pop();
  10392. cancelRequest(request);
  10393. }
  10394. var length = activeRequests.length;
  10395. for (var i = 0; i < length; ++i) {
  10396. cancelRequest(activeRequests[i]);
  10397. }
  10398. activeRequests.length = 0;
  10399. numberOfActiveRequestsByServer = {};
  10400. // Clear stats
  10401. statistics.numberOfAttemptedRequests = 0;
  10402. statistics.numberOfActiveRequests = 0;
  10403. statistics.numberOfCancelledRequests = 0;
  10404. statistics.numberOfCancelledActiveRequests = 0;
  10405. statistics.numberOfFailedRequests = 0;
  10406. statistics.numberOfActiveRequestsEver = 0;
  10407. statistics.lastNumberOfActiveRequests = 0;
  10408. };
  10409. /**
  10410. * For testing only.
  10411. *
  10412. * @private
  10413. */
  10414. RequestScheduler.numberOfActiveRequestsByServer = function(serverKey) {
  10415. return numberOfActiveRequestsByServer[serverKey];
  10416. };
  10417. /**
  10418. * For testing only.
  10419. *
  10420. * @private
  10421. */
  10422. RequestScheduler.requestHeap = requestHeap;
  10423. /**
  10424. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  10425. * any requests to these servers.
  10426. *
  10427. * @exports TrustedServers
  10428. *
  10429. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  10430. */
  10431. var TrustedServers = {};
  10432. var _servers = {};
  10433. /**
  10434. * Adds a trusted server to the registry
  10435. *
  10436. * @param {String} host The host to be added.
  10437. * @param {Number} port The port used to access the host.
  10438. *
  10439. * @example
  10440. * // Add a trusted server
  10441. * TrustedServers.add('my.server.com', 80);
  10442. */
  10443. TrustedServers.add = function(host, port) {
  10444. //>>includeStart('debug', pragmas.debug);
  10445. if (!defined.defined(host)) {
  10446. throw new Check.DeveloperError('host is required.');
  10447. }
  10448. if (!defined.defined(port) || port <= 0) {
  10449. throw new Check.DeveloperError('port is required to be greater than 0.');
  10450. }
  10451. //>>includeEnd('debug');
  10452. var authority = host.toLowerCase() + ':' + port;
  10453. if (!defined.defined(_servers[authority])) {
  10454. _servers[authority] = true;
  10455. }
  10456. };
  10457. /**
  10458. * Removes a trusted server from the registry
  10459. *
  10460. * @param {String} host The host to be removed.
  10461. * @param {Number} port The port used to access the host.
  10462. *
  10463. * @example
  10464. * // Remove a trusted server
  10465. * TrustedServers.remove('my.server.com', 80);
  10466. */
  10467. TrustedServers.remove = function(host, port) {
  10468. //>>includeStart('debug', pragmas.debug);
  10469. if (!defined.defined(host)) {
  10470. throw new Check.DeveloperError('host is required.');
  10471. }
  10472. if (!defined.defined(port) || port <= 0) {
  10473. throw new Check.DeveloperError('port is required to be greater than 0.');
  10474. }
  10475. //>>includeEnd('debug');
  10476. var authority = host.toLowerCase() + ':' + port;
  10477. if (defined.defined(_servers[authority])) {
  10478. delete _servers[authority];
  10479. }
  10480. };
  10481. function getAuthority(url) {
  10482. var uri = new URI(url);
  10483. uri.normalize();
  10484. // Removes username:password@ so we just have host[:port]
  10485. var authority = uri.getAuthority();
  10486. if (!defined.defined(authority)) {
  10487. return undefined; // Relative URL
  10488. }
  10489. if (authority.indexOf('@') !== -1) {
  10490. var parts = authority.split('@');
  10491. authority = parts[1];
  10492. }
  10493. // If the port is missing add one based on the scheme
  10494. if (authority.indexOf(':') === -1) {
  10495. var scheme = uri.getScheme();
  10496. if (!defined.defined(scheme)) {
  10497. scheme = window.location.protocol;
  10498. scheme = scheme.substring(0, scheme.length-1);
  10499. }
  10500. if (scheme === 'http') {
  10501. authority += ':80';
  10502. } else if (scheme === 'https') {
  10503. authority += ':443';
  10504. } else {
  10505. return undefined;
  10506. }
  10507. }
  10508. return authority;
  10509. }
  10510. /**
  10511. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  10512. *
  10513. * @param {String} url The url to be tested against the trusted list
  10514. *
  10515. * @returns {boolean} Returns true if url is trusted, false otherwise.
  10516. *
  10517. * @example
  10518. * // Add server
  10519. * TrustedServers.add('my.server.com', 81);
  10520. *
  10521. * // Check if server is trusted
  10522. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  10523. * // my.server.com:81 is trusted
  10524. * }
  10525. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  10526. * // my.server.com isn't trusted
  10527. * }
  10528. */
  10529. TrustedServers.contains = function(url) {
  10530. //>>includeStart('debug', pragmas.debug);
  10531. if (!defined.defined(url)) {
  10532. throw new Check.DeveloperError('url is required.');
  10533. }
  10534. //>>includeEnd('debug');
  10535. var authority = getAuthority(url);
  10536. if (defined.defined(authority) && defined.defined(_servers[authority])) {
  10537. return true;
  10538. }
  10539. return false;
  10540. };
  10541. /**
  10542. * Clears the registry
  10543. *
  10544. * @example
  10545. * // Remove a trusted server
  10546. * TrustedServers.clear();
  10547. */
  10548. TrustedServers.clear = function() {
  10549. _servers = {};
  10550. };
  10551. var xhrBlobSupported = (function() {
  10552. try {
  10553. var xhr = new XMLHttpRequest();
  10554. xhr.open('GET', '#', true);
  10555. xhr.responseType = 'blob';
  10556. return xhr.responseType === 'blob';
  10557. } catch (e) {
  10558. return false;
  10559. }
  10560. })();
  10561. /**
  10562. * Parses a query string and returns the object equivalent.
  10563. *
  10564. * @param {Uri} uri The Uri with a query object.
  10565. * @param {Resource} resource The Resource that will be assigned queryParameters.
  10566. * @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
  10567. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
  10568. *
  10569. * @private
  10570. */
  10571. function parseQuery(uri, resource, merge, preserveQueryParameters) {
  10572. var queryString = uri.query;
  10573. if (!defined.defined(queryString) || (queryString.length === 0)) {
  10574. return {};
  10575. }
  10576. var query;
  10577. // Special case we run into where the querystring is just a string, not key/value pairs
  10578. if (queryString.indexOf('=') === -1) {
  10579. var result = {};
  10580. result[queryString] = undefined;
  10581. query = result;
  10582. } else {
  10583. query = queryToObject(queryString);
  10584. }
  10585. if (merge) {
  10586. resource._queryParameters = combineQueryParameters(query, resource._queryParameters, preserveQueryParameters);
  10587. } else {
  10588. resource._queryParameters = query;
  10589. }
  10590. uri.query = undefined;
  10591. }
  10592. /**
  10593. * Converts a query object into a string.
  10594. *
  10595. * @param {Uri} uri The Uri object that will have the query object set.
  10596. * @param {Resource} resource The resource that has queryParameters
  10597. *
  10598. * @private
  10599. */
  10600. function stringifyQuery(uri, resource) {
  10601. var queryObject = resource._queryParameters;
  10602. var keys = Object.keys(queryObject);
  10603. // We have 1 key with an undefined value, so this is just a string, not key/value pairs
  10604. if (keys.length === 1 && !defined.defined(queryObject[keys[0]])) {
  10605. uri.query = keys[0];
  10606. } else {
  10607. uri.query = objectToQuery(queryObject);
  10608. }
  10609. }
  10610. /**
  10611. * Clones a value if it is defined, otherwise returns the default value
  10612. *
  10613. * @param {*} [val] The value to clone.
  10614. * @param {*} [defaultVal] The default value.
  10615. *
  10616. * @returns {*} A clone of val or the defaultVal.
  10617. *
  10618. * @private
  10619. */
  10620. function defaultClone(val, defaultVal) {
  10621. if (!defined.defined(val)) {
  10622. return defaultVal;
  10623. }
  10624. return defined.defined(val.clone) ? val.clone() : clone(val);
  10625. }
  10626. /**
  10627. * Checks to make sure the Resource isn't already being requested.
  10628. *
  10629. * @param {Request} request The request to check.
  10630. *
  10631. * @private
  10632. */
  10633. function checkAndResetRequest(request) {
  10634. if (request.state === RequestState$1.ISSUED || request.state === RequestState$1.ACTIVE) {
  10635. throw new RuntimeError.RuntimeError('The Resource is already being fetched.');
  10636. }
  10637. request.state = RequestState$1.UNISSUED;
  10638. request.deferred = undefined;
  10639. }
  10640. /**
  10641. * This combines a map of query parameters.
  10642. *
  10643. * @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
  10644. * @param {Object} q2 The second map of query parameters.
  10645. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
  10646. *
  10647. * @returns {Object} The combined map of query parameters.
  10648. *
  10649. * @example
  10650. * var q1 = {
  10651. * a: 1,
  10652. * b: 2
  10653. * };
  10654. * var q2 = {
  10655. * a: 3,
  10656. * c: 4
  10657. * };
  10658. * var q3 = {
  10659. * b: [5, 6],
  10660. * d: 7
  10661. * }
  10662. *
  10663. * // Returns
  10664. * // {
  10665. * // a: [1, 3],
  10666. * // b: 2,
  10667. * // c: 4
  10668. * // };
  10669. * combineQueryParameters(q1, q2, true);
  10670. *
  10671. * // Returns
  10672. * // {
  10673. * // a: 1,
  10674. * // b: 2,
  10675. * // c: 4
  10676. * // };
  10677. * combineQueryParameters(q1, q2, false);
  10678. *
  10679. * // Returns
  10680. * // {
  10681. * // a: 1,
  10682. * // b: [2, 5, 6],
  10683. * // d: 7
  10684. * // };
  10685. * combineQueryParameters(q1, q3, true);
  10686. *
  10687. * // Returns
  10688. * // {
  10689. * // a: 1,
  10690. * // b: 2,
  10691. * // d: 7
  10692. * // };
  10693. * combineQueryParameters(q1, q3, false);
  10694. *
  10695. * @private
  10696. */
  10697. function combineQueryParameters(q1, q2, preserveQueryParameters) {
  10698. if (!preserveQueryParameters) {
  10699. return combine(q1, q2);
  10700. }
  10701. var result = clone(q1, true);
  10702. for (var param in q2) {
  10703. if (q2.hasOwnProperty(param)) {
  10704. var value = result[param];
  10705. var q2Value = q2[param];
  10706. if (defined.defined(value)) {
  10707. if (!Array.isArray(value)) {
  10708. value = result[param] = [value];
  10709. }
  10710. result[param] = value.concat(q2Value);
  10711. } else {
  10712. result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
  10713. }
  10714. }
  10715. }
  10716. return result;
  10717. }
  10718. /**
  10719. * 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.
  10720. *
  10721. * @alias Resource
  10722. * @constructor
  10723. *
  10724. * @param {String|Object} options A url or an object with the following properties
  10725. * @param {String} options.url The url of the resource.
  10726. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  10727. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  10728. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  10729. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  10730. * @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.
  10731. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  10732. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  10733. *
  10734. * @example
  10735. * function refreshTokenRetryCallback(resource, error) {
  10736. * if (error.statusCode === 403) {
  10737. * // 403 status code means a new token should be generated
  10738. * return getNewAccessToken()
  10739. * .then(function(token) {
  10740. * resource.queryParameters.access_token = token;
  10741. * return true;
  10742. * })
  10743. * .otherwise(function() {
  10744. * return false;
  10745. * });
  10746. * }
  10747. *
  10748. * return false;
  10749. * }
  10750. *
  10751. * var resource = new Resource({
  10752. * url: 'http://server.com/path/to/resource.json',
  10753. * proxy: new DefaultProxy('/proxy/'),
  10754. * headers: {
  10755. * 'X-My-Header': 'valueOfHeader'
  10756. * },
  10757. * queryParameters: {
  10758. * 'access_token': '123-435-456-000'
  10759. * },
  10760. * retryCallback: refreshTokenRetryCallback,
  10761. * retryAttempts: 1
  10762. * });
  10763. */
  10764. function Resource(options) {
  10765. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  10766. if (typeof options === 'string') {
  10767. options = {
  10768. url: options
  10769. };
  10770. }
  10771. //>>includeStart('debug', pragmas.debug);
  10772. Check.Check.typeOf.string('options.url', options.url);
  10773. //>>includeEnd('debug');
  10774. this._url = undefined;
  10775. this._templateValues = defaultClone(options.templateValues, {});
  10776. this._queryParameters = defaultClone(options.queryParameters, {});
  10777. /**
  10778. * Additional HTTP headers that will be sent with the request.
  10779. *
  10780. * @type {Object}
  10781. */
  10782. this.headers = defaultClone(options.headers, {});
  10783. /**
  10784. * A Request object that will be used. Intended for internal use only.
  10785. *
  10786. * @type {Request}
  10787. */
  10788. this.request = defaultValue.defaultValue(options.request, new Request());
  10789. /**
  10790. * A proxy to be used when loading the resource.
  10791. *
  10792. * @type {DefaultProxy}
  10793. */
  10794. this.proxy = options.proxy;
  10795. /**
  10796. * 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.
  10797. *
  10798. * @type {Function}
  10799. */
  10800. this.retryCallback = options.retryCallback;
  10801. /**
  10802. * The number of times the retryCallback should be called before giving up.
  10803. *
  10804. * @type {Number}
  10805. */
  10806. this.retryAttempts = defaultValue.defaultValue(options.retryAttempts, 0);
  10807. this._retryCount = 0;
  10808. var uri = new URI(options.url);
  10809. parseQuery(uri, this, true, true);
  10810. // Remove the fragment as it's not sent with a request
  10811. uri.fragment = undefined;
  10812. this._url = uri.toString();
  10813. }
  10814. /**
  10815. * A helper function to create a resource depending on whether we have a String or a Resource
  10816. *
  10817. * @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
  10818. *
  10819. * @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
  10820. *
  10821. * @private
  10822. */
  10823. Resource.createIfNeeded = function(resource) {
  10824. if (resource instanceof Resource) {
  10825. // Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
  10826. // be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
  10827. // 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
  10828. // in the underlying tiling code the requests for this resource will use it.
  10829. return resource.getDerivedResource({
  10830. request: resource.request
  10831. });
  10832. }
  10833. if (typeof resource !== 'string') {
  10834. return resource;
  10835. }
  10836. return new Resource({
  10837. url: resource
  10838. });
  10839. };
  10840. var supportsImageBitmapOptionsPromise;
  10841. /**
  10842. * A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
  10843. *
  10844. * @returns {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
  10845. *
  10846. * @private
  10847. */
  10848. Resource.supportsImageBitmapOptions = function() {
  10849. // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
  10850. // know if this browser supports passing options to the createImageBitmap function.
  10851. // https://github.com/whatwg/html/pull/4248
  10852. if (defined.defined(supportsImageBitmapOptionsPromise)) {
  10853. return supportsImageBitmapOptionsPromise;
  10854. }
  10855. if (typeof createImageBitmap !== 'function') {
  10856. supportsImageBitmapOptionsPromise = when.when.resolve(false);
  10857. return supportsImageBitmapOptionsPromise;
  10858. }
  10859. var imageDataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWP4////fwAJ+wP9CNHoHgAAAABJRU5ErkJggg==';
  10860. supportsImageBitmapOptionsPromise = Resource.fetchBlob({
  10861. url : imageDataUri
  10862. })
  10863. .then(function(blob) {
  10864. return createImageBitmap(blob, {
  10865. imageOrientation: 'flipY',
  10866. premultiplyAlpha: 'none'
  10867. });
  10868. })
  10869. .then(function(imageBitmap) {
  10870. return true;
  10871. })
  10872. .otherwise(function() {
  10873. return false;
  10874. });
  10875. return supportsImageBitmapOptionsPromise;
  10876. };
  10877. defineProperties.defineProperties(Resource, {
  10878. /**
  10879. * Returns true if blobs are supported.
  10880. *
  10881. * @memberof Resource
  10882. * @type {Boolean}
  10883. *
  10884. * @readonly
  10885. */
  10886. isBlobSupported : {
  10887. get : function() {
  10888. return xhrBlobSupported;
  10889. }
  10890. }
  10891. });
  10892. defineProperties.defineProperties(Resource.prototype, {
  10893. /**
  10894. * Query parameters appended to the url.
  10895. *
  10896. * @memberof Resource.prototype
  10897. * @type {Object}
  10898. *
  10899. * @readonly
  10900. */
  10901. queryParameters: {
  10902. get: function() {
  10903. return this._queryParameters;
  10904. }
  10905. },
  10906. /**
  10907. * The key/value pairs used to replace template parameters in the url.
  10908. *
  10909. * @memberof Resource.prototype
  10910. * @type {Object}
  10911. *
  10912. * @readonly
  10913. */
  10914. templateValues: {
  10915. get: function() {
  10916. return this._templateValues;
  10917. }
  10918. },
  10919. /**
  10920. * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
  10921. *
  10922. * @memberof Resource.prototype
  10923. * @type {String}
  10924. */
  10925. url: {
  10926. get: function() {
  10927. return this.getUrlComponent(true, true);
  10928. },
  10929. set: function(value) {
  10930. var uri = new URI(value);
  10931. parseQuery(uri, this, false);
  10932. // Remove the fragment as it's not sent with a request
  10933. uri.fragment = undefined;
  10934. this._url = uri.toString();
  10935. }
  10936. },
  10937. /**
  10938. * The file extension of the resource.
  10939. *
  10940. * @memberof Resource.prototype
  10941. * @type {String}
  10942. *
  10943. * @readonly
  10944. */
  10945. extension: {
  10946. get: function() {
  10947. return getExtensionFromUri(this._url);
  10948. }
  10949. },
  10950. /**
  10951. * True if the Resource refers to a data URI.
  10952. *
  10953. * @memberof Resource.prototype
  10954. * @type {Boolean}
  10955. */
  10956. isDataUri: {
  10957. get: function() {
  10958. return isDataUri(this._url);
  10959. }
  10960. },
  10961. /**
  10962. * True if the Resource refers to a blob URI.
  10963. *
  10964. * @memberof Resource.prototype
  10965. * @type {Boolean}
  10966. */
  10967. isBlobUri: {
  10968. get: function() {
  10969. return isBlobUri(this._url);
  10970. }
  10971. },
  10972. /**
  10973. * True if the Resource refers to a cross origin URL.
  10974. *
  10975. * @memberof Resource.prototype
  10976. * @type {Boolean}
  10977. */
  10978. isCrossOriginUrl: {
  10979. get: function() {
  10980. return isCrossOriginUrl(this._url);
  10981. }
  10982. },
  10983. /**
  10984. * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
  10985. *
  10986. * @memberof Resource.prototype
  10987. * @type {Boolean}
  10988. */
  10989. hasHeaders: {
  10990. get: function() {
  10991. return (Object.keys(this.headers).length > 0);
  10992. }
  10993. }
  10994. });
  10995. /**
  10996. * Returns the url, optional with the query string and processed by a proxy.
  10997. *
  10998. * @param {Boolean} [query=false] If true, the query string is included.
  10999. * @param {Boolean} [proxy=false] If true, the url is processed the proxy object if defined.
  11000. *
  11001. * @returns {String} The url with all the requested components.
  11002. */
  11003. Resource.prototype.getUrlComponent = function(query, proxy) {
  11004. if(this.isDataUri) {
  11005. return this._url;
  11006. }
  11007. var uri = new URI(this._url);
  11008. if (query) {
  11009. stringifyQuery(uri, this);
  11010. }
  11011. // objectToQuery escapes the placeholders. Undo that.
  11012. var url = uri.toString().replace(/%7B/g, '{').replace(/%7D/g, '}');
  11013. var templateValues = this._templateValues;
  11014. url = url.replace(/{(.*?)}/g, function(match, key) {
  11015. var replacement = templateValues[key];
  11016. if (defined.defined(replacement)) {
  11017. // use the replacement value from templateValues if there is one...
  11018. return encodeURIComponent(replacement);
  11019. }
  11020. // otherwise leave it unchanged
  11021. return match;
  11022. });
  11023. if (proxy && defined.defined(this.proxy)) {
  11024. url = this.proxy.getURL(url);
  11025. }
  11026. return url;
  11027. };
  11028. /**
  11029. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  11030. * 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.
  11031. *
  11032. * @param {Object} params The query parameters
  11033. * @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.
  11034. */
  11035. Resource.prototype.setQueryParameters = function(params, useAsDefault) {
  11036. if (useAsDefault) {
  11037. this._queryParameters = combineQueryParameters(this._queryParameters, params, false);
  11038. } else {
  11039. this._queryParameters = combineQueryParameters(params, this._queryParameters, false);
  11040. }
  11041. };
  11042. /**
  11043. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  11044. * as opposed to adding them one at a time to the queryParameters property.
  11045. *
  11046. * @param {Object} params The query parameters
  11047. */
  11048. Resource.prototype.appendQueryParameters = function(params) {
  11049. this._queryParameters = combineQueryParameters(params, this._queryParameters, true);
  11050. };
  11051. /**
  11052. * Combines the specified object and the existing template values. This allows you to add many values at once,
  11053. * 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.
  11054. *
  11055. * @param {Object} template The template values
  11056. * @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.
  11057. */
  11058. Resource.prototype.setTemplateValues = function(template, useAsDefault) {
  11059. if (useAsDefault) {
  11060. this._templateValues = combine(this._templateValues, template);
  11061. } else {
  11062. this._templateValues = combine(template, this._templateValues);
  11063. }
  11064. };
  11065. /**
  11066. * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
  11067. *
  11068. * @param {Object} options An object with the following properties
  11069. * @param {String} [options.url] The url that will be resolved relative to the url of the current instance.
  11070. * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
  11071. * @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.
  11072. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11073. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11074. * @param {Resource~RetryCallback} [options.retryCallback] The function to call when loading the resource fails.
  11075. * @param {Number} [options.retryAttempts] The number of times the retryCallback should be called before giving up.
  11076. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11077. * @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.
  11078. *
  11079. * @returns {Resource} The resource derived from the current one.
  11080. */
  11081. Resource.prototype.getDerivedResource = function(options) {
  11082. var resource = this.clone();
  11083. resource._retryCount = 0;
  11084. if (defined.defined(options.url)) {
  11085. var uri = new URI(options.url);
  11086. var preserveQueryParameters = defaultValue.defaultValue(options.preserveQueryParameters, false);
  11087. parseQuery(uri, resource, true, preserveQueryParameters);
  11088. // Remove the fragment as it's not sent with a request
  11089. uri.fragment = undefined;
  11090. resource._url = uri.resolve(new URI(getAbsoluteUri(this._url))).toString();
  11091. }
  11092. if (defined.defined(options.queryParameters)) {
  11093. resource._queryParameters = combine(options.queryParameters, resource._queryParameters);
  11094. }
  11095. if (defined.defined(options.templateValues)) {
  11096. resource._templateValues = combine(options.templateValues, resource.templateValues);
  11097. }
  11098. if (defined.defined(options.headers)) {
  11099. resource.headers = combine(options.headers, resource.headers);
  11100. }
  11101. if (defined.defined(options.proxy)) {
  11102. resource.proxy = options.proxy;
  11103. }
  11104. if (defined.defined(options.request)) {
  11105. resource.request = options.request;
  11106. }
  11107. if (defined.defined(options.retryCallback)) {
  11108. resource.retryCallback = options.retryCallback;
  11109. }
  11110. if (defined.defined(options.retryAttempts)) {
  11111. resource.retryAttempts = options.retryAttempts;
  11112. }
  11113. return resource;
  11114. };
  11115. /**
  11116. * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
  11117. *
  11118. * @param {Error} [error] The error that was encountered.
  11119. *
  11120. * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
  11121. *
  11122. * @private
  11123. */
  11124. Resource.prototype.retryOnError = function(error) {
  11125. var retryCallback = this.retryCallback;
  11126. if ((typeof retryCallback !== 'function') || (this._retryCount >= this.retryAttempts)) {
  11127. return when.when(false);
  11128. }
  11129. var that = this;
  11130. return when.when(retryCallback(this, error))
  11131. .then(function(result) {
  11132. ++that._retryCount;
  11133. return result;
  11134. });
  11135. };
  11136. /**
  11137. * Duplicates a Resource instance.
  11138. *
  11139. * @param {Resource} [result] The object onto which to store the result.
  11140. *
  11141. * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
  11142. */
  11143. Resource.prototype.clone = function(result) {
  11144. if (!defined.defined(result)) {
  11145. result = new Resource({
  11146. url : this._url
  11147. });
  11148. }
  11149. result._url = this._url;
  11150. result._queryParameters = clone(this._queryParameters);
  11151. result._templateValues = clone(this._templateValues);
  11152. result.headers = clone(this.headers);
  11153. result.proxy = this.proxy;
  11154. result.retryCallback = this.retryCallback;
  11155. result.retryAttempts = this.retryAttempts;
  11156. result._retryCount = 0;
  11157. result.request = this.request.clone();
  11158. return result;
  11159. };
  11160. /**
  11161. * Returns the base path of the Resource.
  11162. *
  11163. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  11164. *
  11165. * @returns {String} The base URI of the resource
  11166. */
  11167. Resource.prototype.getBaseUri = function(includeQuery) {
  11168. return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  11169. };
  11170. /**
  11171. * Appends a forward slash to the URL.
  11172. */
  11173. Resource.prototype.appendForwardSlash = function() {
  11174. this._url = appendForwardSlash(this._url);
  11175. };
  11176. /**
  11177. * Asynchronously loads the resource as raw binary data. Returns a promise that will resolve to
  11178. * an ArrayBuffer once loaded, or reject if the resource failed to load. The data is loaded
  11179. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11180. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11181. *
  11182. * @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.
  11183. *
  11184. * @example
  11185. * // load a single URL asynchronously
  11186. * resource.fetchArrayBuffer().then(function(arrayBuffer) {
  11187. * // use the data
  11188. * }).otherwise(function(error) {
  11189. * // an error occurred
  11190. * });
  11191. *
  11192. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11193. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11194. */
  11195. Resource.prototype.fetchArrayBuffer = function () {
  11196. return this.fetch({
  11197. responseType : 'arraybuffer'
  11198. });
  11199. };
  11200. /**
  11201. * Creates a Resource and calls fetchArrayBuffer() on it.
  11202. *
  11203. * @param {String|Object} options A url or an object with the following properties
  11204. * @param {String} options.url The url of the resource.
  11205. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11206. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11207. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11208. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11209. * @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.
  11210. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11211. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11212. * @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.
  11213. */
  11214. Resource.fetchArrayBuffer = function (options) {
  11215. var resource = new Resource(options);
  11216. return resource.fetchArrayBuffer();
  11217. };
  11218. /**
  11219. * Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
  11220. * a Blob once loaded, or reject if the resource failed to load. The data is loaded
  11221. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11222. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11223. *
  11224. * @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.
  11225. *
  11226. * @example
  11227. * // load a single URL asynchronously
  11228. * resource.fetchBlob().then(function(blob) {
  11229. * // use the data
  11230. * }).otherwise(function(error) {
  11231. * // an error occurred
  11232. * });
  11233. *
  11234. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11235. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11236. */
  11237. Resource.prototype.fetchBlob = function () {
  11238. return this.fetch({
  11239. responseType : 'blob'
  11240. });
  11241. };
  11242. /**
  11243. * Creates a Resource and calls fetchBlob() on it.
  11244. *
  11245. * @param {String|Object} options A url or an object with the following properties
  11246. * @param {String} options.url The url of the resource.
  11247. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11248. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11249. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11250. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11251. * @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.
  11252. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11253. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11254. * @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.
  11255. */
  11256. Resource.fetchBlob = function (options) {
  11257. var resource = new Resource(options);
  11258. return resource.fetchBlob();
  11259. };
  11260. /**
  11261. * Asynchronously loads the given image resource. Returns a promise that will resolve to
  11262. * 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
  11263. * {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
  11264. *
  11265. * @param {Object} [options] An object with the following properties.
  11266. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  11267. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  11268. * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  11269. * @returns {Promise.<ImageBitmap>|Promise.<Image>|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.
  11270. *
  11271. *
  11272. * @example
  11273. * // load a single image asynchronously
  11274. * resource.fetchImage().then(function(image) {
  11275. * // use the loaded image
  11276. * }).otherwise(function(error) {
  11277. * // an error occurred
  11278. * });
  11279. *
  11280. * // load several images in parallel
  11281. * when.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
  11282. * // images is an array containing all the loaded images
  11283. * });
  11284. *
  11285. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11286. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11287. */
  11288. Resource.prototype.fetchImage = function (options) {
  11289. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  11290. var preferImageBitmap = defaultValue.defaultValue(options.preferImageBitmap, false);
  11291. var preferBlob = defaultValue.defaultValue(options.preferBlob, false);
  11292. var flipY = defaultValue.defaultValue(options.flipY, false);
  11293. checkAndResetRequest(this.request);
  11294. // We try to load the image normally if
  11295. // 1. Blobs aren't supported
  11296. // 2. It's a data URI
  11297. // 3. It's a blob URI
  11298. // 4. It doesn't have request headers and we preferBlob is false
  11299. if (!xhrBlobSupported || this.isDataUri || this.isBlobUri || (!this.hasHeaders && !preferBlob)) {
  11300. return fetchImage({
  11301. resource: this,
  11302. flipY: flipY,
  11303. preferImageBitmap: preferImageBitmap
  11304. });
  11305. }
  11306. var blobPromise = this.fetchBlob();
  11307. if (!defined.defined(blobPromise)) {
  11308. return;
  11309. }
  11310. var supportsImageBitmap;
  11311. var useImageBitmap;
  11312. var generatedBlobResource;
  11313. var generatedBlob;
  11314. return Resource.supportsImageBitmapOptions()
  11315. .then(function(result) {
  11316. supportsImageBitmap = result;
  11317. useImageBitmap = supportsImageBitmap && preferImageBitmap;
  11318. return blobPromise;
  11319. })
  11320. .then(function(blob) {
  11321. if (!defined.defined(blob)) {
  11322. return;
  11323. }
  11324. generatedBlob = blob;
  11325. if (useImageBitmap) {
  11326. return Resource.createImageBitmapFromBlob(blob, {
  11327. flipY: flipY,
  11328. premultiplyAlpha: false
  11329. });
  11330. }
  11331. var blobUrl = window.URL.createObjectURL(blob);
  11332. generatedBlobResource = new Resource({
  11333. url: blobUrl
  11334. });
  11335. return fetchImage({
  11336. resource: generatedBlobResource,
  11337. flipY: flipY,
  11338. preferImageBitmap: false
  11339. });
  11340. })
  11341. .then(function(image) {
  11342. if (!defined.defined(image)) {
  11343. return;
  11344. }
  11345. // The blob object may be needed for use by a TileDiscardPolicy,
  11346. // so attach it to the image.
  11347. image.blob = generatedBlob;
  11348. if (useImageBitmap) {
  11349. return image;
  11350. }
  11351. window.URL.revokeObjectURL(generatedBlobResource.url);
  11352. return image;
  11353. })
  11354. .otherwise(function(error) {
  11355. if (defined.defined(generatedBlobResource)) {
  11356. window.URL.revokeObjectURL(generatedBlobResource.url);
  11357. }
  11358. // If the blob load succeeded but the image decode failed, attach the blob
  11359. // to the error object for use by a TileDiscardPolicy.
  11360. // In particular, BingMapsImageryProvider uses this to detect the
  11361. // zero-length response that is returned when a tile is not available.
  11362. error.blob = generatedBlob;
  11363. return when.when.reject(error);
  11364. });
  11365. };
  11366. /**
  11367. * Fetches an image and returns a promise to it.
  11368. *
  11369. * @param {Object} [options] An object with the following properties.
  11370. * @param {Resource} [options.resource] Resource object that points to an image to fetch.
  11371. * @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  11372. * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  11373. *
  11374. * @private
  11375. */
  11376. function fetchImage(options) {
  11377. var resource = options.resource;
  11378. var flipY = options.flipY;
  11379. var preferImageBitmap = options.preferImageBitmap;
  11380. var request = resource.request;
  11381. request.url = resource.url;
  11382. request.requestFunction = function() {
  11383. var url = resource.url;
  11384. var crossOrigin = false;
  11385. // data URIs can't have crossorigin set.
  11386. if (!resource.isDataUri && !resource.isBlobUri) {
  11387. crossOrigin = resource.isCrossOriginUrl;
  11388. }
  11389. var deferred = when.when.defer();
  11390. Resource._Implementations.createImage(url, crossOrigin, deferred, flipY, preferImageBitmap);
  11391. return deferred.promise;
  11392. };
  11393. var promise = RequestScheduler.request(request);
  11394. if (!defined.defined(promise)) {
  11395. return;
  11396. }
  11397. return promise
  11398. .otherwise(function(e) {
  11399. // Don't retry cancelled or otherwise aborted requests
  11400. if (request.state !== RequestState$1.FAILED) {
  11401. return when.when.reject(e);
  11402. }
  11403. return resource.retryOnError(e)
  11404. .then(function(retry) {
  11405. if (retry) {
  11406. // Reset request so it can try again
  11407. request.state = RequestState$1.UNISSUED;
  11408. request.deferred = undefined;
  11409. return fetchImage({
  11410. resource: resource,
  11411. flipY: flipY,
  11412. preferImageBitmap: preferImageBitmap
  11413. });
  11414. }
  11415. return when.when.reject(e);
  11416. });
  11417. });
  11418. }
  11419. /**
  11420. * Creates a Resource and calls fetchImage() on it.
  11421. *
  11422. * @param {String|Object} options A url or an object with the following properties
  11423. * @param {String} options.url The url of the resource.
  11424. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11425. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11426. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11427. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11428. * @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>.
  11429. * @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.
  11430. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11431. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11432. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  11433. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  11434. * @returns {Promise.<ImageBitmap>|Promise.<Image>|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.
  11435. */
  11436. Resource.fetchImage = function (options) {
  11437. var resource = new Resource(options);
  11438. return resource.fetchImage({
  11439. flipY: options.flipY,
  11440. preferBlob: options.preferBlob,
  11441. preferImageBitmap: options.preferImageBitmap
  11442. });
  11443. };
  11444. /**
  11445. * Asynchronously loads the given resource as text. Returns a promise that will resolve to
  11446. * a String once loaded, or reject if the resource failed to load. The data is loaded
  11447. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11448. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11449. *
  11450. * @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.
  11451. *
  11452. * @example
  11453. * // load text from a URL, setting a custom header
  11454. * var resource = new Resource({
  11455. * url: 'http://someUrl.com/someJson.txt',
  11456. * headers: {
  11457. * 'X-Custom-Header' : 'some value'
  11458. * }
  11459. * });
  11460. * resource.fetchText().then(function(text) {
  11461. * // Do something with the text
  11462. * }).otherwise(function(error) {
  11463. * // an error occurred
  11464. * });
  11465. *
  11466. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  11467. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11468. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11469. */
  11470. Resource.prototype.fetchText = function() {
  11471. return this.fetch({
  11472. responseType : 'text'
  11473. });
  11474. };
  11475. /**
  11476. * Creates a Resource and calls fetchText() on it.
  11477. *
  11478. * @param {String|Object} options A url or an object with the following properties
  11479. * @param {String} options.url The url of the resource.
  11480. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11481. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11482. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11483. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11484. * @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.
  11485. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11486. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11487. * @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.
  11488. */
  11489. Resource.fetchText = function (options) {
  11490. var resource = new Resource(options);
  11491. return resource.fetchText();
  11492. };
  11493. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  11494. /**
  11495. * Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
  11496. * a JSON object once loaded, or reject if the resource failed to load. The data is loaded
  11497. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11498. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  11499. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  11500. * already specified.
  11501. *
  11502. * @returns {Promise.<Object>|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.
  11503. *
  11504. *
  11505. * @example
  11506. * resource.fetchJson().then(function(jsonData) {
  11507. * // Do something with the JSON object
  11508. * }).otherwise(function(error) {
  11509. * // an error occurred
  11510. * });
  11511. *
  11512. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11513. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11514. */
  11515. Resource.prototype.fetchJson = function() {
  11516. var promise = this.fetch({
  11517. responseType : 'text',
  11518. headers: {
  11519. Accept : 'application/json,*/*;q=0.01'
  11520. }
  11521. });
  11522. if (!defined.defined(promise)) {
  11523. return undefined;
  11524. }
  11525. return promise
  11526. .then(function(value) {
  11527. if (!defined.defined(value)) {
  11528. return;
  11529. }
  11530. return JSON.parse(value);
  11531. });
  11532. };
  11533. /**
  11534. * Creates a Resource and calls fetchJson() on it.
  11535. *
  11536. * @param {String|Object} options A url or an object with the following properties
  11537. * @param {String} options.url The url of the resource.
  11538. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11539. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11540. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11541. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11542. * @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.
  11543. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11544. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11545. * @returns {Promise.<Object>|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.
  11546. */
  11547. Resource.fetchJson = function (options) {
  11548. var resource = new Resource(options);
  11549. return resource.fetchJson();
  11550. };
  11551. /**
  11552. * Asynchronously loads the given resource as XML. Returns a promise that will resolve to
  11553. * an XML Document once loaded, or reject if the resource failed to load. The data is loaded
  11554. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11555. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11556. *
  11557. * @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.
  11558. *
  11559. *
  11560. * @example
  11561. * // load XML from a URL, setting a custom header
  11562. * Cesium.loadXML('http://someUrl.com/someXML.xml', {
  11563. * 'X-Custom-Header' : 'some value'
  11564. * }).then(function(document) {
  11565. * // Do something with the document
  11566. * }).otherwise(function(error) {
  11567. * // an error occurred
  11568. * });
  11569. *
  11570. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  11571. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11572. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11573. */
  11574. Resource.prototype.fetchXML = function() {
  11575. return this.fetch({
  11576. responseType : 'document',
  11577. overrideMimeType : 'text/xml'
  11578. });
  11579. };
  11580. /**
  11581. * Creates a Resource and calls fetchXML() on it.
  11582. *
  11583. * @param {String|Object} options A url or an object with the following properties
  11584. * @param {String} options.url The url of the resource.
  11585. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11586. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11587. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11588. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11589. * @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.
  11590. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11591. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11592. * @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.
  11593. */
  11594. Resource.fetchXML = function (options) {
  11595. var resource = new Resource(options);
  11596. return resource.fetchXML();
  11597. };
  11598. /**
  11599. * Requests a resource using JSONP.
  11600. *
  11601. * @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
  11602. * @returns {Promise.<Object>|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.
  11603. *
  11604. *
  11605. * @example
  11606. * // load a data asynchronously
  11607. * resource.fetchJsonp().then(function(data) {
  11608. * // use the loaded data
  11609. * }).otherwise(function(error) {
  11610. * // an error occurred
  11611. * });
  11612. *
  11613. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11614. */
  11615. Resource.prototype.fetchJsonp = function(callbackParameterName) {
  11616. callbackParameterName = defaultValue.defaultValue(callbackParameterName, 'callback');
  11617. checkAndResetRequest(this.request);
  11618. //generate a unique function name
  11619. var functionName;
  11620. do {
  11621. functionName = 'loadJsonp' + Math.random().toString().substring(2, 8);
  11622. } while (defined.defined(window[functionName]));
  11623. return fetchJsonp(this, callbackParameterName, functionName);
  11624. };
  11625. function fetchJsonp(resource, callbackParameterName, functionName) {
  11626. var callbackQuery = {};
  11627. callbackQuery[callbackParameterName] = functionName;
  11628. resource.setQueryParameters(callbackQuery);
  11629. var request = resource.request;
  11630. request.url = resource.url;
  11631. request.requestFunction = function() {
  11632. var deferred = when.when.defer();
  11633. //assign a function with that name in the global scope
  11634. window[functionName] = function(data) {
  11635. deferred.resolve(data);
  11636. try {
  11637. delete window[functionName];
  11638. } catch (e) {
  11639. window[functionName] = undefined;
  11640. }
  11641. };
  11642. Resource._Implementations.loadAndExecuteScript(resource.url, functionName, deferred);
  11643. return deferred.promise;
  11644. };
  11645. var promise = RequestScheduler.request(request);
  11646. if (!defined.defined(promise)) {
  11647. return;
  11648. }
  11649. return promise
  11650. .otherwise(function(e) {
  11651. if (request.state !== RequestState$1.FAILED) {
  11652. return when.when.reject(e);
  11653. }
  11654. return resource.retryOnError(e)
  11655. .then(function(retry) {
  11656. if (retry) {
  11657. // Reset request so it can try again
  11658. request.state = RequestState$1.UNISSUED;
  11659. request.deferred = undefined;
  11660. return fetchJsonp(resource, callbackParameterName, functionName);
  11661. }
  11662. return when.when.reject(e);
  11663. });
  11664. });
  11665. }
  11666. /**
  11667. * Creates a Resource from a URL and calls fetchJsonp() on it.
  11668. *
  11669. * @param {String|Object} options A url or an object with the following properties
  11670. * @param {String} options.url The url of the resource.
  11671. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11672. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11673. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11674. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11675. * @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.
  11676. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11677. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11678. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
  11679. * @returns {Promise.<Object>|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.
  11680. */
  11681. Resource.fetchJsonp = function (options) {
  11682. var resource = new Resource(options);
  11683. return resource.fetchJsonp(options.callbackParameterName);
  11684. };
  11685. /**
  11686. * @private
  11687. */
  11688. Resource.prototype._makeRequest = function(options) {
  11689. var resource = this;
  11690. checkAndResetRequest(resource.request);
  11691. var request = resource.request;
  11692. request.url = resource.url;
  11693. request.requestFunction = function() {
  11694. var responseType = options.responseType;
  11695. var headers = combine(options.headers, resource.headers);
  11696. var overrideMimeType = options.overrideMimeType;
  11697. var method = options.method;
  11698. var data = options.data;
  11699. var deferred = when.when.defer();
  11700. var xhr = Resource._Implementations.loadWithXhr(resource.url, responseType, method, data, headers, deferred, overrideMimeType);
  11701. if (defined.defined(xhr) && defined.defined(xhr.abort)) {
  11702. request.cancelFunction = function() {
  11703. xhr.abort();
  11704. };
  11705. }
  11706. return deferred.promise;
  11707. };
  11708. var promise = RequestScheduler.request(request);
  11709. if (!defined.defined(promise)) {
  11710. return;
  11711. }
  11712. return promise
  11713. .then(function(data) {
  11714. return data;
  11715. })
  11716. .otherwise(function(e) {
  11717. if (request.state !== RequestState$1.FAILED) {
  11718. return when.when.reject(e);
  11719. }
  11720. return resource.retryOnError(e)
  11721. .then(function(retry) {
  11722. if (retry) {
  11723. // Reset request so it can try again
  11724. request.state = RequestState$1.UNISSUED;
  11725. request.deferred = undefined;
  11726. return resource.fetch(options);
  11727. }
  11728. return when.when.reject(e);
  11729. });
  11730. });
  11731. };
  11732. var dataUriRegex$1 = /^data:(.*?)(;base64)?,(.*)$/;
  11733. function decodeDataUriText(isBase64, data) {
  11734. var result = decodeURIComponent(data);
  11735. if (isBase64) {
  11736. return atob(result);
  11737. }
  11738. return result;
  11739. }
  11740. function decodeDataUriArrayBuffer(isBase64, data) {
  11741. var byteString = decodeDataUriText(isBase64, data);
  11742. var buffer = new ArrayBuffer(byteString.length);
  11743. var view = new Uint8Array(buffer);
  11744. for (var i = 0; i < byteString.length; i++) {
  11745. view[i] = byteString.charCodeAt(i);
  11746. }
  11747. return buffer;
  11748. }
  11749. function decodeDataUri(dataUriRegexResult, responseType) {
  11750. responseType = defaultValue.defaultValue(responseType, '');
  11751. var mimeType = dataUriRegexResult[1];
  11752. var isBase64 = !!dataUriRegexResult[2];
  11753. var data = dataUriRegexResult[3];
  11754. switch (responseType) {
  11755. case '':
  11756. case 'text':
  11757. return decodeDataUriText(isBase64, data);
  11758. case 'arraybuffer':
  11759. return decodeDataUriArrayBuffer(isBase64, data);
  11760. case 'blob':
  11761. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  11762. return new Blob([buffer], {
  11763. type : mimeType
  11764. });
  11765. case 'document':
  11766. var parser = new DOMParser();
  11767. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  11768. case 'json':
  11769. return JSON.parse(decodeDataUriText(isBase64, data));
  11770. default:
  11771. //>>includeStart('debug', pragmas.debug);
  11772. throw new Check.DeveloperError('Unhandled responseType: ' + responseType);
  11773. //>>includeEnd('debug');
  11774. }
  11775. }
  11776. /**
  11777. * Asynchronously loads the given resource. Returns a promise that will resolve to
  11778. * the result once loaded, or reject if the resource failed to load. The data is loaded
  11779. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11780. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
  11781. * the more specific functions eg. fetchJson, fetchBlob, etc.
  11782. *
  11783. * @param {Object} [options] Object with the following properties:
  11784. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11785. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  11786. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11787. * @returns {Promise.<Object>|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.
  11788. *
  11789. *
  11790. * @example
  11791. * resource.fetch()
  11792. * .then(function(body) {
  11793. * // use the data
  11794. * }).otherwise(function(error) {
  11795. * // an error occurred
  11796. * });
  11797. *
  11798. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11799. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11800. */
  11801. Resource.prototype.fetch = function(options) {
  11802. options = defaultClone(options, {});
  11803. options.method = 'GET';
  11804. return this._makeRequest(options);
  11805. };
  11806. /**
  11807. * Creates a Resource from a URL and calls fetch() on it.
  11808. *
  11809. * @param {String|Object} options A url or an object with the following properties
  11810. * @param {String} options.url The url of the resource.
  11811. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11812. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11813. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11814. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11815. * @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.
  11816. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11817. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11818. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11819. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11820. * @returns {Promise.<Object>|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.
  11821. */
  11822. Resource.fetch = function (options) {
  11823. var resource = new Resource(options);
  11824. return resource.fetch({
  11825. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  11826. responseType: options.responseType,
  11827. overrideMimeType: options.overrideMimeType
  11828. });
  11829. };
  11830. /**
  11831. * Asynchronously deletes the given resource. Returns a promise that will resolve to
  11832. * the result once loaded, or reject if the resource failed to load. The data is loaded
  11833. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11834. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11835. *
  11836. * @param {Object} [options] Object with the following properties:
  11837. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11838. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  11839. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11840. * @returns {Promise.<Object>|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.
  11841. *
  11842. *
  11843. * @example
  11844. * resource.delete()
  11845. * .then(function(body) {
  11846. * // use the data
  11847. * }).otherwise(function(error) {
  11848. * // an error occurred
  11849. * });
  11850. *
  11851. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11852. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11853. */
  11854. Resource.prototype.delete = function(options) {
  11855. options = defaultClone(options, {});
  11856. options.method = 'DELETE';
  11857. return this._makeRequest(options);
  11858. };
  11859. /**
  11860. * Creates a Resource from a URL and calls delete() on it.
  11861. *
  11862. * @param {String|Object} options A url or an object with the following properties
  11863. * @param {String} options.url The url of the resource.
  11864. * @param {Object} [options.data] Data that is posted with the resource.
  11865. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11866. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11867. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11868. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11869. * @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.
  11870. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11871. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11872. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11873. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11874. * @returns {Promise.<Object>|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.
  11875. */
  11876. Resource.delete = function (options) {
  11877. var resource = new Resource(options);
  11878. return resource.delete({
  11879. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  11880. responseType: options.responseType,
  11881. overrideMimeType: options.overrideMimeType,
  11882. data: options.data
  11883. });
  11884. };
  11885. /**
  11886. * Asynchronously gets headers the given resource. Returns a promise that will resolve to
  11887. * the result once loaded, or reject if the resource failed to load. The data is loaded
  11888. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11889. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11890. *
  11891. * @param {Object} [options] Object with the following properties:
  11892. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11893. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  11894. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11895. * @returns {Promise.<Object>|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.
  11896. *
  11897. *
  11898. * @example
  11899. * resource.head()
  11900. * .then(function(headers) {
  11901. * // use the data
  11902. * }).otherwise(function(error) {
  11903. * // an error occurred
  11904. * });
  11905. *
  11906. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11907. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11908. */
  11909. Resource.prototype.head = function(options) {
  11910. options = defaultClone(options, {});
  11911. options.method = 'HEAD';
  11912. return this._makeRequest(options);
  11913. };
  11914. /**
  11915. * Creates a Resource from a URL and calls head() on it.
  11916. *
  11917. * @param {String|Object} options A url or an object with the following properties
  11918. * @param {String} options.url The url of the resource.
  11919. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11920. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11921. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11922. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11923. * @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.
  11924. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11925. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11926. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11927. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11928. * @returns {Promise.<Object>|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.
  11929. */
  11930. Resource.head = function (options) {
  11931. var resource = new Resource(options);
  11932. return resource.head({
  11933. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  11934. responseType: options.responseType,
  11935. overrideMimeType: options.overrideMimeType
  11936. });
  11937. };
  11938. /**
  11939. * Asynchronously gets options the given resource. Returns a promise that will resolve to
  11940. * the result once loaded, or reject if the resource failed to load. The data is loaded
  11941. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11942. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11943. *
  11944. * @param {Object} [options] Object with the following properties:
  11945. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11946. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  11947. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11948. * @returns {Promise.<Object>|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.
  11949. *
  11950. *
  11951. * @example
  11952. * resource.options()
  11953. * .then(function(headers) {
  11954. * // use the data
  11955. * }).otherwise(function(error) {
  11956. * // an error occurred
  11957. * });
  11958. *
  11959. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  11960. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  11961. */
  11962. Resource.prototype.options = function(options) {
  11963. options = defaultClone(options, {});
  11964. options.method = 'OPTIONS';
  11965. return this._makeRequest(options);
  11966. };
  11967. /**
  11968. * Creates a Resource from a URL and calls options() on it.
  11969. *
  11970. * @param {String|Object} options A url or an object with the following properties
  11971. * @param {String} options.url The url of the resource.
  11972. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  11973. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  11974. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  11975. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  11976. * @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.
  11977. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  11978. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  11979. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  11980. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  11981. * @returns {Promise.<Object>|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.
  11982. */
  11983. Resource.options = function (options) {
  11984. var resource = new Resource(options);
  11985. return resource.options({
  11986. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  11987. responseType: options.responseType,
  11988. overrideMimeType: options.overrideMimeType
  11989. });
  11990. };
  11991. /**
  11992. * Asynchronously posts data to the given resource. Returns a promise that will resolve to
  11993. * the result once loaded, or reject if the resource failed to load. The data is loaded
  11994. * using XMLHttpRequest, which means that in order to make requests to another origin,
  11995. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  11996. *
  11997. * @param {Object} data Data that is posted with the resource.
  11998. * @param {Object} [options] Object with the following properties:
  11999. * @param {Object} [options.data] Data that is posted with the resource.
  12000. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12001. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12002. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12003. * @returns {Promise.<Object>|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.
  12004. *
  12005. *
  12006. * @example
  12007. * resource.post(data)
  12008. * .then(function(result) {
  12009. * // use the result
  12010. * }).otherwise(function(error) {
  12011. * // an error occurred
  12012. * });
  12013. *
  12014. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12015. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12016. */
  12017. Resource.prototype.post = function(data, options) {
  12018. Check.Check.defined('data', data);
  12019. options = defaultClone(options, {});
  12020. options.method = 'POST';
  12021. options.data = data;
  12022. return this._makeRequest(options);
  12023. };
  12024. /**
  12025. * Creates a Resource from a URL and calls post() on it.
  12026. *
  12027. * @param {Object} options A url or an object with the following properties
  12028. * @param {String} options.url The url of the resource.
  12029. * @param {Object} options.data Data that is posted with the resource.
  12030. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12031. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12032. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12033. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  12034. * @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.
  12035. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12036. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12037. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12038. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12039. * @returns {Promise.<Object>|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.
  12040. */
  12041. Resource.post = function (options) {
  12042. var resource = new Resource(options);
  12043. return resource.post(options.data, {
  12044. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  12045. responseType: options.responseType,
  12046. overrideMimeType: options.overrideMimeType
  12047. });
  12048. };
  12049. /**
  12050. * Asynchronously puts data to the given resource. Returns a promise that will resolve to
  12051. * the result once loaded, or reject if the resource failed to load. The data is loaded
  12052. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12053. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12054. *
  12055. * @param {Object} data Data that is posted with the resource.
  12056. * @param {Object} [options] Object with the following properties:
  12057. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12058. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12059. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12060. * @returns {Promise.<Object>|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.
  12061. *
  12062. *
  12063. * @example
  12064. * resource.put(data)
  12065. * .then(function(result) {
  12066. * // use the result
  12067. * }).otherwise(function(error) {
  12068. * // an error occurred
  12069. * });
  12070. *
  12071. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12072. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12073. */
  12074. Resource.prototype.put = function(data, options) {
  12075. Check.Check.defined('data', data);
  12076. options = defaultClone(options, {});
  12077. options.method = 'PUT';
  12078. options.data = data;
  12079. return this._makeRequest(options);
  12080. };
  12081. /**
  12082. * Creates a Resource from a URL and calls put() on it.
  12083. *
  12084. * @param {Object} options A url or an object with the following properties
  12085. * @param {String} options.url The url of the resource.
  12086. * @param {Object} options.data Data that is posted with the resource.
  12087. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12088. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12089. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12090. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  12091. * @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.
  12092. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12093. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12094. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12095. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12096. * @returns {Promise.<Object>|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.
  12097. */
  12098. Resource.put = function (options) {
  12099. var resource = new Resource(options);
  12100. return resource.put(options.data, {
  12101. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  12102. responseType: options.responseType,
  12103. overrideMimeType: options.overrideMimeType
  12104. });
  12105. };
  12106. /**
  12107. * Asynchronously patches data to the given resource. Returns a promise that will resolve to
  12108. * the result once loaded, or reject if the resource failed to load. The data is loaded
  12109. * using XMLHttpRequest, which means that in order to make requests to another origin,
  12110. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  12111. *
  12112. * @param {Object} data Data that is posted with the resource.
  12113. * @param {Object} [options] Object with the following properties:
  12114. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12115. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  12116. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12117. * @returns {Promise.<Object>|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.
  12118. *
  12119. *
  12120. * @example
  12121. * resource.patch(data)
  12122. * .then(function(result) {
  12123. * // use the result
  12124. * }).otherwise(function(error) {
  12125. * // an error occurred
  12126. * });
  12127. *
  12128. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  12129. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  12130. */
  12131. Resource.prototype.patch = function(data, options) {
  12132. Check.Check.defined('data', data);
  12133. options = defaultClone(options, {});
  12134. options.method = 'PATCH';
  12135. options.data = data;
  12136. return this._makeRequest(options);
  12137. };
  12138. /**
  12139. * Creates a Resource from a URL and calls patch() on it.
  12140. *
  12141. * @param {Object} options A url or an object with the following properties
  12142. * @param {String} options.url The url of the resource.
  12143. * @param {Object} options.data Data that is posted with the resource.
  12144. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  12145. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  12146. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  12147. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  12148. * @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.
  12149. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  12150. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  12151. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  12152. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  12153. * @returns {Promise.<Object>|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.
  12154. */
  12155. Resource.patch = function (options) {
  12156. var resource = new Resource(options);
  12157. return resource.patch(options.data, {
  12158. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  12159. responseType: options.responseType,
  12160. overrideMimeType: options.overrideMimeType
  12161. });
  12162. };
  12163. /**
  12164. * Contains implementations of functions that can be replaced for testing
  12165. *
  12166. * @private
  12167. */
  12168. Resource._Implementations = {};
  12169. function loadImageElement(url, crossOrigin, deferred) {
  12170. var image = new Image();
  12171. image.onload = function() {
  12172. deferred.resolve(image);
  12173. };
  12174. image.onerror = function(e) {
  12175. deferred.reject(e);
  12176. };
  12177. if (crossOrigin) {
  12178. if (TrustedServers.contains(url)) {
  12179. image.crossOrigin = 'use-credentials';
  12180. } else {
  12181. image.crossOrigin = '';
  12182. }
  12183. }
  12184. image.src = url;
  12185. }
  12186. Resource._Implementations.createImage = function(url, crossOrigin, deferred, flipY, preferImageBitmap) {
  12187. // Passing an Image to createImageBitmap will force it to run on the main thread
  12188. // since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
  12189. // See:
  12190. // https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
  12191. // https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
  12192. Resource.supportsImageBitmapOptions()
  12193. .then(function(supportsImageBitmap) {
  12194. // We can only use ImageBitmap if we can flip on decode.
  12195. // See: https://github.com/AnalyticalGraphicsInc/cesium/pull/7579#issuecomment-466146898
  12196. if (!(supportsImageBitmap && preferImageBitmap)) {
  12197. loadImageElement(url, crossOrigin, deferred);
  12198. return;
  12199. }
  12200. return Resource.fetchBlob({
  12201. url: url
  12202. })
  12203. .then(function(blob) {
  12204. if (!defined.defined(blob)) {
  12205. deferred.reject(new RuntimeError.RuntimeError('Successfully retrieved ' + url + ' but it contained no content.'));
  12206. return;
  12207. }
  12208. return Resource.createImageBitmapFromBlob(blob, {
  12209. flipY: flipY,
  12210. premultiplyAlpha: false
  12211. });
  12212. }).then(deferred.resolve);
  12213. })
  12214. .otherwise(deferred.reject);
  12215. };
  12216. /**
  12217. * Wrapper for createImageBitmap
  12218. *
  12219. * @private
  12220. */
  12221. Resource.createImageBitmapFromBlob = function(blob, options) {
  12222. Check.Check.defined('options', options);
  12223. Check.Check.typeOf.bool('options.flipY', options.flipY);
  12224. Check.Check.typeOf.bool('options.premultiplyAlpha', options.premultiplyAlpha);
  12225. return createImageBitmap(blob, {
  12226. imageOrientation: options.flipY ? 'flipY' : 'none',
  12227. premultiplyAlpha: options.premultiplyAlpha ? 'premultiply' : 'none'
  12228. });
  12229. };
  12230. function decodeResponse(loadWithHttpResponse, responseType) {
  12231. switch (responseType) {
  12232. case 'text':
  12233. return loadWithHttpResponse.toString('utf8');
  12234. case 'json':
  12235. return JSON.parse(loadWithHttpResponse.toString('utf8'));
  12236. default:
  12237. return new Uint8Array(loadWithHttpResponse).buffer;
  12238. }
  12239. }
  12240. function loadWithHttpRequest(url, responseType, method, data, headers, deferred, overrideMimeType) {
  12241. // Specifically use the Node version of require to avoid conflicts with the global
  12242. // require defined in the built version of Cesium.
  12243. var nodeRequire = global.require; // eslint-disable-line
  12244. // Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
  12245. var URL = nodeRequire('url').parse(url);
  12246. var http = URL.protocol === 'https:' ? nodeRequire('https') : nodeRequire('http');
  12247. var zlib = nodeRequire('zlib');
  12248. var options = {
  12249. protocol : URL.protocol,
  12250. hostname : URL.hostname,
  12251. port : URL.port,
  12252. path : URL.path,
  12253. query : URL.query,
  12254. method : method,
  12255. headers : headers
  12256. };
  12257. http.request(options)
  12258. .on('response', function(res) {
  12259. if (res.statusCode < 200 || res.statusCode >= 300) {
  12260. deferred.reject(new RequestErrorEvent(res.statusCode, res, res.headers));
  12261. return;
  12262. }
  12263. var chunkArray = [];
  12264. res.on('data', function(chunk) {
  12265. chunkArray.push(chunk);
  12266. });
  12267. res.on('end', function() {
  12268. var result = Buffer.concat(chunkArray); // eslint-disable-line
  12269. if (res.headers['content-encoding'] === 'gzip') {
  12270. zlib.gunzip(result, function(error, resultUnzipped) {
  12271. if (error) {
  12272. deferred.reject(new RuntimeError.RuntimeError('Error decompressing response.'));
  12273. } else {
  12274. deferred.resolve(decodeResponse(resultUnzipped, responseType));
  12275. }
  12276. });
  12277. } else {
  12278. deferred.resolve(decodeResponse(result, responseType));
  12279. }
  12280. });
  12281. }).on('error', function(e) {
  12282. deferred.reject(new RequestErrorEvent());
  12283. }).end();
  12284. }
  12285. var noXMLHttpRequest = typeof XMLHttpRequest === 'undefined';
  12286. Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  12287. var dataUriRegexResult = dataUriRegex$1.exec(url);
  12288. if (dataUriRegexResult !== null) {
  12289. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  12290. return;
  12291. }
  12292. if (noXMLHttpRequest) {
  12293. loadWithHttpRequest(url, responseType, method, data, headers, deferred);
  12294. return;
  12295. }
  12296. var xhr = new XMLHttpRequest();
  12297. if (TrustedServers.contains(url)) {
  12298. xhr.withCredentials = true;
  12299. }
  12300. xhr.open(method, url, true);
  12301. if (defined.defined(overrideMimeType) && defined.defined(xhr.overrideMimeType)) {
  12302. xhr.overrideMimeType(overrideMimeType);
  12303. }
  12304. if (defined.defined(headers)) {
  12305. for (var key in headers) {
  12306. if (headers.hasOwnProperty(key)) {
  12307. xhr.setRequestHeader(key, headers[key]);
  12308. }
  12309. }
  12310. }
  12311. if (defined.defined(responseType)) {
  12312. xhr.responseType = responseType;
  12313. }
  12314. // While non-standard, file protocol always returns a status of 0 on success
  12315. var localFile = false;
  12316. if (typeof url === 'string') {
  12317. localFile = (url.indexOf('file://') === 0) || (typeof window !== 'undefined' && window.location.origin === 'file://');
  12318. }
  12319. xhr.onload = function() {
  12320. if ((xhr.status < 200 || xhr.status >= 300) && !(localFile && xhr.status === 0)) {
  12321. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  12322. return;
  12323. }
  12324. var response = xhr.response;
  12325. var browserResponseType = xhr.responseType;
  12326. if (method === 'HEAD' || method === 'OPTIONS') {
  12327. var responseHeaderString = xhr.getAllResponseHeaders();
  12328. var splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
  12329. var responseHeaders = {};
  12330. splitHeaders.forEach(function (line) {
  12331. var parts = line.split(': ');
  12332. var header = parts.shift();
  12333. responseHeaders[header] = parts.join(': ');
  12334. });
  12335. deferred.resolve(responseHeaders);
  12336. return;
  12337. }
  12338. //All modern browsers will go into either the first or second if block or last else block.
  12339. //Other code paths support older browsers that either do not support the supplied responseType
  12340. //or do not support the xhr.response property.
  12341. if (xhr.status === 204) {
  12342. // accept no content
  12343. deferred.resolve();
  12344. } else if (defined.defined(response) && (!defined.defined(responseType) || (browserResponseType === responseType))) {
  12345. deferred.resolve(response);
  12346. } else if ((responseType === 'json') && typeof response === 'string') {
  12347. try {
  12348. deferred.resolve(JSON.parse(response));
  12349. } catch (e) {
  12350. deferred.reject(e);
  12351. }
  12352. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined.defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  12353. deferred.resolve(xhr.responseXML);
  12354. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined.defined(xhr.responseText)) {
  12355. deferred.resolve(xhr.responseText);
  12356. } else {
  12357. deferred.reject(new RuntimeError.RuntimeError('Invalid XMLHttpRequest response type.'));
  12358. }
  12359. };
  12360. xhr.onerror = function(e) {
  12361. deferred.reject(new RequestErrorEvent());
  12362. };
  12363. xhr.send(data);
  12364. return xhr;
  12365. };
  12366. Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) {
  12367. return loadAndExecuteScript(url).otherwise(deferred.reject);
  12368. };
  12369. /**
  12370. * The default implementations
  12371. *
  12372. * @private
  12373. */
  12374. Resource._DefaultImplementations = {};
  12375. Resource._DefaultImplementations.createImage = Resource._Implementations.createImage;
  12376. Resource._DefaultImplementations.loadWithXhr = Resource._Implementations.loadWithXhr;
  12377. Resource._DefaultImplementations.loadAndExecuteScript = Resource._Implementations.loadAndExecuteScript;
  12378. /**
  12379. * A resource instance initialized to the current browser location
  12380. *
  12381. * @type {Resource}
  12382. * @constant
  12383. */
  12384. Resource.DEFAULT = freezeObject.freezeObject(new Resource({
  12385. url: (typeof document === 'undefined') ? '' : document.location.href.split('?')[0]
  12386. }));
  12387. /**
  12388. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  12389. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  12390. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  12391. * Reference Frame (ITRF).
  12392. *
  12393. * @alias EarthOrientationParameters
  12394. * @constructor
  12395. *
  12396. * @param {Object} [options] Object with the following properties:
  12397. * @param {Resource|String} [options.url] The URL from which to obtain EOP data. If neither this
  12398. * parameter nor options.data is specified, all EOP values are assumed
  12399. * to be 0.0. If options.data is specified, this parameter is
  12400. * ignored.
  12401. * @param {Object} [options.data] The actual EOP data. If neither this
  12402. * parameter nor options.data is specified, all EOP values are assumed
  12403. * to be 0.0.
  12404. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  12405. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  12406. * should be added to {@link JulianDate.leapSeconds}. False if
  12407. * new leap seconds should be handled correctly in the context
  12408. * of the EOP data but otherwise ignored.
  12409. *
  12410. * @example
  12411. * // An example EOP data file, EOP.json:
  12412. * {
  12413. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  12414. * "samples" : [
  12415. * "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,
  12416. * "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,
  12417. * "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
  12418. * ]
  12419. * }
  12420. *
  12421. * @example
  12422. * // Loading the EOP data
  12423. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  12424. * Cesium.Transforms.earthOrientationParameters = eop;
  12425. *
  12426. * @private
  12427. */
  12428. function EarthOrientationParameters(options) {
  12429. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  12430. this._dates = undefined;
  12431. this._samples = undefined;
  12432. this._dateColumn = -1;
  12433. this._xPoleWanderRadiansColumn = -1;
  12434. this._yPoleWanderRadiansColumn = -1;
  12435. this._ut1MinusUtcSecondsColumn = -1;
  12436. this._xCelestialPoleOffsetRadiansColumn = -1;
  12437. this._yCelestialPoleOffsetRadiansColumn = -1;
  12438. this._taiMinusUtcSecondsColumn = -1;
  12439. this._columnCount = 0;
  12440. this._lastIndex = -1;
  12441. this._downloadPromise = undefined;
  12442. this._dataError = undefined;
  12443. this._addNewLeapSeconds = defaultValue.defaultValue(options.addNewLeapSeconds, true);
  12444. if (defined.defined(options.data)) {
  12445. // Use supplied EOP data.
  12446. onDataReady(this, options.data);
  12447. } else if (defined.defined(options.url)) {
  12448. var resource = Resource.createIfNeeded(options.url);
  12449. // Download EOP data.
  12450. var that = this;
  12451. this._downloadPromise = when.when(resource.fetchJson(), function(eopData) {
  12452. onDataReady(that, eopData);
  12453. }, function() {
  12454. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + resource.url + '.';
  12455. });
  12456. } else {
  12457. // Use all zeros for EOP data.
  12458. onDataReady(this, {
  12459. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  12460. 'samples' : []
  12461. });
  12462. }
  12463. }
  12464. /**
  12465. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  12466. */
  12467. EarthOrientationParameters.NONE = freezeObject.freezeObject({
  12468. getPromiseToLoad : function() {
  12469. return when.when();
  12470. },
  12471. compute : function(date, result) {
  12472. if (!defined.defined(result)) {
  12473. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  12474. } else {
  12475. result.xPoleWander = 0.0;
  12476. result.yPoleWander = 0.0;
  12477. result.xPoleOffset = 0.0;
  12478. result.yPoleOffset = 0.0;
  12479. result.ut1MinusUtc = 0.0;
  12480. }
  12481. return result;
  12482. }
  12483. });
  12484. /**
  12485. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  12486. * ready to use.
  12487. *
  12488. * @returns {Promise} The promise.
  12489. *
  12490. * @see when
  12491. */
  12492. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  12493. return when.when(this._downloadPromise);
  12494. };
  12495. /**
  12496. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  12497. * If the EOP data has not yet been download, this method returns undefined.
  12498. *
  12499. * @param {JulianDate} date The date for each to evaluate the EOP.
  12500. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  12501. * If this parameter is undefined, a new instance is created and returned.
  12502. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  12503. * undefined if the data necessary to evaluate EOP at the date has not yet been
  12504. * downloaded.
  12505. *
  12506. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  12507. *
  12508. * @see EarthOrientationParameters#getPromiseToLoad
  12509. */
  12510. EarthOrientationParameters.prototype.compute = function(date, result) {
  12511. // We cannot compute until the samples are available.
  12512. if (!defined.defined(this._samples)) {
  12513. if (defined.defined(this._dataError)) {
  12514. throw new RuntimeError.RuntimeError(this._dataError);
  12515. }
  12516. return undefined;
  12517. }
  12518. if (!defined.defined(result)) {
  12519. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  12520. }
  12521. if (this._samples.length === 0) {
  12522. result.xPoleWander = 0.0;
  12523. result.yPoleWander = 0.0;
  12524. result.xPoleOffset = 0.0;
  12525. result.yPoleOffset = 0.0;
  12526. result.ut1MinusUtc = 0.0;
  12527. return result;
  12528. }
  12529. var dates = this._dates;
  12530. var lastIndex = this._lastIndex;
  12531. var before = 0;
  12532. var after = 0;
  12533. if (defined.defined(lastIndex)) {
  12534. var previousIndexDate = dates[lastIndex];
  12535. var nextIndexDate = dates[lastIndex + 1];
  12536. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  12537. var isAfterLastSample = !defined.defined(nextIndexDate);
  12538. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  12539. if (isAfterPrevious && isBeforeNext) {
  12540. before = lastIndex;
  12541. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  12542. ++before;
  12543. }
  12544. after = before + 1;
  12545. interpolate(this, dates, this._samples, date, before, after, result);
  12546. return result;
  12547. }
  12548. }
  12549. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  12550. if (index >= 0) {
  12551. // If the next entry is the same date, use the later entry. This way, if two entries
  12552. // describe the same moment, one before a leap second and the other after, then we will use
  12553. // the post-leap second data.
  12554. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  12555. ++index;
  12556. }
  12557. before = index;
  12558. after = index;
  12559. } else {
  12560. after = ~index;
  12561. before = after - 1;
  12562. // Use the first entry if the date requested is before the beginning of the data.
  12563. if (before < 0) {
  12564. before = 0;
  12565. }
  12566. }
  12567. this._lastIndex = before;
  12568. interpolate(this, dates, this._samples, date, before, after, result);
  12569. return result;
  12570. };
  12571. function compareLeapSecondDates$1(leapSecond, dateToFind) {
  12572. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  12573. }
  12574. function onDataReady(eop, eopData) {
  12575. if (!defined.defined(eopData.columnNames)) {
  12576. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  12577. return;
  12578. }
  12579. if (!defined.defined(eopData.samples)) {
  12580. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  12581. return;
  12582. }
  12583. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  12584. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  12585. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  12586. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  12587. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  12588. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  12589. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  12590. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  12591. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  12592. return;
  12593. }
  12594. var samples = eop._samples = eopData.samples;
  12595. var dates = eop._dates = [];
  12596. eop._dateColumn = dateColumn;
  12597. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  12598. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  12599. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  12600. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  12601. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  12602. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  12603. eop._columnCount = eopData.columnNames.length;
  12604. eop._lastIndex = undefined;
  12605. var lastTaiMinusUtc;
  12606. var addNewLeapSeconds = eop._addNewLeapSeconds;
  12607. // Convert the ISO8601 dates to JulianDates.
  12608. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  12609. var mjd = samples[i + dateColumn];
  12610. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  12611. var day = mjd + TimeConstants$1.MODIFIED_JULIAN_DATE_DIFFERENCE;
  12612. var date = new JulianDate(day, taiMinusUtc, TimeStandard$1.TAI);
  12613. dates.push(date);
  12614. if (addNewLeapSeconds) {
  12615. if (taiMinusUtc !== lastTaiMinusUtc && defined.defined(lastTaiMinusUtc)) {
  12616. // We crossed a leap second boundary, so add the leap second
  12617. // if it does not already exist.
  12618. var leapSeconds = JulianDate.leapSeconds;
  12619. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates$1);
  12620. if (leapSecondIndex < 0) {
  12621. var leapSecond = new LeapSecond(date, taiMinusUtc);
  12622. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  12623. }
  12624. }
  12625. lastTaiMinusUtc = taiMinusUtc;
  12626. }
  12627. }
  12628. }
  12629. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  12630. var start = index * columnCount;
  12631. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  12632. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  12633. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  12634. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  12635. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  12636. }
  12637. function linearInterp(dx, y1, y2) {
  12638. return y1 + dx * (y2 - y1);
  12639. }
  12640. function interpolate(eop, dates, samples, date, before, after, result) {
  12641. var columnCount = eop._columnCount;
  12642. // First check the bounds on the EOP data
  12643. // If we are after the bounds of the data, return zeros.
  12644. // The 'before' index should never be less than zero.
  12645. if (after > dates.length - 1) {
  12646. result.xPoleWander = 0;
  12647. result.yPoleWander = 0;
  12648. result.xPoleOffset = 0;
  12649. result.yPoleOffset = 0;
  12650. result.ut1MinusUtc = 0;
  12651. return result;
  12652. }
  12653. var beforeDate = dates[before];
  12654. var afterDate = dates[after];
  12655. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  12656. fillResultFromIndex(eop, samples, before, columnCount, result);
  12657. return result;
  12658. } else if (date.equals(afterDate)) {
  12659. fillResultFromIndex(eop, samples, after, columnCount, result);
  12660. return result;
  12661. }
  12662. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  12663. var startBefore = before * columnCount;
  12664. var startAfter = after * columnCount;
  12665. // Handle UT1 leap second edge case
  12666. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  12667. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  12668. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  12669. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  12670. // The absolute difference between the values is more than 0.5, so we may have
  12671. // crossed a leap second. Check if this is the case and, if so, adjust the
  12672. // afterValue to account for the leap second. This way, our interpolation will
  12673. // produce reasonable results.
  12674. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  12675. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  12676. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  12677. if (afterDate.equals(date)) {
  12678. // If we are at the end of the leap second interval, take the second value
  12679. // Otherwise, the interpolation below will yield the wrong side of the
  12680. // discontinuity
  12681. // At the end of the leap second, we need to start accounting for the jump
  12682. beforeUt1MinusUtc = afterUt1MinusUtc;
  12683. } else {
  12684. // Otherwise, remove the leap second so that the interpolation is correct
  12685. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  12686. }
  12687. }
  12688. }
  12689. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  12690. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  12691. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  12692. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  12693. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  12694. return result;
  12695. }
  12696. /**
  12697. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  12698. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  12699. * the positive x axis.
  12700. * @alias HeadingPitchRoll
  12701. * @constructor
  12702. *
  12703. * @param {Number} [heading=0.0] The heading component in radians.
  12704. * @param {Number} [pitch=0.0] The pitch component in radians.
  12705. * @param {Number} [roll=0.0] The roll component in radians.
  12706. */
  12707. function HeadingPitchRoll(heading, pitch, roll) {
  12708. this.heading = defaultValue.defaultValue(heading, 0.0);
  12709. this.pitch = defaultValue.defaultValue(pitch, 0.0);
  12710. this.roll = defaultValue.defaultValue(roll, 0.0);
  12711. }
  12712. /**
  12713. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  12714. *
  12715. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  12716. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  12717. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  12718. */
  12719. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  12720. //>>includeStart('debug', pragmas.debug);
  12721. if (!defined.defined(quaternion)) {
  12722. throw new Check.DeveloperError('quaternion is required');
  12723. }
  12724. //>>includeEnd('debug');
  12725. if (!defined.defined(result)) {
  12726. result = new HeadingPitchRoll();
  12727. }
  12728. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  12729. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  12730. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  12731. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  12732. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  12733. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  12734. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  12735. result.pitch = -_Math.CesiumMath.asinClamped(test);
  12736. return result;
  12737. };
  12738. /**
  12739. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  12740. *
  12741. * @param {Number} heading the heading in degrees
  12742. * @param {Number} pitch the pitch in degrees
  12743. * @param {Number} roll the heading in degrees
  12744. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  12745. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  12746. */
  12747. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  12748. //>>includeStart('debug', pragmas.debug);
  12749. if (!defined.defined(heading)) {
  12750. throw new Check.DeveloperError('heading is required');
  12751. }
  12752. if (!defined.defined(pitch)) {
  12753. throw new Check.DeveloperError('pitch is required');
  12754. }
  12755. if (!defined.defined(roll)) {
  12756. throw new Check.DeveloperError('roll is required');
  12757. }
  12758. //>>includeEnd('debug');
  12759. if (!defined.defined(result)) {
  12760. result = new HeadingPitchRoll();
  12761. }
  12762. result.heading = heading * _Math.CesiumMath.RADIANS_PER_DEGREE;
  12763. result.pitch = pitch * _Math.CesiumMath.RADIANS_PER_DEGREE;
  12764. result.roll = roll * _Math.CesiumMath.RADIANS_PER_DEGREE;
  12765. return result;
  12766. };
  12767. /**
  12768. * Duplicates a HeadingPitchRoll instance.
  12769. *
  12770. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  12771. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  12772. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  12773. */
  12774. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  12775. if (!defined.defined(headingPitchRoll)) {
  12776. return undefined;
  12777. }
  12778. if (!defined.defined(result)) {
  12779. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  12780. }
  12781. result.heading = headingPitchRoll.heading;
  12782. result.pitch = headingPitchRoll.pitch;
  12783. result.roll = headingPitchRoll.roll;
  12784. return result;
  12785. };
  12786. /**
  12787. * Compares the provided HeadingPitchRolls componentwise and returns
  12788. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12789. *
  12790. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  12791. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  12792. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  12793. */
  12794. HeadingPitchRoll.equals = function(left, right) {
  12795. return (left === right) ||
  12796. ((defined.defined(left)) &&
  12797. (defined.defined(right)) &&
  12798. (left.heading === right.heading) &&
  12799. (left.pitch === right.pitch) &&
  12800. (left.roll === right.roll));
  12801. };
  12802. /**
  12803. * Compares the provided HeadingPitchRolls componentwise and returns
  12804. * <code>true</code> if they pass an absolute or relative tolerance test,
  12805. * <code>false</code> otherwise.
  12806. *
  12807. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  12808. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  12809. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  12810. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  12811. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  12812. */
  12813. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  12814. return (left === right) ||
  12815. (defined.defined(left) &&
  12816. defined.defined(right) &&
  12817. _Math.CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  12818. _Math.CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  12819. _Math.CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  12820. };
  12821. /**
  12822. * Duplicates this HeadingPitchRoll instance.
  12823. *
  12824. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  12825. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  12826. */
  12827. HeadingPitchRoll.prototype.clone = function(result) {
  12828. return HeadingPitchRoll.clone(this, result);
  12829. };
  12830. /**
  12831. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  12832. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12833. *
  12834. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  12835. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  12836. */
  12837. HeadingPitchRoll.prototype.equals = function(right) {
  12838. return HeadingPitchRoll.equals(this, right);
  12839. };
  12840. /**
  12841. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  12842. * <code>true</code> if they pass an absolute or relative tolerance test,
  12843. * <code>false</code> otherwise.
  12844. *
  12845. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  12846. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  12847. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  12848. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  12849. */
  12850. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  12851. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  12852. };
  12853. /**
  12854. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  12855. *
  12856. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  12857. */
  12858. HeadingPitchRoll.prototype.toString = function() {
  12859. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  12860. };
  12861. /*global CESIUM_BASE_URL*/
  12862. var cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js$/;
  12863. function getBaseUrlFromCesiumScript() {
  12864. var scripts = document.getElementsByTagName('script');
  12865. for ( var i = 0, len = scripts.length; i < len; ++i) {
  12866. var src = scripts[i].getAttribute('src');
  12867. var result = cesiumScriptRegex.exec(src);
  12868. if (result !== null) {
  12869. return result[1];
  12870. }
  12871. }
  12872. return undefined;
  12873. }
  12874. var a$1;
  12875. function tryMakeAbsolute(url) {
  12876. if (typeof document === 'undefined') {
  12877. //Node.js and Web Workers. In both cases, the URL will already be absolute.
  12878. return url;
  12879. }
  12880. if (!defined.defined(a$1)) {
  12881. a$1 = document.createElement('a');
  12882. }
  12883. a$1.href = url;
  12884. // IE only absolutizes href on get, not set
  12885. a$1.href = a$1.href; // eslint-disable-line no-self-assign
  12886. return a$1.href;
  12887. }
  12888. var baseResource;
  12889. function getCesiumBaseUrl() {
  12890. if (defined.defined(baseResource)) {
  12891. return baseResource;
  12892. }
  12893. var baseUrlString;
  12894. if (typeof CESIUM_BASE_URL !== 'undefined') {
  12895. baseUrlString = CESIUM_BASE_URL;
  12896. } else if (typeof define === 'object' && defined.defined(define.amd) && !define.amd.toUrlUndefined && defined.defined(require.toUrl)) {
  12897. baseUrlString = getAbsoluteUri('..', buildModuleUrl('Core/buildModuleUrl.js'));
  12898. } else {
  12899. baseUrlString = getBaseUrlFromCesiumScript();
  12900. }
  12901. //>>includeStart('debug', pragmas.debug);
  12902. if (!defined.defined(baseUrlString)) {
  12903. throw new Check.DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  12904. }
  12905. //>>includeEnd('debug');
  12906. baseResource = new Resource({
  12907. url: tryMakeAbsolute(baseUrlString)
  12908. });
  12909. baseResource.appendForwardSlash();
  12910. return baseResource;
  12911. }
  12912. function buildModuleUrlFromRequireToUrl(moduleID) {
  12913. //moduleID will be non-relative, so require it relative to this module, in Core.
  12914. return tryMakeAbsolute(require.toUrl('../' + moduleID));
  12915. }
  12916. function buildModuleUrlFromBaseUrl(moduleID) {
  12917. var resource = getCesiumBaseUrl().getDerivedResource({
  12918. url: moduleID
  12919. });
  12920. return resource.url;
  12921. }
  12922. var implementation;
  12923. /**
  12924. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  12925. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  12926. * the base URL of the Cesium.js script.
  12927. *
  12928. * @private
  12929. */
  12930. function buildModuleUrl(moduleID) {
  12931. if (!defined.defined(implementation)) {
  12932. //select implementation
  12933. if (typeof define === 'object' && defined.defined(define.amd) && !define.amd.toUrlUndefined && defined.defined(require.toUrl)) {
  12934. implementation = buildModuleUrlFromRequireToUrl;
  12935. } else {
  12936. implementation = buildModuleUrlFromBaseUrl;
  12937. }
  12938. }
  12939. var url = implementation(moduleID);
  12940. return url;
  12941. }
  12942. // exposed for testing
  12943. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  12944. buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
  12945. buildModuleUrl._clearBaseResource = function() {
  12946. baseResource = undefined;
  12947. };
  12948. /**
  12949. * Sets the base URL for resolving modules.
  12950. * @param {String} value The new base URL.
  12951. */
  12952. buildModuleUrl.setBaseUrl = function(value) {
  12953. baseResource = Resource.DEFAULT.getDerivedResource({
  12954. url: value
  12955. });
  12956. };
  12957. /**
  12958. * Gets the base URL for resolving modules.
  12959. */
  12960. buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
  12961. /**
  12962. * An IAU 2006 XYS value sampled at a particular time.
  12963. *
  12964. * @alias Iau2006XysSample
  12965. * @constructor
  12966. *
  12967. * @param {Number} x The X value.
  12968. * @param {Number} y The Y value.
  12969. * @param {Number} s The S value.
  12970. *
  12971. * @private
  12972. */
  12973. function Iau2006XysSample(x, y, s) {
  12974. /**
  12975. * The X value.
  12976. * @type {Number}
  12977. */
  12978. this.x = x;
  12979. /**
  12980. * The Y value.
  12981. * @type {Number}
  12982. */
  12983. this.y = y;
  12984. /**
  12985. * The S value.
  12986. * @type {Number}
  12987. */
  12988. this.s = s;
  12989. }
  12990. /**
  12991. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  12992. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  12993. *
  12994. * @alias Iau2006XysData
  12995. * @constructor
  12996. *
  12997. * @param {Object} [options] Object with the following properties:
  12998. * @param {Resource|String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  12999. * `{0}` will be replaced with the file index.
  13000. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  13001. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  13002. * first XYS sample.
  13003. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  13004. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  13005. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  13006. *
  13007. * @private
  13008. */
  13009. function Iau2006XysData(options) {
  13010. options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
  13011. this._xysFileUrlTemplate = Resource.createIfNeeded(options.xysFileUrlTemplate);
  13012. this._interpolationOrder = defaultValue.defaultValue(options.interpolationOrder, 9);
  13013. this._sampleZeroJulianEphemerisDate = defaultValue.defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  13014. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard$1.TAI);
  13015. this._stepSizeDays = defaultValue.defaultValue(options.stepSizeDays, 1.0);
  13016. this._samplesPerXysFile = defaultValue.defaultValue(options.samplesPerXysFile, 1000);
  13017. this._totalSamples = defaultValue.defaultValue(options.totalSamples, 27426);
  13018. this._samples = new Array(this._totalSamples * 3);
  13019. this._chunkDownloadsInProgress = [];
  13020. var order = this._interpolationOrder;
  13021. // Compute denominators and X values for interpolation.
  13022. var denom = this._denominators = new Array(order + 1);
  13023. var xTable = this._xTable = new Array(order + 1);
  13024. var stepN = Math.pow(this._stepSizeDays, order);
  13025. for ( var i = 0; i <= order; ++i) {
  13026. denom[i] = stepN;
  13027. xTable[i] = i * this._stepSizeDays;
  13028. for ( var j = 0; j <= order; ++j) {
  13029. if (j !== i) {
  13030. denom[i] *= (i - j);
  13031. }
  13032. }
  13033. denom[i] = 1.0 / denom[i];
  13034. }
  13035. // Allocate scratch arrays for interpolation.
  13036. this._work = new Array(order + 1);
  13037. this._coef = new Array(order + 1);
  13038. }
  13039. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard$1.TAI);
  13040. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  13041. var dateTT = julianDateScratch;
  13042. dateTT.dayNumber = dayTT;
  13043. dateTT.secondsOfDay = secondTT;
  13044. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  13045. }
  13046. /**
  13047. * Preloads XYS data for a specified date range.
  13048. *
  13049. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  13050. * the Terrestrial Time (TT) time standard.
  13051. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  13052. * the Terrestrial Time (TT) time standard.
  13053. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  13054. * the Terrestrial Time (TT) time standard.
  13055. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  13056. * the Terrestrial Time (TT) time standard.
  13057. * @returns {Promise} A promise that, when resolved, indicates that the requested interval has been
  13058. * preloaded.
  13059. */
  13060. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  13061. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  13062. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  13063. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  13064. if (startIndex < 0) {
  13065. startIndex = 0;
  13066. }
  13067. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  13068. if (stopIndex >= this._totalSamples) {
  13069. stopIndex = this._totalSamples - 1;
  13070. }
  13071. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  13072. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  13073. var promises = [];
  13074. for ( var i = startChunk; i <= stopChunk; ++i) {
  13075. promises.push(requestXysChunk(this, i));
  13076. }
  13077. return when.when.all(promises);
  13078. };
  13079. /**
  13080. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  13081. * this method will return undefined.
  13082. *
  13083. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  13084. * the Terrestrial Time (TT) time standard.
  13085. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  13086. * the Terrestrial Time (TT) time standard.
  13087. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  13088. * is undefined, a new instance is allocated and returned.
  13089. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  13090. * computation has not yet been downloaded.
  13091. *
  13092. * @see Iau2006XysData#preload
  13093. */
  13094. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  13095. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  13096. if (daysSinceEpoch < 0.0) {
  13097. // Can't evaluate prior to the epoch of the data.
  13098. return undefined;
  13099. }
  13100. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  13101. if (centerIndex >= this._totalSamples) {
  13102. // Can't evaluate after the last sample in the data.
  13103. return undefined;
  13104. }
  13105. var degree = this._interpolationOrder;
  13106. var firstIndex = centerIndex - ((degree / 2) | 0);
  13107. if (firstIndex < 0) {
  13108. firstIndex = 0;
  13109. }
  13110. var lastIndex = firstIndex + degree;
  13111. if (lastIndex >= this._totalSamples) {
  13112. lastIndex = this._totalSamples - 1;
  13113. firstIndex = lastIndex - degree;
  13114. if (firstIndex < 0) {
  13115. firstIndex = 0;
  13116. }
  13117. }
  13118. // Are all the samples we need present?
  13119. // We can assume so if the first and last are present
  13120. var isDataMissing = false;
  13121. var samples = this._samples;
  13122. if (!defined.defined(samples[firstIndex * 3])) {
  13123. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  13124. isDataMissing = true;
  13125. }
  13126. if (!defined.defined(samples[lastIndex * 3])) {
  13127. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  13128. isDataMissing = true;
  13129. }
  13130. if (isDataMissing) {
  13131. return undefined;
  13132. }
  13133. if (!defined.defined(result)) {
  13134. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  13135. } else {
  13136. result.x = 0.0;
  13137. result.y = 0.0;
  13138. result.s = 0.0;
  13139. }
  13140. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  13141. var work = this._work;
  13142. var denom = this._denominators;
  13143. var coef = this._coef;
  13144. var xTable = this._xTable;
  13145. var i, j;
  13146. for (i = 0; i <= degree; ++i) {
  13147. work[i] = x - xTable[i];
  13148. }
  13149. for (i = 0; i <= degree; ++i) {
  13150. coef[i] = 1.0;
  13151. for (j = 0; j <= degree; ++j) {
  13152. if (j !== i) {
  13153. coef[i] *= work[j];
  13154. }
  13155. }
  13156. coef[i] *= denom[i];
  13157. var sampleIndex = (firstIndex + i) * 3;
  13158. result.x += coef[i] * samples[sampleIndex++];
  13159. result.y += coef[i] * samples[sampleIndex++];
  13160. result.s += coef[i] * samples[sampleIndex];
  13161. }
  13162. return result;
  13163. };
  13164. function requestXysChunk(xysData, chunkIndex) {
  13165. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  13166. // Chunk has already been requested.
  13167. return xysData._chunkDownloadsInProgress[chunkIndex];
  13168. }
  13169. var deferred = when.when.defer();
  13170. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  13171. var chunkUrl;
  13172. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  13173. if (defined.defined(xysFileUrlTemplate)) {
  13174. chunkUrl = xysFileUrlTemplate.getDerivedResource({
  13175. templateValues: {
  13176. '0': chunkIndex
  13177. }
  13178. });
  13179. } else {
  13180. chunkUrl = new Resource({
  13181. url : buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json')
  13182. });
  13183. }
  13184. when.when(chunkUrl.fetchJson(), function(chunk) {
  13185. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  13186. var samples = xysData._samples;
  13187. var newSamples = chunk.samples;
  13188. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  13189. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  13190. samples[startIndex + i] = newSamples[i];
  13191. }
  13192. deferred.resolve();
  13193. });
  13194. return deferred.promise;
  13195. }
  13196. /**
  13197. * Contains functions for transforming positions to various reference frames.
  13198. *
  13199. * @exports Transforms
  13200. * @namespace
  13201. */
  13202. var Transforms = {};
  13203. var vectorProductLocalFrame = {
  13204. up : {
  13205. south : 'east',
  13206. north : 'west',
  13207. west : 'south',
  13208. east : 'north'
  13209. },
  13210. down : {
  13211. south : 'west',
  13212. north : 'east',
  13213. west : 'north',
  13214. east : 'south'
  13215. },
  13216. south : {
  13217. up : 'west',
  13218. down : 'east',
  13219. west : 'down',
  13220. east : 'up'
  13221. },
  13222. north : {
  13223. up : 'east',
  13224. down : 'west',
  13225. west : 'up',
  13226. east : 'down'
  13227. },
  13228. west : {
  13229. up : 'north',
  13230. down : 'south',
  13231. north : 'down',
  13232. south : 'up'
  13233. },
  13234. east : {
  13235. up : 'south',
  13236. down : 'north',
  13237. north : 'up',
  13238. south : 'down'
  13239. }
  13240. };
  13241. var degeneratePositionLocalFrame = {
  13242. north : [-1, 0, 0],
  13243. east : [0, 1, 0],
  13244. up : [0, 0, 1],
  13245. south : [1, 0, 0],
  13246. west : [0, -1, 0],
  13247. down : [0, 0, -1]
  13248. };
  13249. var localFrameToFixedFrameCache = {};
  13250. var scratchCalculateCartesian = {
  13251. east : new Cartesian2.Cartesian3(),
  13252. north : new Cartesian2.Cartesian3(),
  13253. up : new Cartesian2.Cartesian3(),
  13254. west : new Cartesian2.Cartesian3(),
  13255. south : new Cartesian2.Cartesian3(),
  13256. down : new Cartesian2.Cartesian3()
  13257. };
  13258. var scratchFirstCartesian = new Cartesian2.Cartesian3();
  13259. var scratchSecondCartesian = new Cartesian2.Cartesian3();
  13260. var scratchThirdCartesian = new Cartesian2.Cartesian3();
  13261. /**
  13262. * Generates a function that computes a 4x4 transformation matrix from a reference frame
  13263. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  13264. * @param {String} firstAxis name of the first axis of the local reference frame. Must be
  13265. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  13266. * @param {String} secondAxis name of the second axis of the local reference frame. Must be
  13267. * 'east', 'north', 'up', 'west', 'south' or 'down'.
  13268. * @return {localFrameToFixedFrameGenerator~resultat} The function that will computes a
  13269. * 4x4 transformation matrix from a reference frame, with first axis and second axis compliant with the parameters,
  13270. */
  13271. Transforms.localFrameToFixedFrameGenerator = function (firstAxis, secondAxis) {
  13272. if (!vectorProductLocalFrame.hasOwnProperty(firstAxis) || !vectorProductLocalFrame[firstAxis].hasOwnProperty(secondAxis)) {
  13273. throw new Check.DeveloperError('firstAxis and secondAxis must be east, north, up, west, south or down.');
  13274. }
  13275. var thirdAxis = vectorProductLocalFrame[firstAxis][secondAxis];
  13276. /**
  13277. * Computes a 4x4 transformation matrix from a reference frame
  13278. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  13279. * @callback Transforms~LocalFrameToFixedFrame
  13280. * @param {Cartesian3} origin The center point of the local reference frame.
  13281. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13282. * @param {Matrix4} [result] The object onto which to store the result.
  13283. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  13284. */
  13285. var resultat;
  13286. var hashAxis = firstAxis + secondAxis;
  13287. if (defined.defined(localFrameToFixedFrameCache[hashAxis])) {
  13288. resultat = localFrameToFixedFrameCache[hashAxis];
  13289. } else {
  13290. resultat = function (origin, ellipsoid, result) {
  13291. //>>includeStart('debug', pragmas.debug);
  13292. if (!defined.defined(origin)) {
  13293. throw new Check.DeveloperError('origin is required.');
  13294. }
  13295. //>>includeEnd('debug');
  13296. if (!defined.defined(result)) {
  13297. result = new Matrix4();
  13298. }
  13299. // If x and y are zero, assume origin is at a pole, which is a special case.
  13300. if (_Math.CesiumMath.equalsEpsilon(origin.x, 0.0, _Math.CesiumMath.EPSILON14) && _Math.CesiumMath.equalsEpsilon(origin.y, 0.0, _Math.CesiumMath.EPSILON14)) {
  13301. var sign = _Math.CesiumMath.sign(origin.z);
  13302. Cartesian2.Cartesian3.unpack(degeneratePositionLocalFrame[firstAxis], 0, scratchFirstCartesian);
  13303. if (firstAxis !== 'east' && firstAxis !== 'west') {
  13304. Cartesian2.Cartesian3.multiplyByScalar(scratchFirstCartesian, sign, scratchFirstCartesian);
  13305. }
  13306. Cartesian2.Cartesian3.unpack(degeneratePositionLocalFrame[secondAxis], 0, scratchSecondCartesian);
  13307. if (secondAxis !== 'east' && secondAxis !== 'west') {
  13308. Cartesian2.Cartesian3.multiplyByScalar(scratchSecondCartesian, sign, scratchSecondCartesian);
  13309. }
  13310. Cartesian2.Cartesian3.unpack(degeneratePositionLocalFrame[thirdAxis], 0, scratchThirdCartesian);
  13311. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  13312. Cartesian2.Cartesian3.multiplyByScalar(scratchThirdCartesian, sign, scratchThirdCartesian);
  13313. }
  13314. } else {
  13315. ellipsoid = defaultValue.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  13316. ellipsoid.geodeticSurfaceNormal(origin, scratchCalculateCartesian.up);
  13317. var up = scratchCalculateCartesian.up;
  13318. var east = scratchCalculateCartesian.east;
  13319. east.x = -origin.y;
  13320. east.y = origin.x;
  13321. east.z = 0.0;
  13322. Cartesian2.Cartesian3.normalize(east, scratchCalculateCartesian.east);
  13323. Cartesian2.Cartesian3.cross(up, east, scratchCalculateCartesian.north);
  13324. Cartesian2.Cartesian3.multiplyByScalar(scratchCalculateCartesian.up, -1, scratchCalculateCartesian.down);
  13325. Cartesian2.Cartesian3.multiplyByScalar(scratchCalculateCartesian.east, -1, scratchCalculateCartesian.west);
  13326. Cartesian2.Cartesian3.multiplyByScalar(scratchCalculateCartesian.north, -1, scratchCalculateCartesian.south);
  13327. scratchFirstCartesian = scratchCalculateCartesian[firstAxis];
  13328. scratchSecondCartesian = scratchCalculateCartesian[secondAxis];
  13329. scratchThirdCartesian = scratchCalculateCartesian[thirdAxis];
  13330. }
  13331. result[0] = scratchFirstCartesian.x;
  13332. result[1] = scratchFirstCartesian.y;
  13333. result[2] = scratchFirstCartesian.z;
  13334. result[3] = 0.0;
  13335. result[4] = scratchSecondCartesian.x;
  13336. result[5] = scratchSecondCartesian.y;
  13337. result[6] = scratchSecondCartesian.z;
  13338. result[7] = 0.0;
  13339. result[8] = scratchThirdCartesian.x;
  13340. result[9] = scratchThirdCartesian.y;
  13341. result[10] = scratchThirdCartesian.z;
  13342. result[11] = 0.0;
  13343. result[12] = origin.x;
  13344. result[13] = origin.y;
  13345. result[14] = origin.z;
  13346. result[15] = 1.0;
  13347. return result;
  13348. };
  13349. localFrameToFixedFrameCache[hashAxis] = resultat;
  13350. }
  13351. return resultat;
  13352. };
  13353. /**
  13354. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  13355. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  13356. * The local axes are defined as:
  13357. * <ul>
  13358. * <li>The <code>x</code> axis points in the local east direction.</li>
  13359. * <li>The <code>y</code> axis points in the local north direction.</li>
  13360. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  13361. * </ul>
  13362. *
  13363. * @function
  13364. * @param {Cartesian3} origin The center point of the local reference frame.
  13365. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13366. * @param {Matrix4} [result] The object onto which to store the result.
  13367. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  13368. *
  13369. * @example
  13370. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  13371. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13372. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  13373. */
  13374. Transforms.eastNorthUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator('east','north');
  13375. /**
  13376. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  13377. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  13378. * The local axes are defined as:
  13379. * <ul>
  13380. * <li>The <code>x</code> axis points in the local north direction.</li>
  13381. * <li>The <code>y</code> axis points in the local east direction.</li>
  13382. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  13383. * </ul>
  13384. *
  13385. * @function
  13386. * @param {Cartesian3} origin The center point of the local reference frame.
  13387. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13388. * @param {Matrix4} [result] The object onto which to store the result.
  13389. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  13390. *
  13391. * @example
  13392. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  13393. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13394. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  13395. */
  13396. Transforms.northEastDownToFixedFrame = Transforms.localFrameToFixedFrameGenerator('north','east');
  13397. /**
  13398. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  13399. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  13400. * The local axes are defined as:
  13401. * <ul>
  13402. * <li>The <code>x</code> axis points in the local north direction.</li>
  13403. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  13404. * <li>The <code>z</code> axis points in the local east direction.</li>
  13405. * </ul>
  13406. *
  13407. * @function
  13408. * @param {Cartesian3} origin The center point of the local reference frame.
  13409. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13410. * @param {Matrix4} [result] The object onto which to store the result.
  13411. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  13412. *
  13413. * @example
  13414. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  13415. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13416. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  13417. */
  13418. Transforms.northUpEastToFixedFrame = Transforms.localFrameToFixedFrameGenerator('north','up');
  13419. /**
  13420. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  13421. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  13422. * The local axes are defined as:
  13423. * <ul>
  13424. * <li>The <code>x</code> axis points in the local north direction.</li>
  13425. * <li>The <code>y</code> axis points in the local west direction.</li>
  13426. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  13427. * </ul>
  13428. *
  13429. * @function
  13430. * @param {Cartesian3} origin The center point of the local reference frame.
  13431. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13432. * @param {Matrix4} [result] The object onto which to store the result.
  13433. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  13434. *
  13435. * @example
  13436. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  13437. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13438. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  13439. */
  13440. Transforms.northWestUpToFixedFrame = Transforms.localFrameToFixedFrameGenerator('north','west');
  13441. var scratchHPRQuaternion$1 = new Quaternion();
  13442. var scratchScale$2 = new Cartesian2.Cartesian3(1.0, 1.0, 1.0);
  13443. var scratchHPRMatrix4 = new Matrix4();
  13444. /**
  13445. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  13446. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  13447. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  13448. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  13449. *
  13450. * @param {Cartesian3} origin The center point of the local reference frame.
  13451. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  13452. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13453. * @param {Transforms~LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  13454. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  13455. * @param {Matrix4} [result] The object onto which to store the result.
  13456. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  13457. *
  13458. * @example
  13459. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  13460. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13461. * var heading = -Cesium.Math.PI_OVER_TWO;
  13462. * var pitch = Cesium.Math.PI_OVER_FOUR;
  13463. * var roll = 0.0;
  13464. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  13465. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  13466. */
  13467. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, ellipsoid, fixedFrameTransform, result) {
  13468. //>>includeStart('debug', pragmas.debug);
  13469. Check.Check.typeOf.object( 'HeadingPitchRoll', headingPitchRoll);
  13470. //>>includeEnd('debug');
  13471. fixedFrameTransform = defaultValue.defaultValue(fixedFrameTransform, Transforms.eastNorthUpToFixedFrame);
  13472. var hprQuaternion = Quaternion.fromHeadingPitchRoll(headingPitchRoll, scratchHPRQuaternion$1);
  13473. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian2.Cartesian3.ZERO, hprQuaternion, scratchScale$2, scratchHPRMatrix4);
  13474. result = fixedFrameTransform(origin, ellipsoid, result);
  13475. return Matrix4.multiply(result, hprMatrix, result);
  13476. };
  13477. var scratchENUMatrix4 = new Matrix4();
  13478. var scratchHPRMatrix3 = new Matrix3();
  13479. /**
  13480. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  13481. * centered at the provided origin. Heading is the rotation from the local north
  13482. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  13483. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  13484. *
  13485. * @param {Cartesian3} origin The center point of the local reference frame.
  13486. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  13487. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13488. * @param {Transforms~LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  13489. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  13490. * @param {Quaternion} [result] The object onto which to store the result.
  13491. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  13492. *
  13493. * @example
  13494. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  13495. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13496. * var heading = -Cesium.Math.PI_OVER_TWO;
  13497. * var pitch = Cesium.Math.PI_OVER_FOUR;
  13498. * var roll = 0.0;
  13499. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  13500. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  13501. */
  13502. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, ellipsoid, fixedFrameTransform, result) {
  13503. //>>includeStart('debug', pragmas.debug);
  13504. Check.Check.typeOf.object( 'HeadingPitchRoll', headingPitchRoll);
  13505. //>>includeEnd('debug');
  13506. var transform = Transforms.headingPitchRollToFixedFrame(origin, headingPitchRoll, ellipsoid, fixedFrameTransform, scratchENUMatrix4);
  13507. var rotation = Matrix4.getMatrix3(transform, scratchHPRMatrix3);
  13508. return Quaternion.fromRotationMatrix(rotation, result);
  13509. };
  13510. var noScale = new Cartesian2.Cartesian3(1.0, 1.0, 1.0);
  13511. var hprCenterScratch = new Cartesian2.Cartesian3();
  13512. var ffScratch = new Matrix4();
  13513. var hprTransformScratch = new Matrix4();
  13514. var hprRotationScratch = new Matrix3();
  13515. var hprQuaternionScratch = new Quaternion();
  13516. /**
  13517. * Computes heading-pitch-roll angles from a transform in a particular reference frame. Heading is the rotation from the local north
  13518. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  13519. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  13520. *
  13521. * @param {Matrix4} transform The transform
  13522. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  13523. * @param {Transforms~LocalFrameToFixedFrame} [fixedFrameTransform=Transforms.eastNorthUpToFixedFrame] A 4x4 transformation
  13524. * matrix from a reference frame to the provided ellipsoid's fixed reference frame
  13525. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  13526. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if none was provided.
  13527. */
  13528. Transforms.fixedFrameToHeadingPitchRoll = function(transform, ellipsoid, fixedFrameTransform, result) {
  13529. //>>includeStart('debug', pragmas.debug);
  13530. Check.Check.defined('transform', transform);
  13531. //>>includeEnd('debug');
  13532. ellipsoid = defaultValue.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84);
  13533. fixedFrameTransform = defaultValue.defaultValue(fixedFrameTransform, Transforms.eastNorthUpToFixedFrame);
  13534. if (!defined.defined(result)) {
  13535. result = new HeadingPitchRoll();
  13536. }
  13537. var center = Matrix4.getTranslation(transform, hprCenterScratch);
  13538. if (Cartesian2.Cartesian3.equals(center, Cartesian2.Cartesian3.ZERO)) {
  13539. result.heading = 0;
  13540. result.pitch = 0;
  13541. result.roll = 0;
  13542. return result;
  13543. }
  13544. var toFixedFrame = Matrix4.inverseTransformation(fixedFrameTransform(center, ellipsoid, ffScratch), ffScratch);
  13545. var transformCopy = Matrix4.setScale(transform, noScale, hprTransformScratch);
  13546. transformCopy = Matrix4.setTranslation(transformCopy, Cartesian2.Cartesian3.ZERO, transformCopy);
  13547. toFixedFrame = Matrix4.multiply(toFixedFrame, transformCopy, toFixedFrame);
  13548. var quaternionRotation = Quaternion.fromRotationMatrix(Matrix4.getMatrix3(toFixedFrame, hprRotationScratch), hprQuaternionScratch);
  13549. quaternionRotation = Quaternion.normalize(quaternionRotation, quaternionRotation);
  13550. return HeadingPitchRoll.fromQuaternion(quaternionRotation, result);
  13551. };
  13552. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  13553. var gmstConstant1 = 8640184.812866;
  13554. var gmstConstant2 = 0.093104;
  13555. var gmstConstant3 = -6.2E-6;
  13556. var rateCoef = 1.1772758384668e-19;
  13557. var wgs84WRPrecessing = 7.2921158553E-5;
  13558. var twoPiOverSecondsInDay = _Math.CesiumMath.TWO_PI / 86400.0;
  13559. var dateInUtc = new JulianDate();
  13560. /**
  13561. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  13562. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  13563. *
  13564. * @param {JulianDate} date The time at which to compute the rotation matrix.
  13565. * @param {Matrix3} [result] The object onto which to store the result.
  13566. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  13567. *
  13568. * @example
  13569. * //Set the view to the inertial frame.
  13570. * scene.postUpdate.addEventListener(function(scene, time) {
  13571. * var now = Cesium.JulianDate.now();
  13572. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  13573. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  13574. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  13575. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  13576. * camera.lookAtTransform(transform, offset);
  13577. * });
  13578. */
  13579. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  13580. //>>includeStart('debug', pragmas.debug);
  13581. if (!defined.defined(date)) {
  13582. throw new Check.DeveloperError('date is required.');
  13583. }
  13584. //>>includeEnd('debug');
  13585. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  13586. // We do not want to use the function like convertTaiToUtc in JulianDate because
  13587. // we explicitly do not want to fail when inside the leap second.
  13588. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  13589. var utcDayNumber = dateInUtc.dayNumber;
  13590. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  13591. var t;
  13592. var diffDays = utcDayNumber - 2451545;
  13593. if (utcSecondsIntoDay >= 43200.0) {
  13594. t = (diffDays + 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  13595. } else {
  13596. t = (diffDays - 0.5) / TimeConstants$1.DAYS_PER_JULIAN_CENTURY;
  13597. }
  13598. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  13599. var angle = (gmst0 * twoPiOverSecondsInDay) % _Math.CesiumMath.TWO_PI;
  13600. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  13601. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants$1.SECONDS_PER_DAY * 0.5) % TimeConstants$1.SECONDS_PER_DAY;
  13602. var gha = angle + (ratio * secondsSinceMidnight);
  13603. var cosGha = Math.cos(gha);
  13604. var sinGha = Math.sin(gha);
  13605. if (!defined.defined(result)) {
  13606. return new Matrix3(cosGha, sinGha, 0.0,
  13607. -sinGha, cosGha, 0.0,
  13608. 0.0, 0.0, 1.0);
  13609. }
  13610. result[0] = cosGha;
  13611. result[1] = -sinGha;
  13612. result[2] = 0.0;
  13613. result[3] = sinGha;
  13614. result[4] = cosGha;
  13615. result[5] = 0.0;
  13616. result[6] = 0.0;
  13617. result[7] = 0.0;
  13618. result[8] = 1.0;
  13619. return result;
  13620. };
  13621. /**
  13622. * The source of IAU 2006 XYS data, used for computing the transformation between the
  13623. * Fixed and ICRF axes.
  13624. * @type {Iau2006XysData}
  13625. *
  13626. * @see Transforms.computeIcrfToFixedMatrix
  13627. * @see Transforms.computeFixedToIcrfMatrix
  13628. *
  13629. * @private
  13630. */
  13631. Transforms.iau2006XysData = new Iau2006XysData();
  13632. /**
  13633. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  13634. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  13635. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  13636. * @type {EarthOrientationParameters}
  13637. *
  13638. * @see Transforms.computeIcrfToFixedMatrix
  13639. * @see Transforms.computeFixedToIcrfMatrix
  13640. *
  13641. * @private
  13642. */
  13643. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  13644. var ttMinusTai = 32.184;
  13645. var j2000ttDays = 2451545.0;
  13646. /**
  13647. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  13648. * direction, over a given interval. This function returns a promise that, when resolved,
  13649. * indicates that the preload has completed.
  13650. *
  13651. * @param {TimeInterval} timeInterval The interval to preload.
  13652. * @returns {Promise} A promise that, when resolved, indicates that the preload has completed
  13653. * and evaluation of the transformation between the fixed and ICRF axes will
  13654. * no longer return undefined for a time inside the interval.
  13655. *
  13656. *
  13657. * @example
  13658. * var interval = new Cesium.TimeInterval(...);
  13659. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  13660. * // the data is now loaded
  13661. * });
  13662. *
  13663. * @see Transforms.computeIcrfToFixedMatrix
  13664. * @see Transforms.computeFixedToIcrfMatrix
  13665. * @see when
  13666. */
  13667. Transforms.preloadIcrfFixed = function(timeInterval) {
  13668. var startDayTT = timeInterval.start.dayNumber;
  13669. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  13670. var stopDayTT = timeInterval.stop.dayNumber;
  13671. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  13672. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  13673. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  13674. return when.when.all([xysPromise, eopPromise]);
  13675. };
  13676. /**
  13677. * Computes a rotation matrix to transform a point or vector from the International Celestial
  13678. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  13679. * at a given time. This function may return undefined if the data necessary to
  13680. * do the transformation is not yet loaded.
  13681. *
  13682. * @param {JulianDate} date The time at which to compute the rotation matrix.
  13683. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  13684. * not specified, a new instance is created and returned.
  13685. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  13686. * transformation is not yet loaded.
  13687. *
  13688. *
  13689. * @example
  13690. * scene.postUpdate.addEventListener(function(scene, time) {
  13691. * // View in ICRF.
  13692. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  13693. * if (Cesium.defined(icrfToFixed)) {
  13694. * var offset = Cesium.Cartesian3.clone(camera.position);
  13695. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
  13696. * camera.lookAtTransform(transform, offset);
  13697. * }
  13698. * });
  13699. *
  13700. * @see Transforms.preloadIcrfFixed
  13701. */
  13702. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  13703. //>>includeStart('debug', pragmas.debug);
  13704. if (!defined.defined(date)) {
  13705. throw new Check.DeveloperError('date is required.');
  13706. }
  13707. //>>includeEnd('debug');
  13708. if (!defined.defined(result)) {
  13709. result = new Matrix3();
  13710. }
  13711. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  13712. if (!defined.defined(fixedToIcrfMtx)) {
  13713. return undefined;
  13714. }
  13715. return Matrix3.transpose(fixedToIcrfMtx, result);
  13716. };
  13717. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  13718. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  13719. var rotation1Scratch = new Matrix3();
  13720. var rotation2Scratch = new Matrix3();
  13721. /**
  13722. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  13723. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  13724. * at a given time. This function may return undefined if the data necessary to
  13725. * do the transformation is not yet loaded.
  13726. *
  13727. * @param {JulianDate} date The time at which to compute the rotation matrix.
  13728. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  13729. * not specified, a new instance is created and returned.
  13730. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  13731. * transformation is not yet loaded.
  13732. *
  13733. *
  13734. * @example
  13735. * // Transform a point from the ICRF axes to the Fixed axes.
  13736. * var now = Cesium.JulianDate.now();
  13737. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  13738. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  13739. * var pointInInertial = new Cesium.Cartesian3();
  13740. * if (Cesium.defined(fixedToIcrf)) {
  13741. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  13742. * }
  13743. *
  13744. * @see Transforms.preloadIcrfFixed
  13745. */
  13746. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  13747. //>>includeStart('debug', pragmas.debug);
  13748. if (!defined.defined(date)) {
  13749. throw new Check.DeveloperError('date is required.');
  13750. }
  13751. //>>includeEnd('debug');
  13752. if (!defined.defined(result)) {
  13753. result = new Matrix3();
  13754. }
  13755. // Compute pole wander
  13756. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  13757. if (!defined.defined(eop)) {
  13758. return undefined;
  13759. }
  13760. // There is no external conversion to Terrestrial Time (TT).
  13761. // So use International Atomic Time (TAI) and convert using offsets.
  13762. // Here we are assuming that dayTT and secondTT are positive
  13763. var dayTT = date.dayNumber;
  13764. // It's possible here that secondTT could roll over 86400
  13765. // This does not seem to affect the precision (unit tests check for this)
  13766. var secondTT = date.secondsOfDay + ttMinusTai;
  13767. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  13768. if (!defined.defined(xys)) {
  13769. return undefined;
  13770. }
  13771. var x = xys.x + eop.xPoleOffset;
  13772. var y = xys.y + eop.yPoleOffset;
  13773. // Compute XYS rotation
  13774. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  13775. var rotation1 = rotation1Scratch;
  13776. rotation1[0] = 1.0 - a * x * x;
  13777. rotation1[3] = -a * x * y;
  13778. rotation1[6] = x;
  13779. rotation1[1] = -a * x * y;
  13780. rotation1[4] = 1 - a * y * y;
  13781. rotation1[7] = y;
  13782. rotation1[2] = -x;
  13783. rotation1[5] = -y;
  13784. rotation1[8] = 1 - a * (x * x + y * y);
  13785. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  13786. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  13787. // Similar to TT conversions above
  13788. // It's possible here that secondTT could roll over 86400
  13789. // This does not seem to affect the precision (unit tests check for this)
  13790. var dateUt1day = date.dayNumber;
  13791. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  13792. // Compute Earth rotation angle
  13793. // The IERS standard for era is
  13794. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  13795. // where
  13796. // Tu = JulianDateInUt1 - 2451545.0
  13797. // However, you get much more precision if you make the following simplification
  13798. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  13799. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  13800. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  13801. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  13802. var daysSinceJ2000 = dateUt1day - 2451545;
  13803. var fractionOfDay = dateUt1sec / TimeConstants$1.SECONDS_PER_DAY;
  13804. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  13805. era = (era % 1.0) * _Math.CesiumMath.TWO_PI;
  13806. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  13807. // pseudoFixed to ICRF
  13808. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  13809. // Compute pole wander matrix
  13810. var cosxp = Math.cos(eop.xPoleWander);
  13811. var cosyp = Math.cos(eop.yPoleWander);
  13812. var sinxp = Math.sin(eop.xPoleWander);
  13813. var sinyp = Math.sin(eop.yPoleWander);
  13814. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants$1.SECONDS_PER_DAY;
  13815. ttt /= 36525.0;
  13816. // approximate sp value in rad
  13817. var sp = -47.0e-6 * ttt * _Math.CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  13818. var cossp = Math.cos(sp);
  13819. var sinsp = Math.sin(sp);
  13820. var fToPfMtx = rotation2Scratch;
  13821. fToPfMtx[0] = cosxp * cossp;
  13822. fToPfMtx[1] = cosxp * sinsp;
  13823. fToPfMtx[2] = sinxp;
  13824. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  13825. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  13826. fToPfMtx[5] = -sinyp * cosxp;
  13827. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  13828. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  13829. fToPfMtx[8] = cosyp * cosxp;
  13830. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  13831. };
  13832. var pointToWindowCoordinatesTemp = new Cartesian4();
  13833. /**
  13834. * Transform a point from model coordinates to window coordinates.
  13835. *
  13836. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  13837. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  13838. * @param {Cartesian3} point The point to transform.
  13839. * @param {Cartesian2} [result] The object onto which to store the result.
  13840. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  13841. */
  13842. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  13843. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  13844. result.y = 2.0 * viewportTransformation[5] - result.y;
  13845. return result;
  13846. };
  13847. /**
  13848. * @private
  13849. */
  13850. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  13851. //>>includeStart('debug', pragmas.debug);
  13852. if (!defined.defined(modelViewProjectionMatrix)) {
  13853. throw new Check.DeveloperError('modelViewProjectionMatrix is required.');
  13854. }
  13855. if (!defined.defined(viewportTransformation)) {
  13856. throw new Check.DeveloperError('viewportTransformation is required.');
  13857. }
  13858. if (!defined.defined(point)) {
  13859. throw new Check.DeveloperError('point is required.');
  13860. }
  13861. //>>includeEnd('debug');
  13862. if (!defined.defined(result)) {
  13863. result = new Cartesian2.Cartesian2();
  13864. }
  13865. var tmp = pointToWindowCoordinatesTemp;
  13866. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  13867. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  13868. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  13869. return Cartesian2.Cartesian2.fromCartesian4(tmp, result);
  13870. };
  13871. var normalScratch = new Cartesian2.Cartesian3();
  13872. var rightScratch = new Cartesian2.Cartesian3();
  13873. var upScratch = new Cartesian2.Cartesian3();
  13874. /**
  13875. * @private
  13876. */
  13877. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  13878. //>>includeStart('debug', pragmas.debug);
  13879. if (!defined.defined(position)) {
  13880. throw new Check.DeveloperError('position is required.');
  13881. }
  13882. if (!defined.defined(velocity)) {
  13883. throw new Check.DeveloperError('velocity is required.');
  13884. }
  13885. //>>includeEnd('debug');
  13886. var normal = defaultValue.defaultValue(ellipsoid, Cartesian2.Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  13887. var right = Cartesian2.Cartesian3.cross(velocity, normal, rightScratch);
  13888. if (Cartesian2.Cartesian3.equalsEpsilon(right, Cartesian2.Cartesian3.ZERO, _Math.CesiumMath.EPSILON6)) {
  13889. right = Cartesian2.Cartesian3.clone(Cartesian2.Cartesian3.UNIT_X, right);
  13890. }
  13891. var up = Cartesian2.Cartesian3.cross(right, velocity, upScratch);
  13892. Cartesian2.Cartesian3.normalize(up, up);
  13893. Cartesian2.Cartesian3.cross(velocity, up, right);
  13894. Cartesian2.Cartesian3.negate(right, right);
  13895. Cartesian2.Cartesian3.normalize(right, right);
  13896. if (!defined.defined(result)) {
  13897. result = new Matrix3();
  13898. }
  13899. result[0] = velocity.x;
  13900. result[1] = velocity.y;
  13901. result[2] = velocity.z;
  13902. result[3] = right.x;
  13903. result[4] = right.y;
  13904. result[5] = right.z;
  13905. result[6] = up.x;
  13906. result[7] = up.y;
  13907. result[8] = up.z;
  13908. return result;
  13909. };
  13910. var swizzleMatrix = new Matrix4(
  13911. 0.0, 0.0, 1.0, 0.0,
  13912. 1.0, 0.0, 0.0, 0.0,
  13913. 0.0, 1.0, 0.0, 0.0,
  13914. 0.0, 0.0, 0.0, 1.0
  13915. );
  13916. var scratchCartographic = new Cartesian2.Cartographic();
  13917. var scratchCartesian3Projection = new Cartesian2.Cartesian3();
  13918. var scratchCenter = new Cartesian2.Cartesian3();
  13919. var scratchRotation = new Matrix3();
  13920. var scratchFromENU = new Matrix4();
  13921. var scratchToENU = new Matrix4();
  13922. /**
  13923. * @private
  13924. */
  13925. Transforms.basisTo2D = function(projection, matrix, result) {
  13926. //>>includeStart('debug', pragmas.debug);
  13927. if (!defined.defined(projection)) {
  13928. throw new Check.DeveloperError('projection is required.');
  13929. }
  13930. if (!defined.defined(matrix)) {
  13931. throw new Check.DeveloperError('matrix is required.');
  13932. }
  13933. if (!defined.defined(result)) {
  13934. throw new Check.DeveloperError('result is required.');
  13935. }
  13936. //>>includeEnd('debug');
  13937. var rtcCenter = Matrix4.getTranslation(matrix, scratchCenter);
  13938. var ellipsoid = projection.ellipsoid;
  13939. // Get the 2D Center
  13940. var cartographic = ellipsoid.cartesianToCartographic(rtcCenter, scratchCartographic);
  13941. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  13942. Cartesian2.Cartesian3.fromElements(projectedPosition.z, projectedPosition.x, projectedPosition.y, projectedPosition);
  13943. // Assuming the instance are positioned in WGS84, invert the WGS84 transform to get the local transform and then convert to 2D
  13944. var fromENU = Transforms.eastNorthUpToFixedFrame(rtcCenter, ellipsoid, scratchFromENU);
  13945. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  13946. var rotation = Matrix4.getMatrix3(matrix, scratchRotation);
  13947. var local = Matrix4.multiplyByMatrix3(toENU, rotation, result);
  13948. Matrix4.multiply(swizzleMatrix, local, result); // Swap x, y, z for 2D
  13949. Matrix4.setTranslation(result, projectedPosition, result); // Use the projected center
  13950. return result;
  13951. };
  13952. /**
  13953. * @private
  13954. */
  13955. Transforms.wgs84To2DModelMatrix = function(projection, center, result) {
  13956. //>>includeStart('debug', pragmas.debug);
  13957. if (!defined.defined(projection)) {
  13958. throw new Check.DeveloperError('projection is required.');
  13959. }
  13960. if (!defined.defined(center)) {
  13961. throw new Check.DeveloperError('center is required.');
  13962. }
  13963. if (!defined.defined(result)) {
  13964. throw new Check.DeveloperError('result is required.');
  13965. }
  13966. //>>includeEnd('debug');
  13967. var ellipsoid = projection.ellipsoid;
  13968. var fromENU = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, scratchFromENU);
  13969. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  13970. var cartographic = ellipsoid.cartesianToCartographic(center, scratchCartographic);
  13971. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  13972. Cartesian2.Cartesian3.fromElements(projectedPosition.z, projectedPosition.x, projectedPosition.y, projectedPosition);
  13973. var translation = Matrix4.fromTranslation(projectedPosition, scratchFromENU);
  13974. Matrix4.multiply(swizzleMatrix, toENU, result);
  13975. Matrix4.multiply(translation, result, result);
  13976. return result;
  13977. };
  13978. exports.BoundingSphere = BoundingSphere;
  13979. exports.Cartesian4 = Cartesian4;
  13980. exports.FeatureDetection = FeatureDetection;
  13981. exports.GeographicProjection = GeographicProjection;
  13982. exports.Intersect = Intersect$1;
  13983. exports.Interval = Interval;
  13984. exports.Matrix3 = Matrix3;
  13985. exports.Matrix4 = Matrix4;
  13986. exports.Quaternion = Quaternion;
  13987. exports.Resource = Resource;
  13988. exports.Transforms = Transforms;
  13989. exports.buildModuleUrl = buildModuleUrl;
  13990. exports.deprecationWarning = deprecationWarning;
  13991. exports.isArray = isArray$1;
  13992. exports.oneTimeWarning = oneTimeWarning;
  13993. });