createEllipseGeometry.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505
  1. /**
  2. * Cesium - https://github.com/AnalyticalGraphicsInc/cesium
  3. *
  4. * Copyright 2011-2016 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. (function () {
  24. /*global define*/
  25. define('Core/defined',[],function() {
  26. 'use strict';
  27. /**
  28. * @exports defined
  29. *
  30. * @param {Object} value The object.
  31. * @returns {Boolean} Returns true if the object is defined, returns false otherwise.
  32. *
  33. * @example
  34. * if (Cesium.defined(positions)) {
  35. * doSomething();
  36. * } else {
  37. * doSomethingElse();
  38. * }
  39. */
  40. function defined(value) {
  41. return value !== undefined && value !== null;
  42. }
  43. return defined;
  44. });
  45. /*global define*/
  46. define('Core/freezeObject',[
  47. './defined'
  48. ], function(
  49. defined) {
  50. 'use strict';
  51. /**
  52. * Freezes an object, using Object.freeze if available, otherwise returns
  53. * the object unchanged. This function should be used in setup code to prevent
  54. * errors from completely halting JavaScript execution in legacy browsers.
  55. *
  56. * @private
  57. *
  58. * @exports freezeObject
  59. */
  60. var freezeObject = Object.freeze;
  61. if (!defined(freezeObject)) {
  62. freezeObject = function(o) {
  63. return o;
  64. };
  65. }
  66. return freezeObject;
  67. });
  68. /*global define*/
  69. define('Core/defaultValue',[
  70. './freezeObject'
  71. ], function(
  72. freezeObject) {
  73. 'use strict';
  74. /**
  75. * Returns the first parameter if not undefined, otherwise the second parameter.
  76. * Useful for setting a default value for a parameter.
  77. *
  78. * @exports defaultValue
  79. *
  80. * @param {*} a
  81. * @param {*} b
  82. * @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
  83. *
  84. * @example
  85. * param = Cesium.defaultValue(param, 'default');
  86. */
  87. function defaultValue(a, b) {
  88. if (a !== undefined) {
  89. return a;
  90. }
  91. return b;
  92. }
  93. /**
  94. * A frozen empty object that can be used as the default value for options passed as
  95. * an object literal.
  96. */
  97. defaultValue.EMPTY_OBJECT = freezeObject({});
  98. return defaultValue;
  99. });
  100. /*global define*/
  101. define('Core/DeveloperError',[
  102. './defined'
  103. ], function(
  104. defined) {
  105. 'use strict';
  106. /**
  107. * Constructs an exception object that is thrown due to a developer error, e.g., invalid argument,
  108. * argument out of range, etc. This exception should only be thrown during development;
  109. * it usually indicates a bug in the calling code. This exception should never be
  110. * caught; instead the calling code should strive not to generate it.
  111. * <br /><br />
  112. * On the other hand, a {@link RuntimeError} indicates an exception that may
  113. * be thrown at runtime, e.g., out of memory, that the calling code should be prepared
  114. * to catch.
  115. *
  116. * @alias DeveloperError
  117. * @constructor
  118. * @extends Error
  119. *
  120. * @param {String} [message] The error message for this exception.
  121. *
  122. * @see RuntimeError
  123. */
  124. function DeveloperError(message) {
  125. /**
  126. * 'DeveloperError' indicating that this exception was thrown due to a developer error.
  127. * @type {String}
  128. * @readonly
  129. */
  130. this.name = 'DeveloperError';
  131. /**
  132. * The explanation for why this exception was thrown.
  133. * @type {String}
  134. * @readonly
  135. */
  136. this.message = message;
  137. //Browsers such as IE don't have a stack property until you actually throw the error.
  138. var stack;
  139. try {
  140. throw new Error();
  141. } catch (e) {
  142. stack = e.stack;
  143. }
  144. /**
  145. * The stack trace of this exception, if available.
  146. * @type {String}
  147. * @readonly
  148. */
  149. this.stack = stack;
  150. }
  151. if (defined(Object.create)) {
  152. DeveloperError.prototype = Object.create(Error.prototype);
  153. DeveloperError.prototype.constructor = DeveloperError;
  154. }
  155. DeveloperError.prototype.toString = function() {
  156. var str = this.name + ': ' + this.message;
  157. if (defined(this.stack)) {
  158. str += '\n' + this.stack.toString();
  159. }
  160. return str;
  161. };
  162. /**
  163. * @private
  164. */
  165. DeveloperError.throwInstantiationError = function() {
  166. throw new DeveloperError('This function defines an interface and should not be called directly.');
  167. };
  168. return DeveloperError;
  169. });
  170. /*global define*/
  171. define('Core/isArray',[
  172. './defined'
  173. ], function(
  174. defined) {
  175. 'use strict';
  176. /**
  177. * Tests an object to see if it is an array.
  178. * @exports isArray
  179. *
  180. * @param {Object} value The value to test.
  181. * @returns {Boolean} true if the value is an array, false otherwise.
  182. */
  183. var isArray = Array.isArray;
  184. if (!defined(isArray)) {
  185. isArray = function(value) {
  186. return Object.prototype.toString.call(value) === '[object Array]';
  187. };
  188. }
  189. return isArray;
  190. });
  191. /*global define*/
  192. define('Core/Check',[
  193. './defaultValue',
  194. './defined',
  195. './DeveloperError',
  196. './isArray'
  197. ], function(
  198. defaultValue,
  199. defined,
  200. DeveloperError,
  201. isArray) {
  202. 'use strict';
  203. /**
  204. * Contains functions for checking that supplied arguments are of a specified type
  205. * or meet specified conditions
  206. * @private
  207. */
  208. var Check = {};
  209. /**
  210. * Contains type checking functions, all using the typeof operator
  211. */
  212. Check.typeOf = {};
  213. /**
  214. * Contains functions for checking numeric conditions such as minimum and maximum values
  215. */
  216. Check.numeric = {};
  217. function getUndefinedErrorMessage(name) {
  218. return name + ' was required but undefined.';
  219. }
  220. function getFailedTypeErrorMessage(actual, expected, name) {
  221. return 'Expected ' + name + ' to be typeof ' + expected + ', got ' + actual;
  222. }
  223. /**
  224. * Throws if test is not defined
  225. *
  226. * @param {*} test The value that is to be checked
  227. * @param {String} name The name of the variable being tested
  228. * @exception {DeveloperError} test must be defined
  229. */
  230. Check.defined = function (test, name) {
  231. if (!defined(test)) {
  232. throw new DeveloperError(getUndefinedErrorMessage(name));
  233. }
  234. };
  235. /**
  236. * Throws if test is greater than maximum
  237. *
  238. * @param {Number} test The value to test
  239. * @param {Number} maximum The maximum allowed value
  240. * @exception {DeveloperError} test must not be greater than maximum
  241. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  242. */
  243. Check.numeric.maximum = function (test, maximum) {
  244. Check.typeOf.number(test);
  245. Check.typeOf.number(maximum);
  246. if (test > maximum) {
  247. throw new DeveloperError('Expected ' + test + ' to be at most ' + maximum);
  248. }
  249. };
  250. /**
  251. * Throws if test is less than minimum
  252. *
  253. * @param {Number} test The value to test
  254. * @param {Number} minimum The minimum allowed value
  255. * @exception {DeveloperError} test must not be less than mininum
  256. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  257. */
  258. Check.numeric.minimum = function (test, minimum) {
  259. Check.typeOf.number(test);
  260. Check.typeOf.number(minimum);
  261. if (test < minimum) {
  262. throw new DeveloperError('Expected ' + test + ' to be at least ' + minimum);
  263. }
  264. };
  265. /**
  266. * Throws if test is not typeof 'function'
  267. *
  268. * @param {*} test The value to test
  269. * @param {String} name The name of the variable being tested
  270. * @exception {DeveloperError} test must be typeof 'function'
  271. */
  272. Check.typeOf.function = function (test, name) {
  273. if (typeof test !== 'function') {
  274. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'function', name));
  275. }
  276. };
  277. /**
  278. * Throws if test is not typeof 'string'
  279. *
  280. * @param {*} test The value to test
  281. * @param {String} name The name of the variable being tested
  282. * @exception {DeveloperError} test must be typeof 'string'
  283. */
  284. Check.typeOf.string = function (test, name) {
  285. if (typeof test !== 'string') {
  286. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'string', name));
  287. }
  288. };
  289. /**
  290. * Throws if test is not typeof 'number'
  291. *
  292. * @param {*} test The value to test
  293. * @param {String} name The name of the variable being tested
  294. * @exception {DeveloperError} test must be typeof 'number'
  295. */
  296. Check.typeOf.number = function (test, name) {
  297. if (typeof test !== 'number') {
  298. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'number', name));
  299. }
  300. };
  301. /**
  302. * Throws if test is not typeof 'object'
  303. *
  304. * @param {*} test The value to test
  305. * @param {String} name The name of the variable being tested
  306. * @exception {DeveloperError} test must be typeof 'object'
  307. */
  308. Check.typeOf.object = function (test, name) {
  309. if (typeof test !== 'object') {
  310. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'object', name));
  311. }
  312. };
  313. /**
  314. * Throws if test is not typeof 'boolean'
  315. *
  316. * @param {*} test The value to test
  317. * @param {String} name The name of the variable being tested
  318. * @exception {DeveloperError} test must be typeof 'boolean'
  319. */
  320. Check.typeOf.boolean = function (test, name) {
  321. if (typeof test !== 'boolean') {
  322. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'boolean', name));
  323. }
  324. };
  325. return Check;
  326. });
  327. /*
  328. I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
  329. so it's better encapsulated. Now you can have multiple random number generators
  330. and they won't stomp all over eachother's state.
  331. If you want to use this as a substitute for Math.random(), use the random()
  332. method like so:
  333. var m = new MersenneTwister();
  334. var randomNumber = m.random();
  335. You can also call the other genrand_{foo}() methods on the instance.
  336. If you want to use a specific seed in order to get a repeatable random
  337. sequence, pass an integer into the constructor:
  338. var m = new MersenneTwister(123);
  339. and that will always produce the same random sequence.
  340. Sean McCullough (banksean@gmail.com)
  341. */
  342. /*
  343. A C-program for MT19937, with initialization improved 2002/1/26.
  344. Coded by Takuji Nishimura and Makoto Matsumoto.
  345. Before using, initialize the state by using init_genrand(seed)
  346. or init_by_array(init_key, key_length).
  347. */
  348. /**
  349. @license
  350. mersenne-twister.js - https://gist.github.com/banksean/300494
  351. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  352. All rights reserved.
  353. Redistribution and use in source and binary forms, with or without
  354. modification, are permitted provided that the following conditions
  355. are met:
  356. 1. Redistributions of source code must retain the above copyright
  357. notice, this list of conditions and the following disclaimer.
  358. 2. Redistributions in binary form must reproduce the above copyright
  359. notice, this list of conditions and the following disclaimer in the
  360. documentation and/or other materials provided with the distribution.
  361. 3. The names of its contributors may not be used to endorse or promote
  362. products derived from this software without specific prior written
  363. permission.
  364. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  365. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  366. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  367. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  368. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  369. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  370. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  371. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  372. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  373. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  374. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  375. */
  376. /*
  377. Any feedback is very welcome.
  378. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  379. email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
  380. */
  381. define('ThirdParty/mersenne-twister',[],function() {
  382. var MersenneTwister = function(seed) {
  383. if (seed == undefined) {
  384. seed = new Date().getTime();
  385. }
  386. /* Period parameters */
  387. this.N = 624;
  388. this.M = 397;
  389. this.MATRIX_A = 0x9908b0df; /* constant vector a */
  390. this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  391. this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
  392. this.mt = new Array(this.N); /* the array for the state vector */
  393. this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */
  394. this.init_genrand(seed);
  395. }
  396. /* initializes mt[N] with a seed */
  397. MersenneTwister.prototype.init_genrand = function(s) {
  398. this.mt[0] = s >>> 0;
  399. for (this.mti=1; this.mti<this.N; this.mti++) {
  400. var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
  401. this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  402. + this.mti;
  403. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  404. /* In the previous versions, MSBs of the seed affect */
  405. /* only MSBs of the array mt[]. */
  406. /* 2002/01/09 modified by Makoto Matsumoto */
  407. this.mt[this.mti] >>>= 0;
  408. /* for >32 bit machines */
  409. }
  410. }
  411. /* initialize by an array with array-length */
  412. /* init_key is the array for initializing keys */
  413. /* key_length is its length */
  414. /* slight change for C++, 2004/2/26 */
  415. //MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  416. // var i, j, k;
  417. // this.init_genrand(19650218);
  418. // i=1; j=0;
  419. // k = (this.N>key_length ? this.N : key_length);
  420. // for (; k; k--) {
  421. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
  422. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
  423. // + init_key[j] + j; /* non linear */
  424. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  425. // i++; j++;
  426. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  427. // if (j>=key_length) j=0;
  428. // }
  429. // for (k=this.N-1; k; k--) {
  430. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
  431. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
  432. // - i; /* non linear */
  433. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  434. // i++;
  435. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  436. // }
  437. //
  438. // this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
  439. //}
  440. /* generates a random number on [0,0xffffffff]-interval */
  441. MersenneTwister.prototype.genrand_int32 = function() {
  442. var y;
  443. var mag01 = new Array(0x0, this.MATRIX_A);
  444. /* mag01[x] = x * MATRIX_A for x=0,1 */
  445. if (this.mti >= this.N) { /* generate N words at one time */
  446. var kk;
  447. if (this.mti == this.N+1) /* if init_genrand() has not been called, */
  448. this.init_genrand(5489); /* a default initial seed is used */
  449. for (kk=0;kk<this.N-this.M;kk++) {
  450. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  451. this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
  452. }
  453. for (;kk<this.N-1;kk++) {
  454. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  455. this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
  456. }
  457. y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
  458. this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];
  459. this.mti = 0;
  460. }
  461. y = this.mt[this.mti++];
  462. /* Tempering */
  463. y ^= (y >>> 11);
  464. y ^= (y << 7) & 0x9d2c5680;
  465. y ^= (y << 15) & 0xefc60000;
  466. y ^= (y >>> 18);
  467. return y >>> 0;
  468. }
  469. /* generates a random number on [0,0x7fffffff]-interval */
  470. //MersenneTwister.prototype.genrand_int31 = function() {
  471. // return (this.genrand_int32()>>>1);
  472. //}
  473. /* generates a random number on [0,1]-real-interval */
  474. //MersenneTwister.prototype.genrand_real1 = function() {
  475. // return this.genrand_int32()*(1.0/4294967295.0);
  476. // /* divided by 2^32-1 */
  477. //}
  478. /* generates a random number on [0,1)-real-interval */
  479. MersenneTwister.prototype.random = function() {
  480. return this.genrand_int32()*(1.0/4294967296.0);
  481. /* divided by 2^32 */
  482. }
  483. /* generates a random number on (0,1)-real-interval */
  484. //MersenneTwister.prototype.genrand_real3 = function() {
  485. // return (this.genrand_int32() + 0.5)*(1.0/4294967296.0);
  486. // /* divided by 2^32 */
  487. //}
  488. /* generates a random number on [0,1) with 53-bit resolution*/
  489. //MersenneTwister.prototype.genrand_res53 = function() {
  490. // var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
  491. // return(a*67108864.0+b)*(1.0/9007199254740992.0);
  492. //}
  493. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  494. return MersenneTwister;
  495. });
  496. /*global define*/
  497. define('Core/Math',[
  498. '../ThirdParty/mersenne-twister',
  499. './defaultValue',
  500. './defined',
  501. './DeveloperError'
  502. ], function(
  503. MersenneTwister,
  504. defaultValue,
  505. defined,
  506. DeveloperError) {
  507. 'use strict';
  508. /**
  509. * Math functions.
  510. *
  511. * @exports CesiumMath
  512. */
  513. var CesiumMath = {};
  514. /**
  515. * 0.1
  516. * @type {Number}
  517. * @constant
  518. */
  519. CesiumMath.EPSILON1 = 0.1;
  520. /**
  521. * 0.01
  522. * @type {Number}
  523. * @constant
  524. */
  525. CesiumMath.EPSILON2 = 0.01;
  526. /**
  527. * 0.001
  528. * @type {Number}
  529. * @constant
  530. */
  531. CesiumMath.EPSILON3 = 0.001;
  532. /**
  533. * 0.0001
  534. * @type {Number}
  535. * @constant
  536. */
  537. CesiumMath.EPSILON4 = 0.0001;
  538. /**
  539. * 0.00001
  540. * @type {Number}
  541. * @constant
  542. */
  543. CesiumMath.EPSILON5 = 0.00001;
  544. /**
  545. * 0.000001
  546. * @type {Number}
  547. * @constant
  548. */
  549. CesiumMath.EPSILON6 = 0.000001;
  550. /**
  551. * 0.0000001
  552. * @type {Number}
  553. * @constant
  554. */
  555. CesiumMath.EPSILON7 = 0.0000001;
  556. /**
  557. * 0.00000001
  558. * @type {Number}
  559. * @constant
  560. */
  561. CesiumMath.EPSILON8 = 0.00000001;
  562. /**
  563. * 0.000000001
  564. * @type {Number}
  565. * @constant
  566. */
  567. CesiumMath.EPSILON9 = 0.000000001;
  568. /**
  569. * 0.0000000001
  570. * @type {Number}
  571. * @constant
  572. */
  573. CesiumMath.EPSILON10 = 0.0000000001;
  574. /**
  575. * 0.00000000001
  576. * @type {Number}
  577. * @constant
  578. */
  579. CesiumMath.EPSILON11 = 0.00000000001;
  580. /**
  581. * 0.000000000001
  582. * @type {Number}
  583. * @constant
  584. */
  585. CesiumMath.EPSILON12 = 0.000000000001;
  586. /**
  587. * 0.0000000000001
  588. * @type {Number}
  589. * @constant
  590. */
  591. CesiumMath.EPSILON13 = 0.0000000000001;
  592. /**
  593. * 0.00000000000001
  594. * @type {Number}
  595. * @constant
  596. */
  597. CesiumMath.EPSILON14 = 0.00000000000001;
  598. /**
  599. * 0.000000000000001
  600. * @type {Number}
  601. * @constant
  602. */
  603. CesiumMath.EPSILON15 = 0.000000000000001;
  604. /**
  605. * 0.0000000000000001
  606. * @type {Number}
  607. * @constant
  608. */
  609. CesiumMath.EPSILON16 = 0.0000000000000001;
  610. /**
  611. * 0.00000000000000001
  612. * @type {Number}
  613. * @constant
  614. */
  615. CesiumMath.EPSILON17 = 0.00000000000000001;
  616. /**
  617. * 0.000000000000000001
  618. * @type {Number}
  619. * @constant
  620. */
  621. CesiumMath.EPSILON18 = 0.000000000000000001;
  622. /**
  623. * 0.0000000000000000001
  624. * @type {Number}
  625. * @constant
  626. */
  627. CesiumMath.EPSILON19 = 0.0000000000000000001;
  628. /**
  629. * 0.00000000000000000001
  630. * @type {Number}
  631. * @constant
  632. */
  633. CesiumMath.EPSILON20 = 0.00000000000000000001;
  634. /**
  635. * 3.986004418e14
  636. * @type {Number}
  637. * @constant
  638. */
  639. CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
  640. /**
  641. * Radius of the sun in meters: 6.955e8
  642. * @type {Number}
  643. * @constant
  644. */
  645. CesiumMath.SOLAR_RADIUS = 6.955e8;
  646. /**
  647. * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
  648. * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
  649. * Celestial Mechanics 82: 83-110, 2002.
  650. * @type {Number}
  651. * @constant
  652. */
  653. CesiumMath.LUNAR_RADIUS = 1737400.0;
  654. /**
  655. * 64 * 1024
  656. * @type {Number}
  657. * @constant
  658. */
  659. CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
  660. /**
  661. * Returns the sign of the value; 1 if the value is positive, -1 if the value is
  662. * negative, or 0 if the value is 0.
  663. *
  664. * @param {Number} value The value to return the sign of.
  665. * @returns {Number} The sign of value.
  666. */
  667. CesiumMath.sign = function(value) {
  668. if (value > 0) {
  669. return 1;
  670. }
  671. if (value < 0) {
  672. return -1;
  673. }
  674. return 0;
  675. };
  676. /**
  677. * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
  678. * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
  679. * 0.0 when the input value is 0.0.
  680. * @param {Number} value The value to return the sign of.
  681. * @returns {Number} The sign of value.
  682. */
  683. CesiumMath.signNotZero = function(value) {
  684. return value < 0.0 ? -1.0 : 1.0;
  685. };
  686. /**
  687. * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMax]
  688. * @param {Number} value The scalar value in the range [-1.0, 1.0]
  689. * @param {Number} [rangeMax=255] The maximum value in the mapped range, 255 by default.
  690. * @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMax maps to 1.0.
  691. *
  692. * @see CesiumMath.fromSNorm
  693. */
  694. CesiumMath.toSNorm = function(value, rangeMax) {
  695. rangeMax = defaultValue(rangeMax, 255);
  696. return Math.round((CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMax);
  697. };
  698. /**
  699. * Converts a SNORM value in the range [0, rangeMax] to a scalar in the range [-1.0, 1.0].
  700. * @param {Number} value SNORM value in the range [0, 255]
  701. * @param {Number} [rangeMax=255] The maximum value in the SNORM range, 255 by default.
  702. * @returns {Number} Scalar in the range [-1.0, 1.0].
  703. *
  704. * @see CesiumMath.toSNorm
  705. */
  706. CesiumMath.fromSNorm = function(value, rangeMax) {
  707. rangeMax = defaultValue(rangeMax, 255);
  708. return CesiumMath.clamp(value, 0.0, rangeMax) / rangeMax * 2.0 - 1.0;
  709. };
  710. /**
  711. * Returns the hyperbolic sine of a number.
  712. * The hyperbolic sine of <em>value</em> is defined to be
  713. * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
  714. * where <i>e</i> is Euler's number, approximately 2.71828183.
  715. *
  716. * <p>Special cases:
  717. * <ul>
  718. * <li>If the argument is NaN, then the result is NaN.</li>
  719. *
  720. * <li>If the argument is infinite, then the result is an infinity
  721. * with the same sign as the argument.</li>
  722. *
  723. * <li>If the argument is zero, then the result is a zero with the
  724. * same sign as the argument.</li>
  725. * </ul>
  726. *</p>
  727. *
  728. * @param {Number} value The number whose hyperbolic sine is to be returned.
  729. * @returns {Number} The hyperbolic sine of <code>value</code>.
  730. */
  731. CesiumMath.sinh = function(value) {
  732. var part1 = Math.pow(Math.E, value);
  733. var part2 = Math.pow(Math.E, -1.0 * value);
  734. return (part1 - part2) * 0.5;
  735. };
  736. /**
  737. * Returns the hyperbolic cosine of a number.
  738. * The hyperbolic cosine of <strong>value</strong> is defined to be
  739. * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
  740. * where <i>e</i> is Euler's number, approximately 2.71828183.
  741. *
  742. * <p>Special cases:
  743. * <ul>
  744. * <li>If the argument is NaN, then the result is NaN.</li>
  745. *
  746. * <li>If the argument is infinite, then the result is positive infinity.</li>
  747. *
  748. * <li>If the argument is zero, then the result is 1.0.</li>
  749. * </ul>
  750. *</p>
  751. *
  752. * @param {Number} value The number whose hyperbolic cosine is to be returned.
  753. * @returns {Number} The hyperbolic cosine of <code>value</code>.
  754. */
  755. CesiumMath.cosh = function(value) {
  756. var part1 = Math.pow(Math.E, value);
  757. var part2 = Math.pow(Math.E, -1.0 * value);
  758. return (part1 + part2) * 0.5;
  759. };
  760. /**
  761. * Computes the linear interpolation of two values.
  762. *
  763. * @param {Number} p The start value to interpolate.
  764. * @param {Number} q The end value to interpolate.
  765. * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  766. * @returns {Number} The linearly interpolated value.
  767. *
  768. * @example
  769. * var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
  770. */
  771. CesiumMath.lerp = function(p, q, time) {
  772. return ((1.0 - time) * p) + (time * q);
  773. };
  774. /**
  775. * pi
  776. *
  777. * @type {Number}
  778. * @constant
  779. */
  780. CesiumMath.PI = Math.PI;
  781. /**
  782. * 1/pi
  783. *
  784. * @type {Number}
  785. * @constant
  786. */
  787. CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
  788. /**
  789. * pi/2
  790. *
  791. * @type {Number}
  792. * @constant
  793. */
  794. CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
  795. /**
  796. * pi/3
  797. *
  798. * @type {Number}
  799. * @constant
  800. */
  801. CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
  802. /**
  803. * pi/4
  804. *
  805. * @type {Number}
  806. * @constant
  807. */
  808. CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
  809. /**
  810. * pi/6
  811. *
  812. * @type {Number}
  813. * @constant
  814. */
  815. CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
  816. /**
  817. * 3pi/2
  818. *
  819. * @type {Number}
  820. * @constant
  821. */
  822. CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
  823. /**
  824. * 2pi
  825. *
  826. * @type {Number}
  827. * @constant
  828. */
  829. CesiumMath.TWO_PI = 2.0 * Math.PI;
  830. /**
  831. * 1/2pi
  832. *
  833. * @type {Number}
  834. * @constant
  835. */
  836. CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
  837. /**
  838. * The number of radians in a degree.
  839. *
  840. * @type {Number}
  841. * @constant
  842. * @default Math.PI / 180.0
  843. */
  844. CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
  845. /**
  846. * The number of degrees in a radian.
  847. *
  848. * @type {Number}
  849. * @constant
  850. * @default 180.0 / Math.PI
  851. */
  852. CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
  853. /**
  854. * The number of radians in an arc second.
  855. *
  856. * @type {Number}
  857. * @constant
  858. * @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
  859. */
  860. CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  861. /**
  862. * Converts degrees to radians.
  863. * @param {Number} degrees The angle to convert in degrees.
  864. * @returns {Number} The corresponding angle in radians.
  865. */
  866. CesiumMath.toRadians = function(degrees) {
  867. if (!defined(degrees)) {
  868. throw new DeveloperError('degrees is required.');
  869. }
  870. return degrees * CesiumMath.RADIANS_PER_DEGREE;
  871. };
  872. /**
  873. * Converts radians to degrees.
  874. * @param {Number} radians The angle to convert in radians.
  875. * @returns {Number} The corresponding angle in degrees.
  876. */
  877. CesiumMath.toDegrees = function(radians) {
  878. if (!defined(radians)) {
  879. throw new DeveloperError('radians is required.');
  880. }
  881. return radians * CesiumMath.DEGREES_PER_RADIAN;
  882. };
  883. /**
  884. * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  885. *
  886. * @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  887. * @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  888. *
  889. * @example
  890. * // Convert 270 degrees to -90 degrees longitude
  891. * var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
  892. */
  893. CesiumMath.convertLongitudeRange = function(angle) {
  894. if (!defined(angle)) {
  895. throw new DeveloperError('angle is required.');
  896. }
  897. var twoPi = CesiumMath.TWO_PI;
  898. var simplified = angle - Math.floor(angle / twoPi) * twoPi;
  899. if (simplified < -Math.PI) {
  900. return simplified + twoPi;
  901. }
  902. if (simplified >= Math.PI) {
  903. return simplified - twoPi;
  904. }
  905. return simplified;
  906. };
  907. /**
  908. * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  909. * Useful for sanitizing data before use in objects requiring correct range.
  910. *
  911. * @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  912. * @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  913. *
  914. * @example
  915. * // Clamp 108 degrees latitude to 90 degrees latitude
  916. * var latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
  917. */
  918. CesiumMath.clampToLatitudeRange = function(angle) {
  919. if (!defined(angle)) {
  920. throw new DeveloperError('angle is required.');
  921. }
  922. return CesiumMath.clamp(angle, -1*CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO);
  923. };
  924. /**
  925. * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
  926. *
  927. * @param {Number} angle in radians
  928. * @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
  929. */
  930. CesiumMath.negativePiToPi = function(x) {
  931. if (!defined(x)) {
  932. throw new DeveloperError('x is required.');
  933. }
  934. return CesiumMath.zeroToTwoPi(x + CesiumMath.PI) - CesiumMath.PI;
  935. };
  936. /**
  937. * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
  938. *
  939. * @param {Number} angle in radians
  940. * @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
  941. */
  942. CesiumMath.zeroToTwoPi = function(x) {
  943. if (!defined(x)) {
  944. throw new DeveloperError('x is required.');
  945. }
  946. var mod = CesiumMath.mod(x, CesiumMath.TWO_PI);
  947. if (Math.abs(mod) < CesiumMath.EPSILON14 && Math.abs(x) > CesiumMath.EPSILON14) {
  948. return CesiumMath.TWO_PI;
  949. }
  950. return mod;
  951. };
  952. /**
  953. * The modulo operation that also works for negative dividends.
  954. *
  955. * @param {Number} m The dividend.
  956. * @param {Number} n The divisor.
  957. * @returns {Number} The remainder.
  958. */
  959. CesiumMath.mod = function(m, n) {
  960. if (!defined(m)) {
  961. throw new DeveloperError('m is required.');
  962. }
  963. if (!defined(n)) {
  964. throw new DeveloperError('n is required.');
  965. }
  966. return ((m % n) + n) % n;
  967. };
  968. /**
  969. * Determines if two values are equal using an absolute or relative tolerance test. This is useful
  970. * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
  971. * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
  972. * Use this test if you are unsure of the magnitudes of left and right.
  973. *
  974. * @param {Number} left The first value to compare.
  975. * @param {Number} right The other value to compare.
  976. * @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
  977. * @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
  978. * @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
  979. *
  980. * @example
  981. * var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
  982. * var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
  983. * var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
  984. * var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
  985. */
  986. CesiumMath.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  987. if (!defined(left)) {
  988. throw new DeveloperError('left is required.');
  989. }
  990. if (!defined(right)) {
  991. throw new DeveloperError('right is required.');
  992. }
  993. if (!defined(relativeEpsilon)) {
  994. throw new DeveloperError('relativeEpsilon is required.');
  995. }
  996. absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
  997. var absDiff = Math.abs(left - right);
  998. return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right));
  999. };
  1000. var factorials = [1];
  1001. /**
  1002. * Computes the factorial of the provided number.
  1003. *
  1004. * @param {Number} n The number whose factorial is to be computed.
  1005. * @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
  1006. *
  1007. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1008. *
  1009. *
  1010. * @example
  1011. * //Compute 7!, which is equal to 5040
  1012. * var computedFactorial = Cesium.Math.factorial(7);
  1013. *
  1014. * @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
  1015. */
  1016. CesiumMath.factorial = function(n) {
  1017. if (typeof n !== 'number' || n < 0) {
  1018. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1019. }
  1020. var length = factorials.length;
  1021. if (n >= length) {
  1022. var sum = factorials[length - 1];
  1023. for (var i = length; i <= n; i++) {
  1024. factorials.push(sum * i);
  1025. }
  1026. }
  1027. return factorials[n];
  1028. };
  1029. /**
  1030. * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
  1031. *
  1032. * @param {Number} [n] The number to be incremented.
  1033. * @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
  1034. * @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
  1035. * @returns {Number} The incremented number.
  1036. *
  1037. * @exception {DeveloperError} Maximum value must be greater than minimum value.
  1038. *
  1039. * @example
  1040. * var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
  1041. * var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
  1042. */
  1043. CesiumMath.incrementWrap = function(n, maximumValue, minimumValue) {
  1044. minimumValue = defaultValue(minimumValue, 0.0);
  1045. if (!defined(n)) {
  1046. throw new DeveloperError('n is required.');
  1047. }
  1048. if (maximumValue <= minimumValue) {
  1049. throw new DeveloperError('maximumValue must be greater than minimumValue.');
  1050. }
  1051. ++n;
  1052. if (n > maximumValue) {
  1053. n = minimumValue;
  1054. }
  1055. return n;
  1056. };
  1057. /**
  1058. * Determines if a positive integer is a power of two.
  1059. *
  1060. * @param {Number} n The positive integer to test.
  1061. * @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
  1062. *
  1063. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1064. *
  1065. * @example
  1066. * var t = Cesium.Math.isPowerOfTwo(16); // true
  1067. * var f = Cesium.Math.isPowerOfTwo(20); // false
  1068. */
  1069. CesiumMath.isPowerOfTwo = function(n) {
  1070. if (typeof n !== 'number' || n < 0) {
  1071. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1072. }
  1073. return (n !== 0) && ((n & (n - 1)) === 0);
  1074. };
  1075. /**
  1076. * Computes the next power-of-two integer greater than or equal to the provided positive integer.
  1077. *
  1078. * @param {Number} n The positive integer to test.
  1079. * @returns {Number} The next power-of-two integer.
  1080. *
  1081. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1082. *
  1083. * @example
  1084. * var n = Cesium.Math.nextPowerOfTwo(29); // 32
  1085. * var m = Cesium.Math.nextPowerOfTwo(32); // 32
  1086. */
  1087. CesiumMath.nextPowerOfTwo = function(n) {
  1088. if (typeof n !== 'number' || n < 0) {
  1089. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1090. }
  1091. // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  1092. --n;
  1093. n |= n >> 1;
  1094. n |= n >> 2;
  1095. n |= n >> 4;
  1096. n |= n >> 8;
  1097. n |= n >> 16;
  1098. ++n;
  1099. return n;
  1100. };
  1101. /**
  1102. * Constraint a value to lie between two values.
  1103. *
  1104. * @param {Number} value The value to constrain.
  1105. * @param {Number} min The minimum value.
  1106. * @param {Number} max The maximum value.
  1107. * @returns {Number} The value clamped so that min <= value <= max.
  1108. */
  1109. CesiumMath.clamp = function(value, min, max) {
  1110. if (!defined(value)) {
  1111. throw new DeveloperError('value is required');
  1112. }
  1113. if (!defined(min)) {
  1114. throw new DeveloperError('min is required.');
  1115. }
  1116. if (!defined(max)) {
  1117. throw new DeveloperError('max is required.');
  1118. }
  1119. return value < min ? min : value > max ? max : value;
  1120. };
  1121. var randomNumberGenerator = new MersenneTwister();
  1122. /**
  1123. * Sets the seed used by the random number generator
  1124. * in {@link CesiumMath#nextRandomNumber}.
  1125. *
  1126. * @param {Number} seed An integer used as the seed.
  1127. */
  1128. CesiumMath.setRandomNumberSeed = function(seed) {
  1129. if (!defined(seed)) {
  1130. throw new DeveloperError('seed is required.');
  1131. }
  1132. randomNumberGenerator = new MersenneTwister(seed);
  1133. };
  1134. /**
  1135. * Generates a random number in the range of [0.0, 1.0)
  1136. * using a Mersenne twister.
  1137. *
  1138. * @returns {Number} A random number in the range of [0.0, 1.0).
  1139. *
  1140. * @see CesiumMath.setRandomNumberSeed
  1141. * @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
  1142. */
  1143. CesiumMath.nextRandomNumber = function() {
  1144. return randomNumberGenerator.random();
  1145. };
  1146. /**
  1147. * Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1148. * so that the function will never return NaN.
  1149. *
  1150. * @param {Number} value The value for which to compute acos.
  1151. * @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
  1152. * whichever is closer, if the value is outside the range.
  1153. */
  1154. CesiumMath.acosClamped = function(value) {
  1155. if (!defined(value)) {
  1156. throw new DeveloperError('value is required.');
  1157. }
  1158. return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
  1159. };
  1160. /**
  1161. * Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1162. * so that the function will never return NaN.
  1163. *
  1164. * @param {Number} value The value for which to compute asin.
  1165. * @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
  1166. * whichever is closer, if the value is outside the range.
  1167. */
  1168. CesiumMath.asinClamped = function(value) {
  1169. if (!defined(value)) {
  1170. throw new DeveloperError('value is required.');
  1171. }
  1172. return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
  1173. };
  1174. /**
  1175. * Finds the chord length between two points given the circle's radius and the angle between the points.
  1176. *
  1177. * @param {Number} angle The angle between the two points.
  1178. * @param {Number} radius The radius of the circle.
  1179. * @returns {Number} The chord length.
  1180. */
  1181. CesiumMath.chordLength = function(angle, radius) {
  1182. if (!defined(angle)) {
  1183. throw new DeveloperError('angle is required.');
  1184. }
  1185. if (!defined(radius)) {
  1186. throw new DeveloperError('radius is required.');
  1187. }
  1188. return 2.0 * radius * Math.sin(angle * 0.5);
  1189. };
  1190. /**
  1191. * Finds the logarithm of a number to a base.
  1192. *
  1193. * @param {Number} number The number.
  1194. * @param {Number} base The base.
  1195. * @returns {Number} The result.
  1196. */
  1197. CesiumMath.logBase = function(number, base) {
  1198. if (!defined(number)) {
  1199. throw new DeveloperError('number is required.');
  1200. }
  1201. if (!defined(base)) {
  1202. throw new DeveloperError('base is required.');
  1203. }
  1204. return Math.log(number) / Math.log(base);
  1205. };
  1206. /**
  1207. * @private
  1208. */
  1209. CesiumMath.fog = function(distanceToCamera, density) {
  1210. var scalar = distanceToCamera * density;
  1211. return 1.0 - Math.exp(-(scalar * scalar));
  1212. };
  1213. return CesiumMath;
  1214. });
  1215. /*global define*/
  1216. define('Core/Cartesian3',[
  1217. './Check',
  1218. './defaultValue',
  1219. './defined',
  1220. './DeveloperError',
  1221. './freezeObject',
  1222. './Math'
  1223. ], function(
  1224. Check,
  1225. defaultValue,
  1226. defined,
  1227. DeveloperError,
  1228. freezeObject,
  1229. CesiumMath) {
  1230. 'use strict';
  1231. /**
  1232. * A 3D Cartesian point.
  1233. * @alias Cartesian3
  1234. * @constructor
  1235. *
  1236. * @param {Number} [x=0.0] The X component.
  1237. * @param {Number} [y=0.0] The Y component.
  1238. * @param {Number} [z=0.0] The Z component.
  1239. *
  1240. * @see Cartesian2
  1241. * @see Cartesian4
  1242. * @see Packable
  1243. */
  1244. function Cartesian3(x, y, z) {
  1245. /**
  1246. * The X component.
  1247. * @type {Number}
  1248. * @default 0.0
  1249. */
  1250. this.x = defaultValue(x, 0.0);
  1251. /**
  1252. * The Y component.
  1253. * @type {Number}
  1254. * @default 0.0
  1255. */
  1256. this.y = defaultValue(y, 0.0);
  1257. /**
  1258. * The Z component.
  1259. * @type {Number}
  1260. * @default 0.0
  1261. */
  1262. this.z = defaultValue(z, 0.0);
  1263. }
  1264. /**
  1265. * Converts the provided Spherical into Cartesian3 coordinates.
  1266. *
  1267. * @param {Spherical} spherical The Spherical to be converted to Cartesian3.
  1268. * @param {Cartesian3} [result] The object onto which to store the result.
  1269. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1270. */
  1271. Cartesian3.fromSpherical = function(spherical, result) {
  1272. Check.typeOf.object(spherical, 'spherical');
  1273. if (!defined(result)) {
  1274. result = new Cartesian3();
  1275. }
  1276. var clock = spherical.clock;
  1277. var cone = spherical.cone;
  1278. var magnitude = defaultValue(spherical.magnitude, 1.0);
  1279. var radial = magnitude * Math.sin(cone);
  1280. result.x = radial * Math.cos(clock);
  1281. result.y = radial * Math.sin(clock);
  1282. result.z = magnitude * Math.cos(cone);
  1283. return result;
  1284. };
  1285. /**
  1286. * Creates a Cartesian3 instance from x, y and z coordinates.
  1287. *
  1288. * @param {Number} x The x coordinate.
  1289. * @param {Number} y The y coordinate.
  1290. * @param {Number} z The z coordinate.
  1291. * @param {Cartesian3} [result] The object onto which to store the result.
  1292. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1293. */
  1294. Cartesian3.fromElements = function(x, y, z, result) {
  1295. if (!defined(result)) {
  1296. return new Cartesian3(x, y, z);
  1297. }
  1298. result.x = x;
  1299. result.y = y;
  1300. result.z = z;
  1301. return result;
  1302. };
  1303. /**
  1304. * Duplicates a Cartesian3 instance.
  1305. *
  1306. * @param {Cartesian3} cartesian The Cartesian to duplicate.
  1307. * @param {Cartesian3} [result] The object onto which to store the result.
  1308. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
  1309. */
  1310. Cartesian3.clone = function(cartesian, result) {
  1311. if (!defined(cartesian)) {
  1312. return undefined;
  1313. }
  1314. if (!defined(result)) {
  1315. return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
  1316. }
  1317. result.x = cartesian.x;
  1318. result.y = cartesian.y;
  1319. result.z = cartesian.z;
  1320. return result;
  1321. };
  1322. /**
  1323. * Creates a Cartesian3 instance from an existing Cartesian4. This simply takes the
  1324. * x, y, and z properties of the Cartesian4 and drops w.
  1325. * @function
  1326. *
  1327. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
  1328. * @param {Cartesian3} [result] The object onto which to store the result.
  1329. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1330. */
  1331. Cartesian3.fromCartesian4 = Cartesian3.clone;
  1332. /**
  1333. * The number of elements used to pack the object into an array.
  1334. * @type {Number}
  1335. */
  1336. Cartesian3.packedLength = 3;
  1337. /**
  1338. * Stores the provided instance into the provided array.
  1339. *
  1340. * @param {Cartesian3} value The value to pack.
  1341. * @param {Number[]} array The array to pack into.
  1342. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  1343. *
  1344. * @returns {Number[]} The array that was packed into
  1345. */
  1346. Cartesian3.pack = function(value, array, startingIndex) {
  1347. Check.typeOf.object(value, 'value');
  1348. Check.defined(array, 'array');
  1349. startingIndex = defaultValue(startingIndex, 0);
  1350. array[startingIndex++] = value.x;
  1351. array[startingIndex++] = value.y;
  1352. array[startingIndex] = value.z;
  1353. return array;
  1354. };
  1355. /**
  1356. * Retrieves an instance from a packed array.
  1357. *
  1358. * @param {Number[]} array The packed array.
  1359. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  1360. * @param {Cartesian3} [result] The object into which to store the result.
  1361. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1362. */
  1363. Cartesian3.unpack = function(array, startingIndex, result) {
  1364. Check.defined(array, 'array');
  1365. startingIndex = defaultValue(startingIndex, 0);
  1366. if (!defined(result)) {
  1367. result = new Cartesian3();
  1368. }
  1369. result.x = array[startingIndex++];
  1370. result.y = array[startingIndex++];
  1371. result.z = array[startingIndex];
  1372. return result;
  1373. };
  1374. /**
  1375. * Flattens an array of Cartesian3s into an array of components.
  1376. *
  1377. * @param {Cartesian3[]} array The array of cartesians to pack.
  1378. * @param {Number[]} result The array onto which to store the result.
  1379. * @returns {Number[]} The packed array.
  1380. */
  1381. Cartesian3.packArray = function(array, result) {
  1382. Check.defined(array, 'array');
  1383. var length = array.length;
  1384. if (!defined(result)) {
  1385. result = new Array(length * 3);
  1386. } else {
  1387. result.length = length * 3;
  1388. }
  1389. for (var i = 0; i < length; ++i) {
  1390. Cartesian3.pack(array[i], result, i * 3);
  1391. }
  1392. return result;
  1393. };
  1394. /**
  1395. * Unpacks an array of cartesian components into an array of Cartesian3s.
  1396. *
  1397. * @param {Number[]} array The array of components to unpack.
  1398. * @param {Cartesian3[]} result The array onto which to store the result.
  1399. * @returns {Cartesian3[]} The unpacked array.
  1400. */
  1401. Cartesian3.unpackArray = function(array, result) {
  1402. Check.defined(array, 'array');
  1403. Check.numeric.minimum(array.length, 3);
  1404. if (array.length % 3 !== 0) {
  1405. throw new DeveloperError('array length must be a multiple of 3.');
  1406. }
  1407. var length = array.length;
  1408. if (!defined(result)) {
  1409. result = new Array(length / 3);
  1410. } else {
  1411. result.length = length / 3;
  1412. }
  1413. for (var i = 0; i < length; i += 3) {
  1414. var index = i / 3;
  1415. result[index] = Cartesian3.unpack(array, i, result[index]);
  1416. }
  1417. return result;
  1418. };
  1419. /**
  1420. * Creates a Cartesian3 from three consecutive elements in an array.
  1421. * @function
  1422. *
  1423. * @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
  1424. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  1425. * @param {Cartesian3} [result] The object onto which to store the result.
  1426. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1427. *
  1428. * @example
  1429. * // Create a Cartesian3 with (1.0, 2.0, 3.0)
  1430. * var v = [1.0, 2.0, 3.0];
  1431. * var p = Cesium.Cartesian3.fromArray(v);
  1432. *
  1433. * // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
  1434. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
  1435. * var p2 = Cesium.Cartesian3.fromArray(v2, 2);
  1436. */
  1437. Cartesian3.fromArray = Cartesian3.unpack;
  1438. /**
  1439. * Computes the value of the maximum component for the supplied Cartesian.
  1440. *
  1441. * @param {Cartesian3} cartesian The cartesian to use.
  1442. * @returns {Number} The value of the maximum component.
  1443. */
  1444. Cartesian3.maximumComponent = function(cartesian) {
  1445. Check.typeOf.object(cartesian, 'cartesian');
  1446. return Math.max(cartesian.x, cartesian.y, cartesian.z);
  1447. };
  1448. /**
  1449. * Computes the value of the minimum component for the supplied Cartesian.
  1450. *
  1451. * @param {Cartesian3} cartesian The cartesian to use.
  1452. * @returns {Number} The value of the minimum component.
  1453. */
  1454. Cartesian3.minimumComponent = function(cartesian) {
  1455. Check.typeOf.object(cartesian, 'cartesian');
  1456. return Math.min(cartesian.x, cartesian.y, cartesian.z);
  1457. };
  1458. /**
  1459. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  1460. *
  1461. * @param {Cartesian3} first A cartesian to compare.
  1462. * @param {Cartesian3} second A cartesian to compare.
  1463. * @param {Cartesian3} result The object into which to store the result.
  1464. * @returns {Cartesian3} A cartesian with the minimum components.
  1465. */
  1466. Cartesian3.minimumByComponent = function(first, second, result) {
  1467. Check.typeOf.object(first, 'first');
  1468. Check.typeOf.object(second, 'second');
  1469. Check.typeOf.object(result, 'result');
  1470. result.x = Math.min(first.x, second.x);
  1471. result.y = Math.min(first.y, second.y);
  1472. result.z = Math.min(first.z, second.z);
  1473. return result;
  1474. };
  1475. /**
  1476. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  1477. *
  1478. * @param {Cartesian3} first A cartesian to compare.
  1479. * @param {Cartesian3} second A cartesian to compare.
  1480. * @param {Cartesian3} result The object into which to store the result.
  1481. * @returns {Cartesian3} A cartesian with the maximum components.
  1482. */
  1483. Cartesian3.maximumByComponent = function(first, second, result) {
  1484. Check.typeOf.object(first, 'first');
  1485. Check.typeOf.object(second, 'second');
  1486. Check.typeOf.object(result, 'result');
  1487. result.x = Math.max(first.x, second.x);
  1488. result.y = Math.max(first.y, second.y);
  1489. result.z = Math.max(first.z, second.z);
  1490. return result;
  1491. };
  1492. /**
  1493. * Computes the provided Cartesian's squared magnitude.
  1494. *
  1495. * @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
  1496. * @returns {Number} The squared magnitude.
  1497. */
  1498. Cartesian3.magnitudeSquared = function(cartesian) {
  1499. Check.typeOf.object(cartesian, 'cartesian');
  1500. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z;
  1501. };
  1502. /**
  1503. * Computes the Cartesian's magnitude (length).
  1504. *
  1505. * @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
  1506. * @returns {Number} The magnitude.
  1507. */
  1508. Cartesian3.magnitude = function(cartesian) {
  1509. return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
  1510. };
  1511. var distanceScratch = new Cartesian3();
  1512. /**
  1513. * Computes the distance between two points.
  1514. *
  1515. * @param {Cartesian3} left The first point to compute the distance from.
  1516. * @param {Cartesian3} right The second point to compute the distance to.
  1517. * @returns {Number} The distance between two points.
  1518. *
  1519. * @example
  1520. * // Returns 1.0
  1521. * var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
  1522. */
  1523. Cartesian3.distance = function(left, right) {
  1524. Check.typeOf.object(left, 'left');
  1525. Check.typeOf.object(right, 'right');
  1526. Cartesian3.subtract(left, right, distanceScratch);
  1527. return Cartesian3.magnitude(distanceScratch);
  1528. };
  1529. /**
  1530. * Computes the squared distance between two points. Comparing squared distances
  1531. * using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
  1532. *
  1533. * @param {Cartesian3} left The first point to compute the distance from.
  1534. * @param {Cartesian3} right The second point to compute the distance to.
  1535. * @returns {Number} The distance between two points.
  1536. *
  1537. * @example
  1538. * // Returns 4.0, not 2.0
  1539. * var d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
  1540. */
  1541. Cartesian3.distanceSquared = function(left, right) {
  1542. Check.typeOf.object(left, 'left');
  1543. Check.typeOf.object(right, 'right');
  1544. Cartesian3.subtract(left, right, distanceScratch);
  1545. return Cartesian3.magnitudeSquared(distanceScratch);
  1546. };
  1547. /**
  1548. * Computes the normalized form of the supplied Cartesian.
  1549. *
  1550. * @param {Cartesian3} cartesian The Cartesian to be normalized.
  1551. * @param {Cartesian3} result The object onto which to store the result.
  1552. * @returns {Cartesian3} The modified result parameter.
  1553. */
  1554. Cartesian3.normalize = function(cartesian, result) {
  1555. Check.typeOf.object(cartesian, 'cartesian');
  1556. Check.typeOf.object(result, 'result');
  1557. var magnitude = Cartesian3.magnitude(cartesian);
  1558. result.x = cartesian.x / magnitude;
  1559. result.y = cartesian.y / magnitude;
  1560. result.z = cartesian.z / magnitude;
  1561. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
  1562. throw new DeveloperError('normalized result is not a number');
  1563. }
  1564. return result;
  1565. };
  1566. /**
  1567. * Computes the dot (scalar) product of two Cartesians.
  1568. *
  1569. * @param {Cartesian3} left The first Cartesian.
  1570. * @param {Cartesian3} right The second Cartesian.
  1571. * @returns {Number} The dot product.
  1572. */
  1573. Cartesian3.dot = function(left, right) {
  1574. Check.typeOf.object(left, 'left');
  1575. Check.typeOf.object(right, 'right');
  1576. return left.x * right.x + left.y * right.y + left.z * right.z;
  1577. };
  1578. /**
  1579. * Computes the componentwise product of two Cartesians.
  1580. *
  1581. * @param {Cartesian3} left The first Cartesian.
  1582. * @param {Cartesian3} right The second Cartesian.
  1583. * @param {Cartesian3} result The object onto which to store the result.
  1584. * @returns {Cartesian3} The modified result parameter.
  1585. */
  1586. Cartesian3.multiplyComponents = function(left, right, result) {
  1587. Check.typeOf.object(left, 'left');
  1588. Check.typeOf.object(right, 'right');
  1589. Check.typeOf.object(result, 'result');
  1590. result.x = left.x * right.x;
  1591. result.y = left.y * right.y;
  1592. result.z = left.z * right.z;
  1593. return result;
  1594. };
  1595. /**
  1596. * Computes the componentwise quotient of two Cartesians.
  1597. *
  1598. * @param {Cartesian3} left The first Cartesian.
  1599. * @param {Cartesian3} right The second Cartesian.
  1600. * @param {Cartesian3} result The object onto which to store the result.
  1601. * @returns {Cartesian3} The modified result parameter.
  1602. */
  1603. Cartesian3.divideComponents = function(left, right, result) {
  1604. if (!defined(left)) {
  1605. throw new DeveloperError('left is required');
  1606. }
  1607. if (!defined(right)) {
  1608. throw new DeveloperError('right is required');
  1609. }
  1610. if (!defined(result)) {
  1611. throw new DeveloperError('result is required');
  1612. }
  1613. result.x = left.x / right.x;
  1614. result.y = left.y / right.y;
  1615. result.z = left.z / right.z;
  1616. return result;
  1617. };
  1618. /**
  1619. * Computes the componentwise sum of two Cartesians.
  1620. *
  1621. * @param {Cartesian3} left The first Cartesian.
  1622. * @param {Cartesian3} right The second Cartesian.
  1623. * @param {Cartesian3} result The object onto which to store the result.
  1624. * @returns {Cartesian3} The modified result parameter.
  1625. */
  1626. Cartesian3.add = function(left, right, result) {
  1627. Check.typeOf.object(left, 'left');
  1628. Check.typeOf.object(right, 'right');
  1629. Check.typeOf.object(result, 'result');
  1630. result.x = left.x + right.x;
  1631. result.y = left.y + right.y;
  1632. result.z = left.z + right.z;
  1633. return result;
  1634. };
  1635. /**
  1636. * Computes the componentwise difference of two Cartesians.
  1637. *
  1638. * @param {Cartesian3} left The first Cartesian.
  1639. * @param {Cartesian3} right The second Cartesian.
  1640. * @param {Cartesian3} result The object onto which to store the result.
  1641. * @returns {Cartesian3} The modified result parameter.
  1642. */
  1643. Cartesian3.subtract = function(left, right, result) {
  1644. Check.typeOf.object(left, 'left');
  1645. Check.typeOf.object(right, 'right');
  1646. Check.typeOf.object(result, 'result');
  1647. result.x = left.x - right.x;
  1648. result.y = left.y - right.y;
  1649. result.z = left.z - right.z;
  1650. return result;
  1651. };
  1652. /**
  1653. * Multiplies the provided Cartesian componentwise by the provided scalar.
  1654. *
  1655. * @param {Cartesian3} cartesian The Cartesian to be scaled.
  1656. * @param {Number} scalar The scalar to multiply with.
  1657. * @param {Cartesian3} result The object onto which to store the result.
  1658. * @returns {Cartesian3} The modified result parameter.
  1659. */
  1660. Cartesian3.multiplyByScalar = function(cartesian, scalar, result) {
  1661. Check.typeOf.object(cartesian, 'cartesian');
  1662. Check.typeOf.number(scalar, 'scalar');
  1663. Check.typeOf.object(result, 'result');
  1664. result.x = cartesian.x * scalar;
  1665. result.y = cartesian.y * scalar;
  1666. result.z = cartesian.z * scalar;
  1667. return result;
  1668. };
  1669. /**
  1670. * Divides the provided Cartesian componentwise by the provided scalar.
  1671. *
  1672. * @param {Cartesian3} cartesian The Cartesian to be divided.
  1673. * @param {Number} scalar The scalar to divide by.
  1674. * @param {Cartesian3} result The object onto which to store the result.
  1675. * @returns {Cartesian3} The modified result parameter.
  1676. */
  1677. Cartesian3.divideByScalar = function(cartesian, scalar, result) {
  1678. Check.typeOf.object(cartesian, 'cartesian');
  1679. Check.typeOf.number(scalar, 'scalar');
  1680. Check.typeOf.object(result, 'result');
  1681. result.x = cartesian.x / scalar;
  1682. result.y = cartesian.y / scalar;
  1683. result.z = cartesian.z / scalar;
  1684. return result;
  1685. };
  1686. /**
  1687. * Negates the provided Cartesian.
  1688. *
  1689. * @param {Cartesian3} cartesian The Cartesian to be negated.
  1690. * @param {Cartesian3} result The object onto which to store the result.
  1691. * @returns {Cartesian3} The modified result parameter.
  1692. */
  1693. Cartesian3.negate = function(cartesian, result) {
  1694. Check.typeOf.object(cartesian, 'cartesian');
  1695. Check.typeOf.object(result, 'result');
  1696. result.x = -cartesian.x;
  1697. result.y = -cartesian.y;
  1698. result.z = -cartesian.z;
  1699. return result;
  1700. };
  1701. /**
  1702. * Computes the absolute value of the provided Cartesian.
  1703. *
  1704. * @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
  1705. * @param {Cartesian3} result The object onto which to store the result.
  1706. * @returns {Cartesian3} The modified result parameter.
  1707. */
  1708. Cartesian3.abs = function(cartesian, result) {
  1709. Check.typeOf.object(cartesian, 'cartesian');
  1710. Check.typeOf.object(result, 'result');
  1711. result.x = Math.abs(cartesian.x);
  1712. result.y = Math.abs(cartesian.y);
  1713. result.z = Math.abs(cartesian.z);
  1714. return result;
  1715. };
  1716. var lerpScratch = new Cartesian3();
  1717. /**
  1718. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  1719. *
  1720. * @param {Cartesian3} start The value corresponding to t at 0.0.
  1721. * @param {Cartesian3} end The value corresponding to t at 1.0.
  1722. * @param {Number} t The point along t at which to interpolate.
  1723. * @param {Cartesian3} result The object onto which to store the result.
  1724. * @returns {Cartesian3} The modified result parameter.
  1725. */
  1726. Cartesian3.lerp = function(start, end, t, result) {
  1727. Check.typeOf.object(start, 'start');
  1728. Check.typeOf.object(end, 'end');
  1729. Check.typeOf.number(t, 't');
  1730. Check.typeOf.object(result, 'result');
  1731. Cartesian3.multiplyByScalar(end, t, lerpScratch);
  1732. result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
  1733. return Cartesian3.add(lerpScratch, result, result);
  1734. };
  1735. var angleBetweenScratch = new Cartesian3();
  1736. var angleBetweenScratch2 = new Cartesian3();
  1737. /**
  1738. * Returns the angle, in radians, between the provided Cartesians.
  1739. *
  1740. * @param {Cartesian3} left The first Cartesian.
  1741. * @param {Cartesian3} right The second Cartesian.
  1742. * @returns {Number} The angle between the Cartesians.
  1743. */
  1744. Cartesian3.angleBetween = function(left, right) {
  1745. Check.typeOf.object(left, 'left');
  1746. Check.typeOf.object(right, 'right');
  1747. Cartesian3.normalize(left, angleBetweenScratch);
  1748. Cartesian3.normalize(right, angleBetweenScratch2);
  1749. var cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
  1750. var sine = Cartesian3.magnitude(Cartesian3.cross(angleBetweenScratch, angleBetweenScratch2, angleBetweenScratch));
  1751. return Math.atan2(sine, cosine);
  1752. };
  1753. var mostOrthogonalAxisScratch = new Cartesian3();
  1754. /**
  1755. * Returns the axis that is most orthogonal to the provided Cartesian.
  1756. *
  1757. * @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
  1758. * @param {Cartesian3} result The object onto which to store the result.
  1759. * @returns {Cartesian3} The most orthogonal axis.
  1760. */
  1761. Cartesian3.mostOrthogonalAxis = function(cartesian, result) {
  1762. Check.typeOf.object(cartesian, 'cartesian');
  1763. Check.typeOf.object(result, 'result');
  1764. var f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
  1765. Cartesian3.abs(f, f);
  1766. if (f.x <= f.y) {
  1767. if (f.x <= f.z) {
  1768. result = Cartesian3.clone(Cartesian3.UNIT_X, result);
  1769. } else {
  1770. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  1771. }
  1772. } else {
  1773. if (f.y <= f.z) {
  1774. result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
  1775. } else {
  1776. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  1777. }
  1778. }
  1779. return result;
  1780. };
  1781. /**
  1782. * Compares the provided Cartesians componentwise and returns
  1783. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1784. *
  1785. * @param {Cartesian3} [left] The first Cartesian.
  1786. * @param {Cartesian3} [right] The second Cartesian.
  1787. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1788. */
  1789. Cartesian3.equals = function(left, right) {
  1790. return (left === right) ||
  1791. ((defined(left)) &&
  1792. (defined(right)) &&
  1793. (left.x === right.x) &&
  1794. (left.y === right.y) &&
  1795. (left.z === right.z));
  1796. };
  1797. /**
  1798. * @private
  1799. */
  1800. Cartesian3.equalsArray = function(cartesian, array, offset) {
  1801. return cartesian.x === array[offset] &&
  1802. cartesian.y === array[offset + 1] &&
  1803. cartesian.z === array[offset + 2];
  1804. };
  1805. /**
  1806. * Compares the provided Cartesians componentwise and returns
  1807. * <code>true</code> if they pass an absolute or relative tolerance test,
  1808. * <code>false</code> otherwise.
  1809. *
  1810. * @param {Cartesian3} [left] The first Cartesian.
  1811. * @param {Cartesian3} [right] The second Cartesian.
  1812. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  1813. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  1814. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  1815. */
  1816. Cartesian3.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  1817. return (left === right) ||
  1818. (defined(left) &&
  1819. defined(right) &&
  1820. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  1821. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  1822. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon));
  1823. };
  1824. /**
  1825. * Computes the cross (outer) product of two Cartesians.
  1826. *
  1827. * @param {Cartesian3} left The first Cartesian.
  1828. * @param {Cartesian3} right The second Cartesian.
  1829. * @param {Cartesian3} result The object onto which to store the result.
  1830. * @returns {Cartesian3} The cross product.
  1831. */
  1832. Cartesian3.cross = function(left, right, result) {
  1833. Check.typeOf.object(left, 'left');
  1834. Check.typeOf.object(right, 'right');
  1835. Check.typeOf.object(result, 'result');
  1836. var leftX = left.x;
  1837. var leftY = left.y;
  1838. var leftZ = left.z;
  1839. var rightX = right.x;
  1840. var rightY = right.y;
  1841. var rightZ = right.z;
  1842. var x = leftY * rightZ - leftZ * rightY;
  1843. var y = leftZ * rightX - leftX * rightZ;
  1844. var z = leftX * rightY - leftY * rightX;
  1845. result.x = x;
  1846. result.y = y;
  1847. result.z = z;
  1848. return result;
  1849. };
  1850. /**
  1851. * Returns a Cartesian3 position from longitude and latitude values given in degrees.
  1852. *
  1853. * @param {Number} longitude The longitude, in degrees
  1854. * @param {Number} latitude The latitude, in degrees
  1855. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  1856. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1857. * @param {Cartesian3} [result] The object onto which to store the result.
  1858. * @returns {Cartesian3} The position
  1859. *
  1860. * @example
  1861. * var position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
  1862. */
  1863. Cartesian3.fromDegrees = function(longitude, latitude, height, ellipsoid, result) {
  1864. Check.typeOf.number(longitude, 'longitude');
  1865. Check.typeOf.number(latitude, 'latitude');
  1866. longitude = CesiumMath.toRadians(longitude);
  1867. latitude = CesiumMath.toRadians(latitude);
  1868. return Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result);
  1869. };
  1870. var scratchN = new Cartesian3();
  1871. var scratchK = new Cartesian3();
  1872. var wgs84RadiiSquared = new Cartesian3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
  1873. /**
  1874. * Returns a Cartesian3 position from longitude and latitude values given in radians.
  1875. *
  1876. * @param {Number} longitude The longitude, in radians
  1877. * @param {Number} latitude The latitude, in radians
  1878. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  1879. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1880. * @param {Cartesian3} [result] The object onto which to store the result.
  1881. * @returns {Cartesian3} The position
  1882. *
  1883. * @example
  1884. * var position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
  1885. */
  1886. Cartesian3.fromRadians = function(longitude, latitude, height, ellipsoid, result) {
  1887. Check.typeOf.number(longitude, 'longitude');
  1888. Check.typeOf.number(latitude, 'latitude');
  1889. height = defaultValue(height, 0.0);
  1890. var radiiSquared = defined(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared;
  1891. var cosLatitude = Math.cos(latitude);
  1892. scratchN.x = cosLatitude * Math.cos(longitude);
  1893. scratchN.y = cosLatitude * Math.sin(longitude);
  1894. scratchN.z = Math.sin(latitude);
  1895. scratchN = Cartesian3.normalize(scratchN, scratchN);
  1896. Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
  1897. var gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
  1898. scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
  1899. scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);
  1900. if (!defined(result)) {
  1901. result = new Cartesian3();
  1902. }
  1903. return Cartesian3.add(scratchK, scratchN, result);
  1904. };
  1905. /**
  1906. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
  1907. *
  1908. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  1909. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  1910. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1911. * @returns {Cartesian3[]} The array of positions.
  1912. *
  1913. * @example
  1914. * var positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
  1915. */
  1916. Cartesian3.fromDegreesArray = function(coordinates, ellipsoid, result) {
  1917. Check.defined(coordinates, 'coordinates');
  1918. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  1919. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  1920. }
  1921. var length = coordinates.length;
  1922. if (!defined(result)) {
  1923. result = new Array(length / 2);
  1924. } else {
  1925. result.length = length / 2;
  1926. }
  1927. for (var i = 0; i < length; i += 2) {
  1928. var longitude = coordinates[i];
  1929. var latitude = coordinates[i + 1];
  1930. var index = i / 2;
  1931. result[index] = Cartesian3.fromDegrees(longitude, latitude, 0, ellipsoid, result[index]);
  1932. }
  1933. return result;
  1934. };
  1935. /**
  1936. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
  1937. *
  1938. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  1939. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  1940. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1941. * @returns {Cartesian3[]} The array of positions.
  1942. *
  1943. * @example
  1944. * var positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
  1945. */
  1946. Cartesian3.fromRadiansArray = function(coordinates, ellipsoid, result) {
  1947. Check.defined(coordinates, 'coordinates');
  1948. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  1949. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  1950. }
  1951. var length = coordinates.length;
  1952. if (!defined(result)) {
  1953. result = new Array(length / 2);
  1954. } else {
  1955. result.length = length / 2;
  1956. }
  1957. for (var i = 0; i < length; i += 2) {
  1958. var longitude = coordinates[i];
  1959. var latitude = coordinates[i + 1];
  1960. var index = i / 2;
  1961. result[index] = Cartesian3.fromRadians(longitude, latitude, 0, ellipsoid, result[index]);
  1962. }
  1963. return result;
  1964. };
  1965. /**
  1966. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
  1967. *
  1968. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  1969. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1970. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1971. * @returns {Cartesian3[]} The array of positions.
  1972. *
  1973. * @example
  1974. * var positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
  1975. */
  1976. Cartesian3.fromDegreesArrayHeights = function(coordinates, ellipsoid, result) {
  1977. Check.defined(coordinates, 'coordinates');
  1978. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  1979. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  1980. }
  1981. var length = coordinates.length;
  1982. if (!defined(result)) {
  1983. result = new Array(length / 3);
  1984. } else {
  1985. result.length = length / 3;
  1986. }
  1987. for (var i = 0; i < length; i += 3) {
  1988. var longitude = coordinates[i];
  1989. var latitude = coordinates[i + 1];
  1990. var height = coordinates[i + 2];
  1991. var index = i / 3;
  1992. result[index] = Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result[index]);
  1993. }
  1994. return result;
  1995. };
  1996. /**
  1997. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
  1998. *
  1999. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  2000. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2001. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2002. * @returns {Cartesian3[]} The array of positions.
  2003. *
  2004. * @example
  2005. * var positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
  2006. */
  2007. Cartesian3.fromRadiansArrayHeights = function(coordinates, ellipsoid, result) {
  2008. Check.defined(coordinates, 'coordinates');
  2009. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  2010. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  2011. }
  2012. var length = coordinates.length;
  2013. if (!defined(result)) {
  2014. result = new Array(length / 3);
  2015. } else {
  2016. result.length = length / 3;
  2017. }
  2018. for (var i = 0; i < length; i += 3) {
  2019. var longitude = coordinates[i];
  2020. var latitude = coordinates[i + 1];
  2021. var height = coordinates[i + 2];
  2022. var index = i / 3;
  2023. result[index] = Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result[index]);
  2024. }
  2025. return result;
  2026. };
  2027. /**
  2028. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
  2029. *
  2030. * @type {Cartesian3}
  2031. * @constant
  2032. */
  2033. Cartesian3.ZERO = freezeObject(new Cartesian3(0.0, 0.0, 0.0));
  2034. /**
  2035. * An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
  2036. *
  2037. * @type {Cartesian3}
  2038. * @constant
  2039. */
  2040. Cartesian3.UNIT_X = freezeObject(new Cartesian3(1.0, 0.0, 0.0));
  2041. /**
  2042. * An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
  2043. *
  2044. * @type {Cartesian3}
  2045. * @constant
  2046. */
  2047. Cartesian3.UNIT_Y = freezeObject(new Cartesian3(0.0, 1.0, 0.0));
  2048. /**
  2049. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
  2050. *
  2051. * @type {Cartesian3}
  2052. * @constant
  2053. */
  2054. Cartesian3.UNIT_Z = freezeObject(new Cartesian3(0.0, 0.0, 1.0));
  2055. /**
  2056. * Duplicates this Cartesian3 instance.
  2057. *
  2058. * @param {Cartesian3} [result] The object onto which to store the result.
  2059. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2060. */
  2061. Cartesian3.prototype.clone = function(result) {
  2062. return Cartesian3.clone(this, result);
  2063. };
  2064. /**
  2065. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2066. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2067. *
  2068. * @param {Cartesian3} [right] The right hand side Cartesian.
  2069. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  2070. */
  2071. Cartesian3.prototype.equals = function(right) {
  2072. return Cartesian3.equals(this, right);
  2073. };
  2074. /**
  2075. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2076. * <code>true</code> if they pass an absolute or relative tolerance test,
  2077. * <code>false</code> otherwise.
  2078. *
  2079. * @param {Cartesian3} [right] The right hand side Cartesian.
  2080. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2081. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2082. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  2083. */
  2084. Cartesian3.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  2085. return Cartesian3.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  2086. };
  2087. /**
  2088. * Creates a string representing this Cartesian in the format '(x, y, z)'.
  2089. *
  2090. * @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
  2091. */
  2092. Cartesian3.prototype.toString = function() {
  2093. return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
  2094. };
  2095. return Cartesian3;
  2096. });
  2097. /*global define*/
  2098. define('Core/scaleToGeodeticSurface',[
  2099. './Cartesian3',
  2100. './defined',
  2101. './DeveloperError',
  2102. './Math'
  2103. ], function(
  2104. Cartesian3,
  2105. defined,
  2106. DeveloperError,
  2107. CesiumMath) {
  2108. 'use strict';
  2109. var scaleToGeodeticSurfaceIntersection = new Cartesian3();
  2110. var scaleToGeodeticSurfaceGradient = new Cartesian3();
  2111. /**
  2112. * Scales the provided Cartesian position along the geodetic surface normal
  2113. * so that it is on the surface of this ellipsoid. If the position is
  2114. * at the center of the ellipsoid, this function returns undefined.
  2115. *
  2116. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2117. * @param {Cartesian3} oneOverRadii One over radii of the ellipsoid.
  2118. * @param {Cartesian3} oneOverRadiiSquared One over radii squared of the ellipsoid.
  2119. * @param {Number} centerToleranceSquared Tolerance for closeness to the center.
  2120. * @param {Cartesian3} [result] The object onto which to store the result.
  2121. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  2122. *
  2123. * @exports scaleToGeodeticSurface
  2124. *
  2125. * @private
  2126. */
  2127. function scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) {
  2128. if (!defined(cartesian)) {
  2129. throw new DeveloperError('cartesian is required.');
  2130. }
  2131. if (!defined(oneOverRadii)) {
  2132. throw new DeveloperError('oneOverRadii is required.');
  2133. }
  2134. if (!defined(oneOverRadiiSquared)) {
  2135. throw new DeveloperError('oneOverRadiiSquared is required.');
  2136. }
  2137. if (!defined(centerToleranceSquared)) {
  2138. throw new DeveloperError('centerToleranceSquared is required.');
  2139. }
  2140. var positionX = cartesian.x;
  2141. var positionY = cartesian.y;
  2142. var positionZ = cartesian.z;
  2143. var oneOverRadiiX = oneOverRadii.x;
  2144. var oneOverRadiiY = oneOverRadii.y;
  2145. var oneOverRadiiZ = oneOverRadii.z;
  2146. var x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  2147. var y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  2148. var z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  2149. // Compute the squared ellipsoid norm.
  2150. var squaredNorm = x2 + y2 + z2;
  2151. var ratio = Math.sqrt(1.0 / squaredNorm);
  2152. // As an initial approximation, assume that the radial intersection is the projection point.
  2153. var intersection = Cartesian3.multiplyByScalar(cartesian, ratio, scaleToGeodeticSurfaceIntersection);
  2154. // If the position is near the center, the iteration will not converge.
  2155. if (squaredNorm < centerToleranceSquared) {
  2156. return !isFinite(ratio) ? undefined : Cartesian3.clone(intersection, result);
  2157. }
  2158. var oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  2159. var oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  2160. var oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  2161. // Use the gradient at the intersection point in place of the true unit normal.
  2162. // The difference in magnitude will be absorbed in the multiplier.
  2163. var gradient = scaleToGeodeticSurfaceGradient;
  2164. gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
  2165. gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
  2166. gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;
  2167. // Compute the initial guess at the normal vector multiplier, lambda.
  2168. var lambda = (1.0 - ratio) * Cartesian3.magnitude(cartesian) / (0.5 * Cartesian3.magnitude(gradient));
  2169. var correction = 0.0;
  2170. var func;
  2171. var denominator;
  2172. var xMultiplier;
  2173. var yMultiplier;
  2174. var zMultiplier;
  2175. var xMultiplier2;
  2176. var yMultiplier2;
  2177. var zMultiplier2;
  2178. var xMultiplier3;
  2179. var yMultiplier3;
  2180. var zMultiplier3;
  2181. do {
  2182. lambda -= correction;
  2183. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  2184. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  2185. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  2186. xMultiplier2 = xMultiplier * xMultiplier;
  2187. yMultiplier2 = yMultiplier * yMultiplier;
  2188. zMultiplier2 = zMultiplier * zMultiplier;
  2189. xMultiplier3 = xMultiplier2 * xMultiplier;
  2190. yMultiplier3 = yMultiplier2 * yMultiplier;
  2191. zMultiplier3 = zMultiplier2 * zMultiplier;
  2192. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  2193. // "denominator" here refers to the use of this expression in the velocity and acceleration
  2194. // computations in the sections to follow.
  2195. denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  2196. var derivative = -2.0 * denominator;
  2197. correction = func / derivative;
  2198. } while (Math.abs(func) > CesiumMath.EPSILON12);
  2199. if (!defined(result)) {
  2200. return new Cartesian3(positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier);
  2201. }
  2202. result.x = positionX * xMultiplier;
  2203. result.y = positionY * yMultiplier;
  2204. result.z = positionZ * zMultiplier;
  2205. return result;
  2206. }
  2207. return scaleToGeodeticSurface;
  2208. });
  2209. /*global define*/
  2210. define('Core/Cartographic',[
  2211. './Cartesian3',
  2212. './defaultValue',
  2213. './defined',
  2214. './DeveloperError',
  2215. './freezeObject',
  2216. './Math',
  2217. './scaleToGeodeticSurface'
  2218. ], function(
  2219. Cartesian3,
  2220. defaultValue,
  2221. defined,
  2222. DeveloperError,
  2223. freezeObject,
  2224. CesiumMath,
  2225. scaleToGeodeticSurface) {
  2226. 'use strict';
  2227. /**
  2228. * A position defined by longitude, latitude, and height.
  2229. * @alias Cartographic
  2230. * @constructor
  2231. *
  2232. * @param {Number} [longitude=0.0] The longitude, in radians.
  2233. * @param {Number} [latitude=0.0] The latitude, in radians.
  2234. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2235. *
  2236. * @see Ellipsoid
  2237. */
  2238. function Cartographic(longitude, latitude, height) {
  2239. /**
  2240. * The longitude, in radians.
  2241. * @type {Number}
  2242. * @default 0.0
  2243. */
  2244. this.longitude = defaultValue(longitude, 0.0);
  2245. /**
  2246. * The latitude, in radians.
  2247. * @type {Number}
  2248. * @default 0.0
  2249. */
  2250. this.latitude = defaultValue(latitude, 0.0);
  2251. /**
  2252. * The height, in meters, above the ellipsoid.
  2253. * @type {Number}
  2254. * @default 0.0
  2255. */
  2256. this.height = defaultValue(height, 0.0);
  2257. }
  2258. /**
  2259. * Creates a new Cartographic instance from longitude and latitude
  2260. * specified in radians.
  2261. *
  2262. * @param {Number} longitude The longitude, in radians.
  2263. * @param {Number} latitude The latitude, in radians.
  2264. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2265. * @param {Cartographic} [result] The object onto which to store the result.
  2266. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2267. */
  2268. Cartographic.fromRadians = function(longitude, latitude, height, result) {
  2269. if (!defined(longitude)) {
  2270. throw new DeveloperError('longitude is required.');
  2271. }
  2272. if (!defined(latitude)) {
  2273. throw new DeveloperError('latitude is required.');
  2274. }
  2275. height = defaultValue(height, 0.0);
  2276. if (!defined(result)) {
  2277. return new Cartographic(longitude, latitude, height);
  2278. }
  2279. result.longitude = longitude;
  2280. result.latitude = latitude;
  2281. result.height = height;
  2282. return result;
  2283. };
  2284. /**
  2285. * Creates a new Cartographic instance from longitude and latitude
  2286. * specified in degrees. The values in the resulting object will
  2287. * be in radians.
  2288. *
  2289. * @param {Number} longitude The longitude, in degrees.
  2290. * @param {Number} latitude The latitude, in degrees.
  2291. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2292. * @param {Cartographic} [result] The object onto which to store the result.
  2293. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2294. */
  2295. Cartographic.fromDegrees = function(longitude, latitude, height, result) {
  2296. if (!defined(longitude)) {
  2297. throw new DeveloperError('longitude is required.');
  2298. }
  2299. if (!defined(latitude)) {
  2300. throw new DeveloperError('latitude is required.');
  2301. }
  2302. longitude = CesiumMath.toRadians(longitude);
  2303. latitude = CesiumMath.toRadians(latitude);
  2304. return Cartographic.fromRadians(longitude, latitude, height, result);
  2305. };
  2306. var cartesianToCartographicN = new Cartesian3();
  2307. var cartesianToCartographicP = new Cartesian3();
  2308. var cartesianToCartographicH = new Cartesian3();
  2309. var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
  2310. var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
  2311. var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;
  2312. /**
  2313. * Creates a new Cartographic instance from a Cartesian position. The values in the
  2314. * resulting object will be in radians.
  2315. *
  2316. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  2317. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2318. * @param {Cartographic} [result] The object onto which to store the result.
  2319. * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
  2320. */
  2321. Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
  2322. var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
  2323. var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
  2324. var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;
  2325. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  2326. var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);
  2327. if (!defined(p)) {
  2328. return undefined;
  2329. }
  2330. var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
  2331. n = Cartesian3.normalize(n, n);
  2332. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  2333. var longitude = Math.atan2(n.y, n.x);
  2334. var latitude = Math.asin(n.z);
  2335. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  2336. if (!defined(result)) {
  2337. return new Cartographic(longitude, latitude, height);
  2338. }
  2339. result.longitude = longitude;
  2340. result.latitude = latitude;
  2341. result.height = height;
  2342. return result;
  2343. };
  2344. /**
  2345. * Duplicates a Cartographic instance.
  2346. *
  2347. * @param {Cartographic} cartographic The cartographic to duplicate.
  2348. * @param {Cartographic} [result] The object onto which to store the result.
  2349. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
  2350. */
  2351. Cartographic.clone = function(cartographic, result) {
  2352. if (!defined(cartographic)) {
  2353. return undefined;
  2354. }
  2355. if (!defined(result)) {
  2356. return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
  2357. }
  2358. result.longitude = cartographic.longitude;
  2359. result.latitude = cartographic.latitude;
  2360. result.height = cartographic.height;
  2361. return result;
  2362. };
  2363. /**
  2364. * Compares the provided cartographics componentwise and returns
  2365. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2366. *
  2367. * @param {Cartographic} [left] The first cartographic.
  2368. * @param {Cartographic} [right] The second cartographic.
  2369. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2370. */
  2371. Cartographic.equals = function(left, right) {
  2372. return (left === right) ||
  2373. ((defined(left)) &&
  2374. (defined(right)) &&
  2375. (left.longitude === right.longitude) &&
  2376. (left.latitude === right.latitude) &&
  2377. (left.height === right.height));
  2378. };
  2379. /**
  2380. * Compares the provided cartographics componentwise and returns
  2381. * <code>true</code> if they are within the provided epsilon,
  2382. * <code>false</code> otherwise.
  2383. *
  2384. * @param {Cartographic} [left] The first cartographic.
  2385. * @param {Cartographic} [right] The second cartographic.
  2386. * @param {Number} epsilon The epsilon to use for equality testing.
  2387. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2388. */
  2389. Cartographic.equalsEpsilon = function(left, right, epsilon) {
  2390. if (typeof epsilon !== 'number') {
  2391. throw new DeveloperError('epsilon is required and must be a number.');
  2392. }
  2393. return (left === right) ||
  2394. ((defined(left)) &&
  2395. (defined(right)) &&
  2396. (Math.abs(left.longitude - right.longitude) <= epsilon) &&
  2397. (Math.abs(left.latitude - right.latitude) <= epsilon) &&
  2398. (Math.abs(left.height - right.height) <= epsilon));
  2399. };
  2400. /**
  2401. * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
  2402. *
  2403. * @type {Cartographic}
  2404. * @constant
  2405. */
  2406. Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));
  2407. /**
  2408. * Duplicates this instance.
  2409. *
  2410. * @param {Cartographic} [result] The object onto which to store the result.
  2411. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2412. */
  2413. Cartographic.prototype.clone = function(result) {
  2414. return Cartographic.clone(this, result);
  2415. };
  2416. /**
  2417. * Compares the provided against this cartographic componentwise and returns
  2418. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2419. *
  2420. * @param {Cartographic} [right] The second cartographic.
  2421. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2422. */
  2423. Cartographic.prototype.equals = function(right) {
  2424. return Cartographic.equals(this, right);
  2425. };
  2426. /**
  2427. * Compares the provided against this cartographic componentwise and returns
  2428. * <code>true</code> if they are within the provided epsilon,
  2429. * <code>false</code> otherwise.
  2430. *
  2431. * @param {Cartographic} [right] The second cartographic.
  2432. * @param {Number} epsilon The epsilon to use for equality testing.
  2433. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2434. */
  2435. Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
  2436. return Cartographic.equalsEpsilon(this, right, epsilon);
  2437. };
  2438. /**
  2439. * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
  2440. *
  2441. * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
  2442. */
  2443. Cartographic.prototype.toString = function() {
  2444. return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
  2445. };
  2446. return Cartographic;
  2447. });
  2448. /*global define*/
  2449. define('Core/defineProperties',[
  2450. './defined'
  2451. ], function(
  2452. defined) {
  2453. 'use strict';
  2454. var definePropertyWorks = (function() {
  2455. try {
  2456. return 'x' in Object.defineProperty({}, 'x', {});
  2457. } catch (e) {
  2458. return false;
  2459. }
  2460. })();
  2461. /**
  2462. * Defines properties on an object, using Object.defineProperties if available,
  2463. * otherwise returns the object unchanged. This function should be used in
  2464. * setup code to prevent errors from completely halting JavaScript execution
  2465. * in legacy browsers.
  2466. *
  2467. * @private
  2468. *
  2469. * @exports defineProperties
  2470. */
  2471. var defineProperties = Object.defineProperties;
  2472. if (!definePropertyWorks || !defined(defineProperties)) {
  2473. defineProperties = function(o) {
  2474. return o;
  2475. };
  2476. }
  2477. return defineProperties;
  2478. });
  2479. /*global define*/
  2480. define('Core/Ellipsoid',[
  2481. './Cartesian3',
  2482. './Cartographic',
  2483. './defaultValue',
  2484. './defined',
  2485. './defineProperties',
  2486. './DeveloperError',
  2487. './freezeObject',
  2488. './Math',
  2489. './scaleToGeodeticSurface'
  2490. ], function(
  2491. Cartesian3,
  2492. Cartographic,
  2493. defaultValue,
  2494. defined,
  2495. defineProperties,
  2496. DeveloperError,
  2497. freezeObject,
  2498. CesiumMath,
  2499. scaleToGeodeticSurface) {
  2500. 'use strict';
  2501. function initialize(ellipsoid, x, y, z) {
  2502. x = defaultValue(x, 0.0);
  2503. y = defaultValue(y, 0.0);
  2504. z = defaultValue(z, 0.0);
  2505. if (x < 0.0 || y < 0.0 || z < 0.0) {
  2506. throw new DeveloperError('All radii components must be greater than or equal to zero.');
  2507. }
  2508. ellipsoid._radii = new Cartesian3(x, y, z);
  2509. ellipsoid._radiiSquared = new Cartesian3(x * x,
  2510. y * y,
  2511. z * z);
  2512. ellipsoid._radiiToTheFourth = new Cartesian3(x * x * x * x,
  2513. y * y * y * y,
  2514. z * z * z * z);
  2515. ellipsoid._oneOverRadii = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / x,
  2516. y === 0.0 ? 0.0 : 1.0 / y,
  2517. z === 0.0 ? 0.0 : 1.0 / z);
  2518. ellipsoid._oneOverRadiiSquared = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / (x * x),
  2519. y === 0.0 ? 0.0 : 1.0 / (y * y),
  2520. z === 0.0 ? 0.0 : 1.0 / (z * z));
  2521. ellipsoid._minimumRadius = Math.min(x, y, z);
  2522. ellipsoid._maximumRadius = Math.max(x, y, z);
  2523. ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;
  2524. if (ellipsoid._radiiSquared.z !== 0) {
  2525. ellipsoid._sqauredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
  2526. }
  2527. }
  2528. /**
  2529. * A quadratic surface defined in Cartesian coordinates by the equation
  2530. * <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>. Primarily used
  2531. * by Cesium to represent the shape of planetary bodies.
  2532. *
  2533. * Rather than constructing this object directly, one of the provided
  2534. * constants is normally used.
  2535. * @alias Ellipsoid
  2536. * @constructor
  2537. *
  2538. * @param {Number} [x=0] The radius in the x direction.
  2539. * @param {Number} [y=0] The radius in the y direction.
  2540. * @param {Number} [z=0] The radius in the z direction.
  2541. *
  2542. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  2543. *
  2544. * @see Ellipsoid.fromCartesian3
  2545. * @see Ellipsoid.WGS84
  2546. * @see Ellipsoid.UNIT_SPHERE
  2547. */
  2548. function Ellipsoid(x, y, z) {
  2549. this._radii = undefined;
  2550. this._radiiSquared = undefined;
  2551. this._radiiToTheFourth = undefined;
  2552. this._oneOverRadii = undefined;
  2553. this._oneOverRadiiSquared = undefined;
  2554. this._minimumRadius = undefined;
  2555. this._maximumRadius = undefined;
  2556. this._centerToleranceSquared = undefined;
  2557. this._sqauredXOverSquaredZ = undefined;
  2558. initialize(this, x, y, z);
  2559. }
  2560. defineProperties(Ellipsoid.prototype, {
  2561. /**
  2562. * Gets the radii of the ellipsoid.
  2563. * @memberof Ellipsoid.prototype
  2564. * @type {Cartesian3}
  2565. * @readonly
  2566. */
  2567. radii : {
  2568. get: function() {
  2569. return this._radii;
  2570. }
  2571. },
  2572. /**
  2573. * Gets the squared radii of the ellipsoid.
  2574. * @memberof Ellipsoid.prototype
  2575. * @type {Cartesian3}
  2576. * @readonly
  2577. */
  2578. radiiSquared : {
  2579. get : function() {
  2580. return this._radiiSquared;
  2581. }
  2582. },
  2583. /**
  2584. * Gets the radii of the ellipsoid raise to the fourth power.
  2585. * @memberof Ellipsoid.prototype
  2586. * @type {Cartesian3}
  2587. * @readonly
  2588. */
  2589. radiiToTheFourth : {
  2590. get : function() {
  2591. return this._radiiToTheFourth;
  2592. }
  2593. },
  2594. /**
  2595. * Gets one over the radii of the ellipsoid.
  2596. * @memberof Ellipsoid.prototype
  2597. * @type {Cartesian3}
  2598. * @readonly
  2599. */
  2600. oneOverRadii : {
  2601. get : function() {
  2602. return this._oneOverRadii;
  2603. }
  2604. },
  2605. /**
  2606. * Gets one over the squared radii of the ellipsoid.
  2607. * @memberof Ellipsoid.prototype
  2608. * @type {Cartesian3}
  2609. * @readonly
  2610. */
  2611. oneOverRadiiSquared : {
  2612. get : function() {
  2613. return this._oneOverRadiiSquared;
  2614. }
  2615. },
  2616. /**
  2617. * Gets the minimum radius of the ellipsoid.
  2618. * @memberof Ellipsoid.prototype
  2619. * @type {Number}
  2620. * @readonly
  2621. */
  2622. minimumRadius : {
  2623. get : function() {
  2624. return this._minimumRadius;
  2625. }
  2626. },
  2627. /**
  2628. * Gets the maximum radius of the ellipsoid.
  2629. * @memberof Ellipsoid.prototype
  2630. * @type {Number}
  2631. * @readonly
  2632. */
  2633. maximumRadius : {
  2634. get : function() {
  2635. return this._maximumRadius;
  2636. }
  2637. }
  2638. });
  2639. /**
  2640. * Duplicates an Ellipsoid instance.
  2641. *
  2642. * @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
  2643. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  2644. * instance should be created.
  2645. * @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
  2646. */
  2647. Ellipsoid.clone = function(ellipsoid, result) {
  2648. if (!defined(ellipsoid)) {
  2649. return undefined;
  2650. }
  2651. var radii = ellipsoid._radii;
  2652. if (!defined(result)) {
  2653. return new Ellipsoid(radii.x, radii.y, radii.z);
  2654. }
  2655. Cartesian3.clone(radii, result._radii);
  2656. Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
  2657. Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
  2658. Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
  2659. Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
  2660. result._minimumRadius = ellipsoid._minimumRadius;
  2661. result._maximumRadius = ellipsoid._maximumRadius;
  2662. result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
  2663. return result;
  2664. };
  2665. /**
  2666. * Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
  2667. *
  2668. * @param {Cartesian3} [radii=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
  2669. * @returns {Ellipsoid} A new Ellipsoid instance.
  2670. *
  2671. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  2672. *
  2673. * @see Ellipsoid.WGS84
  2674. * @see Ellipsoid.UNIT_SPHERE
  2675. */
  2676. Ellipsoid.fromCartesian3 = function(cartesian, result) {
  2677. if (!defined(result)) {
  2678. result = new Ellipsoid();
  2679. }
  2680. if (!defined(cartesian)) {
  2681. return result;
  2682. }
  2683. initialize(result, cartesian.x, cartesian.y, cartesian.z);
  2684. return result;
  2685. };
  2686. /**
  2687. * An Ellipsoid instance initialized to the WGS84 standard.
  2688. *
  2689. * @type {Ellipsoid}
  2690. * @constant
  2691. */
  2692. Ellipsoid.WGS84 = freezeObject(new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793));
  2693. /**
  2694. * An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
  2695. *
  2696. * @type {Ellipsoid}
  2697. * @constant
  2698. */
  2699. Ellipsoid.UNIT_SPHERE = freezeObject(new Ellipsoid(1.0, 1.0, 1.0));
  2700. /**
  2701. * An Ellipsoid instance initialized to a sphere with the lunar radius.
  2702. *
  2703. * @type {Ellipsoid}
  2704. * @constant
  2705. */
  2706. Ellipsoid.MOON = freezeObject(new Ellipsoid(CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS));
  2707. /**
  2708. * Duplicates an Ellipsoid instance.
  2709. *
  2710. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  2711. * instance should be created.
  2712. * @returns {Ellipsoid} The cloned Ellipsoid.
  2713. */
  2714. Ellipsoid.prototype.clone = function(result) {
  2715. return Ellipsoid.clone(this, result);
  2716. };
  2717. /**
  2718. * The number of elements used to pack the object into an array.
  2719. * @type {Number}
  2720. */
  2721. Ellipsoid.packedLength = Cartesian3.packedLength;
  2722. /**
  2723. * Stores the provided instance into the provided array.
  2724. *
  2725. * @param {Ellipsoid} value The value to pack.
  2726. * @param {Number[]} array The array to pack into.
  2727. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2728. *
  2729. * @returns {Number[]} The array that was packed into
  2730. */
  2731. Ellipsoid.pack = function(value, array, startingIndex) {
  2732. if (!defined(value)) {
  2733. throw new DeveloperError('value is required');
  2734. }
  2735. if (!defined(array)) {
  2736. throw new DeveloperError('array is required');
  2737. }
  2738. startingIndex = defaultValue(startingIndex, 0);
  2739. Cartesian3.pack(value._radii, array, startingIndex);
  2740. return array;
  2741. };
  2742. /**
  2743. * Retrieves an instance from a packed array.
  2744. *
  2745. * @param {Number[]} array The packed array.
  2746. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2747. * @param {Ellipsoid} [result] The object into which to store the result.
  2748. * @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
  2749. */
  2750. Ellipsoid.unpack = function(array, startingIndex, result) {
  2751. if (!defined(array)) {
  2752. throw new DeveloperError('array is required');
  2753. }
  2754. startingIndex = defaultValue(startingIndex, 0);
  2755. var radii = Cartesian3.unpack(array, startingIndex);
  2756. return Ellipsoid.fromCartesian3(radii, result);
  2757. };
  2758. /**
  2759. * Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
  2760. * @function
  2761. *
  2762. * @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
  2763. * @param {Cartesian3} [result] The object onto which to store the result.
  2764. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2765. */
  2766. Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;
  2767. /**
  2768. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  2769. *
  2770. * @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
  2771. * @param {Cartesian3} [result] The object onto which to store the result.
  2772. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2773. */
  2774. Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) {
  2775. if (!defined(cartographic)) {
  2776. throw new DeveloperError('cartographic is required.');
  2777. }
  2778. var longitude = cartographic.longitude;
  2779. var latitude = cartographic.latitude;
  2780. var cosLatitude = Math.cos(latitude);
  2781. var x = cosLatitude * Math.cos(longitude);
  2782. var y = cosLatitude * Math.sin(longitude);
  2783. var z = Math.sin(latitude);
  2784. if (!defined(result)) {
  2785. result = new Cartesian3();
  2786. }
  2787. result.x = x;
  2788. result.y = y;
  2789. result.z = z;
  2790. return Cartesian3.normalize(result, result);
  2791. };
  2792. /**
  2793. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  2794. *
  2795. * @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
  2796. * @param {Cartesian3} [result] The object onto which to store the result.
  2797. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2798. */
  2799. Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian, result) {
  2800. if (!defined(result)) {
  2801. result = new Cartesian3();
  2802. }
  2803. result = Cartesian3.multiplyComponents(cartesian, this._oneOverRadiiSquared, result);
  2804. return Cartesian3.normalize(result, result);
  2805. };
  2806. var cartographicToCartesianNormal = new Cartesian3();
  2807. var cartographicToCartesianK = new Cartesian3();
  2808. /**
  2809. * Converts the provided cartographic to Cartesian representation.
  2810. *
  2811. * @param {Cartographic} cartographic The cartographic position.
  2812. * @param {Cartesian3} [result] The object onto which to store the result.
  2813. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2814. *
  2815. * @example
  2816. * //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
  2817. * var position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
  2818. * var cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
  2819. */
  2820. Ellipsoid.prototype.cartographicToCartesian = function(cartographic, result) {
  2821. //`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
  2822. var n = cartographicToCartesianNormal;
  2823. var k = cartographicToCartesianK;
  2824. this.geodeticSurfaceNormalCartographic(cartographic, n);
  2825. Cartesian3.multiplyComponents(this._radiiSquared, n, k);
  2826. var gamma = Math.sqrt(Cartesian3.dot(n, k));
  2827. Cartesian3.divideByScalar(k, gamma, k);
  2828. Cartesian3.multiplyByScalar(n, cartographic.height, n);
  2829. if (!defined(result)) {
  2830. result = new Cartesian3();
  2831. }
  2832. return Cartesian3.add(k, n, result);
  2833. };
  2834. /**
  2835. * Converts the provided array of cartographics to an array of Cartesians.
  2836. *
  2837. * @param {Cartographic[]} cartographics An array of cartographic positions.
  2838. * @param {Cartesian3[]} [result] The object onto which to store the result.
  2839. * @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
  2840. *
  2841. * @example
  2842. * //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
  2843. * var positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
  2844. * new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
  2845. * new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
  2846. * var cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
  2847. */
  2848. Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
  2849. if (!defined(cartographics)) {
  2850. throw new DeveloperError('cartographics is required.');
  2851. }
  2852. var length = cartographics.length;
  2853. if (!defined(result)) {
  2854. result = new Array(length);
  2855. } else {
  2856. result.length = length;
  2857. }
  2858. for ( var i = 0; i < length; i++) {
  2859. result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
  2860. }
  2861. return result;
  2862. };
  2863. var cartesianToCartographicN = new Cartesian3();
  2864. var cartesianToCartographicP = new Cartesian3();
  2865. var cartesianToCartographicH = new Cartesian3();
  2866. /**
  2867. * Converts the provided cartesian to cartographic representation.
  2868. * The cartesian is undefined at the center of the ellipsoid.
  2869. *
  2870. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  2871. * @param {Cartographic} [result] The object onto which to store the result.
  2872. * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
  2873. *
  2874. * @example
  2875. * //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
  2876. * var position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
  2877. * var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
  2878. */
  2879. Ellipsoid.prototype.cartesianToCartographic = function(cartesian, result) {
  2880. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  2881. var p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);
  2882. if (!defined(p)) {
  2883. return undefined;
  2884. }
  2885. var n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
  2886. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  2887. var longitude = Math.atan2(n.y, n.x);
  2888. var latitude = Math.asin(n.z);
  2889. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  2890. if (!defined(result)) {
  2891. return new Cartographic(longitude, latitude, height);
  2892. }
  2893. result.longitude = longitude;
  2894. result.latitude = latitude;
  2895. result.height = height;
  2896. return result;
  2897. };
  2898. /**
  2899. * Converts the provided array of cartesians to an array of cartographics.
  2900. *
  2901. * @param {Cartesian3[]} cartesians An array of Cartesian positions.
  2902. * @param {Cartographic[]} [result] The object onto which to store the result.
  2903. * @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
  2904. *
  2905. * @example
  2906. * //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
  2907. * var positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
  2908. * new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
  2909. * new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
  2910. * var cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
  2911. */
  2912. Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
  2913. if (!defined(cartesians)) {
  2914. throw new DeveloperError('cartesians is required.');
  2915. }
  2916. var length = cartesians.length;
  2917. if (!defined(result)) {
  2918. result = new Array(length);
  2919. } else {
  2920. result.length = length;
  2921. }
  2922. for ( var i = 0; i < length; ++i) {
  2923. result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
  2924. }
  2925. return result;
  2926. };
  2927. /**
  2928. * Scales the provided Cartesian position along the geodetic surface normal
  2929. * so that it is on the surface of this ellipsoid. If the position is
  2930. * at the center of the ellipsoid, this function returns undefined.
  2931. *
  2932. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2933. * @param {Cartesian3} [result] The object onto which to store the result.
  2934. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  2935. */
  2936. Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian, result) {
  2937. return scaleToGeodeticSurface(cartesian, this._oneOverRadii, this._oneOverRadiiSquared, this._centerToleranceSquared, result);
  2938. };
  2939. /**
  2940. * Scales the provided Cartesian position along the geocentric surface normal
  2941. * so that it is on the surface of this ellipsoid.
  2942. *
  2943. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2944. * @param {Cartesian3} [result] The object onto which to store the result.
  2945. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2946. */
  2947. Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian, result) {
  2948. if (!defined(cartesian)) {
  2949. throw new DeveloperError('cartesian is required.');
  2950. }
  2951. if (!defined(result)) {
  2952. result = new Cartesian3();
  2953. }
  2954. var positionX = cartesian.x;
  2955. var positionY = cartesian.y;
  2956. var positionZ = cartesian.z;
  2957. var oneOverRadiiSquared = this._oneOverRadiiSquared;
  2958. var beta = 1.0 / Math.sqrt((positionX * positionX) * oneOverRadiiSquared.x +
  2959. (positionY * positionY) * oneOverRadiiSquared.y +
  2960. (positionZ * positionZ) * oneOverRadiiSquared.z);
  2961. return Cartesian3.multiplyByScalar(cartesian, beta, result);
  2962. };
  2963. /**
  2964. * Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
  2965. * its components by the result of {@link Ellipsoid#oneOverRadii}.
  2966. *
  2967. * @param {Cartesian3} position The position to transform.
  2968. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  2969. * return a new instance.
  2970. * @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
  2971. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  2972. */
  2973. Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
  2974. if (!defined(result)) {
  2975. result = new Cartesian3();
  2976. }
  2977. return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
  2978. };
  2979. /**
  2980. * Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
  2981. * its components by the result of {@link Ellipsoid#radii}.
  2982. *
  2983. * @param {Cartesian3} position The position to transform.
  2984. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  2985. * return a new instance.
  2986. * @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
  2987. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  2988. */
  2989. Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
  2990. if (!defined(result)) {
  2991. result = new Cartesian3();
  2992. }
  2993. return Cartesian3.multiplyComponents(position, this._radii, result);
  2994. };
  2995. /**
  2996. * Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
  2997. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2998. *
  2999. * @param {Ellipsoid} [right] The other Ellipsoid.
  3000. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3001. */
  3002. Ellipsoid.prototype.equals = function(right) {
  3003. return (this === right) ||
  3004. (defined(right) &&
  3005. Cartesian3.equals(this._radii, right._radii));
  3006. };
  3007. /**
  3008. * Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  3009. *
  3010. * @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  3011. */
  3012. Ellipsoid.prototype.toString = function() {
  3013. return this._radii.toString();
  3014. };
  3015. /**
  3016. * Computes a point which is the intersection of the surface normal with the z-axis.
  3017. *
  3018. * @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
  3019. * @param {Number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
  3020. * In earth case, with common earth datums, there is no need for this buffer since the intersection point is always (relatively) very close to the center.
  3021. * In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
  3022. * Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
  3023. * @param {Cartesian} [result] The cartesian to which to copy the result, or undefined to create and
  3024. * return a new instance.
  3025. * @returns {Cartesian | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
  3026. *
  3027. * @exception {DeveloperError} position is required.
  3028. * @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
  3029. * @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
  3030. */
  3031. Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) {
  3032. if (!defined(position)) {
  3033. throw new DeveloperError('position is required.');
  3034. }
  3035. if (!CesiumMath.equalsEpsilon(this._radii.x, this._radii.y, CesiumMath.EPSILON15)) {
  3036. throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
  3037. }
  3038. if (this._radii.z === 0) {
  3039. throw new DeveloperError('Ellipsoid.radii.z must be greater than 0');
  3040. }
  3041. buffer = defaultValue(buffer, 0.0);
  3042. var sqauredXOverSquaredZ = this._sqauredXOverSquaredZ;
  3043. if (!defined(result)) {
  3044. result = new Cartesian3();
  3045. }
  3046. result.x = 0.0;
  3047. result.y = 0.0;
  3048. result.z = position.z * (1 - sqauredXOverSquaredZ);
  3049. if (Math.abs(result.z) >= this._radii.z - buffer) {
  3050. return undefined;
  3051. }
  3052. return result;
  3053. };
  3054. return Ellipsoid;
  3055. });
  3056. /*global define*/
  3057. define('Core/GeographicProjection',[
  3058. './Cartesian3',
  3059. './Cartographic',
  3060. './defaultValue',
  3061. './defined',
  3062. './defineProperties',
  3063. './DeveloperError',
  3064. './Ellipsoid'
  3065. ], function(
  3066. Cartesian3,
  3067. Cartographic,
  3068. defaultValue,
  3069. defined,
  3070. defineProperties,
  3071. DeveloperError,
  3072. Ellipsoid) {
  3073. 'use strict';
  3074. /**
  3075. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  3076. * them by the {@link Ellipsoid#maximumRadius}. This projection
  3077. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  3078. * is also known as EPSG:4326.
  3079. *
  3080. * @alias GeographicProjection
  3081. * @constructor
  3082. *
  3083. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  3084. *
  3085. * @see WebMercatorProjection
  3086. */
  3087. function GeographicProjection(ellipsoid) {
  3088. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  3089. this._semimajorAxis = this._ellipsoid.maximumRadius;
  3090. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  3091. }
  3092. defineProperties(GeographicProjection.prototype, {
  3093. /**
  3094. * Gets the {@link Ellipsoid}.
  3095. *
  3096. * @memberof GeographicProjection.prototype
  3097. *
  3098. * @type {Ellipsoid}
  3099. * @readonly
  3100. */
  3101. ellipsoid : {
  3102. get : function() {
  3103. return this._ellipsoid;
  3104. }
  3105. }
  3106. });
  3107. /**
  3108. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  3109. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  3110. * ellipsoid. Z is the unmodified height.
  3111. *
  3112. * @param {Cartographic} cartographic The coordinates to project.
  3113. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  3114. * undefined, a new instance is created and returned.
  3115. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  3116. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3117. * created and returned.
  3118. */
  3119. GeographicProjection.prototype.project = function(cartographic, result) {
  3120. // Actually this is the special case of equidistant cylindrical called the plate carree
  3121. var semimajorAxis = this._semimajorAxis;
  3122. var x = cartographic.longitude * semimajorAxis;
  3123. var y = cartographic.latitude * semimajorAxis;
  3124. var z = cartographic.height;
  3125. if (!defined(result)) {
  3126. return new Cartesian3(x, y, z);
  3127. }
  3128. result.x = x;
  3129. result.y = y;
  3130. result.z = z;
  3131. return result;
  3132. };
  3133. /**
  3134. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  3135. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  3136. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  3137. *
  3138. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  3139. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  3140. * undefined, a new instance is created and returned.
  3141. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  3142. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3143. * created and returned.
  3144. */
  3145. GeographicProjection.prototype.unproject = function(cartesian, result) {
  3146. if (!defined(cartesian)) {
  3147. throw new DeveloperError('cartesian is required');
  3148. }
  3149. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  3150. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  3151. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  3152. var height = cartesian.z;
  3153. if (!defined(result)) {
  3154. return new Cartographic(longitude, latitude, height);
  3155. }
  3156. result.longitude = longitude;
  3157. result.latitude = latitude;
  3158. result.height = height;
  3159. return result;
  3160. };
  3161. return GeographicProjection;
  3162. });
  3163. /*global define*/
  3164. define('Core/Intersect',[
  3165. './freezeObject'
  3166. ], function(
  3167. freezeObject) {
  3168. 'use strict';
  3169. /**
  3170. * This enumerated type is used in determining where, relative to the frustum, an
  3171. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3172. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3173. * outside of the frustum's 6 planes (OUTSIDE).
  3174. *
  3175. * @exports Intersect
  3176. */
  3177. var Intersect = {
  3178. /**
  3179. * Represents that an object is not contained within the frustum.
  3180. *
  3181. * @type {Number}
  3182. * @constant
  3183. */
  3184. OUTSIDE : -1,
  3185. /**
  3186. * Represents that an object intersects one of the frustum's planes.
  3187. *
  3188. * @type {Number}
  3189. * @constant
  3190. */
  3191. INTERSECTING : 0,
  3192. /**
  3193. * Represents that an object is fully within the frustum.
  3194. *
  3195. * @type {Number}
  3196. * @constant
  3197. */
  3198. INSIDE : 1
  3199. };
  3200. return freezeObject(Intersect);
  3201. });
  3202. /*global define*/
  3203. define('Core/Interval',[
  3204. './defaultValue'
  3205. ], function(
  3206. defaultValue) {
  3207. 'use strict';
  3208. /**
  3209. * Represents the closed interval [start, stop].
  3210. * @alias Interval
  3211. * @constructor
  3212. *
  3213. * @param {Number} [start=0.0] The beginning of the interval.
  3214. * @param {Number} [stop=0.0] The end of the interval.
  3215. */
  3216. function Interval(start, stop) {
  3217. /**
  3218. * The beginning of the interval.
  3219. * @type {Number}
  3220. * @default 0.0
  3221. */
  3222. this.start = defaultValue(start, 0.0);
  3223. /**
  3224. * The end of the interval.
  3225. * @type {Number}
  3226. * @default 0.0
  3227. */
  3228. this.stop = defaultValue(stop, 0.0);
  3229. }
  3230. return Interval;
  3231. });
  3232. /*global define*/
  3233. define('Core/Matrix3',[
  3234. './Cartesian3',
  3235. './defaultValue',
  3236. './defined',
  3237. './defineProperties',
  3238. './DeveloperError',
  3239. './freezeObject',
  3240. './Math'
  3241. ], function(
  3242. Cartesian3,
  3243. defaultValue,
  3244. defined,
  3245. defineProperties,
  3246. DeveloperError,
  3247. freezeObject,
  3248. CesiumMath) {
  3249. 'use strict';
  3250. /**
  3251. * A 3x3 matrix, indexable as a column-major order array.
  3252. * Constructor parameters are in row-major order for code readability.
  3253. * @alias Matrix3
  3254. * @constructor
  3255. *
  3256. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  3257. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  3258. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  3259. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  3260. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  3261. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  3262. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  3263. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  3264. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  3265. *
  3266. * @see Matrix3.fromColumnMajorArray
  3267. * @see Matrix3.fromRowMajorArray
  3268. * @see Matrix3.fromQuaternion
  3269. * @see Matrix3.fromScale
  3270. * @see Matrix3.fromUniformScale
  3271. * @see Matrix2
  3272. * @see Matrix4
  3273. */
  3274. function Matrix3(column0Row0, column1Row0, column2Row0,
  3275. column0Row1, column1Row1, column2Row1,
  3276. column0Row2, column1Row2, column2Row2) {
  3277. this[0] = defaultValue(column0Row0, 0.0);
  3278. this[1] = defaultValue(column0Row1, 0.0);
  3279. this[2] = defaultValue(column0Row2, 0.0);
  3280. this[3] = defaultValue(column1Row0, 0.0);
  3281. this[4] = defaultValue(column1Row1, 0.0);
  3282. this[5] = defaultValue(column1Row2, 0.0);
  3283. this[6] = defaultValue(column2Row0, 0.0);
  3284. this[7] = defaultValue(column2Row1, 0.0);
  3285. this[8] = defaultValue(column2Row2, 0.0);
  3286. }
  3287. /**
  3288. * The number of elements used to pack the object into an array.
  3289. * @type {Number}
  3290. */
  3291. Matrix3.packedLength = 9;
  3292. /**
  3293. * Stores the provided instance into the provided array.
  3294. *
  3295. * @param {Matrix3} value The value to pack.
  3296. * @param {Number[]} array The array to pack into.
  3297. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3298. *
  3299. * @returns {Number[]} The array that was packed into
  3300. */
  3301. Matrix3.pack = function(value, array, startingIndex) {
  3302. if (!defined(value)) {
  3303. throw new DeveloperError('value is required');
  3304. }
  3305. if (!defined(array)) {
  3306. throw new DeveloperError('array is required');
  3307. }
  3308. startingIndex = defaultValue(startingIndex, 0);
  3309. array[startingIndex++] = value[0];
  3310. array[startingIndex++] = value[1];
  3311. array[startingIndex++] = value[2];
  3312. array[startingIndex++] = value[3];
  3313. array[startingIndex++] = value[4];
  3314. array[startingIndex++] = value[5];
  3315. array[startingIndex++] = value[6];
  3316. array[startingIndex++] = value[7];
  3317. array[startingIndex++] = value[8];
  3318. return array;
  3319. };
  3320. /**
  3321. * Retrieves an instance from a packed array.
  3322. *
  3323. * @param {Number[]} array The packed array.
  3324. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3325. * @param {Matrix3} [result] The object into which to store the result.
  3326. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  3327. */
  3328. Matrix3.unpack = function(array, startingIndex, result) {
  3329. if (!defined(array)) {
  3330. throw new DeveloperError('array is required');
  3331. }
  3332. startingIndex = defaultValue(startingIndex, 0);
  3333. if (!defined(result)) {
  3334. result = new Matrix3();
  3335. }
  3336. result[0] = array[startingIndex++];
  3337. result[1] = array[startingIndex++];
  3338. result[2] = array[startingIndex++];
  3339. result[3] = array[startingIndex++];
  3340. result[4] = array[startingIndex++];
  3341. result[5] = array[startingIndex++];
  3342. result[6] = array[startingIndex++];
  3343. result[7] = array[startingIndex++];
  3344. result[8] = array[startingIndex++];
  3345. return result;
  3346. };
  3347. /**
  3348. * Duplicates a Matrix3 instance.
  3349. *
  3350. * @param {Matrix3} matrix The matrix to duplicate.
  3351. * @param {Matrix3} [result] The object onto which to store the result.
  3352. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  3353. */
  3354. Matrix3.clone = function(values, result) {
  3355. if (!defined(values)) {
  3356. return undefined;
  3357. }
  3358. if (!defined(result)) {
  3359. return new Matrix3(values[0], values[3], values[6],
  3360. values[1], values[4], values[7],
  3361. values[2], values[5], values[8]);
  3362. }
  3363. result[0] = values[0];
  3364. result[1] = values[1];
  3365. result[2] = values[2];
  3366. result[3] = values[3];
  3367. result[4] = values[4];
  3368. result[5] = values[5];
  3369. result[6] = values[6];
  3370. result[7] = values[7];
  3371. result[8] = values[8];
  3372. return result;
  3373. };
  3374. /**
  3375. * Creates a Matrix3 from 9 consecutive elements in an array.
  3376. *
  3377. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  3378. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  3379. * @param {Matrix3} [result] The object onto which to store the result.
  3380. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  3381. *
  3382. * @example
  3383. * // Create the Matrix3:
  3384. * // [1.0, 2.0, 3.0]
  3385. * // [1.0, 2.0, 3.0]
  3386. * // [1.0, 2.0, 3.0]
  3387. *
  3388. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  3389. * var m = Cesium.Matrix3.fromArray(v);
  3390. *
  3391. * // Create same Matrix3 with using an offset into an array
  3392. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  3393. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  3394. */
  3395. Matrix3.fromArray = function(array, startingIndex, result) {
  3396. if (!defined(array)) {
  3397. throw new DeveloperError('array is required');
  3398. }
  3399. startingIndex = defaultValue(startingIndex, 0);
  3400. if (!defined(result)) {
  3401. result = new Matrix3();
  3402. }
  3403. result[0] = array[startingIndex];
  3404. result[1] = array[startingIndex + 1];
  3405. result[2] = array[startingIndex + 2];
  3406. result[3] = array[startingIndex + 3];
  3407. result[4] = array[startingIndex + 4];
  3408. result[5] = array[startingIndex + 5];
  3409. result[6] = array[startingIndex + 6];
  3410. result[7] = array[startingIndex + 7];
  3411. result[8] = array[startingIndex + 8];
  3412. return result;
  3413. };
  3414. /**
  3415. * Creates a Matrix3 instance from a column-major order array.
  3416. *
  3417. * @param {Number[]} values The column-major order array.
  3418. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3419. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3420. */
  3421. Matrix3.fromColumnMajorArray = function(values, result) {
  3422. if (!defined(values)) {
  3423. throw new DeveloperError('values parameter is required');
  3424. }
  3425. return Matrix3.clone(values, result);
  3426. };
  3427. /**
  3428. * Creates a Matrix3 instance from a row-major order array.
  3429. * The resulting matrix will be in column-major order.
  3430. *
  3431. * @param {Number[]} values The row-major order array.
  3432. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3433. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3434. */
  3435. Matrix3.fromRowMajorArray = function(values, result) {
  3436. if (!defined(values)) {
  3437. throw new DeveloperError('values is required.');
  3438. }
  3439. if (!defined(result)) {
  3440. return new Matrix3(values[0], values[1], values[2],
  3441. values[3], values[4], values[5],
  3442. values[6], values[7], values[8]);
  3443. }
  3444. result[0] = values[0];
  3445. result[1] = values[3];
  3446. result[2] = values[6];
  3447. result[3] = values[1];
  3448. result[4] = values[4];
  3449. result[5] = values[7];
  3450. result[6] = values[2];
  3451. result[7] = values[5];
  3452. result[8] = values[8];
  3453. return result;
  3454. };
  3455. /**
  3456. * Computes a 3x3 rotation matrix from the provided quaternion.
  3457. *
  3458. * @param {Quaternion} quaternion the quaternion to use.
  3459. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3460. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  3461. */
  3462. Matrix3.fromQuaternion = function(quaternion, result) {
  3463. if (!defined(quaternion)) {
  3464. throw new DeveloperError('quaternion is required');
  3465. }
  3466. var x2 = quaternion.x * quaternion.x;
  3467. var xy = quaternion.x * quaternion.y;
  3468. var xz = quaternion.x * quaternion.z;
  3469. var xw = quaternion.x * quaternion.w;
  3470. var y2 = quaternion.y * quaternion.y;
  3471. var yz = quaternion.y * quaternion.z;
  3472. var yw = quaternion.y * quaternion.w;
  3473. var z2 = quaternion.z * quaternion.z;
  3474. var zw = quaternion.z * quaternion.w;
  3475. var w2 = quaternion.w * quaternion.w;
  3476. var m00 = x2 - y2 - z2 + w2;
  3477. var m01 = 2.0 * (xy - zw);
  3478. var m02 = 2.0 * (xz + yw);
  3479. var m10 = 2.0 * (xy + zw);
  3480. var m11 = -x2 + y2 - z2 + w2;
  3481. var m12 = 2.0 * (yz - xw);
  3482. var m20 = 2.0 * (xz - yw);
  3483. var m21 = 2.0 * (yz + xw);
  3484. var m22 = -x2 - y2 + z2 + w2;
  3485. if (!defined(result)) {
  3486. return new Matrix3(m00, m01, m02,
  3487. m10, m11, m12,
  3488. m20, m21, m22);
  3489. }
  3490. result[0] = m00;
  3491. result[1] = m10;
  3492. result[2] = m20;
  3493. result[3] = m01;
  3494. result[4] = m11;
  3495. result[5] = m21;
  3496. result[6] = m02;
  3497. result[7] = m12;
  3498. result[8] = m22;
  3499. return result;
  3500. };
  3501. /**
  3502. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  3503. *
  3504. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  3505. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3506. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  3507. */
  3508. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  3509. if (!defined(headingPitchRoll)) {
  3510. throw new DeveloperError('headingPitchRoll is required');
  3511. }
  3512. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  3513. var cosPsi = Math.cos(-headingPitchRoll.heading);
  3514. var cosPhi = Math.cos(headingPitchRoll.roll);
  3515. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  3516. var sinPsi = Math.sin(-headingPitchRoll.heading);
  3517. var sinPhi = Math.sin(headingPitchRoll.roll);
  3518. var m00 = cosTheta * cosPsi;
  3519. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  3520. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  3521. var m10 = cosTheta * sinPsi;
  3522. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  3523. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  3524. var m20 = -sinTheta;
  3525. var m21 = sinPhi * cosTheta;
  3526. var m22 = cosPhi * cosTheta;
  3527. if (!defined(result)) {
  3528. return new Matrix3(m00, m01, m02,
  3529. m10, m11, m12,
  3530. m20, m21, m22);
  3531. }
  3532. result[0] = m00;
  3533. result[1] = m10;
  3534. result[2] = m20;
  3535. result[3] = m01;
  3536. result[4] = m11;
  3537. result[5] = m21;
  3538. result[6] = m02;
  3539. result[7] = m12;
  3540. result[8] = m22;
  3541. return result;
  3542. };
  3543. /**
  3544. * Computes a Matrix3 instance representing a non-uniform scale.
  3545. *
  3546. * @param {Cartesian3} scale The x, y, and z scale factors.
  3547. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3548. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3549. *
  3550. * @example
  3551. * // Creates
  3552. * // [7.0, 0.0, 0.0]
  3553. * // [0.0, 8.0, 0.0]
  3554. * // [0.0, 0.0, 9.0]
  3555. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  3556. */
  3557. Matrix3.fromScale = function(scale, result) {
  3558. if (!defined(scale)) {
  3559. throw new DeveloperError('scale is required.');
  3560. }
  3561. if (!defined(result)) {
  3562. return new Matrix3(
  3563. scale.x, 0.0, 0.0,
  3564. 0.0, scale.y, 0.0,
  3565. 0.0, 0.0, scale.z);
  3566. }
  3567. result[0] = scale.x;
  3568. result[1] = 0.0;
  3569. result[2] = 0.0;
  3570. result[3] = 0.0;
  3571. result[4] = scale.y;
  3572. result[5] = 0.0;
  3573. result[6] = 0.0;
  3574. result[7] = 0.0;
  3575. result[8] = scale.z;
  3576. return result;
  3577. };
  3578. /**
  3579. * Computes a Matrix3 instance representing a uniform scale.
  3580. *
  3581. * @param {Number} scale The uniform scale factor.
  3582. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3583. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3584. *
  3585. * @example
  3586. * // Creates
  3587. * // [2.0, 0.0, 0.0]
  3588. * // [0.0, 2.0, 0.0]
  3589. * // [0.0, 0.0, 2.0]
  3590. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  3591. */
  3592. Matrix3.fromUniformScale = function(scale, result) {
  3593. if (typeof scale !== 'number') {
  3594. throw new DeveloperError('scale is required.');
  3595. }
  3596. if (!defined(result)) {
  3597. return new Matrix3(
  3598. scale, 0.0, 0.0,
  3599. 0.0, scale, 0.0,
  3600. 0.0, 0.0, scale);
  3601. }
  3602. result[0] = scale;
  3603. result[1] = 0.0;
  3604. result[2] = 0.0;
  3605. result[3] = 0.0;
  3606. result[4] = scale;
  3607. result[5] = 0.0;
  3608. result[6] = 0.0;
  3609. result[7] = 0.0;
  3610. result[8] = scale;
  3611. return result;
  3612. };
  3613. /**
  3614. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  3615. *
  3616. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  3617. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3618. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3619. *
  3620. * @example
  3621. * // Creates
  3622. * // [0.0, -9.0, 8.0]
  3623. * // [9.0, 0.0, -7.0]
  3624. * // [-8.0, 7.0, 0.0]
  3625. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  3626. */
  3627. Matrix3.fromCrossProduct = function(vector, result) {
  3628. if (!defined(vector)) {
  3629. throw new DeveloperError('vector is required.');
  3630. }
  3631. if (!defined(result)) {
  3632. return new Matrix3(
  3633. 0.0, -vector.z, vector.y,
  3634. vector.z, 0.0, -vector.x,
  3635. -vector.y, vector.x, 0.0);
  3636. }
  3637. result[0] = 0.0;
  3638. result[1] = vector.z;
  3639. result[2] = -vector.y;
  3640. result[3] = -vector.z;
  3641. result[4] = 0.0;
  3642. result[5] = vector.x;
  3643. result[6] = vector.y;
  3644. result[7] = -vector.x;
  3645. result[8] = 0.0;
  3646. return result;
  3647. };
  3648. /**
  3649. * Creates a rotation matrix around the x-axis.
  3650. *
  3651. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3652. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3653. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3654. *
  3655. * @example
  3656. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  3657. * var p = new Cesium.Cartesian3(5, 6, 7);
  3658. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  3659. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3660. */
  3661. Matrix3.fromRotationX = function(angle, result) {
  3662. if (!defined(angle)) {
  3663. throw new DeveloperError('angle is required.');
  3664. }
  3665. var cosAngle = Math.cos(angle);
  3666. var sinAngle = Math.sin(angle);
  3667. if (!defined(result)) {
  3668. return new Matrix3(
  3669. 1.0, 0.0, 0.0,
  3670. 0.0, cosAngle, -sinAngle,
  3671. 0.0, sinAngle, cosAngle);
  3672. }
  3673. result[0] = 1.0;
  3674. result[1] = 0.0;
  3675. result[2] = 0.0;
  3676. result[3] = 0.0;
  3677. result[4] = cosAngle;
  3678. result[5] = sinAngle;
  3679. result[6] = 0.0;
  3680. result[7] = -sinAngle;
  3681. result[8] = cosAngle;
  3682. return result;
  3683. };
  3684. /**
  3685. * Creates a rotation matrix around the y-axis.
  3686. *
  3687. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3688. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3689. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3690. *
  3691. * @example
  3692. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  3693. * var p = new Cesium.Cartesian3(5, 6, 7);
  3694. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  3695. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3696. */
  3697. Matrix3.fromRotationY = function(angle, result) {
  3698. if (!defined(angle)) {
  3699. throw new DeveloperError('angle is required.');
  3700. }
  3701. var cosAngle = Math.cos(angle);
  3702. var sinAngle = Math.sin(angle);
  3703. if (!defined(result)) {
  3704. return new Matrix3(
  3705. cosAngle, 0.0, sinAngle,
  3706. 0.0, 1.0, 0.0,
  3707. -sinAngle, 0.0, cosAngle);
  3708. }
  3709. result[0] = cosAngle;
  3710. result[1] = 0.0;
  3711. result[2] = -sinAngle;
  3712. result[3] = 0.0;
  3713. result[4] = 1.0;
  3714. result[5] = 0.0;
  3715. result[6] = sinAngle;
  3716. result[7] = 0.0;
  3717. result[8] = cosAngle;
  3718. return result;
  3719. };
  3720. /**
  3721. * Creates a rotation matrix around the z-axis.
  3722. *
  3723. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3724. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3725. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3726. *
  3727. * @example
  3728. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  3729. * var p = new Cesium.Cartesian3(5, 6, 7);
  3730. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  3731. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3732. */
  3733. Matrix3.fromRotationZ = function(angle, result) {
  3734. if (!defined(angle)) {
  3735. throw new DeveloperError('angle is required.');
  3736. }
  3737. var cosAngle = Math.cos(angle);
  3738. var sinAngle = Math.sin(angle);
  3739. if (!defined(result)) {
  3740. return new Matrix3(
  3741. cosAngle, -sinAngle, 0.0,
  3742. sinAngle, cosAngle, 0.0,
  3743. 0.0, 0.0, 1.0);
  3744. }
  3745. result[0] = cosAngle;
  3746. result[1] = sinAngle;
  3747. result[2] = 0.0;
  3748. result[3] = -sinAngle;
  3749. result[4] = cosAngle;
  3750. result[5] = 0.0;
  3751. result[6] = 0.0;
  3752. result[7] = 0.0;
  3753. result[8] = 1.0;
  3754. return result;
  3755. };
  3756. /**
  3757. * Creates an Array from the provided Matrix3 instance.
  3758. * The array will be in column-major order.
  3759. *
  3760. * @param {Matrix3} matrix The matrix to use..
  3761. * @param {Number[]} [result] The Array onto which to store the result.
  3762. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  3763. */
  3764. Matrix3.toArray = function(matrix, result) {
  3765. if (!defined(matrix)) {
  3766. throw new DeveloperError('matrix is required');
  3767. }
  3768. if (!defined(result)) {
  3769. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  3770. }
  3771. result[0] = matrix[0];
  3772. result[1] = matrix[1];
  3773. result[2] = matrix[2];
  3774. result[3] = matrix[3];
  3775. result[4] = matrix[4];
  3776. result[5] = matrix[5];
  3777. result[6] = matrix[6];
  3778. result[7] = matrix[7];
  3779. result[8] = matrix[8];
  3780. return result;
  3781. };
  3782. /**
  3783. * Computes the array index of the element at the provided row and column.
  3784. *
  3785. * @param {Number} row The zero-based index of the row.
  3786. * @param {Number} column The zero-based index of the column.
  3787. * @returns {Number} The index of the element at the provided row and column.
  3788. *
  3789. * @exception {DeveloperError} row must be 0, 1, or 2.
  3790. * @exception {DeveloperError} column must be 0, 1, or 2.
  3791. *
  3792. * @example
  3793. * var myMatrix = new Cesium.Matrix3();
  3794. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  3795. * var column1Row0 = myMatrix[column1Row0Index]
  3796. * myMatrix[column1Row0Index] = 10.0;
  3797. */
  3798. Matrix3.getElementIndex = function(column, row) {
  3799. if (typeof row !== 'number' || row < 0 || row > 2) {
  3800. throw new DeveloperError('row must be 0, 1, or 2.');
  3801. }
  3802. if (typeof column !== 'number' || column < 0 || column > 2) {
  3803. throw new DeveloperError('column must be 0, 1, or 2.');
  3804. }
  3805. return column * 3 + row;
  3806. };
  3807. /**
  3808. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  3809. *
  3810. * @param {Matrix3} matrix The matrix to use.
  3811. * @param {Number} index The zero-based index of the column to retrieve.
  3812. * @param {Cartesian3} result The object onto which to store the result.
  3813. * @returns {Cartesian3} The modified result parameter.
  3814. *
  3815. * @exception {DeveloperError} index must be 0, 1, or 2.
  3816. */
  3817. Matrix3.getColumn = function(matrix, index, result) {
  3818. if (!defined(matrix)) {
  3819. throw new DeveloperError('matrix is required.');
  3820. }
  3821. if (typeof index !== 'number' || index < 0 || index > 2) {
  3822. throw new DeveloperError('index must be 0, 1, or 2.');
  3823. }
  3824. if (!defined(result)) {
  3825. throw new DeveloperError('result is required');
  3826. }
  3827. var startIndex = index * 3;
  3828. var x = matrix[startIndex];
  3829. var y = matrix[startIndex + 1];
  3830. var z = matrix[startIndex + 2];
  3831. result.x = x;
  3832. result.y = y;
  3833. result.z = z;
  3834. return result;
  3835. };
  3836. /**
  3837. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  3838. *
  3839. * @param {Matrix3} matrix The matrix to use.
  3840. * @param {Number} index The zero-based index of the column to set.
  3841. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  3842. * @param {Matrix3} result The object onto which to store the result.
  3843. * @returns {Matrix3} The modified result parameter.
  3844. *
  3845. * @exception {DeveloperError} index must be 0, 1, or 2.
  3846. */
  3847. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  3848. if (!defined(matrix)) {
  3849. throw new DeveloperError('matrix is required');
  3850. }
  3851. if (!defined(cartesian)) {
  3852. throw new DeveloperError('cartesian is required');
  3853. }
  3854. if (typeof index !== 'number' || index < 0 || index > 2) {
  3855. throw new DeveloperError('index must be 0, 1, or 2.');
  3856. }
  3857. if (!defined(result)) {
  3858. throw new DeveloperError('result is required');
  3859. }
  3860. result = Matrix3.clone(matrix, result);
  3861. var startIndex = index * 3;
  3862. result[startIndex] = cartesian.x;
  3863. result[startIndex + 1] = cartesian.y;
  3864. result[startIndex + 2] = cartesian.z;
  3865. return result;
  3866. };
  3867. /**
  3868. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  3869. *
  3870. * @param {Matrix3} matrix The matrix to use.
  3871. * @param {Number} index The zero-based index of the row to retrieve.
  3872. * @param {Cartesian3} result The object onto which to store the result.
  3873. * @returns {Cartesian3} The modified result parameter.
  3874. *
  3875. * @exception {DeveloperError} index must be 0, 1, or 2.
  3876. */
  3877. Matrix3.getRow = function(matrix, index, result) {
  3878. if (!defined(matrix)) {
  3879. throw new DeveloperError('matrix is required.');
  3880. }
  3881. if (typeof index !== 'number' || index < 0 || index > 2) {
  3882. throw new DeveloperError('index must be 0, 1, or 2.');
  3883. }
  3884. if (!defined(result)) {
  3885. throw new DeveloperError('result is required');
  3886. }
  3887. var x = matrix[index];
  3888. var y = matrix[index + 3];
  3889. var z = matrix[index + 6];
  3890. result.x = x;
  3891. result.y = y;
  3892. result.z = z;
  3893. return result;
  3894. };
  3895. /**
  3896. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  3897. *
  3898. * @param {Matrix3} matrix The matrix to use.
  3899. * @param {Number} index The zero-based index of the row to set.
  3900. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  3901. * @param {Matrix3} result The object onto which to store the result.
  3902. * @returns {Matrix3} The modified result parameter.
  3903. *
  3904. * @exception {DeveloperError} index must be 0, 1, or 2.
  3905. */
  3906. Matrix3.setRow = function(matrix, index, cartesian, result) {
  3907. if (!defined(matrix)) {
  3908. throw new DeveloperError('matrix is required');
  3909. }
  3910. if (!defined(cartesian)) {
  3911. throw new DeveloperError('cartesian is required');
  3912. }
  3913. if (typeof index !== 'number' || index < 0 || index > 2) {
  3914. throw new DeveloperError('index must be 0, 1, or 2.');
  3915. }
  3916. if (!defined(result)) {
  3917. throw new DeveloperError('result is required');
  3918. }
  3919. result = Matrix3.clone(matrix, result);
  3920. result[index] = cartesian.x;
  3921. result[index + 3] = cartesian.y;
  3922. result[index + 6] = cartesian.z;
  3923. return result;
  3924. };
  3925. var scratchColumn = new Cartesian3();
  3926. /**
  3927. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  3928. *
  3929. * @param {Matrix3} matrix The matrix.
  3930. * @param {Cartesian3} result The object onto which to store the result.
  3931. * @returns {Cartesian3} The modified result parameter.
  3932. */
  3933. Matrix3.getScale = function(matrix, result) {
  3934. if (!defined(matrix)) {
  3935. throw new DeveloperError('matrix is required.');
  3936. }
  3937. if (!defined(result)) {
  3938. throw new DeveloperError('result is required');
  3939. }
  3940. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  3941. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  3942. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  3943. return result;
  3944. };
  3945. var scratchScale = new Cartesian3();
  3946. /**
  3947. * Computes the maximum scale assuming the matrix is an affine transformation.
  3948. * The maximum scale is the maximum length of the column vectors.
  3949. *
  3950. * @param {Matrix3} matrix The matrix.
  3951. * @returns {Number} The maximum scale.
  3952. */
  3953. Matrix3.getMaximumScale = function(matrix) {
  3954. Matrix3.getScale(matrix, scratchScale);
  3955. return Cartesian3.maximumComponent(scratchScale);
  3956. };
  3957. /**
  3958. * Computes the product of two matrices.
  3959. *
  3960. * @param {Matrix3} left The first matrix.
  3961. * @param {Matrix3} right The second matrix.
  3962. * @param {Matrix3} result The object onto which to store the result.
  3963. * @returns {Matrix3} The modified result parameter.
  3964. */
  3965. Matrix3.multiply = function(left, right, result) {
  3966. if (!defined(left)) {
  3967. throw new DeveloperError('left is required');
  3968. }
  3969. if (!defined(right)) {
  3970. throw new DeveloperError('right is required');
  3971. }
  3972. if (!defined(result)) {
  3973. throw new DeveloperError('result is required');
  3974. }
  3975. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  3976. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  3977. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  3978. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  3979. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  3980. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  3981. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  3982. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  3983. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  3984. result[0] = column0Row0;
  3985. result[1] = column0Row1;
  3986. result[2] = column0Row2;
  3987. result[3] = column1Row0;
  3988. result[4] = column1Row1;
  3989. result[5] = column1Row2;
  3990. result[6] = column2Row0;
  3991. result[7] = column2Row1;
  3992. result[8] = column2Row2;
  3993. return result;
  3994. };
  3995. /**
  3996. * Computes the sum of two matrices.
  3997. *
  3998. * @param {Matrix3} left The first matrix.
  3999. * @param {Matrix3} right The second matrix.
  4000. * @param {Matrix3} result The object onto which to store the result.
  4001. * @returns {Matrix3} The modified result parameter.
  4002. */
  4003. Matrix3.add = function(left, right, result) {
  4004. if (!defined(left)) {
  4005. throw new DeveloperError('left is required');
  4006. }
  4007. if (!defined(right)) {
  4008. throw new DeveloperError('right is required');
  4009. }
  4010. if (!defined(result)) {
  4011. throw new DeveloperError('result is required');
  4012. }
  4013. result[0] = left[0] + right[0];
  4014. result[1] = left[1] + right[1];
  4015. result[2] = left[2] + right[2];
  4016. result[3] = left[3] + right[3];
  4017. result[4] = left[4] + right[4];
  4018. result[5] = left[5] + right[5];
  4019. result[6] = left[6] + right[6];
  4020. result[7] = left[7] + right[7];
  4021. result[8] = left[8] + right[8];
  4022. return result;
  4023. };
  4024. /**
  4025. * Computes the difference of two matrices.
  4026. *
  4027. * @param {Matrix3} left The first matrix.
  4028. * @param {Matrix3} right The second matrix.
  4029. * @param {Matrix3} result The object onto which to store the result.
  4030. * @returns {Matrix3} The modified result parameter.
  4031. */
  4032. Matrix3.subtract = function(left, right, result) {
  4033. if (!defined(left)) {
  4034. throw new DeveloperError('left is required');
  4035. }
  4036. if (!defined(right)) {
  4037. throw new DeveloperError('right is required');
  4038. }
  4039. if (!defined(result)) {
  4040. throw new DeveloperError('result is required');
  4041. }
  4042. result[0] = left[0] - right[0];
  4043. result[1] = left[1] - right[1];
  4044. result[2] = left[2] - right[2];
  4045. result[3] = left[3] - right[3];
  4046. result[4] = left[4] - right[4];
  4047. result[5] = left[5] - right[5];
  4048. result[6] = left[6] - right[6];
  4049. result[7] = left[7] - right[7];
  4050. result[8] = left[8] - right[8];
  4051. return result;
  4052. };
  4053. /**
  4054. * Computes the product of a matrix and a column vector.
  4055. *
  4056. * @param {Matrix3} matrix The matrix.
  4057. * @param {Cartesian3} cartesian The column.
  4058. * @param {Cartesian3} result The object onto which to store the result.
  4059. * @returns {Cartesian3} The modified result parameter.
  4060. */
  4061. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  4062. if (!defined(matrix)) {
  4063. throw new DeveloperError('matrix is required');
  4064. }
  4065. if (!defined(cartesian)) {
  4066. throw new DeveloperError('cartesian is required');
  4067. }
  4068. if (!defined(result)) {
  4069. throw new DeveloperError('result is required');
  4070. }
  4071. var vX = cartesian.x;
  4072. var vY = cartesian.y;
  4073. var vZ = cartesian.z;
  4074. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  4075. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  4076. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  4077. result.x = x;
  4078. result.y = y;
  4079. result.z = z;
  4080. return result;
  4081. };
  4082. /**
  4083. * Computes the product of a matrix and a scalar.
  4084. *
  4085. * @param {Matrix3} matrix The matrix.
  4086. * @param {Number} scalar The number to multiply by.
  4087. * @param {Matrix3} result The object onto which to store the result.
  4088. * @returns {Matrix3} The modified result parameter.
  4089. */
  4090. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  4091. if (!defined(matrix)) {
  4092. throw new DeveloperError('matrix is required');
  4093. }
  4094. if (typeof scalar !== 'number') {
  4095. throw new DeveloperError('scalar must be a number');
  4096. }
  4097. if (!defined(result)) {
  4098. throw new DeveloperError('result is required');
  4099. }
  4100. result[0] = matrix[0] * scalar;
  4101. result[1] = matrix[1] * scalar;
  4102. result[2] = matrix[2] * scalar;
  4103. result[3] = matrix[3] * scalar;
  4104. result[4] = matrix[4] * scalar;
  4105. result[5] = matrix[5] * scalar;
  4106. result[6] = matrix[6] * scalar;
  4107. result[7] = matrix[7] * scalar;
  4108. result[8] = matrix[8] * scalar;
  4109. return result;
  4110. };
  4111. /**
  4112. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  4113. *
  4114. * @param {Matrix3} matrix The matrix on the left-hand side.
  4115. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  4116. * @param {Matrix3} result The object onto which to store the result.
  4117. * @returns {Matrix3} The modified result parameter.
  4118. *
  4119. *
  4120. * @example
  4121. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  4122. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  4123. *
  4124. * @see Matrix3.fromScale
  4125. * @see Matrix3.multiplyByUniformScale
  4126. */
  4127. Matrix3.multiplyByScale = function(matrix, scale, result) {
  4128. if (!defined(matrix)) {
  4129. throw new DeveloperError('matrix is required');
  4130. }
  4131. if (!defined(scale)) {
  4132. throw new DeveloperError('scale is required');
  4133. }
  4134. if (!defined(result)) {
  4135. throw new DeveloperError('result is required');
  4136. }
  4137. result[0] = matrix[0] * scale.x;
  4138. result[1] = matrix[1] * scale.x;
  4139. result[2] = matrix[2] * scale.x;
  4140. result[3] = matrix[3] * scale.y;
  4141. result[4] = matrix[4] * scale.y;
  4142. result[5] = matrix[5] * scale.y;
  4143. result[6] = matrix[6] * scale.z;
  4144. result[7] = matrix[7] * scale.z;
  4145. result[8] = matrix[8] * scale.z;
  4146. return result;
  4147. };
  4148. /**
  4149. * Creates a negated copy of the provided matrix.
  4150. *
  4151. * @param {Matrix3} matrix The matrix to negate.
  4152. * @param {Matrix3} result The object onto which to store the result.
  4153. * @returns {Matrix3} The modified result parameter.
  4154. */
  4155. Matrix3.negate = function(matrix, result) {
  4156. if (!defined(matrix)) {
  4157. throw new DeveloperError('matrix is required');
  4158. }
  4159. if (!defined(result)) {
  4160. throw new DeveloperError('result is required');
  4161. }
  4162. result[0] = -matrix[0];
  4163. result[1] = -matrix[1];
  4164. result[2] = -matrix[2];
  4165. result[3] = -matrix[3];
  4166. result[4] = -matrix[4];
  4167. result[5] = -matrix[5];
  4168. result[6] = -matrix[6];
  4169. result[7] = -matrix[7];
  4170. result[8] = -matrix[8];
  4171. return result;
  4172. };
  4173. /**
  4174. * Computes the transpose of the provided matrix.
  4175. *
  4176. * @param {Matrix3} matrix The matrix to transpose.
  4177. * @param {Matrix3} result The object onto which to store the result.
  4178. * @returns {Matrix3} The modified result parameter.
  4179. */
  4180. Matrix3.transpose = function(matrix, result) {
  4181. if (!defined(matrix)) {
  4182. throw new DeveloperError('matrix is required');
  4183. }
  4184. if (!defined(result)) {
  4185. throw new DeveloperError('result is required');
  4186. }
  4187. var column0Row0 = matrix[0];
  4188. var column0Row1 = matrix[3];
  4189. var column0Row2 = matrix[6];
  4190. var column1Row0 = matrix[1];
  4191. var column1Row1 = matrix[4];
  4192. var column1Row2 = matrix[7];
  4193. var column2Row0 = matrix[2];
  4194. var column2Row1 = matrix[5];
  4195. var column2Row2 = matrix[8];
  4196. result[0] = column0Row0;
  4197. result[1] = column0Row1;
  4198. result[2] = column0Row2;
  4199. result[3] = column1Row0;
  4200. result[4] = column1Row1;
  4201. result[5] = column1Row2;
  4202. result[6] = column2Row0;
  4203. result[7] = column2Row1;
  4204. result[8] = column2Row2;
  4205. return result;
  4206. };
  4207. function computeFrobeniusNorm(matrix) {
  4208. var norm = 0.0;
  4209. for (var i = 0; i < 9; ++i) {
  4210. var temp = matrix[i];
  4211. norm += temp * temp;
  4212. }
  4213. return Math.sqrt(norm);
  4214. }
  4215. var rowVal = [1, 0, 0];
  4216. var colVal = [2, 2, 1];
  4217. function offDiagonalFrobeniusNorm(matrix) {
  4218. // Computes the "off-diagonal" Frobenius norm.
  4219. // Assumes matrix is symmetric.
  4220. var norm = 0.0;
  4221. for (var i = 0; i < 3; ++i) {
  4222. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  4223. norm += 2.0 * temp * temp;
  4224. }
  4225. return Math.sqrt(norm);
  4226. }
  4227. function shurDecomposition(matrix, result) {
  4228. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  4229. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  4230. //
  4231. // The routine takes a matrix, which is assumed to be symmetric, and
  4232. // finds the largest off-diagonal term, and then creates
  4233. // a matrix (result) which can be used to help reduce it
  4234. var tolerance = CesiumMath.EPSILON15;
  4235. var maxDiagonal = 0.0;
  4236. var rotAxis = 1;
  4237. // find pivot (rotAxis) based on max diagonal of matrix
  4238. for (var i = 0; i < 3; ++i) {
  4239. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  4240. if (temp > maxDiagonal) {
  4241. rotAxis = i;
  4242. maxDiagonal = temp;
  4243. }
  4244. }
  4245. var c = 1.0;
  4246. var s = 0.0;
  4247. var p = rowVal[rotAxis];
  4248. var q = colVal[rotAxis];
  4249. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  4250. var qq = matrix[Matrix3.getElementIndex(q, q)];
  4251. var pp = matrix[Matrix3.getElementIndex(p, p)];
  4252. var qp = matrix[Matrix3.getElementIndex(q, p)];
  4253. var tau = (qq - pp) / 2.0 / qp;
  4254. var t;
  4255. if (tau < 0.0) {
  4256. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  4257. } else {
  4258. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  4259. }
  4260. c = 1.0 / Math.sqrt(1.0 + t * t);
  4261. s = t * c;
  4262. }
  4263. result = Matrix3.clone(Matrix3.IDENTITY, result);
  4264. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  4265. result[Matrix3.getElementIndex(q, p)] = s;
  4266. result[Matrix3.getElementIndex(p, q)] = -s;
  4267. return result;
  4268. }
  4269. var jMatrix = new Matrix3();
  4270. var jMatrixTranspose = new Matrix3();
  4271. /**
  4272. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  4273. * <p>
  4274. * Returns a diagonal matrix and unitary matrix such that:
  4275. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  4276. * </p>
  4277. * <p>
  4278. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  4279. * of the unitary matrix are the corresponding eigenvectors.
  4280. * </p>
  4281. *
  4282. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  4283. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  4284. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  4285. *
  4286. * @example
  4287. * var a = //... symetric matrix
  4288. * var result = {
  4289. * unitary : new Cesium.Matrix3(),
  4290. * diagonal : new Cesium.Matrix3()
  4291. * };
  4292. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  4293. *
  4294. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  4295. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  4296. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  4297. *
  4298. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  4299. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  4300. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  4301. */
  4302. Matrix3.computeEigenDecomposition = function(matrix, result) {
  4303. if (!defined(matrix)) {
  4304. throw new DeveloperError('matrix is required.');
  4305. }
  4306. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  4307. // section 8.4.3 The Classical Jacobi Algorithm
  4308. var tolerance = CesiumMath.EPSILON20;
  4309. var maxSweeps = 10;
  4310. var count = 0;
  4311. var sweep = 0;
  4312. if (!defined(result)) {
  4313. result = {};
  4314. }
  4315. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  4316. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  4317. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  4318. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  4319. shurDecomposition(diagMatrix, jMatrix);
  4320. Matrix3.transpose(jMatrix, jMatrixTranspose);
  4321. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  4322. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  4323. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  4324. if (++count > 2) {
  4325. ++sweep;
  4326. count = 0;
  4327. }
  4328. }
  4329. return result;
  4330. };
  4331. /**
  4332. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  4333. *
  4334. * @param {Matrix3} matrix The matrix with signed elements.
  4335. * @param {Matrix3} result The object onto which to store the result.
  4336. * @returns {Matrix3} The modified result parameter.
  4337. */
  4338. Matrix3.abs = function(matrix, result) {
  4339. if (!defined(matrix)) {
  4340. throw new DeveloperError('matrix is required');
  4341. }
  4342. if (!defined(result)) {
  4343. throw new DeveloperError('result is required');
  4344. }
  4345. result[0] = Math.abs(matrix[0]);
  4346. result[1] = Math.abs(matrix[1]);
  4347. result[2] = Math.abs(matrix[2]);
  4348. result[3] = Math.abs(matrix[3]);
  4349. result[4] = Math.abs(matrix[4]);
  4350. result[5] = Math.abs(matrix[5]);
  4351. result[6] = Math.abs(matrix[6]);
  4352. result[7] = Math.abs(matrix[7]);
  4353. result[8] = Math.abs(matrix[8]);
  4354. return result;
  4355. };
  4356. /**
  4357. * Computes the determinant of the provided matrix.
  4358. *
  4359. * @param {Matrix3} matrix The matrix to use.
  4360. * @returns {Number} The value of the determinant of the matrix.
  4361. */
  4362. Matrix3.determinant = function(matrix) {
  4363. if (!defined(matrix)) {
  4364. throw new DeveloperError('matrix is required');
  4365. }
  4366. var m11 = matrix[0];
  4367. var m21 = matrix[3];
  4368. var m31 = matrix[6];
  4369. var m12 = matrix[1];
  4370. var m22 = matrix[4];
  4371. var m32 = matrix[7];
  4372. var m13 = matrix[2];
  4373. var m23 = matrix[5];
  4374. var m33 = matrix[8];
  4375. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  4376. };
  4377. /**
  4378. * Computes the inverse of the provided matrix.
  4379. *
  4380. * @param {Matrix3} matrix The matrix to invert.
  4381. * @param {Matrix3} result The object onto which to store the result.
  4382. * @returns {Matrix3} The modified result parameter.
  4383. *
  4384. * @exception {DeveloperError} matrix is not invertible.
  4385. */
  4386. Matrix3.inverse = function(matrix, result) {
  4387. if (!defined(matrix)) {
  4388. throw new DeveloperError('matrix is required');
  4389. }
  4390. if (!defined(result)) {
  4391. throw new DeveloperError('result is required');
  4392. }
  4393. var m11 = matrix[0];
  4394. var m21 = matrix[1];
  4395. var m31 = matrix[2];
  4396. var m12 = matrix[3];
  4397. var m22 = matrix[4];
  4398. var m32 = matrix[5];
  4399. var m13 = matrix[6];
  4400. var m23 = matrix[7];
  4401. var m33 = matrix[8];
  4402. var determinant = Matrix3.determinant(matrix);
  4403. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  4404. throw new DeveloperError('matrix is not invertible');
  4405. }
  4406. result[0] = m22 * m33 - m23 * m32;
  4407. result[1] = m23 * m31 - m21 * m33;
  4408. result[2] = m21 * m32 - m22 * m31;
  4409. result[3] = m13 * m32 - m12 * m33;
  4410. result[4] = m11 * m33 - m13 * m31;
  4411. result[5] = m12 * m31 - m11 * m32;
  4412. result[6] = m12 * m23 - m13 * m22;
  4413. result[7] = m13 * m21 - m11 * m23;
  4414. result[8] = m11 * m22 - m12 * m21;
  4415. var scale = 1.0 / determinant;
  4416. return Matrix3.multiplyByScalar(result, scale, result);
  4417. };
  4418. /**
  4419. * Compares the provided matrices componentwise and returns
  4420. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4421. *
  4422. * @param {Matrix3} [left] The first matrix.
  4423. * @param {Matrix3} [right] The second matrix.
  4424. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  4425. */
  4426. Matrix3.equals = function(left, right) {
  4427. return (left === right) ||
  4428. (defined(left) &&
  4429. defined(right) &&
  4430. left[0] === right[0] &&
  4431. left[1] === right[1] &&
  4432. left[2] === right[2] &&
  4433. left[3] === right[3] &&
  4434. left[4] === right[4] &&
  4435. left[5] === right[5] &&
  4436. left[6] === right[6] &&
  4437. left[7] === right[7] &&
  4438. left[8] === right[8]);
  4439. };
  4440. /**
  4441. * Compares the provided matrices componentwise and returns
  4442. * <code>true</code> if they are within the provided epsilon,
  4443. * <code>false</code> otherwise.
  4444. *
  4445. * @param {Matrix3} [left] The first matrix.
  4446. * @param {Matrix3} [right] The second matrix.
  4447. * @param {Number} epsilon The epsilon to use for equality testing.
  4448. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  4449. */
  4450. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  4451. if (typeof epsilon !== 'number') {
  4452. throw new DeveloperError('epsilon must be a number');
  4453. }
  4454. return (left === right) ||
  4455. (defined(left) &&
  4456. defined(right) &&
  4457. Math.abs(left[0] - right[0]) <= epsilon &&
  4458. Math.abs(left[1] - right[1]) <= epsilon &&
  4459. Math.abs(left[2] - right[2]) <= epsilon &&
  4460. Math.abs(left[3] - right[3]) <= epsilon &&
  4461. Math.abs(left[4] - right[4]) <= epsilon &&
  4462. Math.abs(left[5] - right[5]) <= epsilon &&
  4463. Math.abs(left[6] - right[6]) <= epsilon &&
  4464. Math.abs(left[7] - right[7]) <= epsilon &&
  4465. Math.abs(left[8] - right[8]) <= epsilon);
  4466. };
  4467. /**
  4468. * An immutable Matrix3 instance initialized to the identity matrix.
  4469. *
  4470. * @type {Matrix3}
  4471. * @constant
  4472. */
  4473. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  4474. 0.0, 1.0, 0.0,
  4475. 0.0, 0.0, 1.0));
  4476. /**
  4477. * An immutable Matrix3 instance initialized to the zero matrix.
  4478. *
  4479. * @type {Matrix3}
  4480. * @constant
  4481. */
  4482. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  4483. 0.0, 0.0, 0.0,
  4484. 0.0, 0.0, 0.0));
  4485. /**
  4486. * The index into Matrix3 for column 0, row 0.
  4487. *
  4488. * @type {Number}
  4489. * @constant
  4490. */
  4491. Matrix3.COLUMN0ROW0 = 0;
  4492. /**
  4493. * The index into Matrix3 for column 0, row 1.
  4494. *
  4495. * @type {Number}
  4496. * @constant
  4497. */
  4498. Matrix3.COLUMN0ROW1 = 1;
  4499. /**
  4500. * The index into Matrix3 for column 0, row 2.
  4501. *
  4502. * @type {Number}
  4503. * @constant
  4504. */
  4505. Matrix3.COLUMN0ROW2 = 2;
  4506. /**
  4507. * The index into Matrix3 for column 1, row 0.
  4508. *
  4509. * @type {Number}
  4510. * @constant
  4511. */
  4512. Matrix3.COLUMN1ROW0 = 3;
  4513. /**
  4514. * The index into Matrix3 for column 1, row 1.
  4515. *
  4516. * @type {Number}
  4517. * @constant
  4518. */
  4519. Matrix3.COLUMN1ROW1 = 4;
  4520. /**
  4521. * The index into Matrix3 for column 1, row 2.
  4522. *
  4523. * @type {Number}
  4524. * @constant
  4525. */
  4526. Matrix3.COLUMN1ROW2 = 5;
  4527. /**
  4528. * The index into Matrix3 for column 2, row 0.
  4529. *
  4530. * @type {Number}
  4531. * @constant
  4532. */
  4533. Matrix3.COLUMN2ROW0 = 6;
  4534. /**
  4535. * The index into Matrix3 for column 2, row 1.
  4536. *
  4537. * @type {Number}
  4538. * @constant
  4539. */
  4540. Matrix3.COLUMN2ROW1 = 7;
  4541. /**
  4542. * The index into Matrix3 for column 2, row 2.
  4543. *
  4544. * @type {Number}
  4545. * @constant
  4546. */
  4547. Matrix3.COLUMN2ROW2 = 8;
  4548. defineProperties(Matrix3.prototype, {
  4549. /**
  4550. * Gets the number of items in the collection.
  4551. * @memberof Matrix3.prototype
  4552. *
  4553. * @type {Number}
  4554. */
  4555. length : {
  4556. get : function() {
  4557. return Matrix3.packedLength;
  4558. }
  4559. }
  4560. });
  4561. /**
  4562. * Duplicates the provided Matrix3 instance.
  4563. *
  4564. * @param {Matrix3} [result] The object onto which to store the result.
  4565. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  4566. */
  4567. Matrix3.prototype.clone = function(result) {
  4568. return Matrix3.clone(this, result);
  4569. };
  4570. /**
  4571. * Compares this matrix to the provided matrix componentwise and returns
  4572. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4573. *
  4574. * @param {Matrix3} [right] The right hand side matrix.
  4575. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  4576. */
  4577. Matrix3.prototype.equals = function(right) {
  4578. return Matrix3.equals(this, right);
  4579. };
  4580. /**
  4581. * @private
  4582. */
  4583. Matrix3.equalsArray = function(matrix, array, offset) {
  4584. return matrix[0] === array[offset] &&
  4585. matrix[1] === array[offset + 1] &&
  4586. matrix[2] === array[offset + 2] &&
  4587. matrix[3] === array[offset + 3] &&
  4588. matrix[4] === array[offset + 4] &&
  4589. matrix[5] === array[offset + 5] &&
  4590. matrix[6] === array[offset + 6] &&
  4591. matrix[7] === array[offset + 7] &&
  4592. matrix[8] === array[offset + 8];
  4593. };
  4594. /**
  4595. * Compares this matrix to the provided matrix componentwise and returns
  4596. * <code>true</code> if they are within the provided epsilon,
  4597. * <code>false</code> otherwise.
  4598. *
  4599. * @param {Matrix3} [right] The right hand side matrix.
  4600. * @param {Number} epsilon The epsilon to use for equality testing.
  4601. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  4602. */
  4603. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  4604. return Matrix3.equalsEpsilon(this, right, epsilon);
  4605. };
  4606. /**
  4607. * Creates a string representing this Matrix with each row being
  4608. * on a separate line and in the format '(column0, column1, column2)'.
  4609. *
  4610. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  4611. */
  4612. Matrix3.prototype.toString = function() {
  4613. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  4614. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  4615. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  4616. };
  4617. return Matrix3;
  4618. });
  4619. /*global define*/
  4620. define('Core/Cartesian4',[
  4621. './defaultValue',
  4622. './defined',
  4623. './DeveloperError',
  4624. './freezeObject',
  4625. './Math'
  4626. ], function(
  4627. defaultValue,
  4628. defined,
  4629. DeveloperError,
  4630. freezeObject,
  4631. CesiumMath) {
  4632. 'use strict';
  4633. /**
  4634. * A 4D Cartesian point.
  4635. * @alias Cartesian4
  4636. * @constructor
  4637. *
  4638. * @param {Number} [x=0.0] The X component.
  4639. * @param {Number} [y=0.0] The Y component.
  4640. * @param {Number} [z=0.0] The Z component.
  4641. * @param {Number} [w=0.0] The W component.
  4642. *
  4643. * @see Cartesian2
  4644. * @see Cartesian3
  4645. * @see Packable
  4646. */
  4647. function Cartesian4(x, y, z, w) {
  4648. /**
  4649. * The X component.
  4650. * @type {Number}
  4651. * @default 0.0
  4652. */
  4653. this.x = defaultValue(x, 0.0);
  4654. /**
  4655. * The Y component.
  4656. * @type {Number}
  4657. * @default 0.0
  4658. */
  4659. this.y = defaultValue(y, 0.0);
  4660. /**
  4661. * The Z component.
  4662. * @type {Number}
  4663. * @default 0.0
  4664. */
  4665. this.z = defaultValue(z, 0.0);
  4666. /**
  4667. * The W component.
  4668. * @type {Number}
  4669. * @default 0.0
  4670. */
  4671. this.w = defaultValue(w, 0.0);
  4672. }
  4673. /**
  4674. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  4675. *
  4676. * @param {Number} x The x coordinate.
  4677. * @param {Number} y The y coordinate.
  4678. * @param {Number} z The z coordinate.
  4679. * @param {Number} w The w coordinate.
  4680. * @param {Cartesian4} [result] The object onto which to store the result.
  4681. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4682. */
  4683. Cartesian4.fromElements = function(x, y, z, w, result) {
  4684. if (!defined(result)) {
  4685. return new Cartesian4(x, y, z, w);
  4686. }
  4687. result.x = x;
  4688. result.y = y;
  4689. result.z = z;
  4690. result.w = w;
  4691. return result;
  4692. };
  4693. /**
  4694. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  4695. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  4696. *
  4697. * @param {Color} color The source color.
  4698. * @param {Cartesian4} [result] The object onto which to store the result.
  4699. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4700. */
  4701. Cartesian4.fromColor = function(color, result) {
  4702. if (!defined(color)) {
  4703. throw new DeveloperError('color is required');
  4704. }
  4705. if (!defined(result)) {
  4706. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  4707. }
  4708. result.x = color.red;
  4709. result.y = color.green;
  4710. result.z = color.blue;
  4711. result.w = color.alpha;
  4712. return result;
  4713. };
  4714. /**
  4715. * Duplicates a Cartesian4 instance.
  4716. *
  4717. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  4718. * @param {Cartesian4} [result] The object onto which to store the result.
  4719. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  4720. */
  4721. Cartesian4.clone = function(cartesian, result) {
  4722. if (!defined(cartesian)) {
  4723. return undefined;
  4724. }
  4725. if (!defined(result)) {
  4726. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4727. }
  4728. result.x = cartesian.x;
  4729. result.y = cartesian.y;
  4730. result.z = cartesian.z;
  4731. result.w = cartesian.w;
  4732. return result;
  4733. };
  4734. /**
  4735. * The number of elements used to pack the object into an array.
  4736. * @type {Number}
  4737. */
  4738. Cartesian4.packedLength = 4;
  4739. /**
  4740. * Stores the provided instance into the provided array.
  4741. *
  4742. * @param {Cartesian4} value The value to pack.
  4743. * @param {Number[]} array The array to pack into.
  4744. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4745. *
  4746. * @returns {Number[]} The array that was packed into
  4747. */
  4748. Cartesian4.pack = function(value, array, startingIndex) {
  4749. if (!defined(value)) {
  4750. throw new DeveloperError('value is required');
  4751. }
  4752. if (!defined(array)) {
  4753. throw new DeveloperError('array is required');
  4754. }
  4755. startingIndex = defaultValue(startingIndex, 0);
  4756. array[startingIndex++] = value.x;
  4757. array[startingIndex++] = value.y;
  4758. array[startingIndex++] = value.z;
  4759. array[startingIndex] = value.w;
  4760. return array;
  4761. };
  4762. /**
  4763. * Retrieves an instance from a packed array.
  4764. *
  4765. * @param {Number[]} array The packed array.
  4766. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4767. * @param {Cartesian4} [result] The object into which to store the result.
  4768. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4769. */
  4770. Cartesian4.unpack = function(array, startingIndex, result) {
  4771. if (!defined(array)) {
  4772. throw new DeveloperError('array is required');
  4773. }
  4774. startingIndex = defaultValue(startingIndex, 0);
  4775. if (!defined(result)) {
  4776. result = new Cartesian4();
  4777. }
  4778. result.x = array[startingIndex++];
  4779. result.y = array[startingIndex++];
  4780. result.z = array[startingIndex++];
  4781. result.w = array[startingIndex];
  4782. return result;
  4783. };
  4784. /**
  4785. * Flattens an array of Cartesian4s into and array of components.
  4786. *
  4787. * @param {Cartesian4[]} array The array of cartesians to pack.
  4788. * @param {Number[]} result The array onto which to store the result.
  4789. * @returns {Number[]} The packed array.
  4790. */
  4791. Cartesian4.packArray = function(array, result) {
  4792. if (!defined(array)) {
  4793. throw new DeveloperError('array is required');
  4794. }
  4795. var length = array.length;
  4796. if (!defined(result)) {
  4797. result = new Array(length * 4);
  4798. } else {
  4799. result.length = length * 4;
  4800. }
  4801. for (var i = 0; i < length; ++i) {
  4802. Cartesian4.pack(array[i], result, i * 4);
  4803. }
  4804. return result;
  4805. };
  4806. /**
  4807. * Unpacks an array of cartesian components into and array of Cartesian4s.
  4808. *
  4809. * @param {Number[]} array The array of components to unpack.
  4810. * @param {Cartesian4[]} result The array onto which to store the result.
  4811. * @returns {Cartesian4[]} The unpacked array.
  4812. */
  4813. Cartesian4.unpackArray = function(array, result) {
  4814. if (!defined(array)) {
  4815. throw new DeveloperError('array is required');
  4816. }
  4817. var length = array.length;
  4818. if (!defined(result)) {
  4819. result = new Array(length / 4);
  4820. } else {
  4821. result.length = length / 4;
  4822. }
  4823. for (var i = 0; i < length; i += 4) {
  4824. var index = i / 4;
  4825. result[index] = Cartesian4.unpack(array, i, result[index]);
  4826. }
  4827. return result;
  4828. };
  4829. /**
  4830. * Creates a Cartesian4 from four consecutive elements in an array.
  4831. * @function
  4832. *
  4833. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  4834. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  4835. * @param {Cartesian4} [result] The object onto which to store the result.
  4836. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4837. *
  4838. * @example
  4839. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  4840. * var v = [1.0, 2.0, 3.0, 4.0];
  4841. * var p = Cesium.Cartesian4.fromArray(v);
  4842. *
  4843. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  4844. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  4845. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  4846. */
  4847. Cartesian4.fromArray = Cartesian4.unpack;
  4848. /**
  4849. * Computes the value of the maximum component for the supplied Cartesian.
  4850. *
  4851. * @param {Cartesian4} cartesian The cartesian to use.
  4852. * @returns {Number} The value of the maximum component.
  4853. */
  4854. Cartesian4.maximumComponent = function(cartesian) {
  4855. if (!defined(cartesian)) {
  4856. throw new DeveloperError('cartesian is required');
  4857. }
  4858. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4859. };
  4860. /**
  4861. * Computes the value of the minimum component for the supplied Cartesian.
  4862. *
  4863. * @param {Cartesian4} cartesian The cartesian to use.
  4864. * @returns {Number} The value of the minimum component.
  4865. */
  4866. Cartesian4.minimumComponent = function(cartesian) {
  4867. if (!defined(cartesian)) {
  4868. throw new DeveloperError('cartesian is required');
  4869. }
  4870. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4871. };
  4872. /**
  4873. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  4874. *
  4875. * @param {Cartesian4} first A cartesian to compare.
  4876. * @param {Cartesian4} second A cartesian to compare.
  4877. * @param {Cartesian4} result The object into which to store the result.
  4878. * @returns {Cartesian4} A cartesian with the minimum components.
  4879. */
  4880. Cartesian4.minimumByComponent = function(first, second, result) {
  4881. if (!defined(first)) {
  4882. throw new DeveloperError('first is required.');
  4883. }
  4884. if (!defined(second)) {
  4885. throw new DeveloperError('second is required.');
  4886. }
  4887. if (!defined(result)) {
  4888. throw new DeveloperError('result is required.');
  4889. }
  4890. result.x = Math.min(first.x, second.x);
  4891. result.y = Math.min(first.y, second.y);
  4892. result.z = Math.min(first.z, second.z);
  4893. result.w = Math.min(first.w, second.w);
  4894. return result;
  4895. };
  4896. /**
  4897. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  4898. *
  4899. * @param {Cartesian4} first A cartesian to compare.
  4900. * @param {Cartesian4} second A cartesian to compare.
  4901. * @param {Cartesian4} result The object into which to store the result.
  4902. * @returns {Cartesian4} A cartesian with the maximum components.
  4903. */
  4904. Cartesian4.maximumByComponent = function(first, second, result) {
  4905. if (!defined(first)) {
  4906. throw new DeveloperError('first is required.');
  4907. }
  4908. if (!defined(second)) {
  4909. throw new DeveloperError('second is required.');
  4910. }
  4911. if (!defined(result)) {
  4912. throw new DeveloperError('result is required.');
  4913. }
  4914. result.x = Math.max(first.x, second.x);
  4915. result.y = Math.max(first.y, second.y);
  4916. result.z = Math.max(first.z, second.z);
  4917. result.w = Math.max(first.w, second.w);
  4918. return result;
  4919. };
  4920. /**
  4921. * Computes the provided Cartesian's squared magnitude.
  4922. *
  4923. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  4924. * @returns {Number} The squared magnitude.
  4925. */
  4926. Cartesian4.magnitudeSquared = function(cartesian) {
  4927. if (!defined(cartesian)) {
  4928. throw new DeveloperError('cartesian is required');
  4929. }
  4930. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  4931. };
  4932. /**
  4933. * Computes the Cartesian's magnitude (length).
  4934. *
  4935. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  4936. * @returns {Number} The magnitude.
  4937. */
  4938. Cartesian4.magnitude = function(cartesian) {
  4939. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  4940. };
  4941. var distanceScratch = new Cartesian4();
  4942. /**
  4943. * Computes the 4-space distance between two points.
  4944. *
  4945. * @param {Cartesian4} left The first point to compute the distance from.
  4946. * @param {Cartesian4} right The second point to compute the distance to.
  4947. * @returns {Number} The distance between two points.
  4948. *
  4949. * @example
  4950. * // Returns 1.0
  4951. * var d = Cesium.Cartesian4.distance(
  4952. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  4953. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  4954. */
  4955. Cartesian4.distance = function(left, right) {
  4956. if (!defined(left) || !defined(right)) {
  4957. throw new DeveloperError('left and right are required.');
  4958. }
  4959. Cartesian4.subtract(left, right, distanceScratch);
  4960. return Cartesian4.magnitude(distanceScratch);
  4961. };
  4962. /**
  4963. * Computes the squared distance between two points. Comparing squared distances
  4964. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  4965. *
  4966. * @param {Cartesian4} left The first point to compute the distance from.
  4967. * @param {Cartesian4} right The second point to compute the distance to.
  4968. * @returns {Number} The distance between two points.
  4969. *
  4970. * @example
  4971. * // Returns 4.0, not 2.0
  4972. * var d = Cesium.Cartesian4.distance(
  4973. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  4974. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  4975. */
  4976. Cartesian4.distanceSquared = function(left, right) {
  4977. if (!defined(left) || !defined(right)) {
  4978. throw new DeveloperError('left and right are required.');
  4979. }
  4980. Cartesian4.subtract(left, right, distanceScratch);
  4981. return Cartesian4.magnitudeSquared(distanceScratch);
  4982. };
  4983. /**
  4984. * Computes the normalized form of the supplied Cartesian.
  4985. *
  4986. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  4987. * @param {Cartesian4} result The object onto which to store the result.
  4988. * @returns {Cartesian4} The modified result parameter.
  4989. */
  4990. Cartesian4.normalize = function(cartesian, result) {
  4991. if (!defined(cartesian)) {
  4992. throw new DeveloperError('cartesian is required');
  4993. }
  4994. if (!defined(result)) {
  4995. throw new DeveloperError('result is required');
  4996. }
  4997. var magnitude = Cartesian4.magnitude(cartesian);
  4998. result.x = cartesian.x / magnitude;
  4999. result.y = cartesian.y / magnitude;
  5000. result.z = cartesian.z / magnitude;
  5001. result.w = cartesian.w / magnitude;
  5002. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  5003. throw new DeveloperError('normalized result is not a number');
  5004. }
  5005. return result;
  5006. };
  5007. /**
  5008. * Computes the dot (scalar) product of two Cartesians.
  5009. *
  5010. * @param {Cartesian4} left The first Cartesian.
  5011. * @param {Cartesian4} right The second Cartesian.
  5012. * @returns {Number} The dot product.
  5013. */
  5014. Cartesian4.dot = function(left, right) {
  5015. if (!defined(left)) {
  5016. throw new DeveloperError('left is required');
  5017. }
  5018. if (!defined(right)) {
  5019. throw new DeveloperError('right is required');
  5020. }
  5021. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  5022. };
  5023. /**
  5024. * Computes the componentwise product of two Cartesians.
  5025. *
  5026. * @param {Cartesian4} left The first Cartesian.
  5027. * @param {Cartesian4} right The second Cartesian.
  5028. * @param {Cartesian4} result The object onto which to store the result.
  5029. * @returns {Cartesian4} The modified result parameter.
  5030. */
  5031. Cartesian4.multiplyComponents = function(left, right, result) {
  5032. if (!defined(left)) {
  5033. throw new DeveloperError('left is required');
  5034. }
  5035. if (!defined(right)) {
  5036. throw new DeveloperError('right is required');
  5037. }
  5038. if (!defined(result)) {
  5039. throw new DeveloperError('result is required');
  5040. }
  5041. result.x = left.x * right.x;
  5042. result.y = left.y * right.y;
  5043. result.z = left.z * right.z;
  5044. result.w = left.w * right.w;
  5045. return result;
  5046. };
  5047. /**
  5048. * Computes the componentwise quotient of two Cartesians.
  5049. *
  5050. * @param {Cartesian4} left The first Cartesian.
  5051. * @param {Cartesian4} right The second Cartesian.
  5052. * @param {Cartesian4} result The object onto which to store the result.
  5053. * @returns {Cartesian4} The modified result parameter.
  5054. */
  5055. Cartesian4.divideComponents = function(left, right, result) {
  5056. if (!defined(left)) {
  5057. throw new DeveloperError('left is required');
  5058. }
  5059. if (!defined(right)) {
  5060. throw new DeveloperError('right is required');
  5061. }
  5062. if (!defined(result)) {
  5063. throw new DeveloperError('result is required');
  5064. }
  5065. result.x = left.x / right.x;
  5066. result.y = left.y / right.y;
  5067. result.z = left.z / right.z;
  5068. result.w = left.w / right.w;
  5069. return result;
  5070. };
  5071. /**
  5072. * Computes the componentwise sum of two Cartesians.
  5073. *
  5074. * @param {Cartesian4} left The first Cartesian.
  5075. * @param {Cartesian4} right The second Cartesian.
  5076. * @param {Cartesian4} result The object onto which to store the result.
  5077. * @returns {Cartesian4} The modified result parameter.
  5078. */
  5079. Cartesian4.add = function(left, right, result) {
  5080. if (!defined(left)) {
  5081. throw new DeveloperError('left is required');
  5082. }
  5083. if (!defined(right)) {
  5084. throw new DeveloperError('right is required');
  5085. }
  5086. if (!defined(result)) {
  5087. throw new DeveloperError('result is required');
  5088. }
  5089. result.x = left.x + right.x;
  5090. result.y = left.y + right.y;
  5091. result.z = left.z + right.z;
  5092. result.w = left.w + right.w;
  5093. return result;
  5094. };
  5095. /**
  5096. * Computes the componentwise difference of two Cartesians.
  5097. *
  5098. * @param {Cartesian4} left The first Cartesian.
  5099. * @param {Cartesian4} right The second Cartesian.
  5100. * @param {Cartesian4} result The object onto which to store the result.
  5101. * @returns {Cartesian4} The modified result parameter.
  5102. */
  5103. Cartesian4.subtract = function(left, right, result) {
  5104. if (!defined(left)) {
  5105. throw new DeveloperError('left is required');
  5106. }
  5107. if (!defined(right)) {
  5108. throw new DeveloperError('right is required');
  5109. }
  5110. if (!defined(result)) {
  5111. throw new DeveloperError('result is required');
  5112. }
  5113. result.x = left.x - right.x;
  5114. result.y = left.y - right.y;
  5115. result.z = left.z - right.z;
  5116. result.w = left.w - right.w;
  5117. return result;
  5118. };
  5119. /**
  5120. * Multiplies the provided Cartesian componentwise by the provided scalar.
  5121. *
  5122. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  5123. * @param {Number} scalar The scalar to multiply with.
  5124. * @param {Cartesian4} result The object onto which to store the result.
  5125. * @returns {Cartesian4} The modified result parameter.
  5126. */
  5127. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  5128. if (!defined(cartesian)) {
  5129. throw new DeveloperError('cartesian is required');
  5130. }
  5131. if (typeof scalar !== 'number') {
  5132. throw new DeveloperError('scalar is required and must be a number.');
  5133. }
  5134. if (!defined(result)) {
  5135. throw new DeveloperError('result is required');
  5136. }
  5137. result.x = cartesian.x * scalar;
  5138. result.y = cartesian.y * scalar;
  5139. result.z = cartesian.z * scalar;
  5140. result.w = cartesian.w * scalar;
  5141. return result;
  5142. };
  5143. /**
  5144. * Divides the provided Cartesian componentwise by the provided scalar.
  5145. *
  5146. * @param {Cartesian4} cartesian The Cartesian to be divided.
  5147. * @param {Number} scalar The scalar to divide by.
  5148. * @param {Cartesian4} result The object onto which to store the result.
  5149. * @returns {Cartesian4} The modified result parameter.
  5150. */
  5151. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  5152. if (!defined(cartesian)) {
  5153. throw new DeveloperError('cartesian is required');
  5154. }
  5155. if (typeof scalar !== 'number') {
  5156. throw new DeveloperError('scalar is required and must be a number.');
  5157. }
  5158. if (!defined(result)) {
  5159. throw new DeveloperError('result is required');
  5160. }
  5161. result.x = cartesian.x / scalar;
  5162. result.y = cartesian.y / scalar;
  5163. result.z = cartesian.z / scalar;
  5164. result.w = cartesian.w / scalar;
  5165. return result;
  5166. };
  5167. /**
  5168. * Negates the provided Cartesian.
  5169. *
  5170. * @param {Cartesian4} cartesian The Cartesian to be negated.
  5171. * @param {Cartesian4} result The object onto which to store the result.
  5172. * @returns {Cartesian4} The modified result parameter.
  5173. */
  5174. Cartesian4.negate = function(cartesian, result) {
  5175. if (!defined(cartesian)) {
  5176. throw new DeveloperError('cartesian is required');
  5177. }
  5178. if (!defined(result)) {
  5179. throw new DeveloperError('result is required');
  5180. }
  5181. result.x = -cartesian.x;
  5182. result.y = -cartesian.y;
  5183. result.z = -cartesian.z;
  5184. result.w = -cartesian.w;
  5185. return result;
  5186. };
  5187. /**
  5188. * Computes the absolute value of the provided Cartesian.
  5189. *
  5190. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  5191. * @param {Cartesian4} result The object onto which to store the result.
  5192. * @returns {Cartesian4} The modified result parameter.
  5193. */
  5194. Cartesian4.abs = function(cartesian, result) {
  5195. if (!defined(cartesian)) {
  5196. throw new DeveloperError('cartesian is required');
  5197. }
  5198. if (!defined(result)) {
  5199. throw new DeveloperError('result is required');
  5200. }
  5201. result.x = Math.abs(cartesian.x);
  5202. result.y = Math.abs(cartesian.y);
  5203. result.z = Math.abs(cartesian.z);
  5204. result.w = Math.abs(cartesian.w);
  5205. return result;
  5206. };
  5207. var lerpScratch = new Cartesian4();
  5208. /**
  5209. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  5210. *
  5211. * @param {Cartesian4} start The value corresponding to t at 0.0.
  5212. * @param {Cartesian4}end The value corresponding to t at 1.0.
  5213. * @param {Number} t The point along t at which to interpolate.
  5214. * @param {Cartesian4} result The object onto which to store the result.
  5215. * @returns {Cartesian4} The modified result parameter.
  5216. */
  5217. Cartesian4.lerp = function(start, end, t, result) {
  5218. if (!defined(start)) {
  5219. throw new DeveloperError('start is required.');
  5220. }
  5221. if (!defined(end)) {
  5222. throw new DeveloperError('end is required.');
  5223. }
  5224. if (typeof t !== 'number') {
  5225. throw new DeveloperError('t is required and must be a number.');
  5226. }
  5227. if (!defined(result)) {
  5228. throw new DeveloperError('result is required.');
  5229. }
  5230. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  5231. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  5232. return Cartesian4.add(lerpScratch, result, result);
  5233. };
  5234. var mostOrthogonalAxisScratch = new Cartesian4();
  5235. /**
  5236. * Returns the axis that is most orthogonal to the provided Cartesian.
  5237. *
  5238. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  5239. * @param {Cartesian4} result The object onto which to store the result.
  5240. * @returns {Cartesian4} The most orthogonal axis.
  5241. */
  5242. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  5243. if (!defined(cartesian)) {
  5244. throw new DeveloperError('cartesian is required.');
  5245. }
  5246. if (!defined(result)) {
  5247. throw new DeveloperError('result is required.');
  5248. }
  5249. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  5250. Cartesian4.abs(f, f);
  5251. if (f.x <= f.y) {
  5252. if (f.x <= f.z) {
  5253. if (f.x <= f.w) {
  5254. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  5255. } else {
  5256. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5257. }
  5258. } else if (f.z <= f.w) {
  5259. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  5260. } else {
  5261. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5262. }
  5263. } else if (f.y <= f.z) {
  5264. if (f.y <= f.w) {
  5265. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  5266. } else {
  5267. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5268. }
  5269. } else if (f.z <= f.w) {
  5270. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  5271. } else {
  5272. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5273. }
  5274. return result;
  5275. };
  5276. /**
  5277. * Compares the provided Cartesians componentwise and returns
  5278. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5279. *
  5280. * @param {Cartesian4} [left] The first Cartesian.
  5281. * @param {Cartesian4} [right] The second Cartesian.
  5282. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5283. */
  5284. Cartesian4.equals = function(left, right) {
  5285. return (left === right) ||
  5286. ((defined(left)) &&
  5287. (defined(right)) &&
  5288. (left.x === right.x) &&
  5289. (left.y === right.y) &&
  5290. (left.z === right.z) &&
  5291. (left.w === right.w));
  5292. };
  5293. /**
  5294. * @private
  5295. */
  5296. Cartesian4.equalsArray = function(cartesian, array, offset) {
  5297. return cartesian.x === array[offset] &&
  5298. cartesian.y === array[offset + 1] &&
  5299. cartesian.z === array[offset + 2] &&
  5300. cartesian.w === array[offset + 3];
  5301. };
  5302. /**
  5303. * Compares the provided Cartesians componentwise and returns
  5304. * <code>true</code> if they pass an absolute or relative tolerance test,
  5305. * <code>false</code> otherwise.
  5306. *
  5307. * @param {Cartesian4} [left] The first Cartesian.
  5308. * @param {Cartesian4} [right] The second Cartesian.
  5309. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  5310. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  5311. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  5312. */
  5313. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  5314. return (left === right) ||
  5315. (defined(left) &&
  5316. defined(right) &&
  5317. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  5318. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  5319. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  5320. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  5321. };
  5322. /**
  5323. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  5324. *
  5325. * @type {Cartesian4}
  5326. * @constant
  5327. */
  5328. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  5329. /**
  5330. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  5331. *
  5332. * @type {Cartesian4}
  5333. * @constant
  5334. */
  5335. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  5336. /**
  5337. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  5338. *
  5339. * @type {Cartesian4}
  5340. * @constant
  5341. */
  5342. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  5343. /**
  5344. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  5345. *
  5346. * @type {Cartesian4}
  5347. * @constant
  5348. */
  5349. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  5350. /**
  5351. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  5352. *
  5353. * @type {Cartesian4}
  5354. * @constant
  5355. */
  5356. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  5357. /**
  5358. * Duplicates this Cartesian4 instance.
  5359. *
  5360. * @param {Cartesian4} [result] The object onto which to store the result.
  5361. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5362. */
  5363. Cartesian4.prototype.clone = function(result) {
  5364. return Cartesian4.clone(this, result);
  5365. };
  5366. /**
  5367. * Compares this Cartesian against the provided Cartesian componentwise and returns
  5368. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5369. *
  5370. * @param {Cartesian4} [right] The right hand side Cartesian.
  5371. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5372. */
  5373. Cartesian4.prototype.equals = function(right) {
  5374. return Cartesian4.equals(this, right);
  5375. };
  5376. /**
  5377. * Compares this Cartesian against the provided Cartesian componentwise and returns
  5378. * <code>true</code> if they pass an absolute or relative tolerance test,
  5379. * <code>false</code> otherwise.
  5380. *
  5381. * @param {Cartesian4} [right] The right hand side Cartesian.
  5382. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  5383. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  5384. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  5385. */
  5386. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  5387. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  5388. };
  5389. /**
  5390. * Creates a string representing this Cartesian in the format '(x, y)'.
  5391. *
  5392. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  5393. */
  5394. Cartesian4.prototype.toString = function() {
  5395. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  5396. };
  5397. return Cartesian4;
  5398. });
  5399. /*global define*/
  5400. define('Core/RuntimeError',[
  5401. './defined'
  5402. ], function(
  5403. defined) {
  5404. 'use strict';
  5405. /**
  5406. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  5407. * out of memory, could not compile shader, etc. If a function may throw this
  5408. * exception, the calling code should be prepared to catch it.
  5409. * <br /><br />
  5410. * On the other hand, a {@link DeveloperError} indicates an exception due
  5411. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  5412. * calling code.
  5413. *
  5414. * @alias RuntimeError
  5415. * @constructor
  5416. * @extends Error
  5417. *
  5418. * @param {String} [message] The error message for this exception.
  5419. *
  5420. * @see DeveloperError
  5421. */
  5422. function RuntimeError(message) {
  5423. /**
  5424. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  5425. * @type {String}
  5426. * @readonly
  5427. */
  5428. this.name = 'RuntimeError';
  5429. /**
  5430. * The explanation for why this exception was thrown.
  5431. * @type {String}
  5432. * @readonly
  5433. */
  5434. this.message = message;
  5435. //Browsers such as IE don't have a stack property until you actually throw the error.
  5436. var stack;
  5437. try {
  5438. throw new Error();
  5439. } catch (e) {
  5440. stack = e.stack;
  5441. }
  5442. /**
  5443. * The stack trace of this exception, if available.
  5444. * @type {String}
  5445. * @readonly
  5446. */
  5447. this.stack = stack;
  5448. }
  5449. if (defined(Object.create)) {
  5450. RuntimeError.prototype = Object.create(Error.prototype);
  5451. RuntimeError.prototype.constructor = RuntimeError;
  5452. }
  5453. RuntimeError.prototype.toString = function() {
  5454. var str = this.name + ': ' + this.message;
  5455. if (defined(this.stack)) {
  5456. str += '\n' + this.stack.toString();
  5457. }
  5458. return str;
  5459. };
  5460. return RuntimeError;
  5461. });
  5462. /*global define*/
  5463. define('Core/Matrix4',[
  5464. './Cartesian3',
  5465. './Cartesian4',
  5466. './defaultValue',
  5467. './defined',
  5468. './defineProperties',
  5469. './DeveloperError',
  5470. './freezeObject',
  5471. './Math',
  5472. './Matrix3',
  5473. './RuntimeError'
  5474. ], function(
  5475. Cartesian3,
  5476. Cartesian4,
  5477. defaultValue,
  5478. defined,
  5479. defineProperties,
  5480. DeveloperError,
  5481. freezeObject,
  5482. CesiumMath,
  5483. Matrix3,
  5484. RuntimeError) {
  5485. 'use strict';
  5486. /**
  5487. * A 4x4 matrix, indexable as a column-major order array.
  5488. * Constructor parameters are in row-major order for code readability.
  5489. * @alias Matrix4
  5490. * @constructor
  5491. *
  5492. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  5493. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  5494. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  5495. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  5496. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  5497. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  5498. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  5499. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  5500. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  5501. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  5502. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  5503. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  5504. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  5505. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  5506. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  5507. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  5508. *
  5509. * @see Matrix4.fromColumnMajorArray
  5510. * @see Matrix4.fromRowMajorArray
  5511. * @see Matrix4.fromRotationTranslation
  5512. * @see Matrix4.fromTranslationRotationScale
  5513. * @see Matrix4.fromTranslationQuaternionRotationScale
  5514. * @see Matrix4.fromTranslation
  5515. * @see Matrix4.fromScale
  5516. * @see Matrix4.fromUniformScale
  5517. * @see Matrix4.fromCamera
  5518. * @see Matrix4.computePerspectiveFieldOfView
  5519. * @see Matrix4.computeOrthographicOffCenter
  5520. * @see Matrix4.computePerspectiveOffCenter
  5521. * @see Matrix4.computeInfinitePerspectiveOffCenter
  5522. * @see Matrix4.computeViewportTransformation
  5523. * @see Matrix4.computeView
  5524. * @see Matrix2
  5525. * @see Matrix3
  5526. * @see Packable
  5527. */
  5528. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  5529. column0Row1, column1Row1, column2Row1, column3Row1,
  5530. column0Row2, column1Row2, column2Row2, column3Row2,
  5531. column0Row3, column1Row3, column2Row3, column3Row3) {
  5532. this[0] = defaultValue(column0Row0, 0.0);
  5533. this[1] = defaultValue(column0Row1, 0.0);
  5534. this[2] = defaultValue(column0Row2, 0.0);
  5535. this[3] = defaultValue(column0Row3, 0.0);
  5536. this[4] = defaultValue(column1Row0, 0.0);
  5537. this[5] = defaultValue(column1Row1, 0.0);
  5538. this[6] = defaultValue(column1Row2, 0.0);
  5539. this[7] = defaultValue(column1Row3, 0.0);
  5540. this[8] = defaultValue(column2Row0, 0.0);
  5541. this[9] = defaultValue(column2Row1, 0.0);
  5542. this[10] = defaultValue(column2Row2, 0.0);
  5543. this[11] = defaultValue(column2Row3, 0.0);
  5544. this[12] = defaultValue(column3Row0, 0.0);
  5545. this[13] = defaultValue(column3Row1, 0.0);
  5546. this[14] = defaultValue(column3Row2, 0.0);
  5547. this[15] = defaultValue(column3Row3, 0.0);
  5548. }
  5549. /**
  5550. * The number of elements used to pack the object into an array.
  5551. * @type {Number}
  5552. */
  5553. Matrix4.packedLength = 16;
  5554. /**
  5555. * Stores the provided instance into the provided array.
  5556. *
  5557. * @param {Matrix4} value The value to pack.
  5558. * @param {Number[]} array The array to pack into.
  5559. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5560. *
  5561. * @returns {Number[]} The array that was packed into
  5562. */
  5563. Matrix4.pack = function(value, array, startingIndex) {
  5564. if (!defined(value)) {
  5565. throw new DeveloperError('value is required');
  5566. }
  5567. if (!defined(array)) {
  5568. throw new DeveloperError('array is required');
  5569. }
  5570. startingIndex = defaultValue(startingIndex, 0);
  5571. array[startingIndex++] = value[0];
  5572. array[startingIndex++] = value[1];
  5573. array[startingIndex++] = value[2];
  5574. array[startingIndex++] = value[3];
  5575. array[startingIndex++] = value[4];
  5576. array[startingIndex++] = value[5];
  5577. array[startingIndex++] = value[6];
  5578. array[startingIndex++] = value[7];
  5579. array[startingIndex++] = value[8];
  5580. array[startingIndex++] = value[9];
  5581. array[startingIndex++] = value[10];
  5582. array[startingIndex++] = value[11];
  5583. array[startingIndex++] = value[12];
  5584. array[startingIndex++] = value[13];
  5585. array[startingIndex++] = value[14];
  5586. array[startingIndex] = value[15];
  5587. return array;
  5588. };
  5589. /**
  5590. * Retrieves an instance from a packed array.
  5591. *
  5592. * @param {Number[]} array The packed array.
  5593. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5594. * @param {Matrix4} [result] The object into which to store the result.
  5595. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5596. */
  5597. Matrix4.unpack = function(array, startingIndex, result) {
  5598. if (!defined(array)) {
  5599. throw new DeveloperError('array is required');
  5600. }
  5601. startingIndex = defaultValue(startingIndex, 0);
  5602. if (!defined(result)) {
  5603. result = new Matrix4();
  5604. }
  5605. result[0] = array[startingIndex++];
  5606. result[1] = array[startingIndex++];
  5607. result[2] = array[startingIndex++];
  5608. result[3] = array[startingIndex++];
  5609. result[4] = array[startingIndex++];
  5610. result[5] = array[startingIndex++];
  5611. result[6] = array[startingIndex++];
  5612. result[7] = array[startingIndex++];
  5613. result[8] = array[startingIndex++];
  5614. result[9] = array[startingIndex++];
  5615. result[10] = array[startingIndex++];
  5616. result[11] = array[startingIndex++];
  5617. result[12] = array[startingIndex++];
  5618. result[13] = array[startingIndex++];
  5619. result[14] = array[startingIndex++];
  5620. result[15] = array[startingIndex];
  5621. return result;
  5622. };
  5623. /**
  5624. * Duplicates a Matrix4 instance.
  5625. *
  5626. * @param {Matrix4} matrix The matrix to duplicate.
  5627. * @param {Matrix4} [result] The object onto which to store the result.
  5628. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  5629. */
  5630. Matrix4.clone = function(matrix, result) {
  5631. if (!defined(matrix)) {
  5632. return undefined;
  5633. }
  5634. if (!defined(result)) {
  5635. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  5636. matrix[1], matrix[5], matrix[9], matrix[13],
  5637. matrix[2], matrix[6], matrix[10], matrix[14],
  5638. matrix[3], matrix[7], matrix[11], matrix[15]);
  5639. }
  5640. result[0] = matrix[0];
  5641. result[1] = matrix[1];
  5642. result[2] = matrix[2];
  5643. result[3] = matrix[3];
  5644. result[4] = matrix[4];
  5645. result[5] = matrix[5];
  5646. result[6] = matrix[6];
  5647. result[7] = matrix[7];
  5648. result[8] = matrix[8];
  5649. result[9] = matrix[9];
  5650. result[10] = matrix[10];
  5651. result[11] = matrix[11];
  5652. result[12] = matrix[12];
  5653. result[13] = matrix[13];
  5654. result[14] = matrix[14];
  5655. result[15] = matrix[15];
  5656. return result;
  5657. };
  5658. /**
  5659. * Creates a Matrix4 from 16 consecutive elements in an array.
  5660. * @function
  5661. *
  5662. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  5663. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  5664. * @param {Matrix4} [result] The object onto which to store the result.
  5665. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5666. *
  5667. * @example
  5668. * // Create the Matrix4:
  5669. * // [1.0, 2.0, 3.0, 4.0]
  5670. * // [1.0, 2.0, 3.0, 4.0]
  5671. * // [1.0, 2.0, 3.0, 4.0]
  5672. * // [1.0, 2.0, 3.0, 4.0]
  5673. *
  5674. * 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];
  5675. * var m = Cesium.Matrix4.fromArray(v);
  5676. *
  5677. * // Create same Matrix4 with using an offset into an array
  5678. * 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];
  5679. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  5680. */
  5681. Matrix4.fromArray = Matrix4.unpack;
  5682. /**
  5683. * Computes a Matrix4 instance from a column-major order array.
  5684. *
  5685. * @param {Number[]} values The column-major order array.
  5686. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5687. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5688. */
  5689. Matrix4.fromColumnMajorArray = function(values, result) {
  5690. if (!defined(values)) {
  5691. throw new DeveloperError('values is required');
  5692. }
  5693. return Matrix4.clone(values, result);
  5694. };
  5695. /**
  5696. * Computes a Matrix4 instance from a row-major order array.
  5697. * The resulting matrix will be in column-major order.
  5698. *
  5699. * @param {Number[]} values The row-major order array.
  5700. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5701. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5702. */
  5703. Matrix4.fromRowMajorArray = function(values, result) {
  5704. if (!defined(values)) {
  5705. throw new DeveloperError('values is required.');
  5706. }
  5707. if (!defined(result)) {
  5708. return new Matrix4(values[0], values[1], values[2], values[3],
  5709. values[4], values[5], values[6], values[7],
  5710. values[8], values[9], values[10], values[11],
  5711. values[12], values[13], values[14], values[15]);
  5712. }
  5713. result[0] = values[0];
  5714. result[1] = values[4];
  5715. result[2] = values[8];
  5716. result[3] = values[12];
  5717. result[4] = values[1];
  5718. result[5] = values[5];
  5719. result[6] = values[9];
  5720. result[7] = values[13];
  5721. result[8] = values[2];
  5722. result[9] = values[6];
  5723. result[10] = values[10];
  5724. result[11] = values[14];
  5725. result[12] = values[3];
  5726. result[13] = values[7];
  5727. result[14] = values[11];
  5728. result[15] = values[15];
  5729. return result;
  5730. };
  5731. /**
  5732. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  5733. * and a Cartesian3 representing the translation.
  5734. *
  5735. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  5736. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  5737. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5738. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5739. */
  5740. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  5741. if (!defined(rotation)) {
  5742. throw new DeveloperError('rotation is required.');
  5743. }
  5744. translation = defaultValue(translation, Cartesian3.ZERO);
  5745. if (!defined(result)) {
  5746. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  5747. rotation[1], rotation[4], rotation[7], translation.y,
  5748. rotation[2], rotation[5], rotation[8], translation.z,
  5749. 0.0, 0.0, 0.0, 1.0);
  5750. }
  5751. result[0] = rotation[0];
  5752. result[1] = rotation[1];
  5753. result[2] = rotation[2];
  5754. result[3] = 0.0;
  5755. result[4] = rotation[3];
  5756. result[5] = rotation[4];
  5757. result[6] = rotation[5];
  5758. result[7] = 0.0;
  5759. result[8] = rotation[6];
  5760. result[9] = rotation[7];
  5761. result[10] = rotation[8];
  5762. result[11] = 0.0;
  5763. result[12] = translation.x;
  5764. result[13] = translation.y;
  5765. result[14] = translation.z;
  5766. result[15] = 1.0;
  5767. return result;
  5768. };
  5769. /**
  5770. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  5771. * representation with the rotation represented as a quaternion.
  5772. *
  5773. * @param {Cartesian3} translation The translation transformation.
  5774. * @param {Quaternion} rotation The rotation transformation.
  5775. * @param {Cartesian3} scale The non-uniform scale transformation.
  5776. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5777. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5778. *
  5779. * @example
  5780. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  5781. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  5782. * Cesium.Quaternion.IDENTITY, // rotation
  5783. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  5784. * result);
  5785. */
  5786. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  5787. if (!defined(translation)) {
  5788. throw new DeveloperError('translation is required.');
  5789. }
  5790. if (!defined(rotation)) {
  5791. throw new DeveloperError('rotation is required.');
  5792. }
  5793. if (!defined(scale)) {
  5794. throw new DeveloperError('scale is required.');
  5795. }
  5796. if (!defined(result)) {
  5797. result = new Matrix4();
  5798. }
  5799. var scaleX = scale.x;
  5800. var scaleY = scale.y;
  5801. var scaleZ = scale.z;
  5802. var x2 = rotation.x * rotation.x;
  5803. var xy = rotation.x * rotation.y;
  5804. var xz = rotation.x * rotation.z;
  5805. var xw = rotation.x * rotation.w;
  5806. var y2 = rotation.y * rotation.y;
  5807. var yz = rotation.y * rotation.z;
  5808. var yw = rotation.y * rotation.w;
  5809. var z2 = rotation.z * rotation.z;
  5810. var zw = rotation.z * rotation.w;
  5811. var w2 = rotation.w * rotation.w;
  5812. var m00 = x2 - y2 - z2 + w2;
  5813. var m01 = 2.0 * (xy - zw);
  5814. var m02 = 2.0 * (xz + yw);
  5815. var m10 = 2.0 * (xy + zw);
  5816. var m11 = -x2 + y2 - z2 + w2;
  5817. var m12 = 2.0 * (yz - xw);
  5818. var m20 = 2.0 * (xz - yw);
  5819. var m21 = 2.0 * (yz + xw);
  5820. var m22 = -x2 - y2 + z2 + w2;
  5821. result[0] = m00 * scaleX;
  5822. result[1] = m10 * scaleX;
  5823. result[2] = m20 * scaleX;
  5824. result[3] = 0.0;
  5825. result[4] = m01 * scaleY;
  5826. result[5] = m11 * scaleY;
  5827. result[6] = m21 * scaleY;
  5828. result[7] = 0.0;
  5829. result[8] = m02 * scaleZ;
  5830. result[9] = m12 * scaleZ;
  5831. result[10] = m22 * scaleZ;
  5832. result[11] = 0.0;
  5833. result[12] = translation.x;
  5834. result[13] = translation.y;
  5835. result[14] = translation.z;
  5836. result[15] = 1.0;
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  5841. *
  5842. * @param {TranslationRotationScale} translationRotationScale The instance.
  5843. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5844. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5845. */
  5846. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  5847. if (!defined(translationRotationScale)) {
  5848. throw new DeveloperError('translationRotationScale is required.');
  5849. }
  5850. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  5851. };
  5852. /**
  5853. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  5854. *
  5855. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  5856. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5857. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5858. *
  5859. * @see Matrix4.multiplyByTranslation
  5860. */
  5861. Matrix4.fromTranslation = function(translation, result) {
  5862. if (!defined(translation)) {
  5863. throw new DeveloperError('translation is required.');
  5864. }
  5865. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  5866. };
  5867. /**
  5868. * Computes a Matrix4 instance representing a non-uniform scale.
  5869. *
  5870. * @param {Cartesian3} scale The x, y, and z scale factors.
  5871. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5872. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5873. *
  5874. * @example
  5875. * // Creates
  5876. * // [7.0, 0.0, 0.0, 0.0]
  5877. * // [0.0, 8.0, 0.0, 0.0]
  5878. * // [0.0, 0.0, 9.0, 0.0]
  5879. * // [0.0, 0.0, 0.0, 1.0]
  5880. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5881. */
  5882. Matrix4.fromScale = function(scale, result) {
  5883. if (!defined(scale)) {
  5884. throw new DeveloperError('scale is required.');
  5885. }
  5886. if (!defined(result)) {
  5887. return new Matrix4(
  5888. scale.x, 0.0, 0.0, 0.0,
  5889. 0.0, scale.y, 0.0, 0.0,
  5890. 0.0, 0.0, scale.z, 0.0,
  5891. 0.0, 0.0, 0.0, 1.0);
  5892. }
  5893. result[0] = scale.x;
  5894. result[1] = 0.0;
  5895. result[2] = 0.0;
  5896. result[3] = 0.0;
  5897. result[4] = 0.0;
  5898. result[5] = scale.y;
  5899. result[6] = 0.0;
  5900. result[7] = 0.0;
  5901. result[8] = 0.0;
  5902. result[9] = 0.0;
  5903. result[10] = scale.z;
  5904. result[11] = 0.0;
  5905. result[12] = 0.0;
  5906. result[13] = 0.0;
  5907. result[14] = 0.0;
  5908. result[15] = 1.0;
  5909. return result;
  5910. };
  5911. /**
  5912. * Computes a Matrix4 instance representing a uniform scale.
  5913. *
  5914. * @param {Number} scale The uniform scale factor.
  5915. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5916. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5917. *
  5918. * @example
  5919. * // Creates
  5920. * // [2.0, 0.0, 0.0, 0.0]
  5921. * // [0.0, 2.0, 0.0, 0.0]
  5922. * // [0.0, 0.0, 2.0, 0.0]
  5923. * // [0.0, 0.0, 0.0, 1.0]
  5924. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  5925. */
  5926. Matrix4.fromUniformScale = function(scale, result) {
  5927. if (typeof scale !== 'number') {
  5928. throw new DeveloperError('scale is required.');
  5929. }
  5930. if (!defined(result)) {
  5931. return new Matrix4(scale, 0.0, 0.0, 0.0,
  5932. 0.0, scale, 0.0, 0.0,
  5933. 0.0, 0.0, scale, 0.0,
  5934. 0.0, 0.0, 0.0, 1.0);
  5935. }
  5936. result[0] = scale;
  5937. result[1] = 0.0;
  5938. result[2] = 0.0;
  5939. result[3] = 0.0;
  5940. result[4] = 0.0;
  5941. result[5] = scale;
  5942. result[6] = 0.0;
  5943. result[7] = 0.0;
  5944. result[8] = 0.0;
  5945. result[9] = 0.0;
  5946. result[10] = scale;
  5947. result[11] = 0.0;
  5948. result[12] = 0.0;
  5949. result[13] = 0.0;
  5950. result[14] = 0.0;
  5951. result[15] = 1.0;
  5952. return result;
  5953. };
  5954. var fromCameraF = new Cartesian3();
  5955. var fromCameraR = new Cartesian3();
  5956. var fromCameraU = new Cartesian3();
  5957. /**
  5958. * Computes a Matrix4 instance from a Camera.
  5959. *
  5960. * @param {Camera} camera The camera to use.
  5961. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5962. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5963. */
  5964. Matrix4.fromCamera = function(camera, result) {
  5965. if (!defined(camera)) {
  5966. throw new DeveloperError('camera is required.');
  5967. }
  5968. var position = camera.position;
  5969. var direction = camera.direction;
  5970. var up = camera.up;
  5971. if (!defined(position)) {
  5972. throw new DeveloperError('camera.position is required.');
  5973. }
  5974. if (!defined(direction)) {
  5975. throw new DeveloperError('camera.direction is required.');
  5976. }
  5977. if (!defined(up)) {
  5978. throw new DeveloperError('camera.up is required.');
  5979. }
  5980. Cartesian3.normalize(direction, fromCameraF);
  5981. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  5982. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  5983. var sX = fromCameraR.x;
  5984. var sY = fromCameraR.y;
  5985. var sZ = fromCameraR.z;
  5986. var fX = fromCameraF.x;
  5987. var fY = fromCameraF.y;
  5988. var fZ = fromCameraF.z;
  5989. var uX = fromCameraU.x;
  5990. var uY = fromCameraU.y;
  5991. var uZ = fromCameraU.z;
  5992. var positionX = position.x;
  5993. var positionY = position.y;
  5994. var positionZ = position.z;
  5995. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  5996. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  5997. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  5998. // The code below this comment is an optimized
  5999. // version of the commented lines.
  6000. // Rather that create two matrices and then multiply,
  6001. // we just bake in the multiplcation as part of creation.
  6002. // var rotation = new Matrix4(
  6003. // sX, sY, sZ, 0.0,
  6004. // uX, uY, uZ, 0.0,
  6005. // -fX, -fY, -fZ, 0.0,
  6006. // 0.0, 0.0, 0.0, 1.0);
  6007. // var translation = new Matrix4(
  6008. // 1.0, 0.0, 0.0, -position.x,
  6009. // 0.0, 1.0, 0.0, -position.y,
  6010. // 0.0, 0.0, 1.0, -position.z,
  6011. // 0.0, 0.0, 0.0, 1.0);
  6012. // return rotation.multiply(translation);
  6013. if (!defined(result)) {
  6014. return new Matrix4(
  6015. sX, sY, sZ, t0,
  6016. uX, uY, uZ, t1,
  6017. -fX, -fY, -fZ, t2,
  6018. 0.0, 0.0, 0.0, 1.0);
  6019. }
  6020. result[0] = sX;
  6021. result[1] = uX;
  6022. result[2] = -fX;
  6023. result[3] = 0.0;
  6024. result[4] = sY;
  6025. result[5] = uY;
  6026. result[6] = -fY;
  6027. result[7] = 0.0;
  6028. result[8] = sZ;
  6029. result[9] = uZ;
  6030. result[10] = -fZ;
  6031. result[11] = 0.0;
  6032. result[12] = t0;
  6033. result[13] = t1;
  6034. result[14] = t2;
  6035. result[15] = 1.0;
  6036. return result;
  6037. };
  6038. /**
  6039. * Computes a Matrix4 instance representing a perspective transformation matrix.
  6040. *
  6041. * @param {Number} fovY The field of view along the Y axis in radians.
  6042. * @param {Number} aspectRatio The aspect ratio.
  6043. * @param {Number} near The distance to the near plane in meters.
  6044. * @param {Number} far The distance to the far plane in meters.
  6045. * @param {Matrix4} result The object in which the result will be stored.
  6046. * @returns {Matrix4} The modified result parameter.
  6047. *
  6048. * @exception {DeveloperError} fovY must be in (0, PI].
  6049. * @exception {DeveloperError} aspectRatio must be greater than zero.
  6050. * @exception {DeveloperError} near must be greater than zero.
  6051. * @exception {DeveloperError} far must be greater than zero.
  6052. */
  6053. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  6054. if (fovY <= 0.0 || fovY > Math.PI) {
  6055. throw new DeveloperError('fovY must be in (0, PI].');
  6056. }
  6057. if (aspectRatio <= 0.0) {
  6058. throw new DeveloperError('aspectRatio must be greater than zero.');
  6059. }
  6060. if (near <= 0.0) {
  6061. throw new DeveloperError('near must be greater than zero.');
  6062. }
  6063. if (far <= 0.0) {
  6064. throw new DeveloperError('far must be greater than zero.');
  6065. }
  6066. if (!defined(result)) {
  6067. throw new DeveloperError('result is required');
  6068. }
  6069. var bottom = Math.tan(fovY * 0.5);
  6070. var column1Row1 = 1.0 / bottom;
  6071. var column0Row0 = column1Row1 / aspectRatio;
  6072. var column2Row2 = (far + near) / (near - far);
  6073. var column3Row2 = (2.0 * far * near) / (near - far);
  6074. result[0] = column0Row0;
  6075. result[1] = 0.0;
  6076. result[2] = 0.0;
  6077. result[3] = 0.0;
  6078. result[4] = 0.0;
  6079. result[5] = column1Row1;
  6080. result[6] = 0.0;
  6081. result[7] = 0.0;
  6082. result[8] = 0.0;
  6083. result[9] = 0.0;
  6084. result[10] = column2Row2;
  6085. result[11] = -1.0;
  6086. result[12] = 0.0;
  6087. result[13] = 0.0;
  6088. result[14] = column3Row2;
  6089. result[15] = 0.0;
  6090. return result;
  6091. };
  6092. /**
  6093. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  6094. *
  6095. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6096. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6097. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6098. * @param {Number} top The number of meters above of the camera that will be in view.
  6099. * @param {Number} near The distance to the near plane in meters.
  6100. * @param {Number} far The distance to the far plane in meters.
  6101. * @param {Matrix4} result The object in which the result will be stored.
  6102. * @returns {Matrix4} The modified result parameter.
  6103. */
  6104. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  6105. if (!defined(left)) {
  6106. throw new DeveloperError('left is required.');
  6107. }
  6108. if (!defined(right)) {
  6109. throw new DeveloperError('right is required.');
  6110. }
  6111. if (!defined(bottom)) {
  6112. throw new DeveloperError('bottom is required.');
  6113. }
  6114. if (!defined(top)) {
  6115. throw new DeveloperError('top is required.');
  6116. }
  6117. if (!defined(near)) {
  6118. throw new DeveloperError('near is required.');
  6119. }
  6120. if (!defined(far)) {
  6121. throw new DeveloperError('far is required.');
  6122. }
  6123. if (!defined(result)) {
  6124. throw new DeveloperError('result is required');
  6125. }
  6126. var a = 1.0 / (right - left);
  6127. var b = 1.0 / (top - bottom);
  6128. var c = 1.0 / (far - near);
  6129. var tx = -(right + left) * a;
  6130. var ty = -(top + bottom) * b;
  6131. var tz = -(far + near) * c;
  6132. a *= 2.0;
  6133. b *= 2.0;
  6134. c *= -2.0;
  6135. result[0] = a;
  6136. result[1] = 0.0;
  6137. result[2] = 0.0;
  6138. result[3] = 0.0;
  6139. result[4] = 0.0;
  6140. result[5] = b;
  6141. result[6] = 0.0;
  6142. result[7] = 0.0;
  6143. result[8] = 0.0;
  6144. result[9] = 0.0;
  6145. result[10] = c;
  6146. result[11] = 0.0;
  6147. result[12] = tx;
  6148. result[13] = ty;
  6149. result[14] = tz;
  6150. result[15] = 1.0;
  6151. return result;
  6152. };
  6153. /**
  6154. * Computes a Matrix4 instance representing an off center perspective transformation.
  6155. *
  6156. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6157. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6158. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6159. * @param {Number} top The number of meters above of the camera that will be in view.
  6160. * @param {Number} near The distance to the near plane in meters.
  6161. * @param {Number} far The distance to the far plane in meters.
  6162. * @param {Matrix4} result The object in which the result will be stored.
  6163. * @returns {Matrix4} The modified result parameter.
  6164. */
  6165. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  6166. if (!defined(left)) {
  6167. throw new DeveloperError('left is required.');
  6168. }
  6169. if (!defined(right)) {
  6170. throw new DeveloperError('right is required.');
  6171. }
  6172. if (!defined(bottom)) {
  6173. throw new DeveloperError('bottom is required.');
  6174. }
  6175. if (!defined(top)) {
  6176. throw new DeveloperError('top is required.');
  6177. }
  6178. if (!defined(near)) {
  6179. throw new DeveloperError('near is required.');
  6180. }
  6181. if (!defined(far)) {
  6182. throw new DeveloperError('far is required.');
  6183. }
  6184. if (!defined(result)) {
  6185. throw new DeveloperError('result is required');
  6186. }
  6187. var column0Row0 = 2.0 * near / (right - left);
  6188. var column1Row1 = 2.0 * near / (top - bottom);
  6189. var column2Row0 = (right + left) / (right - left);
  6190. var column2Row1 = (top + bottom) / (top - bottom);
  6191. var column2Row2 = -(far + near) / (far - near);
  6192. var column2Row3 = -1.0;
  6193. var column3Row2 = -2.0 * far * near / (far - near);
  6194. result[0] = column0Row0;
  6195. result[1] = 0.0;
  6196. result[2] = 0.0;
  6197. result[3] = 0.0;
  6198. result[4] = 0.0;
  6199. result[5] = column1Row1;
  6200. result[6] = 0.0;
  6201. result[7] = 0.0;
  6202. result[8] = column2Row0;
  6203. result[9] = column2Row1;
  6204. result[10] = column2Row2;
  6205. result[11] = column2Row3;
  6206. result[12] = 0.0;
  6207. result[13] = 0.0;
  6208. result[14] = column3Row2;
  6209. result[15] = 0.0;
  6210. return result;
  6211. };
  6212. /**
  6213. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  6214. *
  6215. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6216. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6217. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6218. * @param {Number} top The number of meters above of the camera that will be in view.
  6219. * @param {Number} near The distance to the near plane in meters.
  6220. * @param {Matrix4} result The object in which the result will be stored.
  6221. * @returns {Matrix4} The modified result parameter.
  6222. */
  6223. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  6224. if (!defined(left)) {
  6225. throw new DeveloperError('left is required.');
  6226. }
  6227. if (!defined(right)) {
  6228. throw new DeveloperError('right is required.');
  6229. }
  6230. if (!defined(bottom)) {
  6231. throw new DeveloperError('bottom is required.');
  6232. }
  6233. if (!defined(top)) {
  6234. throw new DeveloperError('top is required.');
  6235. }
  6236. if (!defined(near)) {
  6237. throw new DeveloperError('near is required.');
  6238. }
  6239. if (!defined(result)) {
  6240. throw new DeveloperError('result is required');
  6241. }
  6242. var column0Row0 = 2.0 * near / (right - left);
  6243. var column1Row1 = 2.0 * near / (top - bottom);
  6244. var column2Row0 = (right + left) / (right - left);
  6245. var column2Row1 = (top + bottom) / (top - bottom);
  6246. var column2Row2 = -1.0;
  6247. var column2Row3 = -1.0;
  6248. var column3Row2 = -2.0 * near;
  6249. result[0] = column0Row0;
  6250. result[1] = 0.0;
  6251. result[2] = 0.0;
  6252. result[3] = 0.0;
  6253. result[4] = 0.0;
  6254. result[5] = column1Row1;
  6255. result[6] = 0.0;
  6256. result[7] = 0.0;
  6257. result[8] = column2Row0;
  6258. result[9] = column2Row1;
  6259. result[10] = column2Row2;
  6260. result[11] = column2Row3;
  6261. result[12] = 0.0;
  6262. result[13] = 0.0;
  6263. result[14] = column3Row2;
  6264. result[15] = 0.0;
  6265. return result;
  6266. };
  6267. /**
  6268. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  6269. *
  6270. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  6271. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  6272. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  6273. * @param {Matrix4} result The object in which the result will be stored.
  6274. * @returns {Matrix4} The modified result parameter.
  6275. *
  6276. * @example
  6277. * // Create viewport transformation using an explicit viewport and depth range.
  6278. * var m = Cesium.Matrix4.computeViewportTransformation({
  6279. * x : 0.0,
  6280. * y : 0.0,
  6281. * width : 1024.0,
  6282. * height : 768.0
  6283. * }, 0.0, 1.0, new Cesium.Matrix4());
  6284. */
  6285. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  6286. if (!defined(result)) {
  6287. throw new DeveloperError('result is required');
  6288. }
  6289. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  6290. var x = defaultValue(viewport.x, 0.0);
  6291. var y = defaultValue(viewport.y, 0.0);
  6292. var width = defaultValue(viewport.width, 0.0);
  6293. var height = defaultValue(viewport.height, 0.0);
  6294. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  6295. farDepthRange = defaultValue(farDepthRange, 1.0);
  6296. var halfWidth = width * 0.5;
  6297. var halfHeight = height * 0.5;
  6298. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  6299. var column0Row0 = halfWidth;
  6300. var column1Row1 = halfHeight;
  6301. var column2Row2 = halfDepth;
  6302. var column3Row0 = x + halfWidth;
  6303. var column3Row1 = y + halfHeight;
  6304. var column3Row2 = nearDepthRange + halfDepth;
  6305. var column3Row3 = 1.0;
  6306. result[0] = column0Row0;
  6307. result[1] = 0.0;
  6308. result[2] = 0.0;
  6309. result[3] = 0.0;
  6310. result[4] = 0.0;
  6311. result[5] = column1Row1;
  6312. result[6] = 0.0;
  6313. result[7] = 0.0;
  6314. result[8] = 0.0;
  6315. result[9] = 0.0;
  6316. result[10] = column2Row2;
  6317. result[11] = 0.0;
  6318. result[12] = column3Row0;
  6319. result[13] = column3Row1;
  6320. result[14] = column3Row2;
  6321. result[15] = column3Row3;
  6322. return result;
  6323. };
  6324. /**
  6325. * Computes a Matrix4 instance that transforms from world space to view space.
  6326. *
  6327. * @param {Cartesian3} position The position of the camera.
  6328. * @param {Cartesian3} direction The forward direction.
  6329. * @param {Cartesian3} up The up direction.
  6330. * @param {Cartesian3} right The right direction.
  6331. * @param {Matrix4} result The object in which the result will be stored.
  6332. * @returns {Matrix4} The modified result parameter.
  6333. */
  6334. Matrix4.computeView = function(position, direction, up, right, result) {
  6335. if (!defined(position)) {
  6336. throw new DeveloperError('position is required');
  6337. }
  6338. if (!defined(direction)) {
  6339. throw new DeveloperError('direction is required');
  6340. }
  6341. if (!defined(up)) {
  6342. throw new DeveloperError('up is required');
  6343. }
  6344. if (!defined(right)) {
  6345. throw new DeveloperError('right is required');
  6346. }
  6347. if (!defined(result)) {
  6348. throw new DeveloperError('result is required');
  6349. }
  6350. result[0] = right.x;
  6351. result[1] = up.x;
  6352. result[2] = -direction.x;
  6353. result[3] = 0.0;
  6354. result[4] = right.y;
  6355. result[5] = up.y;
  6356. result[6] = -direction.y;
  6357. result[7] = 0.0;
  6358. result[8] = right.z;
  6359. result[9] = up.z;
  6360. result[10] = -direction.z;
  6361. result[11] = 0.0;
  6362. result[12] = -Cartesian3.dot(right, position);
  6363. result[13] = -Cartesian3.dot(up, position);
  6364. result[14] = Cartesian3.dot(direction, position);
  6365. result[15] = 1.0;
  6366. return result;
  6367. };
  6368. /**
  6369. * Computes an Array from the provided Matrix4 instance.
  6370. * The array will be in column-major order.
  6371. *
  6372. * @param {Matrix4} matrix The matrix to use..
  6373. * @param {Number[]} [result] The Array onto which to store the result.
  6374. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  6375. *
  6376. * @example
  6377. * //create an array from an instance of Matrix4
  6378. * // m = [10.0, 14.0, 18.0, 22.0]
  6379. * // [11.0, 15.0, 19.0, 23.0]
  6380. * // [12.0, 16.0, 20.0, 24.0]
  6381. * // [13.0, 17.0, 21.0, 25.0]
  6382. * var a = Cesium.Matrix4.toArray(m);
  6383. *
  6384. * // m remains the same
  6385. * //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]
  6386. */
  6387. Matrix4.toArray = function(matrix, result) {
  6388. if (!defined(matrix)) {
  6389. throw new DeveloperError('matrix is required');
  6390. }
  6391. if (!defined(result)) {
  6392. return [matrix[0], matrix[1], matrix[2], matrix[3],
  6393. matrix[4], matrix[5], matrix[6], matrix[7],
  6394. matrix[8], matrix[9], matrix[10], matrix[11],
  6395. matrix[12], matrix[13], matrix[14], matrix[15]];
  6396. }
  6397. result[0] = matrix[0];
  6398. result[1] = matrix[1];
  6399. result[2] = matrix[2];
  6400. result[3] = matrix[3];
  6401. result[4] = matrix[4];
  6402. result[5] = matrix[5];
  6403. result[6] = matrix[6];
  6404. result[7] = matrix[7];
  6405. result[8] = matrix[8];
  6406. result[9] = matrix[9];
  6407. result[10] = matrix[10];
  6408. result[11] = matrix[11];
  6409. result[12] = matrix[12];
  6410. result[13] = matrix[13];
  6411. result[14] = matrix[14];
  6412. result[15] = matrix[15];
  6413. return result;
  6414. };
  6415. /**
  6416. * Computes the array index of the element at the provided row and column.
  6417. *
  6418. * @param {Number} row The zero-based index of the row.
  6419. * @param {Number} column The zero-based index of the column.
  6420. * @returns {Number} The index of the element at the provided row and column.
  6421. *
  6422. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  6423. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  6424. *
  6425. * @example
  6426. * var myMatrix = new Cesium.Matrix4();
  6427. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  6428. * var column1Row0 = myMatrix[column1Row0Index];
  6429. * myMatrix[column1Row0Index] = 10.0;
  6430. */
  6431. Matrix4.getElementIndex = function(column, row) {
  6432. if (typeof row !== 'number' || row < 0 || row > 3) {
  6433. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  6434. }
  6435. if (typeof column !== 'number' || column < 0 || column > 3) {
  6436. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  6437. }
  6438. return column * 4 + row;
  6439. };
  6440. /**
  6441. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  6442. *
  6443. * @param {Matrix4} matrix The matrix to use.
  6444. * @param {Number} index The zero-based index of the column to retrieve.
  6445. * @param {Cartesian4} result The object onto which to store the result.
  6446. * @returns {Cartesian4} The modified result parameter.
  6447. *
  6448. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6449. *
  6450. * @example
  6451. * //returns a Cartesian4 instance with values from the specified column
  6452. * // m = [10.0, 11.0, 12.0, 13.0]
  6453. * // [14.0, 15.0, 16.0, 17.0]
  6454. * // [18.0, 19.0, 20.0, 21.0]
  6455. * // [22.0, 23.0, 24.0, 25.0]
  6456. *
  6457. * //Example 1: Creates an instance of Cartesian
  6458. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  6459. *
  6460. * @example
  6461. * //Example 2: Sets values for Cartesian instance
  6462. * var a = new Cesium.Cartesian4();
  6463. * Cesium.Matrix4.getColumn(m, 2, a);
  6464. *
  6465. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  6466. */
  6467. Matrix4.getColumn = function(matrix, index, result) {
  6468. if (!defined(matrix)) {
  6469. throw new DeveloperError('matrix is required.');
  6470. }
  6471. if (typeof index !== 'number' || index < 0 || index > 3) {
  6472. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6473. }
  6474. if (!defined(result)) {
  6475. throw new DeveloperError('result is required');
  6476. }
  6477. var startIndex = index * 4;
  6478. var x = matrix[startIndex];
  6479. var y = matrix[startIndex + 1];
  6480. var z = matrix[startIndex + 2];
  6481. var w = matrix[startIndex + 3];
  6482. result.x = x;
  6483. result.y = y;
  6484. result.z = z;
  6485. result.w = w;
  6486. return result;
  6487. };
  6488. /**
  6489. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  6490. *
  6491. * @param {Matrix4} matrix The matrix to use.
  6492. * @param {Number} index The zero-based index of the column to set.
  6493. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  6494. * @param {Matrix4} result The object onto which to store the result.
  6495. * @returns {Matrix4} The modified result parameter.
  6496. *
  6497. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6498. *
  6499. * @example
  6500. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  6501. * // m = [10.0, 11.0, 12.0, 13.0]
  6502. * // [14.0, 15.0, 16.0, 17.0]
  6503. * // [18.0, 19.0, 20.0, 21.0]
  6504. * // [22.0, 23.0, 24.0, 25.0]
  6505. *
  6506. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  6507. *
  6508. * // m remains the same
  6509. * // a = [10.0, 11.0, 99.0, 13.0]
  6510. * // [14.0, 15.0, 98.0, 17.0]
  6511. * // [18.0, 19.0, 97.0, 21.0]
  6512. * // [22.0, 23.0, 96.0, 25.0]
  6513. */
  6514. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  6515. if (!defined(matrix)) {
  6516. throw new DeveloperError('matrix is required');
  6517. }
  6518. if (!defined(cartesian)) {
  6519. throw new DeveloperError('cartesian is required');
  6520. }
  6521. if (typeof index !== 'number' || index < 0 || index > 3) {
  6522. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6523. }
  6524. if (!defined(result)) {
  6525. throw new DeveloperError('result is required');
  6526. }
  6527. result = Matrix4.clone(matrix, result);
  6528. var startIndex = index * 4;
  6529. result[startIndex] = cartesian.x;
  6530. result[startIndex + 1] = cartesian.y;
  6531. result[startIndex + 2] = cartesian.z;
  6532. result[startIndex + 3] = cartesian.w;
  6533. return result;
  6534. };
  6535. /**
  6536. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  6537. * matrix with the provided translation. This assumes the matrix is an affine transformation
  6538. *
  6539. * @param {Matrix4} matrix The matrix to use.
  6540. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  6541. * @param {Cartesian4} result The object onto which to store the result.
  6542. * @returns {Matrix4} The modified result parameter.
  6543. */
  6544. Matrix4.setTranslation = function(matrix, translation, result) {
  6545. if (!defined(matrix)) {
  6546. throw new DeveloperError('matrix is required');
  6547. }
  6548. if (!defined(translation)) {
  6549. throw new DeveloperError('translation is required');
  6550. }
  6551. if (!defined(result)) {
  6552. throw new DeveloperError('result is required');
  6553. }
  6554. result[0] = matrix[0];
  6555. result[1] = matrix[1];
  6556. result[2] = matrix[2];
  6557. result[3] = matrix[3];
  6558. result[4] = matrix[4];
  6559. result[5] = matrix[5];
  6560. result[6] = matrix[6];
  6561. result[7] = matrix[7];
  6562. result[8] = matrix[8];
  6563. result[9] = matrix[9];
  6564. result[10] = matrix[10];
  6565. result[11] = matrix[11];
  6566. result[12] = translation.x;
  6567. result[13] = translation.y;
  6568. result[14] = translation.z;
  6569. result[15] = matrix[15];
  6570. return result;
  6571. };
  6572. /**
  6573. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  6574. *
  6575. * @param {Matrix4} matrix The matrix to use.
  6576. * @param {Number} index The zero-based index of the row to retrieve.
  6577. * @param {Cartesian4} result The object onto which to store the result.
  6578. * @returns {Cartesian4} The modified result parameter.
  6579. *
  6580. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6581. *
  6582. * @example
  6583. * //returns a Cartesian4 instance with values from the specified column
  6584. * // m = [10.0, 11.0, 12.0, 13.0]
  6585. * // [14.0, 15.0, 16.0, 17.0]
  6586. * // [18.0, 19.0, 20.0, 21.0]
  6587. * // [22.0, 23.0, 24.0, 25.0]
  6588. *
  6589. * //Example 1: Returns an instance of Cartesian
  6590. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  6591. *
  6592. * @example
  6593. * //Example 2: Sets values for a Cartesian instance
  6594. * var a = new Cesium.Cartesian4();
  6595. * Cesium.Matrix4.getRow(m, 2, a);
  6596. *
  6597. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  6598. */
  6599. Matrix4.getRow = function(matrix, index, result) {
  6600. if (!defined(matrix)) {
  6601. throw new DeveloperError('matrix is required.');
  6602. }
  6603. if (typeof index !== 'number' || index < 0 || index > 3) {
  6604. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6605. }
  6606. if (!defined(result)) {
  6607. throw new DeveloperError('result is required');
  6608. }
  6609. var x = matrix[index];
  6610. var y = matrix[index + 4];
  6611. var z = matrix[index + 8];
  6612. var w = matrix[index + 12];
  6613. result.x = x;
  6614. result.y = y;
  6615. result.z = z;
  6616. result.w = w;
  6617. return result;
  6618. };
  6619. /**
  6620. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  6621. *
  6622. * @param {Matrix4} matrix The matrix to use.
  6623. * @param {Number} index The zero-based index of the row to set.
  6624. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  6625. * @param {Matrix4} result The object onto which to store the result.
  6626. * @returns {Matrix4} The modified result parameter.
  6627. *
  6628. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6629. *
  6630. * @example
  6631. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  6632. * // m = [10.0, 11.0, 12.0, 13.0]
  6633. * // [14.0, 15.0, 16.0, 17.0]
  6634. * // [18.0, 19.0, 20.0, 21.0]
  6635. * // [22.0, 23.0, 24.0, 25.0]
  6636. *
  6637. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  6638. *
  6639. * // m remains the same
  6640. * // a = [10.0, 11.0, 12.0, 13.0]
  6641. * // [14.0, 15.0, 16.0, 17.0]
  6642. * // [99.0, 98.0, 97.0, 96.0]
  6643. * // [22.0, 23.0, 24.0, 25.0]
  6644. */
  6645. Matrix4.setRow = function(matrix, index, cartesian, result) {
  6646. if (!defined(matrix)) {
  6647. throw new DeveloperError('matrix is required');
  6648. }
  6649. if (!defined(cartesian)) {
  6650. throw new DeveloperError('cartesian is required');
  6651. }
  6652. if (typeof index !== 'number' || index < 0 || index > 3) {
  6653. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6654. }
  6655. if (!defined(result)) {
  6656. throw new DeveloperError('result is required');
  6657. }
  6658. result = Matrix4.clone(matrix, result);
  6659. result[index] = cartesian.x;
  6660. result[index + 4] = cartesian.y;
  6661. result[index + 8] = cartesian.z;
  6662. result[index + 12] = cartesian.w;
  6663. return result;
  6664. };
  6665. var scratchColumn = new Cartesian3();
  6666. /**
  6667. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  6668. *
  6669. * @param {Matrix4} matrix The matrix.
  6670. * @param {Cartesian3} result The object onto which to store the result.
  6671. * @returns {Cartesian3} The modified result parameter
  6672. */
  6673. Matrix4.getScale = function(matrix, result) {
  6674. if (!defined(matrix)) {
  6675. throw new DeveloperError('matrix is required.');
  6676. }
  6677. if (!defined(result)) {
  6678. throw new DeveloperError('result is required');
  6679. }
  6680. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  6681. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  6682. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  6683. return result;
  6684. };
  6685. var scratchScale = new Cartesian3();
  6686. /**
  6687. * Computes the maximum scale assuming the matrix is an affine transformation.
  6688. * The maximum scale is the maximum length of the column vectors in the upper-left
  6689. * 3x3 matrix.
  6690. *
  6691. * @param {Matrix4} matrix The matrix.
  6692. * @returns {Number} The maximum scale.
  6693. */
  6694. Matrix4.getMaximumScale = function(matrix) {
  6695. Matrix4.getScale(matrix, scratchScale);
  6696. return Cartesian3.maximumComponent(scratchScale);
  6697. };
  6698. /**
  6699. * Computes the product of two matrices.
  6700. *
  6701. * @param {Matrix4} left The first matrix.
  6702. * @param {Matrix4} right The second matrix.
  6703. * @param {Matrix4} result The object onto which to store the result.
  6704. * @returns {Matrix4} The modified result parameter.
  6705. */
  6706. Matrix4.multiply = function(left, right, result) {
  6707. if (!defined(left)) {
  6708. throw new DeveloperError('left is required');
  6709. }
  6710. if (!defined(right)) {
  6711. throw new DeveloperError('right is required');
  6712. }
  6713. if (!defined(result)) {
  6714. throw new DeveloperError('result is required');
  6715. }
  6716. var left0 = left[0];
  6717. var left1 = left[1];
  6718. var left2 = left[2];
  6719. var left3 = left[3];
  6720. var left4 = left[4];
  6721. var left5 = left[5];
  6722. var left6 = left[6];
  6723. var left7 = left[7];
  6724. var left8 = left[8];
  6725. var left9 = left[9];
  6726. var left10 = left[10];
  6727. var left11 = left[11];
  6728. var left12 = left[12];
  6729. var left13 = left[13];
  6730. var left14 = left[14];
  6731. var left15 = left[15];
  6732. var right0 = right[0];
  6733. var right1 = right[1];
  6734. var right2 = right[2];
  6735. var right3 = right[3];
  6736. var right4 = right[4];
  6737. var right5 = right[5];
  6738. var right6 = right[6];
  6739. var right7 = right[7];
  6740. var right8 = right[8];
  6741. var right9 = right[9];
  6742. var right10 = right[10];
  6743. var right11 = right[11];
  6744. var right12 = right[12];
  6745. var right13 = right[13];
  6746. var right14 = right[14];
  6747. var right15 = right[15];
  6748. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  6749. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  6750. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  6751. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  6752. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  6753. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  6754. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  6755. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  6756. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  6757. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  6758. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  6759. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  6760. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  6761. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  6762. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  6763. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  6764. result[0] = column0Row0;
  6765. result[1] = column0Row1;
  6766. result[2] = column0Row2;
  6767. result[3] = column0Row3;
  6768. result[4] = column1Row0;
  6769. result[5] = column1Row1;
  6770. result[6] = column1Row2;
  6771. result[7] = column1Row3;
  6772. result[8] = column2Row0;
  6773. result[9] = column2Row1;
  6774. result[10] = column2Row2;
  6775. result[11] = column2Row3;
  6776. result[12] = column3Row0;
  6777. result[13] = column3Row1;
  6778. result[14] = column3Row2;
  6779. result[15] = column3Row3;
  6780. return result;
  6781. };
  6782. /**
  6783. * Computes the sum of two matrices.
  6784. *
  6785. * @param {Matrix4} left The first matrix.
  6786. * @param {Matrix4} right The second matrix.
  6787. * @param {Matrix4} result The object onto which to store the result.
  6788. * @returns {Matrix4} The modified result parameter.
  6789. */
  6790. Matrix4.add = function(left, right, result) {
  6791. if (!defined(left)) {
  6792. throw new DeveloperError('left is required');
  6793. }
  6794. if (!defined(right)) {
  6795. throw new DeveloperError('right is required');
  6796. }
  6797. if (!defined(result)) {
  6798. throw new DeveloperError('result is required');
  6799. }
  6800. result[0] = left[0] + right[0];
  6801. result[1] = left[1] + right[1];
  6802. result[2] = left[2] + right[2];
  6803. result[3] = left[3] + right[3];
  6804. result[4] = left[4] + right[4];
  6805. result[5] = left[5] + right[5];
  6806. result[6] = left[6] + right[6];
  6807. result[7] = left[7] + right[7];
  6808. result[8] = left[8] + right[8];
  6809. result[9] = left[9] + right[9];
  6810. result[10] = left[10] + right[10];
  6811. result[11] = left[11] + right[11];
  6812. result[12] = left[12] + right[12];
  6813. result[13] = left[13] + right[13];
  6814. result[14] = left[14] + right[14];
  6815. result[15] = left[15] + right[15];
  6816. return result;
  6817. };
  6818. /**
  6819. * Computes the difference of two matrices.
  6820. *
  6821. * @param {Matrix4} left The first matrix.
  6822. * @param {Matrix4} right The second matrix.
  6823. * @param {Matrix4} result The object onto which to store the result.
  6824. * @returns {Matrix4} The modified result parameter.
  6825. */
  6826. Matrix4.subtract = function(left, right, result) {
  6827. if (!defined(left)) {
  6828. throw new DeveloperError('left is required');
  6829. }
  6830. if (!defined(right)) {
  6831. throw new DeveloperError('right is required');
  6832. }
  6833. if (!defined(result)) {
  6834. throw new DeveloperError('result is required');
  6835. }
  6836. result[0] = left[0] - right[0];
  6837. result[1] = left[1] - right[1];
  6838. result[2] = left[2] - right[2];
  6839. result[3] = left[3] - right[3];
  6840. result[4] = left[4] - right[4];
  6841. result[5] = left[5] - right[5];
  6842. result[6] = left[6] - right[6];
  6843. result[7] = left[7] - right[7];
  6844. result[8] = left[8] - right[8];
  6845. result[9] = left[9] - right[9];
  6846. result[10] = left[10] - right[10];
  6847. result[11] = left[11] - right[11];
  6848. result[12] = left[12] - right[12];
  6849. result[13] = left[13] - right[13];
  6850. result[14] = left[14] - right[14];
  6851. result[15] = left[15] - right[15];
  6852. return result;
  6853. };
  6854. /**
  6855. * Computes the product of two matrices assuming the matrices are
  6856. * affine transformation matrices, where the upper left 3x3 elements
  6857. * are a rotation matrix, and the upper three elements in the fourth
  6858. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  6859. * The matrix is not verified to be in the proper form.
  6860. * This method is faster than computing the product for general 4x4
  6861. * matrices using {@link Matrix4.multiply}.
  6862. *
  6863. * @param {Matrix4} left The first matrix.
  6864. * @param {Matrix4} right The second matrix.
  6865. * @param {Matrix4} result The object onto which to store the result.
  6866. * @returns {Matrix4} The modified result parameter.
  6867. *
  6868. * @example
  6869. * 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);
  6870. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  6871. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  6872. */
  6873. Matrix4.multiplyTransformation = function(left, right, result) {
  6874. if (!defined(left)) {
  6875. throw new DeveloperError('left is required');
  6876. }
  6877. if (!defined(right)) {
  6878. throw new DeveloperError('right is required');
  6879. }
  6880. if (!defined(result)) {
  6881. throw new DeveloperError('result is required');
  6882. }
  6883. var left0 = left[0];
  6884. var left1 = left[1];
  6885. var left2 = left[2];
  6886. var left4 = left[4];
  6887. var left5 = left[5];
  6888. var left6 = left[6];
  6889. var left8 = left[8];
  6890. var left9 = left[9];
  6891. var left10 = left[10];
  6892. var left12 = left[12];
  6893. var left13 = left[13];
  6894. var left14 = left[14];
  6895. var right0 = right[0];
  6896. var right1 = right[1];
  6897. var right2 = right[2];
  6898. var right4 = right[4];
  6899. var right5 = right[5];
  6900. var right6 = right[6];
  6901. var right8 = right[8];
  6902. var right9 = right[9];
  6903. var right10 = right[10];
  6904. var right12 = right[12];
  6905. var right13 = right[13];
  6906. var right14 = right[14];
  6907. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  6908. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  6909. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  6910. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  6911. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  6912. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  6913. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  6914. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  6915. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  6916. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  6917. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  6918. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  6919. result[0] = column0Row0;
  6920. result[1] = column0Row1;
  6921. result[2] = column0Row2;
  6922. result[3] = 0.0;
  6923. result[4] = column1Row0;
  6924. result[5] = column1Row1;
  6925. result[6] = column1Row2;
  6926. result[7] = 0.0;
  6927. result[8] = column2Row0;
  6928. result[9] = column2Row1;
  6929. result[10] = column2Row2;
  6930. result[11] = 0.0;
  6931. result[12] = column3Row0;
  6932. result[13] = column3Row1;
  6933. result[14] = column3Row2;
  6934. result[15] = 1.0;
  6935. return result;
  6936. };
  6937. /**
  6938. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  6939. * by a 3x3 rotation matrix. This is an optimization
  6940. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  6941. *
  6942. * @param {Matrix4} matrix The matrix on the left-hand side.
  6943. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  6944. * @param {Matrix4} result The object onto which to store the result.
  6945. * @returns {Matrix4} The modified result parameter.
  6946. *
  6947. * @example
  6948. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  6949. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  6950. */
  6951. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  6952. if (!defined(matrix)) {
  6953. throw new DeveloperError('matrix is required');
  6954. }
  6955. if (!defined(rotation)) {
  6956. throw new DeveloperError('rotation is required');
  6957. }
  6958. if (!defined(result)) {
  6959. throw new DeveloperError('result is required');
  6960. }
  6961. var left0 = matrix[0];
  6962. var left1 = matrix[1];
  6963. var left2 = matrix[2];
  6964. var left4 = matrix[4];
  6965. var left5 = matrix[5];
  6966. var left6 = matrix[6];
  6967. var left8 = matrix[8];
  6968. var left9 = matrix[9];
  6969. var left10 = matrix[10];
  6970. var right0 = rotation[0];
  6971. var right1 = rotation[1];
  6972. var right2 = rotation[2];
  6973. var right4 = rotation[3];
  6974. var right5 = rotation[4];
  6975. var right6 = rotation[5];
  6976. var right8 = rotation[6];
  6977. var right9 = rotation[7];
  6978. var right10 = rotation[8];
  6979. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  6980. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  6981. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  6982. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  6983. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  6984. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  6985. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  6986. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  6987. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  6988. result[0] = column0Row0;
  6989. result[1] = column0Row1;
  6990. result[2] = column0Row2;
  6991. result[3] = 0.0;
  6992. result[4] = column1Row0;
  6993. result[5] = column1Row1;
  6994. result[6] = column1Row2;
  6995. result[7] = 0.0;
  6996. result[8] = column2Row0;
  6997. result[9] = column2Row1;
  6998. result[10] = column2Row2;
  6999. result[11] = 0.0;
  7000. result[12] = matrix[12];
  7001. result[13] = matrix[13];
  7002. result[14] = matrix[14];
  7003. result[15] = matrix[15];
  7004. return result;
  7005. };
  7006. /**
  7007. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7008. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  7009. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  7010. *
  7011. * @param {Matrix4} matrix The matrix on the left-hand side.
  7012. * @param {Cartesian3} translation The translation on the right-hand side.
  7013. * @param {Matrix4} result The object onto which to store the result.
  7014. * @returns {Matrix4} The modified result parameter.
  7015. *
  7016. * @example
  7017. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  7018. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  7019. */
  7020. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  7021. if (!defined(matrix)) {
  7022. throw new DeveloperError('matrix is required');
  7023. }
  7024. if (!defined(translation)) {
  7025. throw new DeveloperError('translation is required');
  7026. }
  7027. if (!defined(result)) {
  7028. throw new DeveloperError('result is required');
  7029. }
  7030. var x = translation.x;
  7031. var y = translation.y;
  7032. var z = translation.z;
  7033. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  7034. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  7035. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  7036. result[0] = matrix[0];
  7037. result[1] = matrix[1];
  7038. result[2] = matrix[2];
  7039. result[3] = matrix[3];
  7040. result[4] = matrix[4];
  7041. result[5] = matrix[5];
  7042. result[6] = matrix[6];
  7043. result[7] = matrix[7];
  7044. result[8] = matrix[8];
  7045. result[9] = matrix[9];
  7046. result[10] = matrix[10];
  7047. result[11] = matrix[11];
  7048. result[12] = tx;
  7049. result[13] = ty;
  7050. result[14] = tz;
  7051. result[15] = matrix[15];
  7052. return result;
  7053. };
  7054. var uniformScaleScratch = new Cartesian3();
  7055. /**
  7056. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7057. * by an implicit uniform scale matrix. This is an optimization
  7058. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  7059. * <code>m</code> must be an affine matrix.
  7060. * This function performs fewer allocations and arithmetic operations.
  7061. *
  7062. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  7063. * @param {Number} scale The uniform scale on the right-hand side.
  7064. * @param {Matrix4} result The object onto which to store the result.
  7065. * @returns {Matrix4} The modified result parameter.
  7066. *
  7067. *
  7068. * @example
  7069. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  7070. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  7071. *
  7072. * @see Matrix4.fromUniformScale
  7073. * @see Matrix4.multiplyByScale
  7074. */
  7075. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  7076. if (!defined(matrix)) {
  7077. throw new DeveloperError('matrix is required');
  7078. }
  7079. if (typeof scale !== 'number') {
  7080. throw new DeveloperError('scale is required');
  7081. }
  7082. if (!defined(result)) {
  7083. throw new DeveloperError('result is required');
  7084. }
  7085. uniformScaleScratch.x = scale;
  7086. uniformScaleScratch.y = scale;
  7087. uniformScaleScratch.z = scale;
  7088. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  7089. };
  7090. /**
  7091. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7092. * by an implicit non-uniform scale matrix. This is an optimization
  7093. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  7094. * <code>m</code> must be an affine matrix.
  7095. * This function performs fewer allocations and arithmetic operations.
  7096. *
  7097. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  7098. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  7099. * @param {Matrix4} result The object onto which to store the result.
  7100. * @returns {Matrix4} The modified result parameter.
  7101. *
  7102. *
  7103. * @example
  7104. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  7105. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  7106. *
  7107. * @see Matrix4.fromScale
  7108. * @see Matrix4.multiplyByUniformScale
  7109. */
  7110. Matrix4.multiplyByScale = function(matrix, scale, result) {
  7111. if (!defined(matrix)) {
  7112. throw new DeveloperError('matrix is required');
  7113. }
  7114. if (!defined(scale)) {
  7115. throw new DeveloperError('scale is required');
  7116. }
  7117. if (!defined(result)) {
  7118. throw new DeveloperError('result is required');
  7119. }
  7120. var scaleX = scale.x;
  7121. var scaleY = scale.y;
  7122. var scaleZ = scale.z;
  7123. // Faster than Cartesian3.equals
  7124. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  7125. return Matrix4.clone(matrix, result);
  7126. }
  7127. result[0] = scaleX * matrix[0];
  7128. result[1] = scaleX * matrix[1];
  7129. result[2] = scaleX * matrix[2];
  7130. result[3] = 0.0;
  7131. result[4] = scaleY * matrix[4];
  7132. result[5] = scaleY * matrix[5];
  7133. result[6] = scaleY * matrix[6];
  7134. result[7] = 0.0;
  7135. result[8] = scaleZ * matrix[8];
  7136. result[9] = scaleZ * matrix[9];
  7137. result[10] = scaleZ * matrix[10];
  7138. result[11] = 0.0;
  7139. result[12] = matrix[12];
  7140. result[13] = matrix[13];
  7141. result[14] = matrix[14];
  7142. result[15] = 1.0;
  7143. return result;
  7144. };
  7145. /**
  7146. * Computes the product of a matrix and a column vector.
  7147. *
  7148. * @param {Matrix4} matrix The matrix.
  7149. * @param {Cartesian4} cartesian The vector.
  7150. * @param {Cartesian4} result The object onto which to store the result.
  7151. * @returns {Cartesian4} The modified result parameter.
  7152. */
  7153. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  7154. if (!defined(matrix)) {
  7155. throw new DeveloperError('matrix is required');
  7156. }
  7157. if (!defined(cartesian)) {
  7158. throw new DeveloperError('cartesian is required');
  7159. }
  7160. if (!defined(result)) {
  7161. throw new DeveloperError('result is required');
  7162. }
  7163. var vX = cartesian.x;
  7164. var vY = cartesian.y;
  7165. var vZ = cartesian.z;
  7166. var vW = cartesian.w;
  7167. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  7168. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  7169. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  7170. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  7171. result.x = x;
  7172. result.y = y;
  7173. result.z = z;
  7174. result.w = w;
  7175. return result;
  7176. };
  7177. /**
  7178. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  7179. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  7180. *
  7181. * @param {Matrix4} matrix The matrix.
  7182. * @param {Cartesian3} cartesian The point.
  7183. * @param {Cartesian3} result The object onto which to store the result.
  7184. * @returns {Cartesian3} The modified result parameter.
  7185. *
  7186. * @example
  7187. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  7188. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  7189. * // A shortcut for
  7190. * // Cartesian3 p = ...
  7191. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  7192. */
  7193. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  7194. if (!defined(matrix)) {
  7195. throw new DeveloperError('matrix is required');
  7196. }
  7197. if (!defined(cartesian)) {
  7198. throw new DeveloperError('cartesian is required');
  7199. }
  7200. if (!defined(result)) {
  7201. throw new DeveloperError('result is required');
  7202. }
  7203. var vX = cartesian.x;
  7204. var vY = cartesian.y;
  7205. var vZ = cartesian.z;
  7206. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  7207. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  7208. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  7209. result.x = x;
  7210. result.y = y;
  7211. result.z = z;
  7212. return result;
  7213. };
  7214. /**
  7215. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  7216. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  7217. *
  7218. * @param {Matrix4} matrix The matrix.
  7219. * @param {Cartesian3} cartesian The point.
  7220. * @param {Cartesian3} result The object onto which to store the result.
  7221. * @returns {Cartesian3} The modified result parameter.
  7222. *
  7223. * @example
  7224. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  7225. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  7226. */
  7227. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  7228. if (!defined(matrix)) {
  7229. throw new DeveloperError('matrix is required');
  7230. }
  7231. if (!defined(cartesian)) {
  7232. throw new DeveloperError('cartesian is required');
  7233. }
  7234. if (!defined(result)) {
  7235. throw new DeveloperError('result is required');
  7236. }
  7237. var vX = cartesian.x;
  7238. var vY = cartesian.y;
  7239. var vZ = cartesian.z;
  7240. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  7241. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  7242. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  7243. result.x = x;
  7244. result.y = y;
  7245. result.z = z;
  7246. return result;
  7247. };
  7248. /**
  7249. * Computes the product of a matrix and a scalar.
  7250. *
  7251. * @param {Matrix4} matrix The matrix.
  7252. * @param {Number} scalar The number to multiply by.
  7253. * @param {Matrix4} result The object onto which to store the result.
  7254. * @returns {Matrix4} The modified result parameter.
  7255. *
  7256. * @example
  7257. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  7258. * // m = [10.0, 11.0, 12.0, 13.0]
  7259. * // [14.0, 15.0, 16.0, 17.0]
  7260. * // [18.0, 19.0, 20.0, 21.0]
  7261. * // [22.0, 23.0, 24.0, 25.0]
  7262. *
  7263. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  7264. *
  7265. * // m remains the same
  7266. * // a = [-20.0, -22.0, -24.0, -26.0]
  7267. * // [-28.0, -30.0, -32.0, -34.0]
  7268. * // [-36.0, -38.0, -40.0, -42.0]
  7269. * // [-44.0, -46.0, -48.0, -50.0]
  7270. */
  7271. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  7272. if (!defined(matrix)) {
  7273. throw new DeveloperError('matrix is required');
  7274. }
  7275. if (typeof scalar !== 'number') {
  7276. throw new DeveloperError('scalar must be a number');
  7277. }
  7278. if (!defined(result)) {
  7279. throw new DeveloperError('result is required');
  7280. }
  7281. result[0] = matrix[0] * scalar;
  7282. result[1] = matrix[1] * scalar;
  7283. result[2] = matrix[2] * scalar;
  7284. result[3] = matrix[3] * scalar;
  7285. result[4] = matrix[4] * scalar;
  7286. result[5] = matrix[5] * scalar;
  7287. result[6] = matrix[6] * scalar;
  7288. result[7] = matrix[7] * scalar;
  7289. result[8] = matrix[8] * scalar;
  7290. result[9] = matrix[9] * scalar;
  7291. result[10] = matrix[10] * scalar;
  7292. result[11] = matrix[11] * scalar;
  7293. result[12] = matrix[12] * scalar;
  7294. result[13] = matrix[13] * scalar;
  7295. result[14] = matrix[14] * scalar;
  7296. result[15] = matrix[15] * scalar;
  7297. return result;
  7298. };
  7299. /**
  7300. * Computes a negated copy of the provided matrix.
  7301. *
  7302. * @param {Matrix4} matrix The matrix to negate.
  7303. * @param {Matrix4} result The object onto which to store the result.
  7304. * @returns {Matrix4} The modified result parameter.
  7305. *
  7306. * @example
  7307. * //create a new Matrix4 instance which is a negation of a Matrix4
  7308. * // m = [10.0, 11.0, 12.0, 13.0]
  7309. * // [14.0, 15.0, 16.0, 17.0]
  7310. * // [18.0, 19.0, 20.0, 21.0]
  7311. * // [22.0, 23.0, 24.0, 25.0]
  7312. *
  7313. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  7314. *
  7315. * // m remains the same
  7316. * // a = [-10.0, -11.0, -12.0, -13.0]
  7317. * // [-14.0, -15.0, -16.0, -17.0]
  7318. * // [-18.0, -19.0, -20.0, -21.0]
  7319. * // [-22.0, -23.0, -24.0, -25.0]
  7320. */
  7321. Matrix4.negate = function(matrix, result) {
  7322. if (!defined(matrix)) {
  7323. throw new DeveloperError('matrix is required');
  7324. }
  7325. if (!defined(result)) {
  7326. throw new DeveloperError('result is required');
  7327. }
  7328. result[0] = -matrix[0];
  7329. result[1] = -matrix[1];
  7330. result[2] = -matrix[2];
  7331. result[3] = -matrix[3];
  7332. result[4] = -matrix[4];
  7333. result[5] = -matrix[5];
  7334. result[6] = -matrix[6];
  7335. result[7] = -matrix[7];
  7336. result[8] = -matrix[8];
  7337. result[9] = -matrix[9];
  7338. result[10] = -matrix[10];
  7339. result[11] = -matrix[11];
  7340. result[12] = -matrix[12];
  7341. result[13] = -matrix[13];
  7342. result[14] = -matrix[14];
  7343. result[15] = -matrix[15];
  7344. return result;
  7345. };
  7346. /**
  7347. * Computes the transpose of the provided matrix.
  7348. *
  7349. * @param {Matrix4} matrix The matrix to transpose.
  7350. * @param {Matrix4} result The object onto which to store the result.
  7351. * @returns {Matrix4} The modified result parameter.
  7352. *
  7353. * @example
  7354. * //returns transpose of a Matrix4
  7355. * // m = [10.0, 11.0, 12.0, 13.0]
  7356. * // [14.0, 15.0, 16.0, 17.0]
  7357. * // [18.0, 19.0, 20.0, 21.0]
  7358. * // [22.0, 23.0, 24.0, 25.0]
  7359. *
  7360. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  7361. *
  7362. * // m remains the same
  7363. * // a = [10.0, 14.0, 18.0, 22.0]
  7364. * // [11.0, 15.0, 19.0, 23.0]
  7365. * // [12.0, 16.0, 20.0, 24.0]
  7366. * // [13.0, 17.0, 21.0, 25.0]
  7367. */
  7368. Matrix4.transpose = function(matrix, result) {
  7369. if (!defined(matrix)) {
  7370. throw new DeveloperError('matrix is required');
  7371. }
  7372. if (!defined(result)) {
  7373. throw new DeveloperError('result is required');
  7374. }
  7375. var matrix1 = matrix[1];
  7376. var matrix2 = matrix[2];
  7377. var matrix3 = matrix[3];
  7378. var matrix6 = matrix[6];
  7379. var matrix7 = matrix[7];
  7380. var matrix11 = matrix[11];
  7381. result[0] = matrix[0];
  7382. result[1] = matrix[4];
  7383. result[2] = matrix[8];
  7384. result[3] = matrix[12];
  7385. result[4] = matrix1;
  7386. result[5] = matrix[5];
  7387. result[6] = matrix[9];
  7388. result[7] = matrix[13];
  7389. result[8] = matrix2;
  7390. result[9] = matrix6;
  7391. result[10] = matrix[10];
  7392. result[11] = matrix[14];
  7393. result[12] = matrix3;
  7394. result[13] = matrix7;
  7395. result[14] = matrix11;
  7396. result[15] = matrix[15];
  7397. return result;
  7398. };
  7399. /**
  7400. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  7401. *
  7402. * @param {Matrix4} matrix The matrix with signed elements.
  7403. * @param {Matrix4} result The object onto which to store the result.
  7404. * @returns {Matrix4} The modified result parameter.
  7405. */
  7406. Matrix4.abs = function(matrix, result) {
  7407. if (!defined(matrix)) {
  7408. throw new DeveloperError('matrix is required');
  7409. }
  7410. if (!defined(result)) {
  7411. throw new DeveloperError('result is required');
  7412. }
  7413. result[0] = Math.abs(matrix[0]);
  7414. result[1] = Math.abs(matrix[1]);
  7415. result[2] = Math.abs(matrix[2]);
  7416. result[3] = Math.abs(matrix[3]);
  7417. result[4] = Math.abs(matrix[4]);
  7418. result[5] = Math.abs(matrix[5]);
  7419. result[6] = Math.abs(matrix[6]);
  7420. result[7] = Math.abs(matrix[7]);
  7421. result[8] = Math.abs(matrix[8]);
  7422. result[9] = Math.abs(matrix[9]);
  7423. result[10] = Math.abs(matrix[10]);
  7424. result[11] = Math.abs(matrix[11]);
  7425. result[12] = Math.abs(matrix[12]);
  7426. result[13] = Math.abs(matrix[13]);
  7427. result[14] = Math.abs(matrix[14]);
  7428. result[15] = Math.abs(matrix[15]);
  7429. return result;
  7430. };
  7431. /**
  7432. * Compares the provided matrices componentwise and returns
  7433. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7434. *
  7435. * @param {Matrix4} [left] The first matrix.
  7436. * @param {Matrix4} [right] The second matrix.
  7437. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7438. *
  7439. * @example
  7440. * //compares two Matrix4 instances
  7441. *
  7442. * // a = [10.0, 14.0, 18.0, 22.0]
  7443. * // [11.0, 15.0, 19.0, 23.0]
  7444. * // [12.0, 16.0, 20.0, 24.0]
  7445. * // [13.0, 17.0, 21.0, 25.0]
  7446. *
  7447. * // b = [10.0, 14.0, 18.0, 22.0]
  7448. * // [11.0, 15.0, 19.0, 23.0]
  7449. * // [12.0, 16.0, 20.0, 24.0]
  7450. * // [13.0, 17.0, 21.0, 25.0]
  7451. *
  7452. * if(Cesium.Matrix4.equals(a,b)) {
  7453. * console.log("Both matrices are equal");
  7454. * } else {
  7455. * console.log("They are not equal");
  7456. * }
  7457. *
  7458. * //Prints "Both matrices are equal" on the console
  7459. */
  7460. Matrix4.equals = function(left, right) {
  7461. // Given that most matrices will be transformation matrices, the elements
  7462. // are tested in order such that the test is likely to fail as early
  7463. // as possible. I _think_ this is just as friendly to the L1 cache
  7464. // as testing in index order. It is certainty faster in practice.
  7465. return (left === right) ||
  7466. (defined(left) &&
  7467. defined(right) &&
  7468. // Translation
  7469. left[12] === right[12] &&
  7470. left[13] === right[13] &&
  7471. left[14] === right[14] &&
  7472. // Rotation/scale
  7473. left[0] === right[0] &&
  7474. left[1] === right[1] &&
  7475. left[2] === right[2] &&
  7476. left[4] === right[4] &&
  7477. left[5] === right[5] &&
  7478. left[6] === right[6] &&
  7479. left[8] === right[8] &&
  7480. left[9] === right[9] &&
  7481. left[10] === right[10] &&
  7482. // Bottom row
  7483. left[3] === right[3] &&
  7484. left[7] === right[7] &&
  7485. left[11] === right[11] &&
  7486. left[15] === right[15]);
  7487. };
  7488. /**
  7489. * Compares the provided matrices componentwise and returns
  7490. * <code>true</code> if they are within the provided epsilon,
  7491. * <code>false</code> otherwise.
  7492. *
  7493. * @param {Matrix4} [left] The first matrix.
  7494. * @param {Matrix4} [right] The second matrix.
  7495. * @param {Number} epsilon The epsilon to use for equality testing.
  7496. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7497. *
  7498. * @example
  7499. * //compares two Matrix4 instances
  7500. *
  7501. * // a = [10.5, 14.5, 18.5, 22.5]
  7502. * // [11.5, 15.5, 19.5, 23.5]
  7503. * // [12.5, 16.5, 20.5, 24.5]
  7504. * // [13.5, 17.5, 21.5, 25.5]
  7505. *
  7506. * // b = [10.0, 14.0, 18.0, 22.0]
  7507. * // [11.0, 15.0, 19.0, 23.0]
  7508. * // [12.0, 16.0, 20.0, 24.0]
  7509. * // [13.0, 17.0, 21.0, 25.0]
  7510. *
  7511. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  7512. * console.log("Difference between both the matrices is less than 0.1");
  7513. * } else {
  7514. * console.log("Difference between both the matrices is not less than 0.1");
  7515. * }
  7516. *
  7517. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  7518. */
  7519. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  7520. if (typeof epsilon !== 'number') {
  7521. throw new DeveloperError('epsilon must be a number');
  7522. }
  7523. return (left === right) ||
  7524. (defined(left) &&
  7525. defined(right) &&
  7526. Math.abs(left[0] - right[0]) <= epsilon &&
  7527. Math.abs(left[1] - right[1]) <= epsilon &&
  7528. Math.abs(left[2] - right[2]) <= epsilon &&
  7529. Math.abs(left[3] - right[3]) <= epsilon &&
  7530. Math.abs(left[4] - right[4]) <= epsilon &&
  7531. Math.abs(left[5] - right[5]) <= epsilon &&
  7532. Math.abs(left[6] - right[6]) <= epsilon &&
  7533. Math.abs(left[7] - right[7]) <= epsilon &&
  7534. Math.abs(left[8] - right[8]) <= epsilon &&
  7535. Math.abs(left[9] - right[9]) <= epsilon &&
  7536. Math.abs(left[10] - right[10]) <= epsilon &&
  7537. Math.abs(left[11] - right[11]) <= epsilon &&
  7538. Math.abs(left[12] - right[12]) <= epsilon &&
  7539. Math.abs(left[13] - right[13]) <= epsilon &&
  7540. Math.abs(left[14] - right[14]) <= epsilon &&
  7541. Math.abs(left[15] - right[15]) <= epsilon);
  7542. };
  7543. /**
  7544. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  7545. *
  7546. * @param {Matrix4} matrix The matrix to use.
  7547. * @param {Cartesian3} result The object onto which to store the result.
  7548. * @returns {Cartesian3} The modified result parameter.
  7549. */
  7550. Matrix4.getTranslation = function(matrix, result) {
  7551. if (!defined(matrix)) {
  7552. throw new DeveloperError('matrix is required');
  7553. }
  7554. if (!defined(result)) {
  7555. throw new DeveloperError('result is required');
  7556. }
  7557. result.x = matrix[12];
  7558. result.y = matrix[13];
  7559. result.z = matrix[14];
  7560. return result;
  7561. };
  7562. /**
  7563. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  7564. *
  7565. * @param {Matrix4} matrix The matrix to use.
  7566. * @param {Matrix3} result The object onto which to store the result.
  7567. * @returns {Matrix3} The modified result parameter.
  7568. *
  7569. * @example
  7570. * // returns a Matrix3 instance from a Matrix4 instance
  7571. *
  7572. * // m = [10.0, 14.0, 18.0, 22.0]
  7573. * // [11.0, 15.0, 19.0, 23.0]
  7574. * // [12.0, 16.0, 20.0, 24.0]
  7575. * // [13.0, 17.0, 21.0, 25.0]
  7576. *
  7577. * var b = new Cesium.Matrix3();
  7578. * Cesium.Matrix4.getRotation(m,b);
  7579. *
  7580. * // b = [10.0, 14.0, 18.0]
  7581. * // [11.0, 15.0, 19.0]
  7582. * // [12.0, 16.0, 20.0]
  7583. */
  7584. Matrix4.getRotation = function(matrix, result) {
  7585. if (!defined(matrix)) {
  7586. throw new DeveloperError('matrix is required');
  7587. }
  7588. if (!defined(result)) {
  7589. throw new DeveloperError('result is required');
  7590. }
  7591. result[0] = matrix[0];
  7592. result[1] = matrix[1];
  7593. result[2] = matrix[2];
  7594. result[3] = matrix[4];
  7595. result[4] = matrix[5];
  7596. result[5] = matrix[6];
  7597. result[6] = matrix[8];
  7598. result[7] = matrix[9];
  7599. result[8] = matrix[10];
  7600. return result;
  7601. };
  7602. var scratchInverseRotation = new Matrix3();
  7603. var scratchMatrix3Zero = new Matrix3();
  7604. var scratchBottomRow = new Cartesian4();
  7605. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  7606. /**
  7607. * Computes the inverse of the provided matrix using Cramers Rule.
  7608. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  7609. * If the matrix is an affine transformation matrix, it is more efficient
  7610. * to invert it with {@link Matrix4.inverseTransformation}.
  7611. *
  7612. * @param {Matrix4} matrix The matrix to invert.
  7613. * @param {Matrix4} result The object onto which to store the result.
  7614. * @returns {Matrix4} The modified result parameter.
  7615. *
  7616. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  7617. */
  7618. Matrix4.inverse = function(matrix, result) {
  7619. if (!defined(matrix)) {
  7620. throw new DeveloperError('matrix is required');
  7621. }
  7622. if (!defined(result)) {
  7623. throw new DeveloperError('result is required');
  7624. }
  7625. // Special case for a zero scale matrix that can occur, for example,
  7626. // when a model's node has a [0, 0, 0] scale.
  7627. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  7628. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  7629. result[0] = 0.0;
  7630. result[1] = 0.0;
  7631. result[2] = 0.0;
  7632. result[3] = 0.0;
  7633. result[4] = 0.0;
  7634. result[5] = 0.0;
  7635. result[6] = 0.0;
  7636. result[7] = 0.0;
  7637. result[8] = 0.0;
  7638. result[9] = 0.0;
  7639. result[10] = 0.0;
  7640. result[11] = 0.0;
  7641. result[12] = -matrix[12];
  7642. result[13] = -matrix[13];
  7643. result[14] = -matrix[14];
  7644. result[15] = 1.0;
  7645. return result;
  7646. }
  7647. //
  7648. // Ported from:
  7649. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  7650. //
  7651. var src0 = matrix[0];
  7652. var src1 = matrix[4];
  7653. var src2 = matrix[8];
  7654. var src3 = matrix[12];
  7655. var src4 = matrix[1];
  7656. var src5 = matrix[5];
  7657. var src6 = matrix[9];
  7658. var src7 = matrix[13];
  7659. var src8 = matrix[2];
  7660. var src9 = matrix[6];
  7661. var src10 = matrix[10];
  7662. var src11 = matrix[14];
  7663. var src12 = matrix[3];
  7664. var src13 = matrix[7];
  7665. var src14 = matrix[11];
  7666. var src15 = matrix[15];
  7667. // calculate pairs for first 8 elements (cofactors)
  7668. var tmp0 = src10 * src15;
  7669. var tmp1 = src11 * src14;
  7670. var tmp2 = src9 * src15;
  7671. var tmp3 = src11 * src13;
  7672. var tmp4 = src9 * src14;
  7673. var tmp5 = src10 * src13;
  7674. var tmp6 = src8 * src15;
  7675. var tmp7 = src11 * src12;
  7676. var tmp8 = src8 * src14;
  7677. var tmp9 = src10 * src12;
  7678. var tmp10 = src8 * src13;
  7679. var tmp11 = src9 * src12;
  7680. // calculate first 8 elements (cofactors)
  7681. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  7682. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  7683. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  7684. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  7685. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  7686. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  7687. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  7688. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  7689. // calculate pairs for second 8 elements (cofactors)
  7690. tmp0 = src2 * src7;
  7691. tmp1 = src3 * src6;
  7692. tmp2 = src1 * src7;
  7693. tmp3 = src3 * src5;
  7694. tmp4 = src1 * src6;
  7695. tmp5 = src2 * src5;
  7696. tmp6 = src0 * src7;
  7697. tmp7 = src3 * src4;
  7698. tmp8 = src0 * src6;
  7699. tmp9 = src2 * src4;
  7700. tmp10 = src0 * src5;
  7701. tmp11 = src1 * src4;
  7702. // calculate second 8 elements (cofactors)
  7703. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  7704. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  7705. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  7706. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  7707. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  7708. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  7709. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  7710. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  7711. // calculate determinant
  7712. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  7713. if (Math.abs(det) < CesiumMath.EPSILON20) {
  7714. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  7715. }
  7716. // calculate matrix inverse
  7717. det = 1.0 / det;
  7718. result[0] = dst0 * det;
  7719. result[1] = dst1 * det;
  7720. result[2] = dst2 * det;
  7721. result[3] = dst3 * det;
  7722. result[4] = dst4 * det;
  7723. result[5] = dst5 * det;
  7724. result[6] = dst6 * det;
  7725. result[7] = dst7 * det;
  7726. result[8] = dst8 * det;
  7727. result[9] = dst9 * det;
  7728. result[10] = dst10 * det;
  7729. result[11] = dst11 * det;
  7730. result[12] = dst12 * det;
  7731. result[13] = dst13 * det;
  7732. result[14] = dst14 * det;
  7733. result[15] = dst15 * det;
  7734. return result;
  7735. };
  7736. /**
  7737. * Computes the inverse of the provided matrix assuming it is
  7738. * an affine transformation matrix, where the upper left 3x3 elements
  7739. * are a rotation matrix, and the upper three elements in the fourth
  7740. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  7741. * The matrix is not verified to be in the proper form.
  7742. * This method is faster than computing the inverse for a general 4x4
  7743. * matrix using {@link Matrix4.inverse}.
  7744. *
  7745. * @param {Matrix4} matrix The matrix to invert.
  7746. * @param {Matrix4} result The object onto which to store the result.
  7747. * @returns {Matrix4} The modified result parameter.
  7748. */
  7749. Matrix4.inverseTransformation = function(matrix, result) {
  7750. if (!defined(matrix)) {
  7751. throw new DeveloperError('matrix is required');
  7752. }
  7753. if (!defined(result)) {
  7754. throw new DeveloperError('result is required');
  7755. }
  7756. //This function is an optimized version of the below 4 lines.
  7757. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  7758. //var rTN = Matrix3.negate(rT);
  7759. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  7760. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  7761. var matrix0 = matrix[0];
  7762. var matrix1 = matrix[1];
  7763. var matrix2 = matrix[2];
  7764. var matrix4 = matrix[4];
  7765. var matrix5 = matrix[5];
  7766. var matrix6 = matrix[6];
  7767. var matrix8 = matrix[8];
  7768. var matrix9 = matrix[9];
  7769. var matrix10 = matrix[10];
  7770. var vX = matrix[12];
  7771. var vY = matrix[13];
  7772. var vZ = matrix[14];
  7773. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  7774. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  7775. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  7776. result[0] = matrix0;
  7777. result[1] = matrix4;
  7778. result[2] = matrix8;
  7779. result[3] = 0.0;
  7780. result[4] = matrix1;
  7781. result[5] = matrix5;
  7782. result[6] = matrix9;
  7783. result[7] = 0.0;
  7784. result[8] = matrix2;
  7785. result[9] = matrix6;
  7786. result[10] = matrix10;
  7787. result[11] = 0.0;
  7788. result[12] = x;
  7789. result[13] = y;
  7790. result[14] = z;
  7791. result[15] = 1.0;
  7792. return result;
  7793. };
  7794. /**
  7795. * An immutable Matrix4 instance initialized to the identity matrix.
  7796. *
  7797. * @type {Matrix4}
  7798. * @constant
  7799. */
  7800. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  7801. 0.0, 1.0, 0.0, 0.0,
  7802. 0.0, 0.0, 1.0, 0.0,
  7803. 0.0, 0.0, 0.0, 1.0));
  7804. /**
  7805. * An immutable Matrix4 instance initialized to the zero matrix.
  7806. *
  7807. * @type {Matrix4}
  7808. * @constant
  7809. */
  7810. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  7811. 0.0, 0.0, 0.0, 0.0,
  7812. 0.0, 0.0, 0.0, 0.0,
  7813. 0.0, 0.0, 0.0, 0.0));
  7814. /**
  7815. * The index into Matrix4 for column 0, row 0.
  7816. *
  7817. * @type {Number}
  7818. * @constant
  7819. */
  7820. Matrix4.COLUMN0ROW0 = 0;
  7821. /**
  7822. * The index into Matrix4 for column 0, row 1.
  7823. *
  7824. * @type {Number}
  7825. * @constant
  7826. */
  7827. Matrix4.COLUMN0ROW1 = 1;
  7828. /**
  7829. * The index into Matrix4 for column 0, row 2.
  7830. *
  7831. * @type {Number}
  7832. * @constant
  7833. */
  7834. Matrix4.COLUMN0ROW2 = 2;
  7835. /**
  7836. * The index into Matrix4 for column 0, row 3.
  7837. *
  7838. * @type {Number}
  7839. * @constant
  7840. */
  7841. Matrix4.COLUMN0ROW3 = 3;
  7842. /**
  7843. * The index into Matrix4 for column 1, row 0.
  7844. *
  7845. * @type {Number}
  7846. * @constant
  7847. */
  7848. Matrix4.COLUMN1ROW0 = 4;
  7849. /**
  7850. * The index into Matrix4 for column 1, row 1.
  7851. *
  7852. * @type {Number}
  7853. * @constant
  7854. */
  7855. Matrix4.COLUMN1ROW1 = 5;
  7856. /**
  7857. * The index into Matrix4 for column 1, row 2.
  7858. *
  7859. * @type {Number}
  7860. * @constant
  7861. */
  7862. Matrix4.COLUMN1ROW2 = 6;
  7863. /**
  7864. * The index into Matrix4 for column 1, row 3.
  7865. *
  7866. * @type {Number}
  7867. * @constant
  7868. */
  7869. Matrix4.COLUMN1ROW3 = 7;
  7870. /**
  7871. * The index into Matrix4 for column 2, row 0.
  7872. *
  7873. * @type {Number}
  7874. * @constant
  7875. */
  7876. Matrix4.COLUMN2ROW0 = 8;
  7877. /**
  7878. * The index into Matrix4 for column 2, row 1.
  7879. *
  7880. * @type {Number}
  7881. * @constant
  7882. */
  7883. Matrix4.COLUMN2ROW1 = 9;
  7884. /**
  7885. * The index into Matrix4 for column 2, row 2.
  7886. *
  7887. * @type {Number}
  7888. * @constant
  7889. */
  7890. Matrix4.COLUMN2ROW2 = 10;
  7891. /**
  7892. * The index into Matrix4 for column 2, row 3.
  7893. *
  7894. * @type {Number}
  7895. * @constant
  7896. */
  7897. Matrix4.COLUMN2ROW3 = 11;
  7898. /**
  7899. * The index into Matrix4 for column 3, row 0.
  7900. *
  7901. * @type {Number}
  7902. * @constant
  7903. */
  7904. Matrix4.COLUMN3ROW0 = 12;
  7905. /**
  7906. * The index into Matrix4 for column 3, row 1.
  7907. *
  7908. * @type {Number}
  7909. * @constant
  7910. */
  7911. Matrix4.COLUMN3ROW1 = 13;
  7912. /**
  7913. * The index into Matrix4 for column 3, row 2.
  7914. *
  7915. * @type {Number}
  7916. * @constant
  7917. */
  7918. Matrix4.COLUMN3ROW2 = 14;
  7919. /**
  7920. * The index into Matrix4 for column 3, row 3.
  7921. *
  7922. * @type {Number}
  7923. * @constant
  7924. */
  7925. Matrix4.COLUMN3ROW3 = 15;
  7926. defineProperties(Matrix4.prototype, {
  7927. /**
  7928. * Gets the number of items in the collection.
  7929. * @memberof Matrix4.prototype
  7930. *
  7931. * @type {Number}
  7932. */
  7933. length : {
  7934. get : function() {
  7935. return Matrix4.packedLength;
  7936. }
  7937. }
  7938. });
  7939. /**
  7940. * Duplicates the provided Matrix4 instance.
  7941. *
  7942. * @param {Matrix4} [result] The object onto which to store the result.
  7943. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7944. */
  7945. Matrix4.prototype.clone = function(result) {
  7946. return Matrix4.clone(this, result);
  7947. };
  7948. /**
  7949. * Compares this matrix to the provided matrix componentwise and returns
  7950. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7951. *
  7952. * @param {Matrix4} [right] The right hand side matrix.
  7953. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  7954. */
  7955. Matrix4.prototype.equals = function(right) {
  7956. return Matrix4.equals(this, right);
  7957. };
  7958. /**
  7959. * @private
  7960. */
  7961. Matrix4.equalsArray = function(matrix, array, offset) {
  7962. return matrix[0] === array[offset] &&
  7963. matrix[1] === array[offset + 1] &&
  7964. matrix[2] === array[offset + 2] &&
  7965. matrix[3] === array[offset + 3] &&
  7966. matrix[4] === array[offset + 4] &&
  7967. matrix[5] === array[offset + 5] &&
  7968. matrix[6] === array[offset + 6] &&
  7969. matrix[7] === array[offset + 7] &&
  7970. matrix[8] === array[offset + 8] &&
  7971. matrix[9] === array[offset + 9] &&
  7972. matrix[10] === array[offset + 10] &&
  7973. matrix[11] === array[offset + 11] &&
  7974. matrix[12] === array[offset + 12] &&
  7975. matrix[13] === array[offset + 13] &&
  7976. matrix[14] === array[offset + 14] &&
  7977. matrix[15] === array[offset + 15];
  7978. };
  7979. /**
  7980. * Compares this matrix to the provided matrix componentwise and returns
  7981. * <code>true</code> if they are within the provided epsilon,
  7982. * <code>false</code> otherwise.
  7983. *
  7984. * @param {Matrix4} [right] The right hand side matrix.
  7985. * @param {Number} epsilon The epsilon to use for equality testing.
  7986. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  7987. */
  7988. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  7989. return Matrix4.equalsEpsilon(this, right, epsilon);
  7990. };
  7991. /**
  7992. * Computes a string representing this Matrix with each row being
  7993. * on a separate line and in the format '(column0, column1, column2, column3)'.
  7994. *
  7995. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  7996. */
  7997. Matrix4.prototype.toString = function() {
  7998. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  7999. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  8000. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  8001. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  8002. };
  8003. return Matrix4;
  8004. });
  8005. /*global define*/
  8006. define('Core/Rectangle',[
  8007. './Cartographic',
  8008. './defaultValue',
  8009. './defined',
  8010. './defineProperties',
  8011. './DeveloperError',
  8012. './Ellipsoid',
  8013. './freezeObject',
  8014. './Math'
  8015. ], function(
  8016. Cartographic,
  8017. defaultValue,
  8018. defined,
  8019. defineProperties,
  8020. DeveloperError,
  8021. Ellipsoid,
  8022. freezeObject,
  8023. CesiumMath) {
  8024. 'use strict';
  8025. /**
  8026. * A two dimensional region specified as longitude and latitude coordinates.
  8027. *
  8028. * @alias Rectangle
  8029. * @constructor
  8030. *
  8031. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  8032. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  8033. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  8034. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  8035. *
  8036. * @see Packable
  8037. */
  8038. function Rectangle(west, south, east, north) {
  8039. /**
  8040. * The westernmost longitude in radians in the range [-Pi, Pi].
  8041. *
  8042. * @type {Number}
  8043. * @default 0.0
  8044. */
  8045. this.west = defaultValue(west, 0.0);
  8046. /**
  8047. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  8048. *
  8049. * @type {Number}
  8050. * @default 0.0
  8051. */
  8052. this.south = defaultValue(south, 0.0);
  8053. /**
  8054. * The easternmost longitude in radians in the range [-Pi, Pi].
  8055. *
  8056. * @type {Number}
  8057. * @default 0.0
  8058. */
  8059. this.east = defaultValue(east, 0.0);
  8060. /**
  8061. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  8062. *
  8063. * @type {Number}
  8064. * @default 0.0
  8065. */
  8066. this.north = defaultValue(north, 0.0);
  8067. }
  8068. defineProperties(Rectangle.prototype, {
  8069. /**
  8070. * Gets the width of the rectangle in radians.
  8071. * @memberof Rectangle.prototype
  8072. * @type {Number}
  8073. */
  8074. width : {
  8075. get : function() {
  8076. return Rectangle.computeWidth(this);
  8077. }
  8078. },
  8079. /**
  8080. * Gets the height of the rectangle in radians.
  8081. * @memberof Rectangle.prototype
  8082. * @type {Number}
  8083. */
  8084. height : {
  8085. get : function() {
  8086. return Rectangle.computeHeight(this);
  8087. }
  8088. }
  8089. });
  8090. /**
  8091. * The number of elements used to pack the object into an array.
  8092. * @type {Number}
  8093. */
  8094. Rectangle.packedLength = 4;
  8095. /**
  8096. * Stores the provided instance into the provided array.
  8097. *
  8098. * @param {Rectangle} value The value to pack.
  8099. * @param {Number[]} array The array to pack into.
  8100. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  8101. *
  8102. * @returns {Number[]} The array that was packed into
  8103. */
  8104. Rectangle.pack = function(value, array, startingIndex) {
  8105. if (!defined(value)) {
  8106. throw new DeveloperError('value is required');
  8107. }
  8108. if (!defined(array)) {
  8109. throw new DeveloperError('array is required');
  8110. }
  8111. startingIndex = defaultValue(startingIndex, 0);
  8112. array[startingIndex++] = value.west;
  8113. array[startingIndex++] = value.south;
  8114. array[startingIndex++] = value.east;
  8115. array[startingIndex] = value.north;
  8116. return array;
  8117. };
  8118. /**
  8119. * Retrieves an instance from a packed array.
  8120. *
  8121. * @param {Number[]} array The packed array.
  8122. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  8123. * @param {Rectangle} [result] The object into which to store the result.
  8124. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  8125. */
  8126. Rectangle.unpack = function(array, startingIndex, result) {
  8127. if (!defined(array)) {
  8128. throw new DeveloperError('array is required');
  8129. }
  8130. startingIndex = defaultValue(startingIndex, 0);
  8131. if (!defined(result)) {
  8132. result = new Rectangle();
  8133. }
  8134. result.west = array[startingIndex++];
  8135. result.south = array[startingIndex++];
  8136. result.east = array[startingIndex++];
  8137. result.north = array[startingIndex];
  8138. return result;
  8139. };
  8140. /**
  8141. * Computes the width of a rectangle in radians.
  8142. * @param {Rectangle} rectangle The rectangle to compute the width of.
  8143. * @returns {Number} The width.
  8144. */
  8145. Rectangle.computeWidth = function(rectangle) {
  8146. if (!defined(rectangle)) {
  8147. throw new DeveloperError('rectangle is required.');
  8148. }
  8149. var east = rectangle.east;
  8150. var west = rectangle.west;
  8151. if (east < west) {
  8152. east += CesiumMath.TWO_PI;
  8153. }
  8154. return east - west;
  8155. };
  8156. /**
  8157. * Computes the height of a rectangle in radians.
  8158. * @param {Rectangle} rectangle The rectangle to compute the height of.
  8159. * @returns {Number} The height.
  8160. */
  8161. Rectangle.computeHeight = function(rectangle) {
  8162. if (!defined(rectangle)) {
  8163. throw new DeveloperError('rectangle is required.');
  8164. }
  8165. return rectangle.north - rectangle.south;
  8166. };
  8167. /**
  8168. * Creates an rectangle given the boundary longitude and latitude in degrees.
  8169. *
  8170. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  8171. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  8172. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  8173. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  8174. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8175. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8176. *
  8177. * @example
  8178. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  8179. */
  8180. Rectangle.fromDegrees = function(west, south, east, north, result) {
  8181. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  8182. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  8183. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  8184. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  8185. if (!defined(result)) {
  8186. return new Rectangle(west, south, east, north);
  8187. }
  8188. result.west = west;
  8189. result.south = south;
  8190. result.east = east;
  8191. result.north = north;
  8192. return result;
  8193. };
  8194. /**
  8195. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  8196. *
  8197. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  8198. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8199. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8200. */
  8201. Rectangle.fromCartographicArray = function(cartographics, result) {
  8202. if (!defined(cartographics)) {
  8203. throw new DeveloperError('cartographics is required.');
  8204. }
  8205. var west = Number.MAX_VALUE;
  8206. var east = -Number.MAX_VALUE;
  8207. var westOverIDL = Number.MAX_VALUE;
  8208. var eastOverIDL = -Number.MAX_VALUE;
  8209. var south = Number.MAX_VALUE;
  8210. var north = -Number.MAX_VALUE;
  8211. for ( var i = 0, len = cartographics.length; i < len; i++) {
  8212. var position = cartographics[i];
  8213. west = Math.min(west, position.longitude);
  8214. east = Math.max(east, position.longitude);
  8215. south = Math.min(south, position.latitude);
  8216. north = Math.max(north, position.latitude);
  8217. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  8218. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  8219. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  8220. }
  8221. if(east - west > eastOverIDL - westOverIDL) {
  8222. west = westOverIDL;
  8223. east = eastOverIDL;
  8224. if (east > CesiumMath.PI) {
  8225. east = east - CesiumMath.TWO_PI;
  8226. }
  8227. if (west > CesiumMath.PI) {
  8228. west = west - CesiumMath.TWO_PI;
  8229. }
  8230. }
  8231. if (!defined(result)) {
  8232. return new Rectangle(west, south, east, north);
  8233. }
  8234. result.west = west;
  8235. result.south = south;
  8236. result.east = east;
  8237. result.north = north;
  8238. return result;
  8239. };
  8240. /**
  8241. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  8242. *
  8243. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  8244. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  8245. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8246. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8247. */
  8248. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  8249. if (!defined(cartesians)) {
  8250. throw new DeveloperError('cartesians is required.');
  8251. }
  8252. var west = Number.MAX_VALUE;
  8253. var east = -Number.MAX_VALUE;
  8254. var westOverIDL = Number.MAX_VALUE;
  8255. var eastOverIDL = -Number.MAX_VALUE;
  8256. var south = Number.MAX_VALUE;
  8257. var north = -Number.MAX_VALUE;
  8258. for ( var i = 0, len = cartesians.length; i < len; i++) {
  8259. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  8260. west = Math.min(west, position.longitude);
  8261. east = Math.max(east, position.longitude);
  8262. south = Math.min(south, position.latitude);
  8263. north = Math.max(north, position.latitude);
  8264. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  8265. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  8266. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  8267. }
  8268. if(east - west > eastOverIDL - westOverIDL) {
  8269. west = westOverIDL;
  8270. east = eastOverIDL;
  8271. if (east > CesiumMath.PI) {
  8272. east = east - CesiumMath.TWO_PI;
  8273. }
  8274. if (west > CesiumMath.PI) {
  8275. west = west - CesiumMath.TWO_PI;
  8276. }
  8277. }
  8278. if (!defined(result)) {
  8279. return new Rectangle(west, south, east, north);
  8280. }
  8281. result.west = west;
  8282. result.south = south;
  8283. result.east = east;
  8284. result.north = north;
  8285. return result;
  8286. };
  8287. /**
  8288. * Duplicates an Rectangle.
  8289. *
  8290. * @param {Rectangle} rectangle The rectangle to clone.
  8291. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8292. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  8293. */
  8294. Rectangle.clone = function(rectangle, result) {
  8295. if (!defined(rectangle)) {
  8296. return undefined;
  8297. }
  8298. if (!defined(result)) {
  8299. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  8300. }
  8301. result.west = rectangle.west;
  8302. result.south = rectangle.south;
  8303. result.east = rectangle.east;
  8304. result.north = rectangle.north;
  8305. return result;
  8306. };
  8307. /**
  8308. * Duplicates this Rectangle.
  8309. *
  8310. * @param {Rectangle} [result] The object onto which to store the result.
  8311. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8312. */
  8313. Rectangle.prototype.clone = function(result) {
  8314. return Rectangle.clone(this, result);
  8315. };
  8316. /**
  8317. * Compares the provided Rectangle with this Rectangle componentwise and returns
  8318. * <code>true</code> if they are equal, <code>false</code> otherwise.
  8319. *
  8320. * @param {Rectangle} [other] The Rectangle to compare.
  8321. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  8322. */
  8323. Rectangle.prototype.equals = function(other) {
  8324. return Rectangle.equals(this, other);
  8325. };
  8326. /**
  8327. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  8328. * <code>false</code> otherwise.
  8329. *
  8330. * @param {Rectangle} [left] The first Rectangle.
  8331. * @param {Rectangle} [right] The second Rectangle.
  8332. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  8333. */
  8334. Rectangle.equals = function(left, right) {
  8335. return (left === right) ||
  8336. ((defined(left)) &&
  8337. (defined(right)) &&
  8338. (left.west === right.west) &&
  8339. (left.south === right.south) &&
  8340. (left.east === right.east) &&
  8341. (left.north === right.north));
  8342. };
  8343. /**
  8344. * Compares the provided Rectangle with this Rectangle componentwise and returns
  8345. * <code>true</code> if they are within the provided epsilon,
  8346. * <code>false</code> otherwise.
  8347. *
  8348. * @param {Rectangle} [other] The Rectangle to compare.
  8349. * @param {Number} epsilon The epsilon to use for equality testing.
  8350. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  8351. */
  8352. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  8353. if (typeof epsilon !== 'number') {
  8354. throw new DeveloperError('epsilon is required and must be a number.');
  8355. }
  8356. return defined(other) &&
  8357. (Math.abs(this.west - other.west) <= epsilon) &&
  8358. (Math.abs(this.south - other.south) <= epsilon) &&
  8359. (Math.abs(this.east - other.east) <= epsilon) &&
  8360. (Math.abs(this.north - other.north) <= epsilon);
  8361. };
  8362. /**
  8363. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  8364. *
  8365. * @param {Rectangle} rectangle The rectangle to validate
  8366. *
  8367. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  8368. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  8369. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  8370. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  8371. */
  8372. Rectangle.validate = function(rectangle) {
  8373. if (!defined(rectangle)) {
  8374. throw new DeveloperError('rectangle is required');
  8375. }
  8376. var north = rectangle.north;
  8377. if (typeof north !== 'number') {
  8378. throw new DeveloperError('north is required to be a number.');
  8379. }
  8380. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  8381. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  8382. }
  8383. var south = rectangle.south;
  8384. if (typeof south !== 'number') {
  8385. throw new DeveloperError('south is required to be a number.');
  8386. }
  8387. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  8388. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  8389. }
  8390. var west = rectangle.west;
  8391. if (typeof west !== 'number') {
  8392. throw new DeveloperError('west is required to be a number.');
  8393. }
  8394. if (west < -Math.PI || west > Math.PI) {
  8395. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  8396. }
  8397. var east = rectangle.east;
  8398. if (typeof east !== 'number') {
  8399. throw new DeveloperError('east is required to be a number.');
  8400. }
  8401. if (east < -Math.PI || east > Math.PI) {
  8402. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  8403. }
  8404. };
  8405. /**
  8406. * Computes the southwest corner of an rectangle.
  8407. *
  8408. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8409. * @param {Cartographic} [result] The object onto which to store the result.
  8410. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8411. */
  8412. Rectangle.southwest = function(rectangle, result) {
  8413. if (!defined(rectangle)) {
  8414. throw new DeveloperError('rectangle is required');
  8415. }
  8416. if (!defined(result)) {
  8417. return new Cartographic(rectangle.west, rectangle.south);
  8418. }
  8419. result.longitude = rectangle.west;
  8420. result.latitude = rectangle.south;
  8421. result.height = 0.0;
  8422. return result;
  8423. };
  8424. /**
  8425. * Computes the northwest corner of an rectangle.
  8426. *
  8427. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8428. * @param {Cartographic} [result] The object onto which to store the result.
  8429. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8430. */
  8431. Rectangle.northwest = function(rectangle, result) {
  8432. if (!defined(rectangle)) {
  8433. throw new DeveloperError('rectangle is required');
  8434. }
  8435. if (!defined(result)) {
  8436. return new Cartographic(rectangle.west, rectangle.north);
  8437. }
  8438. result.longitude = rectangle.west;
  8439. result.latitude = rectangle.north;
  8440. result.height = 0.0;
  8441. return result;
  8442. };
  8443. /**
  8444. * Computes the northeast corner of an rectangle.
  8445. *
  8446. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8447. * @param {Cartographic} [result] The object onto which to store the result.
  8448. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8449. */
  8450. Rectangle.northeast = function(rectangle, result) {
  8451. if (!defined(rectangle)) {
  8452. throw new DeveloperError('rectangle is required');
  8453. }
  8454. if (!defined(result)) {
  8455. return new Cartographic(rectangle.east, rectangle.north);
  8456. }
  8457. result.longitude = rectangle.east;
  8458. result.latitude = rectangle.north;
  8459. result.height = 0.0;
  8460. return result;
  8461. };
  8462. /**
  8463. * Computes the southeast corner of an rectangle.
  8464. *
  8465. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8466. * @param {Cartographic} [result] The object onto which to store the result.
  8467. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8468. */
  8469. Rectangle.southeast = function(rectangle, result) {
  8470. if (!defined(rectangle)) {
  8471. throw new DeveloperError('rectangle is required');
  8472. }
  8473. if (!defined(result)) {
  8474. return new Cartographic(rectangle.east, rectangle.south);
  8475. }
  8476. result.longitude = rectangle.east;
  8477. result.latitude = rectangle.south;
  8478. result.height = 0.0;
  8479. return result;
  8480. };
  8481. /**
  8482. * Computes the center of an rectangle.
  8483. *
  8484. * @param {Rectangle} rectangle The rectangle for which to find the center
  8485. * @param {Cartographic} [result] The object onto which to store the result.
  8486. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8487. */
  8488. Rectangle.center = function(rectangle, result) {
  8489. if (!defined(rectangle)) {
  8490. throw new DeveloperError('rectangle is required');
  8491. }
  8492. var east = rectangle.east;
  8493. var west = rectangle.west;
  8494. if (east < west) {
  8495. east += CesiumMath.TWO_PI;
  8496. }
  8497. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  8498. var latitude = (rectangle.south + rectangle.north) * 0.5;
  8499. if (!defined(result)) {
  8500. return new Cartographic(longitude, latitude);
  8501. }
  8502. result.longitude = longitude;
  8503. result.latitude = latitude;
  8504. result.height = 0.0;
  8505. return result;
  8506. };
  8507. /**
  8508. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  8509. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  8510. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  8511. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  8512. * coordinates, see {@link Rectangle.simpleIntersection}.
  8513. *
  8514. * @param {Rectangle} rectangle On rectangle to find an intersection
  8515. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  8516. * @param {Rectangle} [result] The object onto which to store the result.
  8517. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  8518. */
  8519. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  8520. if (!defined(rectangle)) {
  8521. throw new DeveloperError('rectangle is required');
  8522. }
  8523. if (!defined(otherRectangle)) {
  8524. throw new DeveloperError('otherRectangle is required.');
  8525. }
  8526. var rectangleEast = rectangle.east;
  8527. var rectangleWest = rectangle.west;
  8528. var otherRectangleEast = otherRectangle.east;
  8529. var otherRectangleWest = otherRectangle.west;
  8530. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  8531. rectangleEast += CesiumMath.TWO_PI;
  8532. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  8533. otherRectangleEast += CesiumMath.TWO_PI;
  8534. }
  8535. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  8536. otherRectangleWest += CesiumMath.TWO_PI;
  8537. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  8538. rectangleWest += CesiumMath.TWO_PI;
  8539. }
  8540. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  8541. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  8542. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  8543. return undefined;
  8544. }
  8545. var south = Math.max(rectangle.south, otherRectangle.south);
  8546. var north = Math.min(rectangle.north, otherRectangle.north);
  8547. if (south >= north) {
  8548. return undefined;
  8549. }
  8550. if (!defined(result)) {
  8551. return new Rectangle(west, south, east, north);
  8552. }
  8553. result.west = west;
  8554. result.south = south;
  8555. result.east = east;
  8556. result.north = north;
  8557. return result;
  8558. };
  8559. /**
  8560. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  8561. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  8562. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  8563. * and longitude (i.e. projected coordinates).
  8564. *
  8565. * @param {Rectangle} rectangle On rectangle to find an intersection
  8566. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  8567. * @param {Rectangle} [result] The object onto which to store the result.
  8568. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  8569. */
  8570. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  8571. if (!defined(rectangle)) {
  8572. throw new DeveloperError('rectangle is required');
  8573. }
  8574. if (!defined(otherRectangle)) {
  8575. throw new DeveloperError('otherRectangle is required.');
  8576. }
  8577. var west = Math.max(rectangle.west, otherRectangle.west);
  8578. var south = Math.max(rectangle.south, otherRectangle.south);
  8579. var east = Math.min(rectangle.east, otherRectangle.east);
  8580. var north = Math.min(rectangle.north, otherRectangle.north);
  8581. if (south >= north || west >= east) {
  8582. return undefined;
  8583. }
  8584. if (!defined(result)) {
  8585. return new Rectangle(west, south, east, north);
  8586. }
  8587. result.west = west;
  8588. result.south = south;
  8589. result.east = east;
  8590. result.north = north;
  8591. return result;
  8592. };
  8593. /**
  8594. * Computes a rectangle that is the union of two rectangles.
  8595. *
  8596. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  8597. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  8598. * @param {Rectangle} [result] The object onto which to store the result.
  8599. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8600. */
  8601. Rectangle.union = function(rectangle, otherRectangle, result) {
  8602. if (!defined(rectangle)) {
  8603. throw new DeveloperError('rectangle is required');
  8604. }
  8605. if (!defined(otherRectangle)) {
  8606. throw new DeveloperError('otherRectangle is required.');
  8607. }
  8608. if (!defined(result)) {
  8609. result = new Rectangle();
  8610. }
  8611. var rectangleEast = rectangle.east;
  8612. var rectangleWest = rectangle.west;
  8613. var otherRectangleEast = otherRectangle.east;
  8614. var otherRectangleWest = otherRectangle.west;
  8615. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  8616. rectangleEast += CesiumMath.TWO_PI;
  8617. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  8618. otherRectangleEast += CesiumMath.TWO_PI;
  8619. }
  8620. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  8621. otherRectangleWest += CesiumMath.TWO_PI;
  8622. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  8623. rectangleWest += CesiumMath.TWO_PI;
  8624. }
  8625. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  8626. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  8627. result.west = west;
  8628. result.south = Math.min(rectangle.south, otherRectangle.south);
  8629. result.east = east;
  8630. result.north = Math.max(rectangle.north, otherRectangle.north);
  8631. return result;
  8632. };
  8633. /**
  8634. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  8635. *
  8636. * @param {Rectangle} rectangle A rectangle to expand.
  8637. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  8638. * @param {Rectangle} [result] The object onto which to store the result.
  8639. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  8640. */
  8641. Rectangle.expand = function(rectangle, cartographic, result) {
  8642. if (!defined(rectangle)) {
  8643. throw new DeveloperError('rectangle is required.');
  8644. }
  8645. if (!defined(cartographic)) {
  8646. throw new DeveloperError('cartographic is required.');
  8647. }
  8648. if (!defined(result)) {
  8649. result = new Rectangle();
  8650. }
  8651. result.west = Math.min(rectangle.west, cartographic.longitude);
  8652. result.south = Math.min(rectangle.south, cartographic.latitude);
  8653. result.east = Math.max(rectangle.east, cartographic.longitude);
  8654. result.north = Math.max(rectangle.north, cartographic.latitude);
  8655. return result;
  8656. };
  8657. /**
  8658. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  8659. *
  8660. * @param {Rectangle} rectangle The rectangle
  8661. * @param {Cartographic} cartographic The cartographic to test.
  8662. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  8663. */
  8664. Rectangle.contains = function(rectangle, cartographic) {
  8665. if (!defined(rectangle)) {
  8666. throw new DeveloperError('rectangle is required');
  8667. }
  8668. if (!defined(cartographic)) {
  8669. throw new DeveloperError('cartographic is required.');
  8670. }
  8671. var longitude = cartographic.longitude;
  8672. var latitude = cartographic.latitude;
  8673. var west = rectangle.west;
  8674. var east = rectangle.east;
  8675. if (east < west) {
  8676. east += CesiumMath.TWO_PI;
  8677. if (longitude < 0.0) {
  8678. longitude += CesiumMath.TWO_PI;
  8679. }
  8680. }
  8681. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  8682. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  8683. latitude >= rectangle.south &&
  8684. latitude <= rectangle.north;
  8685. };
  8686. var subsampleLlaScratch = new Cartographic();
  8687. /**
  8688. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  8689. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  8690. * for rectangles that cover the poles or cross the equator.
  8691. *
  8692. * @param {Rectangle} rectangle The rectangle to subsample.
  8693. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  8694. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  8695. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  8696. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  8697. */
  8698. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  8699. if (!defined(rectangle)) {
  8700. throw new DeveloperError('rectangle is required');
  8701. }
  8702. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  8703. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  8704. if (!defined(result)) {
  8705. result = [];
  8706. }
  8707. var length = 0;
  8708. var north = rectangle.north;
  8709. var south = rectangle.south;
  8710. var east = rectangle.east;
  8711. var west = rectangle.west;
  8712. var lla = subsampleLlaScratch;
  8713. lla.height = surfaceHeight;
  8714. lla.longitude = west;
  8715. lla.latitude = north;
  8716. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8717. length++;
  8718. lla.longitude = east;
  8719. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8720. length++;
  8721. lla.latitude = south;
  8722. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8723. length++;
  8724. lla.longitude = west;
  8725. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8726. length++;
  8727. if (north < 0.0) {
  8728. lla.latitude = north;
  8729. } else if (south > 0.0) {
  8730. lla.latitude = south;
  8731. } else {
  8732. lla.latitude = 0.0;
  8733. }
  8734. for ( var i = 1; i < 8; ++i) {
  8735. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  8736. if (Rectangle.contains(rectangle, lla)) {
  8737. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8738. length++;
  8739. }
  8740. }
  8741. if (lla.latitude === 0.0) {
  8742. lla.longitude = west;
  8743. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8744. length++;
  8745. lla.longitude = east;
  8746. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8747. length++;
  8748. }
  8749. result.length = length;
  8750. return result;
  8751. };
  8752. /**
  8753. * The largest possible rectangle.
  8754. *
  8755. * @type {Rectangle}
  8756. * @constant
  8757. */
  8758. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  8759. return Rectangle;
  8760. });
  8761. /*global define*/
  8762. define('Core/BoundingSphere',[
  8763. './Cartesian3',
  8764. './Cartographic',
  8765. './defaultValue',
  8766. './defined',
  8767. './DeveloperError',
  8768. './Ellipsoid',
  8769. './GeographicProjection',
  8770. './Intersect',
  8771. './Interval',
  8772. './Matrix3',
  8773. './Matrix4',
  8774. './Rectangle'
  8775. ], function(
  8776. Cartesian3,
  8777. Cartographic,
  8778. defaultValue,
  8779. defined,
  8780. DeveloperError,
  8781. Ellipsoid,
  8782. GeographicProjection,
  8783. Intersect,
  8784. Interval,
  8785. Matrix3,
  8786. Matrix4,
  8787. Rectangle) {
  8788. 'use strict';
  8789. /**
  8790. * A bounding sphere with a center and a radius.
  8791. * @alias BoundingSphere
  8792. * @constructor
  8793. *
  8794. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  8795. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  8796. *
  8797. * @see AxisAlignedBoundingBox
  8798. * @see BoundingRectangle
  8799. * @see Packable
  8800. */
  8801. function BoundingSphere(center, radius) {
  8802. /**
  8803. * The center point of the sphere.
  8804. * @type {Cartesian3}
  8805. * @default {@link Cartesian3.ZERO}
  8806. */
  8807. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  8808. /**
  8809. * The radius of the sphere.
  8810. * @type {Number}
  8811. * @default 0.0
  8812. */
  8813. this.radius = defaultValue(radius, 0.0);
  8814. }
  8815. var fromPointsXMin = new Cartesian3();
  8816. var fromPointsYMin = new Cartesian3();
  8817. var fromPointsZMin = new Cartesian3();
  8818. var fromPointsXMax = new Cartesian3();
  8819. var fromPointsYMax = new Cartesian3();
  8820. var fromPointsZMax = new Cartesian3();
  8821. var fromPointsCurrentPos = new Cartesian3();
  8822. var fromPointsScratch = new Cartesian3();
  8823. var fromPointsRitterCenter = new Cartesian3();
  8824. var fromPointsMinBoxPt = new Cartesian3();
  8825. var fromPointsMaxBoxPt = new Cartesian3();
  8826. var fromPointsNaiveCenterScratch = new Cartesian3();
  8827. /**
  8828. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  8829. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  8830. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  8831. *
  8832. * @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.
  8833. * @param {BoundingSphere} [result] The object onto which to store the result.
  8834. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  8835. *
  8836. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  8837. */
  8838. BoundingSphere.fromPoints = function(positions, result) {
  8839. if (!defined(result)) {
  8840. result = new BoundingSphere();
  8841. }
  8842. if (!defined(positions) || positions.length === 0) {
  8843. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  8844. result.radius = 0.0;
  8845. return result;
  8846. }
  8847. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  8848. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  8849. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  8850. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  8851. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  8852. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  8853. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  8854. var numPositions = positions.length;
  8855. for (var i = 1; i < numPositions; i++) {
  8856. Cartesian3.clone(positions[i], currentPos);
  8857. var x = currentPos.x;
  8858. var y = currentPos.y;
  8859. var z = currentPos.z;
  8860. // Store points containing the the smallest and largest components
  8861. if (x < xMin.x) {
  8862. Cartesian3.clone(currentPos, xMin);
  8863. }
  8864. if (x > xMax.x) {
  8865. Cartesian3.clone(currentPos, xMax);
  8866. }
  8867. if (y < yMin.y) {
  8868. Cartesian3.clone(currentPos, yMin);
  8869. }
  8870. if (y > yMax.y) {
  8871. Cartesian3.clone(currentPos, yMax);
  8872. }
  8873. if (z < zMin.z) {
  8874. Cartesian3.clone(currentPos, zMin);
  8875. }
  8876. if (z > zMax.z) {
  8877. Cartesian3.clone(currentPos, zMax);
  8878. }
  8879. }
  8880. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  8881. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  8882. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  8883. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  8884. // Set the diameter endpoints to the largest span.
  8885. var diameter1 = xMin;
  8886. var diameter2 = xMax;
  8887. var maxSpan = xSpan;
  8888. if (ySpan > maxSpan) {
  8889. maxSpan = ySpan;
  8890. diameter1 = yMin;
  8891. diameter2 = yMax;
  8892. }
  8893. if (zSpan > maxSpan) {
  8894. maxSpan = zSpan;
  8895. diameter1 = zMin;
  8896. diameter2 = zMax;
  8897. }
  8898. // Calculate the center of the initial sphere found by Ritter's algorithm
  8899. var ritterCenter = fromPointsRitterCenter;
  8900. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  8901. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  8902. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  8903. // Calculate the radius of the initial sphere found by Ritter's algorithm
  8904. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  8905. var ritterRadius = Math.sqrt(radiusSquared);
  8906. // Find the center of the sphere found using the Naive method.
  8907. var minBoxPt = fromPointsMinBoxPt;
  8908. minBoxPt.x = xMin.x;
  8909. minBoxPt.y = yMin.y;
  8910. minBoxPt.z = zMin.z;
  8911. var maxBoxPt = fromPointsMaxBoxPt;
  8912. maxBoxPt.x = xMax.x;
  8913. maxBoxPt.y = yMax.y;
  8914. maxBoxPt.z = zMax.z;
  8915. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  8916. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  8917. var naiveRadius = 0;
  8918. for (i = 0; i < numPositions; i++) {
  8919. Cartesian3.clone(positions[i], currentPos);
  8920. // Find the furthest point from the naive center to calculate the naive radius.
  8921. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  8922. if (r > naiveRadius) {
  8923. naiveRadius = r;
  8924. }
  8925. // Make adjustments to the Ritter Sphere to include all points.
  8926. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  8927. if (oldCenterToPointSquared > radiusSquared) {
  8928. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  8929. // Calculate new radius to include the point that lies outside
  8930. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  8931. radiusSquared = ritterRadius * ritterRadius;
  8932. // Calculate center of new Ritter sphere
  8933. var oldToNew = oldCenterToPoint - ritterRadius;
  8934. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  8935. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  8936. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  8937. }
  8938. }
  8939. if (ritterRadius < naiveRadius) {
  8940. Cartesian3.clone(ritterCenter, result.center);
  8941. result.radius = ritterRadius;
  8942. } else {
  8943. Cartesian3.clone(naiveCenter, result.center);
  8944. result.radius = naiveRadius;
  8945. }
  8946. return result;
  8947. };
  8948. var defaultProjection = new GeographicProjection();
  8949. var fromRectangle2DLowerLeft = new Cartesian3();
  8950. var fromRectangle2DUpperRight = new Cartesian3();
  8951. var fromRectangle2DSouthwest = new Cartographic();
  8952. var fromRectangle2DNortheast = new Cartographic();
  8953. /**
  8954. * Computes a bounding sphere from an rectangle projected in 2D.
  8955. *
  8956. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  8957. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  8958. * @param {BoundingSphere} [result] The object onto which to store the result.
  8959. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  8960. */
  8961. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  8962. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  8963. };
  8964. /**
  8965. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  8966. * object's minimum and maximum heights over the rectangle.
  8967. *
  8968. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  8969. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  8970. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  8971. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  8972. * @param {BoundingSphere} [result] The object onto which to store the result.
  8973. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  8974. */
  8975. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  8976. if (!defined(result)) {
  8977. result = new BoundingSphere();
  8978. }
  8979. if (!defined(rectangle)) {
  8980. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  8981. result.radius = 0.0;
  8982. return result;
  8983. }
  8984. projection = defaultValue(projection, defaultProjection);
  8985. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  8986. fromRectangle2DSouthwest.height = minimumHeight;
  8987. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  8988. fromRectangle2DNortheast.height = maximumHeight;
  8989. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  8990. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  8991. var width = upperRight.x - lowerLeft.x;
  8992. var height = upperRight.y - lowerLeft.y;
  8993. var elevation = upperRight.z - lowerLeft.z;
  8994. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  8995. var center = result.center;
  8996. center.x = lowerLeft.x + width * 0.5;
  8997. center.y = lowerLeft.y + height * 0.5;
  8998. center.z = lowerLeft.z + elevation * 0.5;
  8999. return result;
  9000. };
  9001. var fromRectangle3DScratch = [];
  9002. /**
  9003. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  9004. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  9005. *
  9006. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  9007. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  9008. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  9009. * @param {BoundingSphere} [result] The object onto which to store the result.
  9010. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9011. */
  9012. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  9013. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  9014. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  9015. var positions;
  9016. if (defined(rectangle)) {
  9017. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  9018. }
  9019. return BoundingSphere.fromPoints(positions, result);
  9020. };
  9021. /**
  9022. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  9023. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  9024. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  9025. * ensure a tight fit.
  9026. *
  9027. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  9028. * is formed from three elements in the array in the order X, Y, Z.
  9029. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  9030. * origin of the coordinate system. This is useful when the positions are to be used for
  9031. * relative-to-center (RTC) rendering.
  9032. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  9033. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  9034. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  9035. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  9036. * the stride is 5, however, two array elements are skipped and the next position begins at array
  9037. * index 5.
  9038. * @param {BoundingSphere} [result] The object onto which to store the result.
  9039. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9040. *
  9041. * @example
  9042. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  9043. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  9044. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  9045. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9046. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  9047. * 4.0, 5.0, 6.0, 0.1, 0.2,
  9048. * 7.0, 8.0, 9.0, 0.1, 0.2];
  9049. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  9050. *
  9051. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9052. */
  9053. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  9054. if (!defined(result)) {
  9055. result = new BoundingSphere();
  9056. }
  9057. if (!defined(positions) || positions.length === 0) {
  9058. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9059. result.radius = 0.0;
  9060. return result;
  9061. }
  9062. center = defaultValue(center, Cartesian3.ZERO);
  9063. stride = defaultValue(stride, 3);
  9064. if (stride < 3) {
  9065. throw new DeveloperError('stride must be 3 or greater.');
  9066. }
  9067. var currentPos = fromPointsCurrentPos;
  9068. currentPos.x = positions[0] + center.x;
  9069. currentPos.y = positions[1] + center.y;
  9070. currentPos.z = positions[2] + center.z;
  9071. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9072. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9073. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9074. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9075. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9076. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9077. var numElements = positions.length;
  9078. for (var i = 0; i < numElements; i += stride) {
  9079. var x = positions[i] + center.x;
  9080. var y = positions[i + 1] + center.y;
  9081. var z = positions[i + 2] + center.z;
  9082. currentPos.x = x;
  9083. currentPos.y = y;
  9084. currentPos.z = z;
  9085. // Store points containing the the smallest and largest components
  9086. if (x < xMin.x) {
  9087. Cartesian3.clone(currentPos, xMin);
  9088. }
  9089. if (x > xMax.x) {
  9090. Cartesian3.clone(currentPos, xMax);
  9091. }
  9092. if (y < yMin.y) {
  9093. Cartesian3.clone(currentPos, yMin);
  9094. }
  9095. if (y > yMax.y) {
  9096. Cartesian3.clone(currentPos, yMax);
  9097. }
  9098. if (z < zMin.z) {
  9099. Cartesian3.clone(currentPos, zMin);
  9100. }
  9101. if (z > zMax.z) {
  9102. Cartesian3.clone(currentPos, zMax);
  9103. }
  9104. }
  9105. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9106. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9107. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9108. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9109. // Set the diameter endpoints to the largest span.
  9110. var diameter1 = xMin;
  9111. var diameter2 = xMax;
  9112. var maxSpan = xSpan;
  9113. if (ySpan > maxSpan) {
  9114. maxSpan = ySpan;
  9115. diameter1 = yMin;
  9116. diameter2 = yMax;
  9117. }
  9118. if (zSpan > maxSpan) {
  9119. maxSpan = zSpan;
  9120. diameter1 = zMin;
  9121. diameter2 = zMax;
  9122. }
  9123. // Calculate the center of the initial sphere found by Ritter's algorithm
  9124. var ritterCenter = fromPointsRitterCenter;
  9125. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9126. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9127. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9128. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9129. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9130. var ritterRadius = Math.sqrt(radiusSquared);
  9131. // Find the center of the sphere found using the Naive method.
  9132. var minBoxPt = fromPointsMinBoxPt;
  9133. minBoxPt.x = xMin.x;
  9134. minBoxPt.y = yMin.y;
  9135. minBoxPt.z = zMin.z;
  9136. var maxBoxPt = fromPointsMaxBoxPt;
  9137. maxBoxPt.x = xMax.x;
  9138. maxBoxPt.y = yMax.y;
  9139. maxBoxPt.z = zMax.z;
  9140. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9141. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9142. var naiveRadius = 0;
  9143. for (i = 0; i < numElements; i += stride) {
  9144. currentPos.x = positions[i] + center.x;
  9145. currentPos.y = positions[i + 1] + center.y;
  9146. currentPos.z = positions[i + 2] + center.z;
  9147. // Find the furthest point from the naive center to calculate the naive radius.
  9148. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9149. if (r > naiveRadius) {
  9150. naiveRadius = r;
  9151. }
  9152. // Make adjustments to the Ritter Sphere to include all points.
  9153. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9154. if (oldCenterToPointSquared > radiusSquared) {
  9155. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9156. // Calculate new radius to include the point that lies outside
  9157. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9158. radiusSquared = ritterRadius * ritterRadius;
  9159. // Calculate center of new Ritter sphere
  9160. var oldToNew = oldCenterToPoint - ritterRadius;
  9161. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9162. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9163. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9164. }
  9165. }
  9166. if (ritterRadius < naiveRadius) {
  9167. Cartesian3.clone(ritterCenter, result.center);
  9168. result.radius = ritterRadius;
  9169. } else {
  9170. Cartesian3.clone(naiveCenter, result.center);
  9171. result.radius = naiveRadius;
  9172. }
  9173. return result;
  9174. };
  9175. /**
  9176. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  9177. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  9178. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  9179. * ensure a tight fit.
  9180. *
  9181. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  9182. * is formed from three elements in the array in the order X, Y, Z.
  9183. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  9184. * is formed from three elements in the array in the order X, Y, Z.
  9185. * @param {BoundingSphere} [result] The object onto which to store the result.
  9186. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9187. *
  9188. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9189. */
  9190. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  9191. if (!defined(result)) {
  9192. result = new BoundingSphere();
  9193. }
  9194. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  9195. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9196. result.radius = 0.0;
  9197. return result;
  9198. }
  9199. var currentPos = fromPointsCurrentPos;
  9200. currentPos.x = positionsHigh[0] + positionsLow[0];
  9201. currentPos.y = positionsHigh[1] + positionsLow[1];
  9202. currentPos.z = positionsHigh[2] + positionsLow[2];
  9203. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9204. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9205. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9206. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9207. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9208. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9209. var numElements = positionsHigh.length;
  9210. for (var i = 0; i < numElements; i += 3) {
  9211. var x = positionsHigh[i] + positionsLow[i];
  9212. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  9213. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  9214. currentPos.x = x;
  9215. currentPos.y = y;
  9216. currentPos.z = z;
  9217. // Store points containing the the smallest and largest components
  9218. if (x < xMin.x) {
  9219. Cartesian3.clone(currentPos, xMin);
  9220. }
  9221. if (x > xMax.x) {
  9222. Cartesian3.clone(currentPos, xMax);
  9223. }
  9224. if (y < yMin.y) {
  9225. Cartesian3.clone(currentPos, yMin);
  9226. }
  9227. if (y > yMax.y) {
  9228. Cartesian3.clone(currentPos, yMax);
  9229. }
  9230. if (z < zMin.z) {
  9231. Cartesian3.clone(currentPos, zMin);
  9232. }
  9233. if (z > zMax.z) {
  9234. Cartesian3.clone(currentPos, zMax);
  9235. }
  9236. }
  9237. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9238. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9239. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9240. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9241. // Set the diameter endpoints to the largest span.
  9242. var diameter1 = xMin;
  9243. var diameter2 = xMax;
  9244. var maxSpan = xSpan;
  9245. if (ySpan > maxSpan) {
  9246. maxSpan = ySpan;
  9247. diameter1 = yMin;
  9248. diameter2 = yMax;
  9249. }
  9250. if (zSpan > maxSpan) {
  9251. maxSpan = zSpan;
  9252. diameter1 = zMin;
  9253. diameter2 = zMax;
  9254. }
  9255. // Calculate the center of the initial sphere found by Ritter's algorithm
  9256. var ritterCenter = fromPointsRitterCenter;
  9257. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9258. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9259. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9260. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9261. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9262. var ritterRadius = Math.sqrt(radiusSquared);
  9263. // Find the center of the sphere found using the Naive method.
  9264. var minBoxPt = fromPointsMinBoxPt;
  9265. minBoxPt.x = xMin.x;
  9266. minBoxPt.y = yMin.y;
  9267. minBoxPt.z = zMin.z;
  9268. var maxBoxPt = fromPointsMaxBoxPt;
  9269. maxBoxPt.x = xMax.x;
  9270. maxBoxPt.y = yMax.y;
  9271. maxBoxPt.z = zMax.z;
  9272. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9273. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9274. var naiveRadius = 0;
  9275. for (i = 0; i < numElements; i += 3) {
  9276. currentPos.x = positionsHigh[i] + positionsLow[i];
  9277. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  9278. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  9279. // Find the furthest point from the naive center to calculate the naive radius.
  9280. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9281. if (r > naiveRadius) {
  9282. naiveRadius = r;
  9283. }
  9284. // Make adjustments to the Ritter Sphere to include all points.
  9285. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9286. if (oldCenterToPointSquared > radiusSquared) {
  9287. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9288. // Calculate new radius to include the point that lies outside
  9289. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9290. radiusSquared = ritterRadius * ritterRadius;
  9291. // Calculate center of new Ritter sphere
  9292. var oldToNew = oldCenterToPoint - ritterRadius;
  9293. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9294. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9295. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9296. }
  9297. }
  9298. if (ritterRadius < naiveRadius) {
  9299. Cartesian3.clone(ritterCenter, result.center);
  9300. result.radius = ritterRadius;
  9301. } else {
  9302. Cartesian3.clone(naiveCenter, result.center);
  9303. result.radius = naiveRadius;
  9304. }
  9305. return result;
  9306. };
  9307. /**
  9308. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  9309. * tighly and fully encompases the box.
  9310. *
  9311. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  9312. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  9313. * @param {BoundingSphere} [result] The object onto which to store the result.
  9314. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9315. *
  9316. * @example
  9317. * // Create a bounding sphere around the unit cube
  9318. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  9319. */
  9320. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  9321. if (!defined(corner) || !defined(oppositeCorner)) {
  9322. throw new DeveloperError('corner and oppositeCorner are required.');
  9323. }
  9324. if (!defined(result)) {
  9325. result = new BoundingSphere();
  9326. }
  9327. var center = result.center;
  9328. Cartesian3.add(corner, oppositeCorner, center);
  9329. Cartesian3.multiplyByScalar(center, 0.5, center);
  9330. result.radius = Cartesian3.distance(center, oppositeCorner);
  9331. return result;
  9332. };
  9333. /**
  9334. * Creates a bounding sphere encompassing an ellipsoid.
  9335. *
  9336. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  9337. * @param {BoundingSphere} [result] The object onto which to store the result.
  9338. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9339. *
  9340. * @example
  9341. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  9342. */
  9343. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  9344. if (!defined(ellipsoid)) {
  9345. throw new DeveloperError('ellipsoid is required.');
  9346. }
  9347. if (!defined(result)) {
  9348. result = new BoundingSphere();
  9349. }
  9350. Cartesian3.clone(Cartesian3.ZERO, result.center);
  9351. result.radius = ellipsoid.maximumRadius;
  9352. return result;
  9353. };
  9354. var fromBoundingSpheresScratch = new Cartesian3();
  9355. /**
  9356. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  9357. *
  9358. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  9359. * @param {BoundingSphere} [result] The object onto which to store the result.
  9360. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9361. */
  9362. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  9363. if (!defined(result)) {
  9364. result = new BoundingSphere();
  9365. }
  9366. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  9367. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9368. result.radius = 0.0;
  9369. return result;
  9370. }
  9371. var length = boundingSpheres.length;
  9372. if (length === 1) {
  9373. return BoundingSphere.clone(boundingSpheres[0], result);
  9374. }
  9375. if (length === 2) {
  9376. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  9377. }
  9378. var positions = [];
  9379. for (var i = 0; i < length; i++) {
  9380. positions.push(boundingSpheres[i].center);
  9381. }
  9382. result = BoundingSphere.fromPoints(positions, result);
  9383. var center = result.center;
  9384. var radius = result.radius;
  9385. for (i = 0; i < length; i++) {
  9386. var tmp = boundingSpheres[i];
  9387. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  9388. }
  9389. result.radius = radius;
  9390. return result;
  9391. };
  9392. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  9393. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  9394. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  9395. /**
  9396. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  9397. *
  9398. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  9399. * @param {BoundingSphere} [result] The object onto which to store the result.
  9400. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9401. */
  9402. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  9403. if (!defined(result)) {
  9404. result = new BoundingSphere();
  9405. }
  9406. var halfAxes = orientedBoundingBox.halfAxes;
  9407. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  9408. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  9409. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  9410. var uHalf = Cartesian3.magnitude(u);
  9411. var vHalf = Cartesian3.magnitude(v);
  9412. var wHalf = Cartesian3.magnitude(w);
  9413. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  9414. result.radius = Math.max(uHalf, vHalf, wHalf);
  9415. return result;
  9416. };
  9417. /**
  9418. * Duplicates a BoundingSphere instance.
  9419. *
  9420. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  9421. * @param {BoundingSphere} [result] The object onto which to store the result.
  9422. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  9423. */
  9424. BoundingSphere.clone = function(sphere, result) {
  9425. if (!defined(sphere)) {
  9426. return undefined;
  9427. }
  9428. if (!defined(result)) {
  9429. return new BoundingSphere(sphere.center, sphere.radius);
  9430. }
  9431. result.center = Cartesian3.clone(sphere.center, result.center);
  9432. result.radius = sphere.radius;
  9433. return result;
  9434. };
  9435. /**
  9436. * The number of elements used to pack the object into an array.
  9437. * @type {Number}
  9438. */
  9439. BoundingSphere.packedLength = 4;
  9440. /**
  9441. * Stores the provided instance into the provided array.
  9442. *
  9443. * @param {BoundingSphere} value The value to pack.
  9444. * @param {Number[]} array The array to pack into.
  9445. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  9446. *
  9447. * @returns {Number[]} The array that was packed into
  9448. */
  9449. BoundingSphere.pack = function(value, array, startingIndex) {
  9450. if (!defined(value)) {
  9451. throw new DeveloperError('value is required');
  9452. }
  9453. if (!defined(array)) {
  9454. throw new DeveloperError('array is required');
  9455. }
  9456. startingIndex = defaultValue(startingIndex, 0);
  9457. var center = value.center;
  9458. array[startingIndex++] = center.x;
  9459. array[startingIndex++] = center.y;
  9460. array[startingIndex++] = center.z;
  9461. array[startingIndex] = value.radius;
  9462. return array;
  9463. };
  9464. /**
  9465. * Retrieves an instance from a packed array.
  9466. *
  9467. * @param {Number[]} array The packed array.
  9468. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  9469. * @param {BoundingSphere} [result] The object into which to store the result.
  9470. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9471. */
  9472. BoundingSphere.unpack = function(array, startingIndex, result) {
  9473. if (!defined(array)) {
  9474. throw new DeveloperError('array is required');
  9475. }
  9476. startingIndex = defaultValue(startingIndex, 0);
  9477. if (!defined(result)) {
  9478. result = new BoundingSphere();
  9479. }
  9480. var center = result.center;
  9481. center.x = array[startingIndex++];
  9482. center.y = array[startingIndex++];
  9483. center.z = array[startingIndex++];
  9484. result.radius = array[startingIndex];
  9485. return result;
  9486. };
  9487. var unionScratch = new Cartesian3();
  9488. var unionScratchCenter = new Cartesian3();
  9489. /**
  9490. * Computes a bounding sphere that contains both the left and right bounding spheres.
  9491. *
  9492. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  9493. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  9494. * @param {BoundingSphere} [result] The object onto which to store the result.
  9495. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9496. */
  9497. BoundingSphere.union = function(left, right, result) {
  9498. if (!defined(left)) {
  9499. throw new DeveloperError('left is required.');
  9500. }
  9501. if (!defined(right)) {
  9502. throw new DeveloperError('right is required.');
  9503. }
  9504. if (!defined(result)) {
  9505. result = new BoundingSphere();
  9506. }
  9507. var leftCenter = left.center;
  9508. var leftRadius = left.radius;
  9509. var rightCenter = right.center;
  9510. var rightRadius = right.radius;
  9511. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  9512. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  9513. if (leftRadius >= (centerSeparation + rightRadius)) {
  9514. // Left sphere wins.
  9515. left.clone(result);
  9516. return result;
  9517. }
  9518. if (rightRadius >= (centerSeparation + leftRadius)) {
  9519. // Right sphere wins.
  9520. right.clone(result);
  9521. return result;
  9522. }
  9523. // There are two tangent points, one on far side of each sphere.
  9524. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  9525. // Compute the center point halfway between the two tangent points.
  9526. var center = Cartesian3.multiplyByScalar(toRightCenter,
  9527. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  9528. Cartesian3.add(center, leftCenter, center);
  9529. Cartesian3.clone(center, result.center);
  9530. result.radius = halfDistanceBetweenTangentPoints;
  9531. return result;
  9532. };
  9533. var expandScratch = new Cartesian3();
  9534. /**
  9535. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  9536. *
  9537. * @param {BoundingSphere} sphere A sphere to expand.
  9538. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  9539. * @param {BoundingSphere} [result] The object onto which to store the result.
  9540. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9541. */
  9542. BoundingSphere.expand = function(sphere, point, result) {
  9543. if (!defined(sphere)) {
  9544. throw new DeveloperError('sphere is required.');
  9545. }
  9546. if (!defined(point)) {
  9547. throw new DeveloperError('point is required.');
  9548. }
  9549. result = BoundingSphere.clone(sphere, result);
  9550. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  9551. if (radius > result.radius) {
  9552. result.radius = radius;
  9553. }
  9554. return result;
  9555. };
  9556. /**
  9557. * Determines which side of a plane a sphere is located.
  9558. *
  9559. * @param {BoundingSphere} sphere The bounding sphere to test.
  9560. * @param {Plane} plane The plane to test against.
  9561. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  9562. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  9563. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  9564. * intersects the plane.
  9565. */
  9566. BoundingSphere.intersectPlane = function(sphere, plane) {
  9567. if (!defined(sphere)) {
  9568. throw new DeveloperError('sphere is required.');
  9569. }
  9570. if (!defined(plane)) {
  9571. throw new DeveloperError('plane is required.');
  9572. }
  9573. var center = sphere.center;
  9574. var radius = sphere.radius;
  9575. var normal = plane.normal;
  9576. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  9577. if (distanceToPlane < -radius) {
  9578. // The center point is negative side of the plane normal
  9579. return Intersect.OUTSIDE;
  9580. } else if (distanceToPlane < radius) {
  9581. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  9582. return Intersect.INTERSECTING;
  9583. }
  9584. return Intersect.INSIDE;
  9585. };
  9586. /**
  9587. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  9588. *
  9589. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  9590. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  9591. * @param {BoundingSphere} [result] The object onto which to store the result.
  9592. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9593. */
  9594. BoundingSphere.transform = function(sphere, transform, result) {
  9595. if (!defined(sphere)) {
  9596. throw new DeveloperError('sphere is required.');
  9597. }
  9598. if (!defined(transform)) {
  9599. throw new DeveloperError('transform is required.');
  9600. }
  9601. if (!defined(result)) {
  9602. result = new BoundingSphere();
  9603. }
  9604. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  9605. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  9606. return result;
  9607. };
  9608. var distanceSquaredToScratch = new Cartesian3();
  9609. /**
  9610. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  9611. *
  9612. * @param {BoundingSphere} sphere The sphere.
  9613. * @param {Cartesian3} cartesian The point
  9614. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  9615. *
  9616. * @example
  9617. * // Sort bounding spheres from back to front
  9618. * spheres.sort(function(a, b) {
  9619. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  9620. * });
  9621. */
  9622. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  9623. if (!defined(sphere)) {
  9624. throw new DeveloperError('sphere is required.');
  9625. }
  9626. if (!defined(cartesian)) {
  9627. throw new DeveloperError('cartesian is required.');
  9628. }
  9629. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  9630. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  9631. };
  9632. /**
  9633. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  9634. * The transformation matrix is not verified to have a uniform scale of 1.
  9635. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  9636. *
  9637. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  9638. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  9639. * @param {BoundingSphere} [result] The object onto which to store the result.
  9640. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9641. *
  9642. * @example
  9643. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  9644. * var boundingSphere = new Cesium.BoundingSphere();
  9645. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  9646. */
  9647. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  9648. if (!defined(sphere)) {
  9649. throw new DeveloperError('sphere is required.');
  9650. }
  9651. if (!defined(transform)) {
  9652. throw new DeveloperError('transform is required.');
  9653. }
  9654. if (!defined(result)) {
  9655. result = new BoundingSphere();
  9656. }
  9657. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  9658. result.radius = sphere.radius;
  9659. return result;
  9660. };
  9661. var scratchCartesian3 = new Cartesian3();
  9662. /**
  9663. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  9664. * plus/minus the radius of the bounding sphere.
  9665. * <br>
  9666. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  9667. * closest and farthest planes from position that intersect the bounding sphere.
  9668. *
  9669. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  9670. * @param {Cartesian3} position The position to calculate the distance from.
  9671. * @param {Cartesian3} direction The direction from position.
  9672. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  9673. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  9674. */
  9675. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  9676. if (!defined(sphere)) {
  9677. throw new DeveloperError('sphere is required.');
  9678. }
  9679. if (!defined(position)) {
  9680. throw new DeveloperError('position is required.');
  9681. }
  9682. if (!defined(direction)) {
  9683. throw new DeveloperError('direction is required.');
  9684. }
  9685. if (!defined(result)) {
  9686. result = new Interval();
  9687. }
  9688. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  9689. var mag = Cartesian3.dot(direction, toCenter);
  9690. result.start = mag - sphere.radius;
  9691. result.stop = mag + sphere.radius;
  9692. return result;
  9693. };
  9694. var projectTo2DNormalScratch = new Cartesian3();
  9695. var projectTo2DEastScratch = new Cartesian3();
  9696. var projectTo2DNorthScratch = new Cartesian3();
  9697. var projectTo2DWestScratch = new Cartesian3();
  9698. var projectTo2DSouthScratch = new Cartesian3();
  9699. var projectTo2DCartographicScratch = new Cartographic();
  9700. var projectTo2DPositionsScratch = new Array(8);
  9701. for (var n = 0; n < 8; ++n) {
  9702. projectTo2DPositionsScratch[n] = new Cartesian3();
  9703. }
  9704. var projectTo2DProjection = new GeographicProjection();
  9705. /**
  9706. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  9707. *
  9708. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  9709. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  9710. * @param {BoundingSphere} [result] The object onto which to store the result.
  9711. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9712. */
  9713. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  9714. if (!defined(sphere)) {
  9715. throw new DeveloperError('sphere is required.');
  9716. }
  9717. projection = defaultValue(projection, projectTo2DProjection);
  9718. var ellipsoid = projection.ellipsoid;
  9719. var center = sphere.center;
  9720. var radius = sphere.radius;
  9721. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  9722. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  9723. Cartesian3.normalize(east, east);
  9724. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  9725. Cartesian3.normalize(north, north);
  9726. Cartesian3.multiplyByScalar(normal, radius, normal);
  9727. Cartesian3.multiplyByScalar(north, radius, north);
  9728. Cartesian3.multiplyByScalar(east, radius, east);
  9729. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  9730. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  9731. var positions = projectTo2DPositionsScratch;
  9732. // top NE corner
  9733. var corner = positions[0];
  9734. Cartesian3.add(normal, north, corner);
  9735. Cartesian3.add(corner, east, corner);
  9736. // top NW corner
  9737. corner = positions[1];
  9738. Cartesian3.add(normal, north, corner);
  9739. Cartesian3.add(corner, west, corner);
  9740. // top SW corner
  9741. corner = positions[2];
  9742. Cartesian3.add(normal, south, corner);
  9743. Cartesian3.add(corner, west, corner);
  9744. // top SE corner
  9745. corner = positions[3];
  9746. Cartesian3.add(normal, south, corner);
  9747. Cartesian3.add(corner, east, corner);
  9748. Cartesian3.negate(normal, normal);
  9749. // bottom NE corner
  9750. corner = positions[4];
  9751. Cartesian3.add(normal, north, corner);
  9752. Cartesian3.add(corner, east, corner);
  9753. // bottom NW corner
  9754. corner = positions[5];
  9755. Cartesian3.add(normal, north, corner);
  9756. Cartesian3.add(corner, west, corner);
  9757. // bottom SW corner
  9758. corner = positions[6];
  9759. Cartesian3.add(normal, south, corner);
  9760. Cartesian3.add(corner, west, corner);
  9761. // bottom SE corner
  9762. corner = positions[7];
  9763. Cartesian3.add(normal, south, corner);
  9764. Cartesian3.add(corner, east, corner);
  9765. var length = positions.length;
  9766. for (var i = 0; i < length; ++i) {
  9767. var position = positions[i];
  9768. Cartesian3.add(center, position, position);
  9769. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  9770. projection.project(cartographic, position);
  9771. }
  9772. result = BoundingSphere.fromPoints(positions, result);
  9773. // swizzle center components
  9774. center = result.center;
  9775. var x = center.x;
  9776. var y = center.y;
  9777. var z = center.z;
  9778. center.x = z;
  9779. center.y = x;
  9780. center.z = y;
  9781. return result;
  9782. };
  9783. /**
  9784. * Determines whether or not a sphere is hidden from view by the occluder.
  9785. *
  9786. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  9787. * @param {Occluder} occluder The occluder.
  9788. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  9789. */
  9790. BoundingSphere.isOccluded = function(sphere, occluder) {
  9791. if (!defined(sphere)) {
  9792. throw new DeveloperError('sphere is required.');
  9793. }
  9794. if (!defined(occluder)) {
  9795. throw new DeveloperError('occluder is required.');
  9796. }
  9797. return !occluder.isBoundingSphereVisible(sphere);
  9798. };
  9799. /**
  9800. * Compares the provided BoundingSphere componentwise and returns
  9801. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9802. *
  9803. * @param {BoundingSphere} [left] The first BoundingSphere.
  9804. * @param {BoundingSphere} [right] The second BoundingSphere.
  9805. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  9806. */
  9807. BoundingSphere.equals = function(left, right) {
  9808. return (left === right) ||
  9809. ((defined(left)) &&
  9810. (defined(right)) &&
  9811. Cartesian3.equals(left.center, right.center) &&
  9812. left.radius === right.radius);
  9813. };
  9814. /**
  9815. * Determines which side of a plane the sphere is located.
  9816. *
  9817. * @param {Plane} plane The plane to test against.
  9818. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  9819. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  9820. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  9821. * intersects the plane.
  9822. */
  9823. BoundingSphere.prototype.intersectPlane = function(plane) {
  9824. return BoundingSphere.intersectPlane(this, plane);
  9825. };
  9826. /**
  9827. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  9828. *
  9829. * @param {Cartesian3} cartesian The point
  9830. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  9831. *
  9832. * @example
  9833. * // Sort bounding spheres from back to front
  9834. * spheres.sort(function(a, b) {
  9835. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  9836. * });
  9837. */
  9838. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  9839. return BoundingSphere.distanceSquaredTo(this, cartesian);
  9840. };
  9841. /**
  9842. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  9843. * plus/minus the radius of the bounding sphere.
  9844. * <br>
  9845. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  9846. * closest and farthest planes from position that intersect the bounding sphere.
  9847. *
  9848. * @param {Cartesian3} position The position to calculate the distance from.
  9849. * @param {Cartesian3} direction The direction from position.
  9850. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  9851. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  9852. */
  9853. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  9854. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  9855. };
  9856. /**
  9857. * Determines whether or not a sphere is hidden from view by the occluder.
  9858. *
  9859. * @param {Occluder} occluder The occluder.
  9860. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  9861. */
  9862. BoundingSphere.prototype.isOccluded = function(occluder) {
  9863. return BoundingSphere.isOccluded(this, occluder);
  9864. };
  9865. /**
  9866. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  9867. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9868. *
  9869. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  9870. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  9871. */
  9872. BoundingSphere.prototype.equals = function(right) {
  9873. return BoundingSphere.equals(this, right);
  9874. };
  9875. /**
  9876. * Duplicates this BoundingSphere instance.
  9877. *
  9878. * @param {BoundingSphere} [result] The object onto which to store the result.
  9879. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9880. */
  9881. BoundingSphere.prototype.clone = function(result) {
  9882. return BoundingSphere.clone(this, result);
  9883. };
  9884. return BoundingSphere;
  9885. });
  9886. /*global define*/
  9887. define('Core/Cartesian2',[
  9888. './defaultValue',
  9889. './defined',
  9890. './DeveloperError',
  9891. './freezeObject',
  9892. './Math'
  9893. ], function(
  9894. defaultValue,
  9895. defined,
  9896. DeveloperError,
  9897. freezeObject,
  9898. CesiumMath) {
  9899. 'use strict';
  9900. /**
  9901. * A 2D Cartesian point.
  9902. * @alias Cartesian2
  9903. * @constructor
  9904. *
  9905. * @param {Number} [x=0.0] The X component.
  9906. * @param {Number} [y=0.0] The Y component.
  9907. *
  9908. * @see Cartesian3
  9909. * @see Cartesian4
  9910. * @see Packable
  9911. */
  9912. function Cartesian2(x, y) {
  9913. /**
  9914. * The X component.
  9915. * @type {Number}
  9916. * @default 0.0
  9917. */
  9918. this.x = defaultValue(x, 0.0);
  9919. /**
  9920. * The Y component.
  9921. * @type {Number}
  9922. * @default 0.0
  9923. */
  9924. this.y = defaultValue(y, 0.0);
  9925. }
  9926. /**
  9927. * Creates a Cartesian2 instance from x and y coordinates.
  9928. *
  9929. * @param {Number} x The x coordinate.
  9930. * @param {Number} y The y coordinate.
  9931. * @param {Cartesian2} [result] The object onto which to store the result.
  9932. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  9933. */
  9934. Cartesian2.fromElements = function(x, y, result) {
  9935. if (!defined(result)) {
  9936. return new Cartesian2(x, y);
  9937. }
  9938. result.x = x;
  9939. result.y = y;
  9940. return result;
  9941. };
  9942. /**
  9943. * Duplicates a Cartesian2 instance.
  9944. *
  9945. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  9946. * @param {Cartesian2} [result] The object onto which to store the result.
  9947. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  9948. */
  9949. Cartesian2.clone = function(cartesian, result) {
  9950. if (!defined(cartesian)) {
  9951. return undefined;
  9952. }
  9953. if (!defined(result)) {
  9954. return new Cartesian2(cartesian.x, cartesian.y);
  9955. }
  9956. result.x = cartesian.x;
  9957. result.y = cartesian.y;
  9958. return result;
  9959. };
  9960. /**
  9961. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  9962. * x and y properties of the Cartesian3 and drops z.
  9963. * @function
  9964. *
  9965. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  9966. * @param {Cartesian2} [result] The object onto which to store the result.
  9967. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  9968. */
  9969. Cartesian2.fromCartesian3 = Cartesian2.clone;
  9970. /**
  9971. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  9972. * x and y properties of the Cartesian4 and drops z and w.
  9973. * @function
  9974. *
  9975. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  9976. * @param {Cartesian2} [result] The object onto which to store the result.
  9977. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  9978. */
  9979. Cartesian2.fromCartesian4 = Cartesian2.clone;
  9980. /**
  9981. * The number of elements used to pack the object into an array.
  9982. * @type {Number}
  9983. */
  9984. Cartesian2.packedLength = 2;
  9985. /**
  9986. * Stores the provided instance into the provided array.
  9987. *
  9988. * @param {Cartesian2} value The value to pack.
  9989. * @param {Number[]} array The array to pack into.
  9990. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  9991. *
  9992. * @returns {Number[]} The array that was packed into
  9993. */
  9994. Cartesian2.pack = function(value, array, startingIndex) {
  9995. if (!defined(value)) {
  9996. throw new DeveloperError('value is required');
  9997. }
  9998. if (!defined(array)) {
  9999. throw new DeveloperError('array is required');
  10000. }
  10001. startingIndex = defaultValue(startingIndex, 0);
  10002. array[startingIndex++] = value.x;
  10003. array[startingIndex] = value.y;
  10004. return array;
  10005. };
  10006. /**
  10007. * Retrieves an instance from a packed array.
  10008. *
  10009. * @param {Number[]} array The packed array.
  10010. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  10011. * @param {Cartesian2} [result] The object into which to store the result.
  10012. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10013. */
  10014. Cartesian2.unpack = function(array, startingIndex, result) {
  10015. if (!defined(array)) {
  10016. throw new DeveloperError('array is required');
  10017. }
  10018. startingIndex = defaultValue(startingIndex, 0);
  10019. if (!defined(result)) {
  10020. result = new Cartesian2();
  10021. }
  10022. result.x = array[startingIndex++];
  10023. result.y = array[startingIndex];
  10024. return result;
  10025. };
  10026. /**
  10027. * Flattens an array of Cartesian2s into and array of components.
  10028. *
  10029. * @param {Cartesian2[]} array The array of cartesians to pack.
  10030. * @param {Number[]} result The array onto which to store the result.
  10031. * @returns {Number[]} The packed array.
  10032. */
  10033. Cartesian2.packArray = function(array, result) {
  10034. if (!defined(array)) {
  10035. throw new DeveloperError('array is required');
  10036. }
  10037. var length = array.length;
  10038. if (!defined(result)) {
  10039. result = new Array(length * 2);
  10040. } else {
  10041. result.length = length * 2;
  10042. }
  10043. for (var i = 0; i < length; ++i) {
  10044. Cartesian2.pack(array[i], result, i * 2);
  10045. }
  10046. return result;
  10047. };
  10048. /**
  10049. * Unpacks an array of cartesian components into and array of Cartesian2s.
  10050. *
  10051. * @param {Number[]} array The array of components to unpack.
  10052. * @param {Cartesian2[]} result The array onto which to store the result.
  10053. * @returns {Cartesian2[]} The unpacked array.
  10054. */
  10055. Cartesian2.unpackArray = function(array, result) {
  10056. if (!defined(array)) {
  10057. throw new DeveloperError('array is required');
  10058. }
  10059. var length = array.length;
  10060. if (!defined(result)) {
  10061. result = new Array(length / 2);
  10062. } else {
  10063. result.length = length / 2;
  10064. }
  10065. for (var i = 0; i < length; i += 2) {
  10066. var index = i / 2;
  10067. result[index] = Cartesian2.unpack(array, i, result[index]);
  10068. }
  10069. return result;
  10070. };
  10071. /**
  10072. * Creates a Cartesian2 from two consecutive elements in an array.
  10073. * @function
  10074. *
  10075. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  10076. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  10077. * @param {Cartesian2} [result] The object onto which to store the result.
  10078. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10079. *
  10080. * @example
  10081. * // Create a Cartesian2 with (1.0, 2.0)
  10082. * var v = [1.0, 2.0];
  10083. * var p = Cesium.Cartesian2.fromArray(v);
  10084. *
  10085. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  10086. * var v2 = [0.0, 0.0, 1.0, 2.0];
  10087. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  10088. */
  10089. Cartesian2.fromArray = Cartesian2.unpack;
  10090. /**
  10091. * Computes the value of the maximum component for the supplied Cartesian.
  10092. *
  10093. * @param {Cartesian2} cartesian The cartesian to use.
  10094. * @returns {Number} The value of the maximum component.
  10095. */
  10096. Cartesian2.maximumComponent = function(cartesian) {
  10097. if (!defined(cartesian)) {
  10098. throw new DeveloperError('cartesian is required');
  10099. }
  10100. return Math.max(cartesian.x, cartesian.y);
  10101. };
  10102. /**
  10103. * Computes the value of the minimum component for the supplied Cartesian.
  10104. *
  10105. * @param {Cartesian2} cartesian The cartesian to use.
  10106. * @returns {Number} The value of the minimum component.
  10107. */
  10108. Cartesian2.minimumComponent = function(cartesian) {
  10109. if (!defined(cartesian)) {
  10110. throw new DeveloperError('cartesian is required');
  10111. }
  10112. return Math.min(cartesian.x, cartesian.y);
  10113. };
  10114. /**
  10115. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  10116. *
  10117. * @param {Cartesian2} first A cartesian to compare.
  10118. * @param {Cartesian2} second A cartesian to compare.
  10119. * @param {Cartesian2} result The object into which to store the result.
  10120. * @returns {Cartesian2} A cartesian with the minimum components.
  10121. */
  10122. Cartesian2.minimumByComponent = function(first, second, result) {
  10123. if (!defined(first)) {
  10124. throw new DeveloperError('first is required.');
  10125. }
  10126. if (!defined(second)) {
  10127. throw new DeveloperError('second is required.');
  10128. }
  10129. if (!defined(result)) {
  10130. throw new DeveloperError('result is required.');
  10131. }
  10132. result.x = Math.min(first.x, second.x);
  10133. result.y = Math.min(first.y, second.y);
  10134. return result;
  10135. };
  10136. /**
  10137. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  10138. *
  10139. * @param {Cartesian2} first A cartesian to compare.
  10140. * @param {Cartesian2} second A cartesian to compare.
  10141. * @param {Cartesian2} result The object into which to store the result.
  10142. * @returns {Cartesian2} A cartesian with the maximum components.
  10143. */
  10144. Cartesian2.maximumByComponent = function(first, second, result) {
  10145. if (!defined(first)) {
  10146. throw new DeveloperError('first is required.');
  10147. }
  10148. if (!defined(second)) {
  10149. throw new DeveloperError('second is required.');
  10150. }
  10151. if (!defined(result)) {
  10152. throw new DeveloperError('result is required.');
  10153. }
  10154. result.x = Math.max(first.x, second.x);
  10155. result.y = Math.max(first.y, second.y);
  10156. return result;
  10157. };
  10158. /**
  10159. * Computes the provided Cartesian's squared magnitude.
  10160. *
  10161. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  10162. * @returns {Number} The squared magnitude.
  10163. */
  10164. Cartesian2.magnitudeSquared = function(cartesian) {
  10165. if (!defined(cartesian)) {
  10166. throw new DeveloperError('cartesian is required');
  10167. }
  10168. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  10169. };
  10170. /**
  10171. * Computes the Cartesian's magnitude (length).
  10172. *
  10173. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  10174. * @returns {Number} The magnitude.
  10175. */
  10176. Cartesian2.magnitude = function(cartesian) {
  10177. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  10178. };
  10179. var distanceScratch = new Cartesian2();
  10180. /**
  10181. * Computes the distance between two points.
  10182. *
  10183. * @param {Cartesian2} left The first point to compute the distance from.
  10184. * @param {Cartesian2} right The second point to compute the distance to.
  10185. * @returns {Number} The distance between two points.
  10186. *
  10187. * @example
  10188. * // Returns 1.0
  10189. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  10190. */
  10191. Cartesian2.distance = function(left, right) {
  10192. if (!defined(left) || !defined(right)) {
  10193. throw new DeveloperError('left and right are required.');
  10194. }
  10195. Cartesian2.subtract(left, right, distanceScratch);
  10196. return Cartesian2.magnitude(distanceScratch);
  10197. };
  10198. /**
  10199. * Computes the squared distance between two points. Comparing squared distances
  10200. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  10201. *
  10202. * @param {Cartesian2} left The first point to compute the distance from.
  10203. * @param {Cartesian2} right The second point to compute the distance to.
  10204. * @returns {Number} The distance between two points.
  10205. *
  10206. * @example
  10207. * // Returns 4.0, not 2.0
  10208. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  10209. */
  10210. Cartesian2.distanceSquared = function(left, right) {
  10211. if (!defined(left) || !defined(right)) {
  10212. throw new DeveloperError('left and right are required.');
  10213. }
  10214. Cartesian2.subtract(left, right, distanceScratch);
  10215. return Cartesian2.magnitudeSquared(distanceScratch);
  10216. };
  10217. /**
  10218. * Computes the normalized form of the supplied Cartesian.
  10219. *
  10220. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  10221. * @param {Cartesian2} result The object onto which to store the result.
  10222. * @returns {Cartesian2} The modified result parameter.
  10223. */
  10224. Cartesian2.normalize = function(cartesian, result) {
  10225. if (!defined(cartesian)) {
  10226. throw new DeveloperError('cartesian is required');
  10227. }
  10228. if (!defined(result)) {
  10229. throw new DeveloperError('result is required');
  10230. }
  10231. var magnitude = Cartesian2.magnitude(cartesian);
  10232. result.x = cartesian.x / magnitude;
  10233. result.y = cartesian.y / magnitude;
  10234. if (isNaN(result.x) || isNaN(result.y)) {
  10235. throw new DeveloperError('normalized result is not a number');
  10236. }
  10237. return result;
  10238. };
  10239. /**
  10240. * Computes the dot (scalar) product of two Cartesians.
  10241. *
  10242. * @param {Cartesian2} left The first Cartesian.
  10243. * @param {Cartesian2} right The second Cartesian.
  10244. * @returns {Number} The dot product.
  10245. */
  10246. Cartesian2.dot = function(left, right) {
  10247. if (!defined(left)) {
  10248. throw new DeveloperError('left is required');
  10249. }
  10250. if (!defined(right)) {
  10251. throw new DeveloperError('right is required');
  10252. }
  10253. return left.x * right.x + left.y * right.y;
  10254. };
  10255. /**
  10256. * Computes the componentwise product of two Cartesians.
  10257. *
  10258. * @param {Cartesian2} left The first Cartesian.
  10259. * @param {Cartesian2} right The second Cartesian.
  10260. * @param {Cartesian2} result The object onto which to store the result.
  10261. * @returns {Cartesian2} The modified result parameter.
  10262. */
  10263. Cartesian2.multiplyComponents = function(left, right, result) {
  10264. if (!defined(left)) {
  10265. throw new DeveloperError('left is required');
  10266. }
  10267. if (!defined(right)) {
  10268. throw new DeveloperError('right is required');
  10269. }
  10270. if (!defined(result)) {
  10271. throw new DeveloperError('result is required');
  10272. }
  10273. result.x = left.x * right.x;
  10274. result.y = left.y * right.y;
  10275. return result;
  10276. };
  10277. /**
  10278. * Computes the componentwise quotient of two Cartesians.
  10279. *
  10280. * @param {Cartesian2} left The first Cartesian.
  10281. * @param {Cartesian2} right The second Cartesian.
  10282. * @param {Cartesian2} result The object onto which to store the result.
  10283. * @returns {Cartesian2} The modified result parameter.
  10284. */
  10285. Cartesian2.divideComponents = function(left, right, result) {
  10286. if (!defined(left)) {
  10287. throw new DeveloperError('left is required');
  10288. }
  10289. if (!defined(right)) {
  10290. throw new DeveloperError('right is required');
  10291. }
  10292. if (!defined(result)) {
  10293. throw new DeveloperError('result is required');
  10294. }
  10295. result.x = left.x / right.x;
  10296. result.y = left.y / right.y;
  10297. return result;
  10298. };
  10299. /**
  10300. * Computes the componentwise sum of two Cartesians.
  10301. *
  10302. * @param {Cartesian2} left The first Cartesian.
  10303. * @param {Cartesian2} right The second Cartesian.
  10304. * @param {Cartesian2} result The object onto which to store the result.
  10305. * @returns {Cartesian2} The modified result parameter.
  10306. */
  10307. Cartesian2.add = function(left, right, result) {
  10308. if (!defined(left)) {
  10309. throw new DeveloperError('left is required');
  10310. }
  10311. if (!defined(right)) {
  10312. throw new DeveloperError('right is required');
  10313. }
  10314. if (!defined(result)) {
  10315. throw new DeveloperError('result is required');
  10316. }
  10317. result.x = left.x + right.x;
  10318. result.y = left.y + right.y;
  10319. return result;
  10320. };
  10321. /**
  10322. * Computes the componentwise difference of two Cartesians.
  10323. *
  10324. * @param {Cartesian2} left The first Cartesian.
  10325. * @param {Cartesian2} right The second Cartesian.
  10326. * @param {Cartesian2} result The object onto which to store the result.
  10327. * @returns {Cartesian2} The modified result parameter.
  10328. */
  10329. Cartesian2.subtract = function(left, right, result) {
  10330. if (!defined(left)) {
  10331. throw new DeveloperError('left is required');
  10332. }
  10333. if (!defined(right)) {
  10334. throw new DeveloperError('right is required');
  10335. }
  10336. if (!defined(result)) {
  10337. throw new DeveloperError('result is required');
  10338. }
  10339. result.x = left.x - right.x;
  10340. result.y = left.y - right.y;
  10341. return result;
  10342. };
  10343. /**
  10344. * Multiplies the provided Cartesian componentwise by the provided scalar.
  10345. *
  10346. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  10347. * @param {Number} scalar The scalar to multiply with.
  10348. * @param {Cartesian2} result The object onto which to store the result.
  10349. * @returns {Cartesian2} The modified result parameter.
  10350. */
  10351. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  10352. if (!defined(cartesian)) {
  10353. throw new DeveloperError('cartesian is required');
  10354. }
  10355. if (typeof scalar !== 'number') {
  10356. throw new DeveloperError('scalar is required and must be a number.');
  10357. }
  10358. if (!defined(result)) {
  10359. throw new DeveloperError('result is required');
  10360. }
  10361. result.x = cartesian.x * scalar;
  10362. result.y = cartesian.y * scalar;
  10363. return result;
  10364. };
  10365. /**
  10366. * Divides the provided Cartesian componentwise by the provided scalar.
  10367. *
  10368. * @param {Cartesian2} cartesian The Cartesian to be divided.
  10369. * @param {Number} scalar The scalar to divide by.
  10370. * @param {Cartesian2} result The object onto which to store the result.
  10371. * @returns {Cartesian2} The modified result parameter.
  10372. */
  10373. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  10374. if (!defined(cartesian)) {
  10375. throw new DeveloperError('cartesian is required');
  10376. }
  10377. if (typeof scalar !== 'number') {
  10378. throw new DeveloperError('scalar is required and must be a number.');
  10379. }
  10380. if (!defined(result)) {
  10381. throw new DeveloperError('result is required');
  10382. }
  10383. result.x = cartesian.x / scalar;
  10384. result.y = cartesian.y / scalar;
  10385. return result;
  10386. };
  10387. /**
  10388. * Negates the provided Cartesian.
  10389. *
  10390. * @param {Cartesian2} cartesian The Cartesian to be negated.
  10391. * @param {Cartesian2} result The object onto which to store the result.
  10392. * @returns {Cartesian2} The modified result parameter.
  10393. */
  10394. Cartesian2.negate = function(cartesian, result) {
  10395. if (!defined(cartesian)) {
  10396. throw new DeveloperError('cartesian is required');
  10397. }
  10398. if (!defined(result)) {
  10399. throw new DeveloperError('result is required');
  10400. }
  10401. result.x = -cartesian.x;
  10402. result.y = -cartesian.y;
  10403. return result;
  10404. };
  10405. /**
  10406. * Computes the absolute value of the provided Cartesian.
  10407. *
  10408. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  10409. * @param {Cartesian2} result The object onto which to store the result.
  10410. * @returns {Cartesian2} The modified result parameter.
  10411. */
  10412. Cartesian2.abs = function(cartesian, result) {
  10413. if (!defined(cartesian)) {
  10414. throw new DeveloperError('cartesian is required');
  10415. }
  10416. if (!defined(result)) {
  10417. throw new DeveloperError('result is required');
  10418. }
  10419. result.x = Math.abs(cartesian.x);
  10420. result.y = Math.abs(cartesian.y);
  10421. return result;
  10422. };
  10423. var lerpScratch = new Cartesian2();
  10424. /**
  10425. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  10426. *
  10427. * @param {Cartesian2} start The value corresponding to t at 0.0.
  10428. * @param {Cartesian2} end The value corresponding to t at 1.0.
  10429. * @param {Number} t The point along t at which to interpolate.
  10430. * @param {Cartesian2} result The object onto which to store the result.
  10431. * @returns {Cartesian2} The modified result parameter.
  10432. */
  10433. Cartesian2.lerp = function(start, end, t, result) {
  10434. if (!defined(start)) {
  10435. throw new DeveloperError('start is required.');
  10436. }
  10437. if (!defined(end)) {
  10438. throw new DeveloperError('end is required.');
  10439. }
  10440. if (typeof t !== 'number') {
  10441. throw new DeveloperError('t is required and must be a number.');
  10442. }
  10443. if (!defined(result)) {
  10444. throw new DeveloperError('result is required.');
  10445. }
  10446. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  10447. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  10448. return Cartesian2.add(lerpScratch, result, result);
  10449. };
  10450. var angleBetweenScratch = new Cartesian2();
  10451. var angleBetweenScratch2 = new Cartesian2();
  10452. /**
  10453. * Returns the angle, in radians, between the provided Cartesians.
  10454. *
  10455. * @param {Cartesian2} left The first Cartesian.
  10456. * @param {Cartesian2} right The second Cartesian.
  10457. * @returns {Number} The angle between the Cartesians.
  10458. */
  10459. Cartesian2.angleBetween = function(left, right) {
  10460. if (!defined(left)) {
  10461. throw new DeveloperError('left is required');
  10462. }
  10463. if (!defined(right)) {
  10464. throw new DeveloperError('right is required');
  10465. }
  10466. Cartesian2.normalize(left, angleBetweenScratch);
  10467. Cartesian2.normalize(right, angleBetweenScratch2);
  10468. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  10469. };
  10470. var mostOrthogonalAxisScratch = new Cartesian2();
  10471. /**
  10472. * Returns the axis that is most orthogonal to the provided Cartesian.
  10473. *
  10474. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  10475. * @param {Cartesian2} result The object onto which to store the result.
  10476. * @returns {Cartesian2} The most orthogonal axis.
  10477. */
  10478. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  10479. if (!defined(cartesian)) {
  10480. throw new DeveloperError('cartesian is required.');
  10481. }
  10482. if (!defined(result)) {
  10483. throw new DeveloperError('result is required.');
  10484. }
  10485. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  10486. Cartesian2.abs(f, f);
  10487. if (f.x <= f.y) {
  10488. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  10489. } else {
  10490. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  10491. }
  10492. return result;
  10493. };
  10494. /**
  10495. * Compares the provided Cartesians componentwise and returns
  10496. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10497. *
  10498. * @param {Cartesian2} [left] The first Cartesian.
  10499. * @param {Cartesian2} [right] The second Cartesian.
  10500. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10501. */
  10502. Cartesian2.equals = function(left, right) {
  10503. return (left === right) ||
  10504. ((defined(left)) &&
  10505. (defined(right)) &&
  10506. (left.x === right.x) &&
  10507. (left.y === right.y));
  10508. };
  10509. /**
  10510. * @private
  10511. */
  10512. Cartesian2.equalsArray = function(cartesian, array, offset) {
  10513. return cartesian.x === array[offset] &&
  10514. cartesian.y === array[offset + 1];
  10515. };
  10516. /**
  10517. * Compares the provided Cartesians componentwise and returns
  10518. * <code>true</code> if they pass an absolute or relative tolerance test,
  10519. * <code>false</code> otherwise.
  10520. *
  10521. * @param {Cartesian2} [left] The first Cartesian.
  10522. * @param {Cartesian2} [right] The second Cartesian.
  10523. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  10524. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  10525. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  10526. */
  10527. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  10528. return (left === right) ||
  10529. (defined(left) &&
  10530. defined(right) &&
  10531. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  10532. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  10533. };
  10534. /**
  10535. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  10536. *
  10537. * @type {Cartesian2}
  10538. * @constant
  10539. */
  10540. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  10541. /**
  10542. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  10543. *
  10544. * @type {Cartesian2}
  10545. * @constant
  10546. */
  10547. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  10548. /**
  10549. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  10550. *
  10551. * @type {Cartesian2}
  10552. * @constant
  10553. */
  10554. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  10555. /**
  10556. * Duplicates this Cartesian2 instance.
  10557. *
  10558. * @param {Cartesian2} [result] The object onto which to store the result.
  10559. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  10560. */
  10561. Cartesian2.prototype.clone = function(result) {
  10562. return Cartesian2.clone(this, result);
  10563. };
  10564. /**
  10565. * Compares this Cartesian against the provided Cartesian componentwise and returns
  10566. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10567. *
  10568. * @param {Cartesian2} [right] The right hand side Cartesian.
  10569. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  10570. */
  10571. Cartesian2.prototype.equals = function(right) {
  10572. return Cartesian2.equals(this, right);
  10573. };
  10574. /**
  10575. * Compares this Cartesian against the provided Cartesian componentwise and returns
  10576. * <code>true</code> if they pass an absolute or relative tolerance test,
  10577. * <code>false</code> otherwise.
  10578. *
  10579. * @param {Cartesian2} [right] The right hand side Cartesian.
  10580. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  10581. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  10582. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  10583. */
  10584. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  10585. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  10586. };
  10587. /**
  10588. * Creates a string representing this Cartesian in the format '(x, y)'.
  10589. *
  10590. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  10591. */
  10592. Cartesian2.prototype.toString = function() {
  10593. return '(' + this.x + ', ' + this.y + ')';
  10594. };
  10595. return Cartesian2;
  10596. });
  10597. /*global define*/
  10598. define('Core/Fullscreen',[
  10599. './defined',
  10600. './defineProperties'
  10601. ], function(
  10602. defined,
  10603. defineProperties) {
  10604. 'use strict';
  10605. var _supportsFullscreen;
  10606. var _names = {
  10607. requestFullscreen : undefined,
  10608. exitFullscreen : undefined,
  10609. fullscreenEnabled : undefined,
  10610. fullscreenElement : undefined,
  10611. fullscreenchange : undefined,
  10612. fullscreenerror : undefined
  10613. };
  10614. /**
  10615. * Browser-independent functions for working with the standard fullscreen API.
  10616. *
  10617. * @exports Fullscreen
  10618. *
  10619. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  10620. */
  10621. var Fullscreen = {};
  10622. defineProperties(Fullscreen, {
  10623. /**
  10624. * The element that is currently fullscreen, if any. To simply check if the
  10625. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  10626. * @memberof Fullscreen
  10627. * @type {Object}
  10628. * @readonly
  10629. */
  10630. element : {
  10631. get : function() {
  10632. if (!Fullscreen.supportsFullscreen()) {
  10633. return undefined;
  10634. }
  10635. return document[_names.fullscreenElement];
  10636. }
  10637. },
  10638. /**
  10639. * The name of the event on the document that is fired when fullscreen is
  10640. * entered or exited. This event name is intended for use with addEventListener.
  10641. * In your event handler, to determine if the browser is in fullscreen mode or not,
  10642. * use {@link Fullscreen#fullscreen}.
  10643. * @memberof Fullscreen
  10644. * @type {String}
  10645. * @readonly
  10646. */
  10647. changeEventName : {
  10648. get : function() {
  10649. if (!Fullscreen.supportsFullscreen()) {
  10650. return undefined;
  10651. }
  10652. return _names.fullscreenchange;
  10653. }
  10654. },
  10655. /**
  10656. * The name of the event that is fired when a fullscreen error
  10657. * occurs. This event name is intended for use with addEventListener.
  10658. * @memberof Fullscreen
  10659. * @type {String}
  10660. * @readonly
  10661. */
  10662. errorEventName : {
  10663. get : function() {
  10664. if (!Fullscreen.supportsFullscreen()) {
  10665. return undefined;
  10666. }
  10667. return _names.fullscreenerror;
  10668. }
  10669. },
  10670. /**
  10671. * Determine whether the browser will allow an element to be made fullscreen, or not.
  10672. * For example, by default, iframes cannot go fullscreen unless the containing page
  10673. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  10674. * @memberof Fullscreen
  10675. * @type {Boolean}
  10676. * @readonly
  10677. */
  10678. enabled : {
  10679. get : function() {
  10680. if (!Fullscreen.supportsFullscreen()) {
  10681. return undefined;
  10682. }
  10683. return document[_names.fullscreenEnabled];
  10684. }
  10685. },
  10686. /**
  10687. * Determines if the browser is currently in fullscreen mode.
  10688. * @memberof Fullscreen
  10689. * @type {Boolean}
  10690. * @readonly
  10691. */
  10692. fullscreen : {
  10693. get : function() {
  10694. if (!Fullscreen.supportsFullscreen()) {
  10695. return undefined;
  10696. }
  10697. return Fullscreen.element !== null;
  10698. }
  10699. }
  10700. });
  10701. /**
  10702. * Detects whether the browser supports the standard fullscreen API.
  10703. *
  10704. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  10705. * <code>false</code> otherwise.
  10706. */
  10707. Fullscreen.supportsFullscreen = function() {
  10708. if (defined(_supportsFullscreen)) {
  10709. return _supportsFullscreen;
  10710. }
  10711. _supportsFullscreen = false;
  10712. var body = document.body;
  10713. if (typeof body.requestFullscreen === 'function') {
  10714. // go with the unprefixed, standard set of names
  10715. _names.requestFullscreen = 'requestFullscreen';
  10716. _names.exitFullscreen = 'exitFullscreen';
  10717. _names.fullscreenEnabled = 'fullscreenEnabled';
  10718. _names.fullscreenElement = 'fullscreenElement';
  10719. _names.fullscreenchange = 'fullscreenchange';
  10720. _names.fullscreenerror = 'fullscreenerror';
  10721. _supportsFullscreen = true;
  10722. return _supportsFullscreen;
  10723. }
  10724. //check for the correct combination of prefix plus the various names that browsers use
  10725. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  10726. var name;
  10727. for (var i = 0, len = prefixes.length; i < len; ++i) {
  10728. var prefix = prefixes[i];
  10729. // casing of Fullscreen differs across browsers
  10730. name = prefix + 'RequestFullscreen';
  10731. if (typeof body[name] === 'function') {
  10732. _names.requestFullscreen = name;
  10733. _supportsFullscreen = true;
  10734. } else {
  10735. name = prefix + 'RequestFullScreen';
  10736. if (typeof body[name] === 'function') {
  10737. _names.requestFullscreen = name;
  10738. _supportsFullscreen = true;
  10739. }
  10740. }
  10741. // disagreement about whether it's "exit" as per spec, or "cancel"
  10742. name = prefix + 'ExitFullscreen';
  10743. if (typeof document[name] === 'function') {
  10744. _names.exitFullscreen = name;
  10745. } else {
  10746. name = prefix + 'CancelFullScreen';
  10747. if (typeof document[name] === 'function') {
  10748. _names.exitFullscreen = name;
  10749. }
  10750. }
  10751. // casing of Fullscreen differs across browsers
  10752. name = prefix + 'FullscreenEnabled';
  10753. if (document[name] !== undefined) {
  10754. _names.fullscreenEnabled = name;
  10755. } else {
  10756. name = prefix + 'FullScreenEnabled';
  10757. if (document[name] !== undefined) {
  10758. _names.fullscreenEnabled = name;
  10759. }
  10760. }
  10761. // casing of Fullscreen differs across browsers
  10762. name = prefix + 'FullscreenElement';
  10763. if (document[name] !== undefined) {
  10764. _names.fullscreenElement = name;
  10765. } else {
  10766. name = prefix + 'FullScreenElement';
  10767. if (document[name] !== undefined) {
  10768. _names.fullscreenElement = name;
  10769. }
  10770. }
  10771. // thankfully, event names are all lowercase per spec
  10772. name = prefix + 'fullscreenchange';
  10773. // event names do not have 'on' in the front, but the property on the document does
  10774. if (document['on' + name] !== undefined) {
  10775. //except on IE
  10776. if (prefix === 'ms') {
  10777. name = 'MSFullscreenChange';
  10778. }
  10779. _names.fullscreenchange = name;
  10780. }
  10781. name = prefix + 'fullscreenerror';
  10782. if (document['on' + name] !== undefined) {
  10783. //except on IE
  10784. if (prefix === 'ms') {
  10785. name = 'MSFullscreenError';
  10786. }
  10787. _names.fullscreenerror = name;
  10788. }
  10789. }
  10790. return _supportsFullscreen;
  10791. };
  10792. /**
  10793. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  10794. * If fullscreen mode is not supported by the browser, does nothing.
  10795. *
  10796. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  10797. * @param {HMDVRDevice} [vrDevice] The VR device.
  10798. *
  10799. * @example
  10800. * // Put the entire page into fullscreen.
  10801. * Cesium.Fullscreen.requestFullscreen(document.body)
  10802. *
  10803. * // Place only the Cesium canvas into fullscreen.
  10804. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  10805. */
  10806. Fullscreen.requestFullscreen = function(element, vrDevice) {
  10807. if (!Fullscreen.supportsFullscreen()) {
  10808. return;
  10809. }
  10810. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  10811. };
  10812. /**
  10813. * Asynchronously exits fullscreen mode. If the browser is not currently
  10814. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  10815. */
  10816. Fullscreen.exitFullscreen = function() {
  10817. if (!Fullscreen.supportsFullscreen()) {
  10818. return;
  10819. }
  10820. document[_names.exitFullscreen]();
  10821. };
  10822. return Fullscreen;
  10823. });
  10824. /*global define*/
  10825. define('Core/FeatureDetection',[
  10826. './defaultValue',
  10827. './defined',
  10828. './Fullscreen'
  10829. ], function(
  10830. defaultValue,
  10831. defined,
  10832. Fullscreen) {
  10833. 'use strict';
  10834. var theNavigator;
  10835. if (typeof navigator !== 'undefined') {
  10836. theNavigator = navigator;
  10837. } else {
  10838. theNavigator = {};
  10839. }
  10840. function extractVersion(versionString) {
  10841. var parts = versionString.split('.');
  10842. for (var i = 0, len = parts.length; i < len; ++i) {
  10843. parts[i] = parseInt(parts[i], 10);
  10844. }
  10845. return parts;
  10846. }
  10847. var isChromeResult;
  10848. var chromeVersionResult;
  10849. function isChrome() {
  10850. if (!defined(isChromeResult)) {
  10851. isChromeResult = false;
  10852. // Edge contains Chrome in the user agent too
  10853. if (!isEdge()) {
  10854. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  10855. if (fields !== null) {
  10856. isChromeResult = true;
  10857. chromeVersionResult = extractVersion(fields[1]);
  10858. }
  10859. }
  10860. }
  10861. return isChromeResult;
  10862. }
  10863. function chromeVersion() {
  10864. return isChrome() && chromeVersionResult;
  10865. }
  10866. var isSafariResult;
  10867. var safariVersionResult;
  10868. function isSafari() {
  10869. if (!defined(isSafariResult)) {
  10870. isSafariResult = false;
  10871. // Chrome and Edge contain Safari in the user agent too
  10872. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  10873. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  10874. if (fields !== null) {
  10875. isSafariResult = true;
  10876. safariVersionResult = extractVersion(fields[1]);
  10877. }
  10878. }
  10879. }
  10880. return isSafariResult;
  10881. }
  10882. function safariVersion() {
  10883. return isSafari() && safariVersionResult;
  10884. }
  10885. var isWebkitResult;
  10886. var webkitVersionResult;
  10887. function isWebkit() {
  10888. if (!defined(isWebkitResult)) {
  10889. isWebkitResult = false;
  10890. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  10891. if (fields !== null) {
  10892. isWebkitResult = true;
  10893. webkitVersionResult = extractVersion(fields[1]);
  10894. webkitVersionResult.isNightly = !!fields[2];
  10895. }
  10896. }
  10897. return isWebkitResult;
  10898. }
  10899. function webkitVersion() {
  10900. return isWebkit() && webkitVersionResult;
  10901. }
  10902. var isInternetExplorerResult;
  10903. var internetExplorerVersionResult;
  10904. function isInternetExplorer() {
  10905. if (!defined(isInternetExplorerResult)) {
  10906. isInternetExplorerResult = false;
  10907. var fields;
  10908. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  10909. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  10910. if (fields !== null) {
  10911. isInternetExplorerResult = true;
  10912. internetExplorerVersionResult = extractVersion(fields[1]);
  10913. }
  10914. } else if (theNavigator.appName === 'Netscape') {
  10915. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  10916. if (fields !== null) {
  10917. isInternetExplorerResult = true;
  10918. internetExplorerVersionResult = extractVersion(fields[1]);
  10919. }
  10920. }
  10921. }
  10922. return isInternetExplorerResult;
  10923. }
  10924. function internetExplorerVersion() {
  10925. return isInternetExplorer() && internetExplorerVersionResult;
  10926. }
  10927. var isEdgeResult;
  10928. var edgeVersionResult;
  10929. function isEdge() {
  10930. if (!defined(isEdgeResult)) {
  10931. isEdgeResult = false;
  10932. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  10933. if (fields !== null) {
  10934. isEdgeResult = true;
  10935. edgeVersionResult = extractVersion(fields[1]);
  10936. }
  10937. }
  10938. return isEdgeResult;
  10939. }
  10940. function edgeVersion() {
  10941. return isEdge() && edgeVersionResult;
  10942. }
  10943. var isFirefoxResult;
  10944. var firefoxVersionResult;
  10945. function isFirefox() {
  10946. if (!defined(isFirefoxResult)) {
  10947. isFirefoxResult = false;
  10948. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  10949. if (fields !== null) {
  10950. isFirefoxResult = true;
  10951. firefoxVersionResult = extractVersion(fields[1]);
  10952. }
  10953. }
  10954. return isFirefoxResult;
  10955. }
  10956. var isWindowsResult;
  10957. function isWindows() {
  10958. if (!defined(isWindowsResult)) {
  10959. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  10960. }
  10961. return isWindowsResult;
  10962. }
  10963. function firefoxVersion() {
  10964. return isFirefox() && firefoxVersionResult;
  10965. }
  10966. var hasPointerEvents;
  10967. function supportsPointerEvents() {
  10968. if (!defined(hasPointerEvents)) {
  10969. //While navigator.pointerEnabled is deprecated in the W3C specification
  10970. //we still need to use it if it exists in order to support browsers
  10971. //that rely on it, such as the Windows WebBrowser control which defines
  10972. //PointerEvent but sets navigator.pointerEnabled to false.
  10973. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  10974. }
  10975. return hasPointerEvents;
  10976. }
  10977. var imageRenderingValueResult;
  10978. var supportsImageRenderingPixelatedResult;
  10979. function supportsImageRenderingPixelated() {
  10980. if (!defined(supportsImageRenderingPixelatedResult)) {
  10981. var canvas = document.createElement('canvas');
  10982. canvas.setAttribute('style',
  10983. 'image-rendering: -moz-crisp-edges;' +
  10984. 'image-rendering: pixelated;');
  10985. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  10986. var tmp = canvas.style.imageRendering;
  10987. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  10988. if (supportsImageRenderingPixelatedResult) {
  10989. imageRenderingValueResult = tmp;
  10990. }
  10991. }
  10992. return supportsImageRenderingPixelatedResult;
  10993. }
  10994. function imageRenderingValue() {
  10995. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  10996. }
  10997. /**
  10998. * A set of functions to detect whether the current browser supports
  10999. * various features.
  11000. *
  11001. * @exports FeatureDetection
  11002. */
  11003. var FeatureDetection = {
  11004. isChrome : isChrome,
  11005. chromeVersion : chromeVersion,
  11006. isSafari : isSafari,
  11007. safariVersion : safariVersion,
  11008. isWebkit : isWebkit,
  11009. webkitVersion : webkitVersion,
  11010. isInternetExplorer : isInternetExplorer,
  11011. internetExplorerVersion : internetExplorerVersion,
  11012. isEdge : isEdge,
  11013. edgeVersion : edgeVersion,
  11014. isFirefox : isFirefox,
  11015. firefoxVersion : firefoxVersion,
  11016. isWindows : isWindows,
  11017. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  11018. supportsPointerEvents : supportsPointerEvents,
  11019. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  11020. imageRenderingValue: imageRenderingValue
  11021. };
  11022. /**
  11023. * Detects whether the current browser supports the full screen standard.
  11024. *
  11025. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  11026. *
  11027. * @see Fullscreen
  11028. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  11029. */
  11030. FeatureDetection.supportsFullscreen = function() {
  11031. return Fullscreen.supportsFullscreen();
  11032. };
  11033. /**
  11034. * Detects whether the current browser supports typed arrays.
  11035. *
  11036. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  11037. *
  11038. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  11039. */
  11040. FeatureDetection.supportsTypedArrays = function() {
  11041. return typeof ArrayBuffer !== 'undefined';
  11042. };
  11043. /**
  11044. * Detects whether the current browser supports Web Workers.
  11045. *
  11046. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  11047. *
  11048. * @see {@link http://www.w3.org/TR/workers/}
  11049. */
  11050. FeatureDetection.supportsWebWorkers = function() {
  11051. return typeof Worker !== 'undefined';
  11052. };
  11053. return FeatureDetection;
  11054. });
  11055. /*global define*/
  11056. define('Core/WebGLConstants',[
  11057. './freezeObject'
  11058. ], function(
  11059. freezeObject) {
  11060. 'use strict';
  11061. /**
  11062. * Enum containing WebGL Constant values by name.
  11063. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  11064. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  11065. *
  11066. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  11067. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  11068. * specifications.
  11069. *
  11070. * @exports WebGLConstants
  11071. */
  11072. var WebGLConstants = {
  11073. DEPTH_BUFFER_BIT : 0x00000100,
  11074. STENCIL_BUFFER_BIT : 0x00000400,
  11075. COLOR_BUFFER_BIT : 0x00004000,
  11076. POINTS : 0x0000,
  11077. LINES : 0x0001,
  11078. LINE_LOOP : 0x0002,
  11079. LINE_STRIP : 0x0003,
  11080. TRIANGLES : 0x0004,
  11081. TRIANGLE_STRIP : 0x0005,
  11082. TRIANGLE_FAN : 0x0006,
  11083. ZERO : 0,
  11084. ONE : 1,
  11085. SRC_COLOR : 0x0300,
  11086. ONE_MINUS_SRC_COLOR : 0x0301,
  11087. SRC_ALPHA : 0x0302,
  11088. ONE_MINUS_SRC_ALPHA : 0x0303,
  11089. DST_ALPHA : 0x0304,
  11090. ONE_MINUS_DST_ALPHA : 0x0305,
  11091. DST_COLOR : 0x0306,
  11092. ONE_MINUS_DST_COLOR : 0x0307,
  11093. SRC_ALPHA_SATURATE : 0x0308,
  11094. FUNC_ADD : 0x8006,
  11095. BLEND_EQUATION : 0x8009,
  11096. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  11097. BLEND_EQUATION_ALPHA : 0x883D,
  11098. FUNC_SUBTRACT : 0x800A,
  11099. FUNC_REVERSE_SUBTRACT : 0x800B,
  11100. BLEND_DST_RGB : 0x80C8,
  11101. BLEND_SRC_RGB : 0x80C9,
  11102. BLEND_DST_ALPHA : 0x80CA,
  11103. BLEND_SRC_ALPHA : 0x80CB,
  11104. CONSTANT_COLOR : 0x8001,
  11105. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  11106. CONSTANT_ALPHA : 0x8003,
  11107. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  11108. BLEND_COLOR : 0x8005,
  11109. ARRAY_BUFFER : 0x8892,
  11110. ELEMENT_ARRAY_BUFFER : 0x8893,
  11111. ARRAY_BUFFER_BINDING : 0x8894,
  11112. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  11113. STREAM_DRAW : 0x88E0,
  11114. STATIC_DRAW : 0x88E4,
  11115. DYNAMIC_DRAW : 0x88E8,
  11116. BUFFER_SIZE : 0x8764,
  11117. BUFFER_USAGE : 0x8765,
  11118. CURRENT_VERTEX_ATTRIB : 0x8626,
  11119. FRONT : 0x0404,
  11120. BACK : 0x0405,
  11121. FRONT_AND_BACK : 0x0408,
  11122. CULL_FACE : 0x0B44,
  11123. BLEND : 0x0BE2,
  11124. DITHER : 0x0BD0,
  11125. STENCIL_TEST : 0x0B90,
  11126. DEPTH_TEST : 0x0B71,
  11127. SCISSOR_TEST : 0x0C11,
  11128. POLYGON_OFFSET_FILL : 0x8037,
  11129. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  11130. SAMPLE_COVERAGE : 0x80A0,
  11131. NO_ERROR : 0,
  11132. INVALID_ENUM : 0x0500,
  11133. INVALID_VALUE : 0x0501,
  11134. INVALID_OPERATION : 0x0502,
  11135. OUT_OF_MEMORY : 0x0505,
  11136. CW : 0x0900,
  11137. CCW : 0x0901,
  11138. LINE_WIDTH : 0x0B21,
  11139. ALIASED_POINT_SIZE_RANGE : 0x846D,
  11140. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  11141. CULL_FACE_MODE : 0x0B45,
  11142. FRONT_FACE : 0x0B46,
  11143. DEPTH_RANGE : 0x0B70,
  11144. DEPTH_WRITEMASK : 0x0B72,
  11145. DEPTH_CLEAR_VALUE : 0x0B73,
  11146. DEPTH_FUNC : 0x0B74,
  11147. STENCIL_CLEAR_VALUE : 0x0B91,
  11148. STENCIL_FUNC : 0x0B92,
  11149. STENCIL_FAIL : 0x0B94,
  11150. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  11151. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  11152. STENCIL_REF : 0x0B97,
  11153. STENCIL_VALUE_MASK : 0x0B93,
  11154. STENCIL_WRITEMASK : 0x0B98,
  11155. STENCIL_BACK_FUNC : 0x8800,
  11156. STENCIL_BACK_FAIL : 0x8801,
  11157. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  11158. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  11159. STENCIL_BACK_REF : 0x8CA3,
  11160. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  11161. STENCIL_BACK_WRITEMASK : 0x8CA5,
  11162. VIEWPORT : 0x0BA2,
  11163. SCISSOR_BOX : 0x0C10,
  11164. COLOR_CLEAR_VALUE : 0x0C22,
  11165. COLOR_WRITEMASK : 0x0C23,
  11166. UNPACK_ALIGNMENT : 0x0CF5,
  11167. PACK_ALIGNMENT : 0x0D05,
  11168. MAX_TEXTURE_SIZE : 0x0D33,
  11169. MAX_VIEWPORT_DIMS : 0x0D3A,
  11170. SUBPIXEL_BITS : 0x0D50,
  11171. RED_BITS : 0x0D52,
  11172. GREEN_BITS : 0x0D53,
  11173. BLUE_BITS : 0x0D54,
  11174. ALPHA_BITS : 0x0D55,
  11175. DEPTH_BITS : 0x0D56,
  11176. STENCIL_BITS : 0x0D57,
  11177. POLYGON_OFFSET_UNITS : 0x2A00,
  11178. POLYGON_OFFSET_FACTOR : 0x8038,
  11179. TEXTURE_BINDING_2D : 0x8069,
  11180. SAMPLE_BUFFERS : 0x80A8,
  11181. SAMPLES : 0x80A9,
  11182. SAMPLE_COVERAGE_VALUE : 0x80AA,
  11183. SAMPLE_COVERAGE_INVERT : 0x80AB,
  11184. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  11185. DONT_CARE : 0x1100,
  11186. FASTEST : 0x1101,
  11187. NICEST : 0x1102,
  11188. GENERATE_MIPMAP_HINT : 0x8192,
  11189. BYTE : 0x1400,
  11190. UNSIGNED_BYTE : 0x1401,
  11191. SHORT : 0x1402,
  11192. UNSIGNED_SHORT : 0x1403,
  11193. INT : 0x1404,
  11194. UNSIGNED_INT : 0x1405,
  11195. FLOAT : 0x1406,
  11196. DEPTH_COMPONENT : 0x1902,
  11197. ALPHA : 0x1906,
  11198. RGB : 0x1907,
  11199. RGBA : 0x1908,
  11200. LUMINANCE : 0x1909,
  11201. LUMINANCE_ALPHA : 0x190A,
  11202. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  11203. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  11204. UNSIGNED_SHORT_5_6_5 : 0x8363,
  11205. FRAGMENT_SHADER : 0x8B30,
  11206. VERTEX_SHADER : 0x8B31,
  11207. MAX_VERTEX_ATTRIBS : 0x8869,
  11208. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  11209. MAX_VARYING_VECTORS : 0x8DFC,
  11210. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  11211. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  11212. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  11213. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  11214. SHADER_TYPE : 0x8B4F,
  11215. DELETE_STATUS : 0x8B80,
  11216. LINK_STATUS : 0x8B82,
  11217. VALIDATE_STATUS : 0x8B83,
  11218. ATTACHED_SHADERS : 0x8B85,
  11219. ACTIVE_UNIFORMS : 0x8B86,
  11220. ACTIVE_ATTRIBUTES : 0x8B89,
  11221. SHADING_LANGUAGE_VERSION : 0x8B8C,
  11222. CURRENT_PROGRAM : 0x8B8D,
  11223. NEVER : 0x0200,
  11224. LESS : 0x0201,
  11225. EQUAL : 0x0202,
  11226. LEQUAL : 0x0203,
  11227. GREATER : 0x0204,
  11228. NOTEQUAL : 0x0205,
  11229. GEQUAL : 0x0206,
  11230. ALWAYS : 0x0207,
  11231. KEEP : 0x1E00,
  11232. REPLACE : 0x1E01,
  11233. INCR : 0x1E02,
  11234. DECR : 0x1E03,
  11235. INVERT : 0x150A,
  11236. INCR_WRAP : 0x8507,
  11237. DECR_WRAP : 0x8508,
  11238. VENDOR : 0x1F00,
  11239. RENDERER : 0x1F01,
  11240. VERSION : 0x1F02,
  11241. NEAREST : 0x2600,
  11242. LINEAR : 0x2601,
  11243. NEAREST_MIPMAP_NEAREST : 0x2700,
  11244. LINEAR_MIPMAP_NEAREST : 0x2701,
  11245. NEAREST_MIPMAP_LINEAR : 0x2702,
  11246. LINEAR_MIPMAP_LINEAR : 0x2703,
  11247. TEXTURE_MAG_FILTER : 0x2800,
  11248. TEXTURE_MIN_FILTER : 0x2801,
  11249. TEXTURE_WRAP_S : 0x2802,
  11250. TEXTURE_WRAP_T : 0x2803,
  11251. TEXTURE_2D : 0x0DE1,
  11252. TEXTURE : 0x1702,
  11253. TEXTURE_CUBE_MAP : 0x8513,
  11254. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  11255. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  11256. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  11257. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  11258. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  11259. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  11260. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  11261. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  11262. TEXTURE0 : 0x84C0,
  11263. TEXTURE1 : 0x84C1,
  11264. TEXTURE2 : 0x84C2,
  11265. TEXTURE3 : 0x84C3,
  11266. TEXTURE4 : 0x84C4,
  11267. TEXTURE5 : 0x84C5,
  11268. TEXTURE6 : 0x84C6,
  11269. TEXTURE7 : 0x84C7,
  11270. TEXTURE8 : 0x84C8,
  11271. TEXTURE9 : 0x84C9,
  11272. TEXTURE10 : 0x84CA,
  11273. TEXTURE11 : 0x84CB,
  11274. TEXTURE12 : 0x84CC,
  11275. TEXTURE13 : 0x84CD,
  11276. TEXTURE14 : 0x84CE,
  11277. TEXTURE15 : 0x84CF,
  11278. TEXTURE16 : 0x84D0,
  11279. TEXTURE17 : 0x84D1,
  11280. TEXTURE18 : 0x84D2,
  11281. TEXTURE19 : 0x84D3,
  11282. TEXTURE20 : 0x84D4,
  11283. TEXTURE21 : 0x84D5,
  11284. TEXTURE22 : 0x84D6,
  11285. TEXTURE23 : 0x84D7,
  11286. TEXTURE24 : 0x84D8,
  11287. TEXTURE25 : 0x84D9,
  11288. TEXTURE26 : 0x84DA,
  11289. TEXTURE27 : 0x84DB,
  11290. TEXTURE28 : 0x84DC,
  11291. TEXTURE29 : 0x84DD,
  11292. TEXTURE30 : 0x84DE,
  11293. TEXTURE31 : 0x84DF,
  11294. ACTIVE_TEXTURE : 0x84E0,
  11295. REPEAT : 0x2901,
  11296. CLAMP_TO_EDGE : 0x812F,
  11297. MIRRORED_REPEAT : 0x8370,
  11298. FLOAT_VEC2 : 0x8B50,
  11299. FLOAT_VEC3 : 0x8B51,
  11300. FLOAT_VEC4 : 0x8B52,
  11301. INT_VEC2 : 0x8B53,
  11302. INT_VEC3 : 0x8B54,
  11303. INT_VEC4 : 0x8B55,
  11304. BOOL : 0x8B56,
  11305. BOOL_VEC2 : 0x8B57,
  11306. BOOL_VEC3 : 0x8B58,
  11307. BOOL_VEC4 : 0x8B59,
  11308. FLOAT_MAT2 : 0x8B5A,
  11309. FLOAT_MAT3 : 0x8B5B,
  11310. FLOAT_MAT4 : 0x8B5C,
  11311. SAMPLER_2D : 0x8B5E,
  11312. SAMPLER_CUBE : 0x8B60,
  11313. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  11314. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  11315. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  11316. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  11317. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  11318. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  11319. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  11320. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  11321. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  11322. COMPILE_STATUS : 0x8B81,
  11323. LOW_FLOAT : 0x8DF0,
  11324. MEDIUM_FLOAT : 0x8DF1,
  11325. HIGH_FLOAT : 0x8DF2,
  11326. LOW_INT : 0x8DF3,
  11327. MEDIUM_INT : 0x8DF4,
  11328. HIGH_INT : 0x8DF5,
  11329. FRAMEBUFFER : 0x8D40,
  11330. RENDERBUFFER : 0x8D41,
  11331. RGBA4 : 0x8056,
  11332. RGB5_A1 : 0x8057,
  11333. RGB565 : 0x8D62,
  11334. DEPTH_COMPONENT16 : 0x81A5,
  11335. STENCIL_INDEX : 0x1901,
  11336. STENCIL_INDEX8 : 0x8D48,
  11337. DEPTH_STENCIL : 0x84F9,
  11338. RENDERBUFFER_WIDTH : 0x8D42,
  11339. RENDERBUFFER_HEIGHT : 0x8D43,
  11340. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  11341. RENDERBUFFER_RED_SIZE : 0x8D50,
  11342. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  11343. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  11344. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  11345. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  11346. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  11347. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  11348. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  11349. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  11350. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  11351. COLOR_ATTACHMENT0 : 0x8CE0,
  11352. DEPTH_ATTACHMENT : 0x8D00,
  11353. STENCIL_ATTACHMENT : 0x8D20,
  11354. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  11355. NONE : 0,
  11356. FRAMEBUFFER_COMPLETE : 0x8CD5,
  11357. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  11358. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  11359. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  11360. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  11361. FRAMEBUFFER_BINDING : 0x8CA6,
  11362. RENDERBUFFER_BINDING : 0x8CA7,
  11363. MAX_RENDERBUFFER_SIZE : 0x84E8,
  11364. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  11365. UNPACK_FLIP_Y_WEBGL : 0x9240,
  11366. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  11367. CONTEXT_LOST_WEBGL : 0x9242,
  11368. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  11369. BROWSER_DEFAULT_WEBGL : 0x9244,
  11370. // Desktop OpenGL
  11371. DOUBLE : 0x140A,
  11372. // WebGL 2
  11373. READ_BUFFER : 0x0C02,
  11374. UNPACK_ROW_LENGTH : 0x0CF2,
  11375. UNPACK_SKIP_ROWS : 0x0CF3,
  11376. UNPACK_SKIP_PIXELS : 0x0CF4,
  11377. PACK_ROW_LENGTH : 0x0D02,
  11378. PACK_SKIP_ROWS : 0x0D03,
  11379. PACK_SKIP_PIXELS : 0x0D04,
  11380. COLOR : 0x1800,
  11381. DEPTH : 0x1801,
  11382. STENCIL : 0x1802,
  11383. RED : 0x1903,
  11384. RGB8 : 0x8051,
  11385. RGBA8 : 0x8058,
  11386. RGB10_A2 : 0x8059,
  11387. TEXTURE_BINDING_3D : 0x806A,
  11388. UNPACK_SKIP_IMAGES : 0x806D,
  11389. UNPACK_IMAGE_HEIGHT : 0x806E,
  11390. TEXTURE_3D : 0x806F,
  11391. TEXTURE_WRAP_R : 0x8072,
  11392. MAX_3D_TEXTURE_SIZE : 0x8073,
  11393. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  11394. MAX_ELEMENTS_VERTICES : 0x80E8,
  11395. MAX_ELEMENTS_INDICES : 0x80E9,
  11396. TEXTURE_MIN_LOD : 0x813A,
  11397. TEXTURE_MAX_LOD : 0x813B,
  11398. TEXTURE_BASE_LEVEL : 0x813C,
  11399. TEXTURE_MAX_LEVEL : 0x813D,
  11400. MIN : 0x8007,
  11401. MAX : 0x8008,
  11402. DEPTH_COMPONENT24 : 0x81A6,
  11403. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  11404. TEXTURE_COMPARE_MODE : 0x884C,
  11405. TEXTURE_COMPARE_FUNC : 0x884D,
  11406. CURRENT_QUERY : 0x8865,
  11407. QUERY_RESULT : 0x8866,
  11408. QUERY_RESULT_AVAILABLE : 0x8867,
  11409. STREAM_READ : 0x88E1,
  11410. STREAM_COPY : 0x88E2,
  11411. STATIC_READ : 0x88E5,
  11412. STATIC_COPY : 0x88E6,
  11413. DYNAMIC_READ : 0x88E9,
  11414. DYNAMIC_COPY : 0x88EA,
  11415. MAX_DRAW_BUFFERS : 0x8824,
  11416. DRAW_BUFFER0 : 0x8825,
  11417. DRAW_BUFFER1 : 0x8826,
  11418. DRAW_BUFFER2 : 0x8827,
  11419. DRAW_BUFFER3 : 0x8828,
  11420. DRAW_BUFFER4 : 0x8829,
  11421. DRAW_BUFFER5 : 0x882A,
  11422. DRAW_BUFFER6 : 0x882B,
  11423. DRAW_BUFFER7 : 0x882C,
  11424. DRAW_BUFFER8 : 0x882D,
  11425. DRAW_BUFFER9 : 0x882E,
  11426. DRAW_BUFFER10 : 0x882F,
  11427. DRAW_BUFFER11 : 0x8830,
  11428. DRAW_BUFFER12 : 0x8831,
  11429. DRAW_BUFFER13 : 0x8832,
  11430. DRAW_BUFFER14 : 0x8833,
  11431. DRAW_BUFFER15 : 0x8834,
  11432. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  11433. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  11434. SAMPLER_3D : 0x8B5F,
  11435. SAMPLER_2D_SHADOW : 0x8B62,
  11436. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  11437. PIXEL_PACK_BUFFER : 0x88EB,
  11438. PIXEL_UNPACK_BUFFER : 0x88EC,
  11439. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  11440. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  11441. FLOAT_MAT2x3 : 0x8B65,
  11442. FLOAT_MAT2x4 : 0x8B66,
  11443. FLOAT_MAT3x2 : 0x8B67,
  11444. FLOAT_MAT3x4 : 0x8B68,
  11445. FLOAT_MAT4x2 : 0x8B69,
  11446. FLOAT_MAT4x3 : 0x8B6A,
  11447. SRGB : 0x8C40,
  11448. SRGB8 : 0x8C41,
  11449. SRGB8_ALPHA8 : 0x8C43,
  11450. COMPARE_REF_TO_TEXTURE : 0x884E,
  11451. RGBA32F : 0x8814,
  11452. RGB32F : 0x8815,
  11453. RGBA16F : 0x881A,
  11454. RGB16F : 0x881B,
  11455. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  11456. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  11457. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  11458. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  11459. MAX_VARYING_COMPONENTS : 0x8B4B,
  11460. TEXTURE_2D_ARRAY : 0x8C1A,
  11461. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  11462. R11F_G11F_B10F : 0x8C3A,
  11463. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  11464. RGB9_E5 : 0x8C3D,
  11465. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  11466. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  11467. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  11468. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  11469. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  11470. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  11471. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  11472. RASTERIZER_DISCARD : 0x8C89,
  11473. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  11474. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  11475. INTERLEAVED_ATTRIBS : 0x8C8C,
  11476. SEPARATE_ATTRIBS : 0x8C8D,
  11477. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  11478. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  11479. RGBA32UI : 0x8D70,
  11480. RGB32UI : 0x8D71,
  11481. RGBA16UI : 0x8D76,
  11482. RGB16UI : 0x8D77,
  11483. RGBA8UI : 0x8D7C,
  11484. RGB8UI : 0x8D7D,
  11485. RGBA32I : 0x8D82,
  11486. RGB32I : 0x8D83,
  11487. RGBA16I : 0x8D88,
  11488. RGB16I : 0x8D89,
  11489. RGBA8I : 0x8D8E,
  11490. RGB8I : 0x8D8F,
  11491. RED_INTEGER : 0x8D94,
  11492. RGB_INTEGER : 0x8D98,
  11493. RGBA_INTEGER : 0x8D99,
  11494. SAMPLER_2D_ARRAY : 0x8DC1,
  11495. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  11496. SAMPLER_CUBE_SHADOW : 0x8DC5,
  11497. UNSIGNED_INT_VEC2 : 0x8DC6,
  11498. UNSIGNED_INT_VEC3 : 0x8DC7,
  11499. UNSIGNED_INT_VEC4 : 0x8DC8,
  11500. INT_SAMPLER_2D : 0x8DCA,
  11501. INT_SAMPLER_3D : 0x8DCB,
  11502. INT_SAMPLER_CUBE : 0x8DCC,
  11503. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  11504. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  11505. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  11506. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  11507. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  11508. DEPTH_COMPONENT32F : 0x8CAC,
  11509. DEPTH32F_STENCIL8 : 0x8CAD,
  11510. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  11511. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  11512. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  11513. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  11514. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  11515. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  11516. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  11517. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  11518. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  11519. FRAMEBUFFER_DEFAULT : 0x8218,
  11520. UNSIGNED_INT_24_8 : 0x84FA,
  11521. DEPTH24_STENCIL8 : 0x88F0,
  11522. UNSIGNED_NORMALIZED : 0x8C17,
  11523. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  11524. READ_FRAMEBUFFER : 0x8CA8,
  11525. DRAW_FRAMEBUFFER : 0x8CA9,
  11526. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  11527. RENDERBUFFER_SAMPLES : 0x8CAB,
  11528. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  11529. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  11530. COLOR_ATTACHMENT1 : 0x8CE1,
  11531. COLOR_ATTACHMENT2 : 0x8CE2,
  11532. COLOR_ATTACHMENT3 : 0x8CE3,
  11533. COLOR_ATTACHMENT4 : 0x8CE4,
  11534. COLOR_ATTACHMENT5 : 0x8CE5,
  11535. COLOR_ATTACHMENT6 : 0x8CE6,
  11536. COLOR_ATTACHMENT7 : 0x8CE7,
  11537. COLOR_ATTACHMENT8 : 0x8CE8,
  11538. COLOR_ATTACHMENT9 : 0x8CE9,
  11539. COLOR_ATTACHMENT10 : 0x8CEA,
  11540. COLOR_ATTACHMENT11 : 0x8CEB,
  11541. COLOR_ATTACHMENT12 : 0x8CEC,
  11542. COLOR_ATTACHMENT13 : 0x8CED,
  11543. COLOR_ATTACHMENT14 : 0x8CEE,
  11544. COLOR_ATTACHMENT15 : 0x8CEF,
  11545. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  11546. MAX_SAMPLES : 0x8D57,
  11547. HALF_FLOAT : 0x140B,
  11548. RG : 0x8227,
  11549. RG_INTEGER : 0x8228,
  11550. R8 : 0x8229,
  11551. RG8 : 0x822B,
  11552. R16F : 0x822D,
  11553. R32F : 0x822E,
  11554. RG16F : 0x822F,
  11555. RG32F : 0x8230,
  11556. R8I : 0x8231,
  11557. R8UI : 0x8232,
  11558. R16I : 0x8233,
  11559. R16UI : 0x8234,
  11560. R32I : 0x8235,
  11561. R32UI : 0x8236,
  11562. RG8I : 0x8237,
  11563. RG8UI : 0x8238,
  11564. RG16I : 0x8239,
  11565. RG16UI : 0x823A,
  11566. RG32I : 0x823B,
  11567. RG32UI : 0x823C,
  11568. VERTEX_ARRAY_BINDING : 0x85B5,
  11569. R8_SNORM : 0x8F94,
  11570. RG8_SNORM : 0x8F95,
  11571. RGB8_SNORM : 0x8F96,
  11572. RGBA8_SNORM : 0x8F97,
  11573. SIGNED_NORMALIZED : 0x8F9C,
  11574. COPY_READ_BUFFER : 0x8F36,
  11575. COPY_WRITE_BUFFER : 0x8F37,
  11576. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  11577. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  11578. UNIFORM_BUFFER : 0x8A11,
  11579. UNIFORM_BUFFER_BINDING : 0x8A28,
  11580. UNIFORM_BUFFER_START : 0x8A29,
  11581. UNIFORM_BUFFER_SIZE : 0x8A2A,
  11582. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  11583. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  11584. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  11585. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  11586. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  11587. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  11588. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  11589. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  11590. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  11591. UNIFORM_TYPE : 0x8A37,
  11592. UNIFORM_SIZE : 0x8A38,
  11593. UNIFORM_BLOCK_INDEX : 0x8A3A,
  11594. UNIFORM_OFFSET : 0x8A3B,
  11595. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  11596. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  11597. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  11598. UNIFORM_BLOCK_BINDING : 0x8A3F,
  11599. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  11600. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  11601. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  11602. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  11603. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  11604. INVALID_INDEX : 0xFFFFFFFF,
  11605. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  11606. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  11607. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  11608. OBJECT_TYPE : 0x9112,
  11609. SYNC_CONDITION : 0x9113,
  11610. SYNC_STATUS : 0x9114,
  11611. SYNC_FLAGS : 0x9115,
  11612. SYNC_FENCE : 0x9116,
  11613. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  11614. UNSIGNALED : 0x9118,
  11615. SIGNALED : 0x9119,
  11616. ALREADY_SIGNALED : 0x911A,
  11617. TIMEOUT_EXPIRED : 0x911B,
  11618. CONDITION_SATISFIED : 0x911C,
  11619. WAIT_FAILED : 0x911D,
  11620. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  11621. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  11622. ANY_SAMPLES_PASSED : 0x8C2F,
  11623. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  11624. SAMPLER_BINDING : 0x8919,
  11625. RGB10_A2UI : 0x906F,
  11626. INT_2_10_10_10_REV : 0x8D9F,
  11627. TRANSFORM_FEEDBACK : 0x8E22,
  11628. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  11629. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  11630. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  11631. COMPRESSED_R11_EAC : 0x9270,
  11632. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  11633. COMPRESSED_RG11_EAC : 0x9272,
  11634. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  11635. COMPRESSED_RGB8_ETC2 : 0x9274,
  11636. COMPRESSED_SRGB8_ETC2 : 0x9275,
  11637. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  11638. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  11639. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  11640. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  11641. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  11642. MAX_ELEMENT_INDEX : 0x8D6B,
  11643. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  11644. };
  11645. return freezeObject(WebGLConstants);
  11646. });
  11647. /*global define*/
  11648. define('Core/ComponentDatatype',[
  11649. './defaultValue',
  11650. './defined',
  11651. './DeveloperError',
  11652. './FeatureDetection',
  11653. './freezeObject',
  11654. './WebGLConstants'
  11655. ], function(
  11656. defaultValue,
  11657. defined,
  11658. DeveloperError,
  11659. FeatureDetection,
  11660. freezeObject,
  11661. WebGLConstants) {
  11662. 'use strict';
  11663. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  11664. // from failing, since we won't be able to create a WebGL context anyway.
  11665. if (!FeatureDetection.supportsTypedArrays()) {
  11666. return {};
  11667. }
  11668. /**
  11669. * WebGL component datatypes. Components are intrinsics,
  11670. * which form attributes, which form vertices.
  11671. *
  11672. * @exports ComponentDatatype
  11673. */
  11674. var ComponentDatatype = {
  11675. /**
  11676. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  11677. * of an element in <code>Int8Array</code>.
  11678. *
  11679. * @type {Number}
  11680. * @constant
  11681. */
  11682. BYTE : WebGLConstants.BYTE,
  11683. /**
  11684. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  11685. * of an element in <code>Uint8Array</code>.
  11686. *
  11687. * @type {Number}
  11688. * @constant
  11689. */
  11690. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  11691. /**
  11692. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  11693. * of an element in <code>Int16Array</code>.
  11694. *
  11695. * @type {Number}
  11696. * @constant
  11697. */
  11698. SHORT : WebGLConstants.SHORT,
  11699. /**
  11700. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  11701. * of an element in <code>Uint16Array</code>.
  11702. *
  11703. * @type {Number}
  11704. * @constant
  11705. */
  11706. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  11707. /**
  11708. * 32-bit signed int corresponding to <code>INT</code> and the type
  11709. * of an element in <code>Int32Array</code>.
  11710. *
  11711. * @memberOf ComponentDatatype
  11712. *
  11713. * @type {Number}
  11714. * @constant
  11715. */
  11716. INT : WebGLConstants.INT,
  11717. /**
  11718. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  11719. * of an element in <code>Uint32Array</code>.
  11720. *
  11721. * @memberOf ComponentDatatype
  11722. *
  11723. * @type {Number}
  11724. * @constant
  11725. */
  11726. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  11727. /**
  11728. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  11729. * of an element in <code>Float32Array</code>.
  11730. *
  11731. * @type {Number}
  11732. * @constant
  11733. */
  11734. FLOAT : WebGLConstants.FLOAT,
  11735. /**
  11736. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  11737. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  11738. * and the type of an element in <code>Float64Array</code>.
  11739. *
  11740. * @memberOf ComponentDatatype
  11741. *
  11742. * @type {Number}
  11743. * @constant
  11744. * @default 0x140A
  11745. */
  11746. DOUBLE : WebGLConstants.DOUBLE
  11747. };
  11748. /**
  11749. * Returns the size, in bytes, of the corresponding datatype.
  11750. *
  11751. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  11752. * @returns {Number} The size in bytes.
  11753. *
  11754. * @exception {DeveloperError} componentDatatype is not a valid value.
  11755. *
  11756. * @example
  11757. * // Returns Int8Array.BYTES_PER_ELEMENT
  11758. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  11759. */
  11760. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  11761. if (!defined(componentDatatype)) {
  11762. throw new DeveloperError('value is required.');
  11763. }
  11764. switch (componentDatatype) {
  11765. case ComponentDatatype.BYTE:
  11766. return Int8Array.BYTES_PER_ELEMENT;
  11767. case ComponentDatatype.UNSIGNED_BYTE:
  11768. return Uint8Array.BYTES_PER_ELEMENT;
  11769. case ComponentDatatype.SHORT:
  11770. return Int16Array.BYTES_PER_ELEMENT;
  11771. case ComponentDatatype.UNSIGNED_SHORT:
  11772. return Uint16Array.BYTES_PER_ELEMENT;
  11773. case ComponentDatatype.INT:
  11774. return Int32Array.BYTES_PER_ELEMENT;
  11775. case ComponentDatatype.UNSIGNED_INT:
  11776. return Uint32Array.BYTES_PER_ELEMENT;
  11777. case ComponentDatatype.FLOAT:
  11778. return Float32Array.BYTES_PER_ELEMENT;
  11779. case ComponentDatatype.DOUBLE:
  11780. return Float64Array.BYTES_PER_ELEMENT;
  11781. default:
  11782. throw new DeveloperError('componentDatatype is not a valid value.');
  11783. }
  11784. };
  11785. /**
  11786. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  11787. *
  11788. * @param {TypedArray} array The typed array.
  11789. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  11790. */
  11791. ComponentDatatype.fromTypedArray = function(array) {
  11792. if (array instanceof Int8Array) {
  11793. return ComponentDatatype.BYTE;
  11794. }
  11795. if (array instanceof Uint8Array) {
  11796. return ComponentDatatype.UNSIGNED_BYTE;
  11797. }
  11798. if (array instanceof Int16Array) {
  11799. return ComponentDatatype.SHORT;
  11800. }
  11801. if (array instanceof Uint16Array) {
  11802. return ComponentDatatype.UNSIGNED_SHORT;
  11803. }
  11804. if (array instanceof Int32Array) {
  11805. return ComponentDatatype.INT;
  11806. }
  11807. if (array instanceof Uint32Array) {
  11808. return ComponentDatatype.UNSIGNED_INT;
  11809. }
  11810. if (array instanceof Float32Array) {
  11811. return ComponentDatatype.FLOAT;
  11812. }
  11813. if (array instanceof Float64Array) {
  11814. return ComponentDatatype.DOUBLE;
  11815. }
  11816. };
  11817. /**
  11818. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  11819. *
  11820. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  11821. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  11822. *
  11823. * @example
  11824. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  11825. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  11826. * }
  11827. */
  11828. ComponentDatatype.validate = function(componentDatatype) {
  11829. return defined(componentDatatype) &&
  11830. (componentDatatype === ComponentDatatype.BYTE ||
  11831. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  11832. componentDatatype === ComponentDatatype.SHORT ||
  11833. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  11834. componentDatatype === ComponentDatatype.INT ||
  11835. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  11836. componentDatatype === ComponentDatatype.FLOAT ||
  11837. componentDatatype === ComponentDatatype.DOUBLE);
  11838. };
  11839. /**
  11840. * Creates a typed array corresponding to component data type.
  11841. *
  11842. * @param {ComponentDatatype} componentDatatype The component data type.
  11843. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  11844. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  11845. *
  11846. * @exception {DeveloperError} componentDatatype is not a valid value.
  11847. *
  11848. * @example
  11849. * // creates a Float32Array with length of 100
  11850. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  11851. */
  11852. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  11853. if (!defined(componentDatatype)) {
  11854. throw new DeveloperError('componentDatatype is required.');
  11855. }
  11856. if (!defined(valuesOrLength)) {
  11857. throw new DeveloperError('valuesOrLength is required.');
  11858. }
  11859. switch (componentDatatype) {
  11860. case ComponentDatatype.BYTE:
  11861. return new Int8Array(valuesOrLength);
  11862. case ComponentDatatype.UNSIGNED_BYTE:
  11863. return new Uint8Array(valuesOrLength);
  11864. case ComponentDatatype.SHORT:
  11865. return new Int16Array(valuesOrLength);
  11866. case ComponentDatatype.UNSIGNED_SHORT:
  11867. return new Uint16Array(valuesOrLength);
  11868. case ComponentDatatype.INT:
  11869. return new Int32Array(valuesOrLength);
  11870. case ComponentDatatype.UNSIGNED_INT:
  11871. return new Uint32Array(valuesOrLength);
  11872. case ComponentDatatype.FLOAT:
  11873. return new Float32Array(valuesOrLength);
  11874. case ComponentDatatype.DOUBLE:
  11875. return new Float64Array(valuesOrLength);
  11876. default:
  11877. throw new DeveloperError('componentDatatype is not a valid value.');
  11878. }
  11879. };
  11880. /**
  11881. * Creates a typed view of an array of bytes.
  11882. *
  11883. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  11884. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  11885. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  11886. * @param {Number} [length] The number of elements in the view.
  11887. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  11888. *
  11889. * @exception {DeveloperError} componentDatatype is not a valid value.
  11890. */
  11891. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  11892. if (!defined(componentDatatype)) {
  11893. throw new DeveloperError('componentDatatype is required.');
  11894. }
  11895. if (!defined(buffer)) {
  11896. throw new DeveloperError('buffer is required.');
  11897. }
  11898. byteOffset = defaultValue(byteOffset, 0);
  11899. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  11900. switch (componentDatatype) {
  11901. case ComponentDatatype.BYTE:
  11902. return new Int8Array(buffer, byteOffset, length);
  11903. case ComponentDatatype.UNSIGNED_BYTE:
  11904. return new Uint8Array(buffer, byteOffset, length);
  11905. case ComponentDatatype.SHORT:
  11906. return new Int16Array(buffer, byteOffset, length);
  11907. case ComponentDatatype.UNSIGNED_SHORT:
  11908. return new Uint16Array(buffer, byteOffset, length);
  11909. case ComponentDatatype.INT:
  11910. return new Int32Array(buffer, byteOffset, length);
  11911. case ComponentDatatype.UNSIGNED_INT:
  11912. return new Uint32Array(buffer, byteOffset, length);
  11913. case ComponentDatatype.FLOAT:
  11914. return new Float32Array(buffer, byteOffset, length);
  11915. case ComponentDatatype.DOUBLE:
  11916. return new Float64Array(buffer, byteOffset, length);
  11917. default:
  11918. throw new DeveloperError('componentDatatype is not a valid value.');
  11919. }
  11920. };
  11921. /**
  11922. * Get the ComponentDatatype from its name.
  11923. *
  11924. * @param {String} name The name of the ComponentDatatype.
  11925. * @returns {ComponentDatatype} The ComponentDatatype.
  11926. *
  11927. * @exception {DeveloperError} name is not a valid value.
  11928. */
  11929. ComponentDatatype.fromName = function(name) {
  11930. switch (name) {
  11931. case 'BYTE':
  11932. return ComponentDatatype.BYTE;
  11933. case 'UNSIGNED_BYTE':
  11934. return ComponentDatatype.UNSIGNED_BYTE;
  11935. case 'SHORT':
  11936. return ComponentDatatype.SHORT;
  11937. case 'UNSIGNED_SHORT':
  11938. return ComponentDatatype.UNSIGNED_SHORT;
  11939. case 'INT':
  11940. return ComponentDatatype.INT;
  11941. case 'UNSIGNED_INT':
  11942. return ComponentDatatype.UNSIGNED_INT;
  11943. case 'FLOAT':
  11944. return ComponentDatatype.FLOAT;
  11945. case 'DOUBLE':
  11946. return ComponentDatatype.DOUBLE;
  11947. default:
  11948. throw new DeveloperError('name is not a valid value.');
  11949. }
  11950. };
  11951. return freezeObject(ComponentDatatype);
  11952. });
  11953. /*global define*/
  11954. define('Core/Quaternion',[
  11955. './Cartesian3',
  11956. './defaultValue',
  11957. './defined',
  11958. './DeveloperError',
  11959. './FeatureDetection',
  11960. './freezeObject',
  11961. './Math',
  11962. './Matrix3'
  11963. ], function(
  11964. Cartesian3,
  11965. defaultValue,
  11966. defined,
  11967. DeveloperError,
  11968. FeatureDetection,
  11969. freezeObject,
  11970. CesiumMath,
  11971. Matrix3) {
  11972. 'use strict';
  11973. /**
  11974. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  11975. * @alias Quaternion
  11976. * @constructor
  11977. *
  11978. * @param {Number} [x=0.0] The X component.
  11979. * @param {Number} [y=0.0] The Y component.
  11980. * @param {Number} [z=0.0] The Z component.
  11981. * @param {Number} [w=0.0] The W component.
  11982. *
  11983. * @see PackableForInterpolation
  11984. */
  11985. function Quaternion(x, y, z, w) {
  11986. /**
  11987. * The X component.
  11988. * @type {Number}
  11989. * @default 0.0
  11990. */
  11991. this.x = defaultValue(x, 0.0);
  11992. /**
  11993. * The Y component.
  11994. * @type {Number}
  11995. * @default 0.0
  11996. */
  11997. this.y = defaultValue(y, 0.0);
  11998. /**
  11999. * The Z component.
  12000. * @type {Number}
  12001. * @default 0.0
  12002. */
  12003. this.z = defaultValue(z, 0.0);
  12004. /**
  12005. * The W component.
  12006. * @type {Number}
  12007. * @default 0.0
  12008. */
  12009. this.w = defaultValue(w, 0.0);
  12010. }
  12011. var fromAxisAngleScratch = new Cartesian3();
  12012. /**
  12013. * Computes a quaternion representing a rotation around an axis.
  12014. *
  12015. * @param {Cartesian3} axis The axis of rotation.
  12016. * @param {Number} angle The angle in radians to rotate around the axis.
  12017. * @param {Quaternion} [result] The object onto which to store the result.
  12018. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  12019. */
  12020. Quaternion.fromAxisAngle = function(axis, angle, result) {
  12021. if (!defined(axis)) {
  12022. throw new DeveloperError('axis is required.');
  12023. }
  12024. if (typeof angle !== 'number') {
  12025. throw new DeveloperError('angle is required and must be a number.');
  12026. }
  12027. var halfAngle = angle / 2.0;
  12028. var s = Math.sin(halfAngle);
  12029. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  12030. var x = fromAxisAngleScratch.x * s;
  12031. var y = fromAxisAngleScratch.y * s;
  12032. var z = fromAxisAngleScratch.z * s;
  12033. var w = Math.cos(halfAngle);
  12034. if (!defined(result)) {
  12035. return new Quaternion(x, y, z, w);
  12036. }
  12037. result.x = x;
  12038. result.y = y;
  12039. result.z = z;
  12040. result.w = w;
  12041. return result;
  12042. };
  12043. var fromRotationMatrixNext = [1, 2, 0];
  12044. var fromRotationMatrixQuat = new Array(3);
  12045. /**
  12046. * Computes a Quaternion from the provided Matrix3 instance.
  12047. *
  12048. * @param {Matrix3} matrix The rotation matrix.
  12049. * @param {Quaternion} [result] The object onto which to store the result.
  12050. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  12051. *
  12052. * @see Matrix3.fromQuaternion
  12053. */
  12054. Quaternion.fromRotationMatrix = function(matrix, result) {
  12055. if (!defined(matrix)) {
  12056. throw new DeveloperError('matrix is required.');
  12057. }
  12058. var root;
  12059. var x;
  12060. var y;
  12061. var z;
  12062. var w;
  12063. var m00 = matrix[Matrix3.COLUMN0ROW0];
  12064. var m11 = matrix[Matrix3.COLUMN1ROW1];
  12065. var m22 = matrix[Matrix3.COLUMN2ROW2];
  12066. var trace = m00 + m11 + m22;
  12067. if (trace > 0.0) {
  12068. // |w| > 1/2, may as well choose w > 1/2
  12069. root = Math.sqrt(trace + 1.0); // 2w
  12070. w = 0.5 * root;
  12071. root = 0.5 / root; // 1/(4w)
  12072. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  12073. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  12074. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  12075. } else {
  12076. // |w| <= 1/2
  12077. var next = fromRotationMatrixNext;
  12078. var i = 0;
  12079. if (m11 > m00) {
  12080. i = 1;
  12081. }
  12082. if (m22 > m00 && m22 > m11) {
  12083. i = 2;
  12084. }
  12085. var j = next[i];
  12086. var k = next[j];
  12087. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  12088. var quat = fromRotationMatrixQuat;
  12089. quat[i] = 0.5 * root;
  12090. root = 0.5 / root;
  12091. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  12092. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  12093. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  12094. x = -quat[0];
  12095. y = -quat[1];
  12096. z = -quat[2];
  12097. }
  12098. if (!defined(result)) {
  12099. return new Quaternion(x, y, z, w);
  12100. }
  12101. result.x = x;
  12102. result.y = y;
  12103. result.z = z;
  12104. result.w = w;
  12105. return result;
  12106. };
  12107. var scratchHPRQuaternion = new Quaternion();
  12108. /**
  12109. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  12110. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  12111. * the positive x axis.
  12112. *
  12113. * @param {Number} heading The heading angle in radians.
  12114. * @param {Number} pitch The pitch angle in radians.
  12115. * @param {Number} roll The roll angle in radians.
  12116. * @param {Quaternion} [result] The object onto which to store the result.
  12117. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  12118. */
  12119. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  12120. if (!defined(heading)) {
  12121. throw new DeveloperError('heading is required.');
  12122. }
  12123. if (!defined(pitch)) {
  12124. throw new DeveloperError('pitch is required.');
  12125. }
  12126. if (!defined(roll)) {
  12127. throw new DeveloperError('roll is required.');
  12128. }
  12129. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  12130. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  12131. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  12132. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  12133. return Quaternion.multiply(headingQuaternion, result, result);
  12134. };
  12135. var sampledQuaternionAxis = new Cartesian3();
  12136. var sampledQuaternionRotation = new Cartesian3();
  12137. var sampledQuaternionTempQuaternion = new Quaternion();
  12138. var sampledQuaternionQuaternion0 = new Quaternion();
  12139. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  12140. /**
  12141. * The number of elements used to pack the object into an array.
  12142. * @type {Number}
  12143. */
  12144. Quaternion.packedLength = 4;
  12145. /**
  12146. * Stores the provided instance into the provided array.
  12147. *
  12148. * @param {Quaternion} value The value to pack.
  12149. * @param {Number[]} array The array to pack into.
  12150. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  12151. *
  12152. * @returns {Number[]} The array that was packed into
  12153. */
  12154. Quaternion.pack = function(value, array, startingIndex) {
  12155. if (!defined(value)) {
  12156. throw new DeveloperError('value is required');
  12157. }
  12158. if (!defined(array)) {
  12159. throw new DeveloperError('array is required');
  12160. }
  12161. startingIndex = defaultValue(startingIndex, 0);
  12162. array[startingIndex++] = value.x;
  12163. array[startingIndex++] = value.y;
  12164. array[startingIndex++] = value.z;
  12165. array[startingIndex] = value.w;
  12166. return array;
  12167. };
  12168. /**
  12169. * Retrieves an instance from a packed array.
  12170. *
  12171. * @param {Number[]} array The packed array.
  12172. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  12173. * @param {Quaternion} [result] The object into which to store the result.
  12174. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  12175. */
  12176. Quaternion.unpack = function(array, startingIndex, result) {
  12177. if (!defined(array)) {
  12178. throw new DeveloperError('array is required');
  12179. }
  12180. startingIndex = defaultValue(startingIndex, 0);
  12181. if (!defined(result)) {
  12182. result = new Quaternion();
  12183. }
  12184. result.x = array[startingIndex];
  12185. result.y = array[startingIndex + 1];
  12186. result.z = array[startingIndex + 2];
  12187. result.w = array[startingIndex + 3];
  12188. return result;
  12189. };
  12190. /**
  12191. * The number of elements used to store the object into an array in its interpolatable form.
  12192. * @type {Number}
  12193. */
  12194. Quaternion.packedInterpolationLength = 3;
  12195. /**
  12196. * Converts a packed array into a form suitable for interpolation.
  12197. *
  12198. * @param {Number[]} packedArray The packed array.
  12199. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  12200. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  12201. * @param {Number[]} result The object into which to store the result.
  12202. */
  12203. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  12204. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  12205. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  12206. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  12207. var offset = i * 3;
  12208. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  12209. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  12210. if (sampledQuaternionTempQuaternion.w < 0) {
  12211. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  12212. }
  12213. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  12214. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  12215. result[offset] = sampledQuaternionAxis.x * angle;
  12216. result[offset + 1] = sampledQuaternionAxis.y * angle;
  12217. result[offset + 2] = sampledQuaternionAxis.z * angle;
  12218. }
  12219. };
  12220. /**
  12221. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  12222. *
  12223. * @param {Number[]} array The array previously packed for interpolation.
  12224. * @param {Number[]} sourceArray The original packed array.
  12225. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  12226. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  12227. * @param {Quaternion} [result] The object into which to store the result.
  12228. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  12229. */
  12230. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  12231. if (!defined(result)) {
  12232. result = new Quaternion();
  12233. }
  12234. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  12235. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  12236. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  12237. if (magnitude === 0) {
  12238. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  12239. } else {
  12240. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  12241. }
  12242. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  12243. };
  12244. /**
  12245. * Duplicates a Quaternion instance.
  12246. *
  12247. * @param {Quaternion} quaternion The quaternion to duplicate.
  12248. * @param {Quaternion} [result] The object onto which to store the result.
  12249. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  12250. */
  12251. Quaternion.clone = function(quaternion, result) {
  12252. if (!defined(quaternion)) {
  12253. return undefined;
  12254. }
  12255. if (!defined(result)) {
  12256. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  12257. }
  12258. result.x = quaternion.x;
  12259. result.y = quaternion.y;
  12260. result.z = quaternion.z;
  12261. result.w = quaternion.w;
  12262. return result;
  12263. };
  12264. /**
  12265. * Computes the conjugate of the provided quaternion.
  12266. *
  12267. * @param {Quaternion} quaternion The quaternion to conjugate.
  12268. * @param {Quaternion} result The object onto which to store the result.
  12269. * @returns {Quaternion} The modified result parameter.
  12270. */
  12271. Quaternion.conjugate = function(quaternion, result) {
  12272. if (!defined(quaternion)) {
  12273. throw new DeveloperError('quaternion is required');
  12274. }
  12275. if (!defined(result)) {
  12276. throw new DeveloperError('result is required');
  12277. }
  12278. result.x = -quaternion.x;
  12279. result.y = -quaternion.y;
  12280. result.z = -quaternion.z;
  12281. result.w = quaternion.w;
  12282. return result;
  12283. };
  12284. /**
  12285. * Computes magnitude squared for the provided quaternion.
  12286. *
  12287. * @param {Quaternion} quaternion The quaternion to conjugate.
  12288. * @returns {Number} The magnitude squared.
  12289. */
  12290. Quaternion.magnitudeSquared = function(quaternion) {
  12291. if (!defined(quaternion)) {
  12292. throw new DeveloperError('quaternion is required');
  12293. }
  12294. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  12295. };
  12296. /**
  12297. * Computes magnitude for the provided quaternion.
  12298. *
  12299. * @param {Quaternion} quaternion The quaternion to conjugate.
  12300. * @returns {Number} The magnitude.
  12301. */
  12302. Quaternion.magnitude = function(quaternion) {
  12303. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  12304. };
  12305. /**
  12306. * Computes the normalized form of the provided quaternion.
  12307. *
  12308. * @param {Quaternion} quaternion The quaternion to normalize.
  12309. * @param {Quaternion} result The object onto which to store the result.
  12310. * @returns {Quaternion} The modified result parameter.
  12311. */
  12312. Quaternion.normalize = function(quaternion, result) {
  12313. if (!defined(result)) {
  12314. throw new DeveloperError('result is required');
  12315. }
  12316. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  12317. var x = quaternion.x * inverseMagnitude;
  12318. var y = quaternion.y * inverseMagnitude;
  12319. var z = quaternion.z * inverseMagnitude;
  12320. var w = quaternion.w * inverseMagnitude;
  12321. result.x = x;
  12322. result.y = y;
  12323. result.z = z;
  12324. result.w = w;
  12325. return result;
  12326. };
  12327. /**
  12328. * Computes the inverse of the provided quaternion.
  12329. *
  12330. * @param {Quaternion} quaternion The quaternion to normalize.
  12331. * @param {Quaternion} result The object onto which to store the result.
  12332. * @returns {Quaternion} The modified result parameter.
  12333. */
  12334. Quaternion.inverse = function(quaternion, result) {
  12335. if (!defined(result)) {
  12336. throw new DeveloperError('result is required');
  12337. }
  12338. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  12339. result = Quaternion.conjugate(quaternion, result);
  12340. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  12341. };
  12342. /**
  12343. * Computes the componentwise sum of two quaternions.
  12344. *
  12345. * @param {Quaternion} left The first quaternion.
  12346. * @param {Quaternion} right The second quaternion.
  12347. * @param {Quaternion} result The object onto which to store the result.
  12348. * @returns {Quaternion} The modified result parameter.
  12349. */
  12350. Quaternion.add = function(left, right, result) {
  12351. if (!defined(left)) {
  12352. throw new DeveloperError('left is required');
  12353. }
  12354. if (!defined(right)) {
  12355. throw new DeveloperError('right is required');
  12356. }
  12357. if (!defined(result)) {
  12358. throw new DeveloperError('result is required');
  12359. }
  12360. result.x = left.x + right.x;
  12361. result.y = left.y + right.y;
  12362. result.z = left.z + right.z;
  12363. result.w = left.w + right.w;
  12364. return result;
  12365. };
  12366. /**
  12367. * Computes the componentwise difference of two quaternions.
  12368. *
  12369. * @param {Quaternion} left The first quaternion.
  12370. * @param {Quaternion} right The second quaternion.
  12371. * @param {Quaternion} result The object onto which to store the result.
  12372. * @returns {Quaternion} The modified result parameter.
  12373. */
  12374. Quaternion.subtract = function(left, right, result) {
  12375. if (!defined(left)) {
  12376. throw new DeveloperError('left is required');
  12377. }
  12378. if (!defined(right)) {
  12379. throw new DeveloperError('right is required');
  12380. }
  12381. if (!defined(result)) {
  12382. throw new DeveloperError('result is required');
  12383. }
  12384. result.x = left.x - right.x;
  12385. result.y = left.y - right.y;
  12386. result.z = left.z - right.z;
  12387. result.w = left.w - right.w;
  12388. return result;
  12389. };
  12390. /**
  12391. * Negates the provided quaternion.
  12392. *
  12393. * @param {Quaternion} quaternion The quaternion to be negated.
  12394. * @param {Quaternion} result The object onto which to store the result.
  12395. * @returns {Quaternion} The modified result parameter.
  12396. */
  12397. Quaternion.negate = function(quaternion, result) {
  12398. if (!defined(quaternion)) {
  12399. throw new DeveloperError('quaternion is required');
  12400. }
  12401. if (!defined(result)) {
  12402. throw new DeveloperError('result is required');
  12403. }
  12404. result.x = -quaternion.x;
  12405. result.y = -quaternion.y;
  12406. result.z = -quaternion.z;
  12407. result.w = -quaternion.w;
  12408. return result;
  12409. };
  12410. /**
  12411. * Computes the dot (scalar) product of two quaternions.
  12412. *
  12413. * @param {Quaternion} left The first quaternion.
  12414. * @param {Quaternion} right The second quaternion.
  12415. * @returns {Number} The dot product.
  12416. */
  12417. Quaternion.dot = function(left, right) {
  12418. if (!defined(left)) {
  12419. throw new DeveloperError('left is required');
  12420. }
  12421. if (!defined(right)) {
  12422. throw new DeveloperError('right is required');
  12423. }
  12424. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  12425. };
  12426. /**
  12427. * Computes the product of two quaternions.
  12428. *
  12429. * @param {Quaternion} left The first quaternion.
  12430. * @param {Quaternion} right The second quaternion.
  12431. * @param {Quaternion} result The object onto which to store the result.
  12432. * @returns {Quaternion} The modified result parameter.
  12433. */
  12434. Quaternion.multiply = function(left, right, result) {
  12435. if (!defined(left)) {
  12436. throw new DeveloperError('left is required');
  12437. }
  12438. if (!defined(right)) {
  12439. throw new DeveloperError('right is required');
  12440. }
  12441. if (!defined(result)) {
  12442. throw new DeveloperError('result is required');
  12443. }
  12444. var leftX = left.x;
  12445. var leftY = left.y;
  12446. var leftZ = left.z;
  12447. var leftW = left.w;
  12448. var rightX = right.x;
  12449. var rightY = right.y;
  12450. var rightZ = right.z;
  12451. var rightW = right.w;
  12452. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  12453. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  12454. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  12455. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  12456. result.x = x;
  12457. result.y = y;
  12458. result.z = z;
  12459. result.w = w;
  12460. return result;
  12461. };
  12462. /**
  12463. * Multiplies the provided quaternion componentwise by the provided scalar.
  12464. *
  12465. * @param {Quaternion} quaternion The quaternion to be scaled.
  12466. * @param {Number} scalar The scalar to multiply with.
  12467. * @param {Quaternion} result The object onto which to store the result.
  12468. * @returns {Quaternion} The modified result parameter.
  12469. */
  12470. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  12471. if (!defined(quaternion)) {
  12472. throw new DeveloperError('quaternion is required');
  12473. }
  12474. if (typeof scalar !== 'number') {
  12475. throw new DeveloperError('scalar is required and must be a number.');
  12476. }
  12477. if (!defined(result)) {
  12478. throw new DeveloperError('result is required');
  12479. }
  12480. result.x = quaternion.x * scalar;
  12481. result.y = quaternion.y * scalar;
  12482. result.z = quaternion.z * scalar;
  12483. result.w = quaternion.w * scalar;
  12484. return result;
  12485. };
  12486. /**
  12487. * Divides the provided quaternion componentwise by the provided scalar.
  12488. *
  12489. * @param {Quaternion} quaternion The quaternion to be divided.
  12490. * @param {Number} scalar The scalar to divide by.
  12491. * @param {Quaternion} result The object onto which to store the result.
  12492. * @returns {Quaternion} The modified result parameter.
  12493. */
  12494. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  12495. if (!defined(quaternion)) {
  12496. throw new DeveloperError('quaternion is required');
  12497. }
  12498. if (typeof scalar !== 'number') {
  12499. throw new DeveloperError('scalar is required and must be a number.');
  12500. }
  12501. if (!defined(result)) {
  12502. throw new DeveloperError('result is required');
  12503. }
  12504. result.x = quaternion.x / scalar;
  12505. result.y = quaternion.y / scalar;
  12506. result.z = quaternion.z / scalar;
  12507. result.w = quaternion.w / scalar;
  12508. return result;
  12509. };
  12510. /**
  12511. * Computes the axis of rotation of the provided quaternion.
  12512. *
  12513. * @param {Quaternion} quaternion The quaternion to use.
  12514. * @param {Cartesian3} result The object onto which to store the result.
  12515. * @returns {Cartesian3} The modified result parameter.
  12516. */
  12517. Quaternion.computeAxis = function(quaternion, result) {
  12518. if (!defined(quaternion)) {
  12519. throw new DeveloperError('quaternion is required');
  12520. }
  12521. if (!defined(result)) {
  12522. throw new DeveloperError('result is required');
  12523. }
  12524. var w = quaternion.w;
  12525. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  12526. result.x = result.y = result.z = 0;
  12527. return result;
  12528. }
  12529. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  12530. result.x = quaternion.x * scalar;
  12531. result.y = quaternion.y * scalar;
  12532. result.z = quaternion.z * scalar;
  12533. return result;
  12534. };
  12535. /**
  12536. * Computes the angle of rotation of the provided quaternion.
  12537. *
  12538. * @param {Quaternion} quaternion The quaternion to use.
  12539. * @returns {Number} The angle of rotation.
  12540. */
  12541. Quaternion.computeAngle = function(quaternion) {
  12542. if (!defined(quaternion)) {
  12543. throw new DeveloperError('quaternion is required');
  12544. }
  12545. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  12546. return 0.0;
  12547. }
  12548. return 2.0 * Math.acos(quaternion.w);
  12549. };
  12550. var lerpScratch = new Quaternion();
  12551. /**
  12552. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  12553. *
  12554. * @param {Quaternion} start The value corresponding to t at 0.0.
  12555. * @param {Quaternion} end The value corresponding to t at 1.0.
  12556. * @param {Number} t The point along t at which to interpolate.
  12557. * @param {Quaternion} result The object onto which to store the result.
  12558. * @returns {Quaternion} The modified result parameter.
  12559. */
  12560. Quaternion.lerp = function(start, end, t, result) {
  12561. if (!defined(start)) {
  12562. throw new DeveloperError('start is required.');
  12563. }
  12564. if (!defined(end)) {
  12565. throw new DeveloperError('end is required.');
  12566. }
  12567. if (typeof t !== 'number') {
  12568. throw new DeveloperError('t is required and must be a number.');
  12569. }
  12570. if (!defined(result)) {
  12571. throw new DeveloperError('result is required');
  12572. }
  12573. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  12574. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  12575. return Quaternion.add(lerpScratch, result, result);
  12576. };
  12577. var slerpEndNegated = new Quaternion();
  12578. var slerpScaledP = new Quaternion();
  12579. var slerpScaledR = new Quaternion();
  12580. /**
  12581. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  12582. *
  12583. * @param {Quaternion} start The value corresponding to t at 0.0.
  12584. * @param {Quaternion} end The value corresponding to t at 1.0.
  12585. * @param {Number} t The point along t at which to interpolate.
  12586. * @param {Quaternion} result The object onto which to store the result.
  12587. * @returns {Quaternion} The modified result parameter.
  12588. *
  12589. * @see Quaternion#fastSlerp
  12590. */
  12591. Quaternion.slerp = function(start, end, t, result) {
  12592. if (!defined(start)) {
  12593. throw new DeveloperError('start is required.');
  12594. }
  12595. if (!defined(end)) {
  12596. throw new DeveloperError('end is required.');
  12597. }
  12598. if (typeof t !== 'number') {
  12599. throw new DeveloperError('t is required and must be a number.');
  12600. }
  12601. if (!defined(result)) {
  12602. throw new DeveloperError('result is required');
  12603. }
  12604. var dot = Quaternion.dot(start, end);
  12605. // The angle between start must be acute. Since q and -q represent
  12606. // the same rotation, negate q to get the acute angle.
  12607. var r = end;
  12608. if (dot < 0.0) {
  12609. dot = -dot;
  12610. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  12611. }
  12612. // dot > 0, as the dot product approaches 1, the angle between the
  12613. // quaternions vanishes. use linear interpolation.
  12614. if (1.0 - dot < CesiumMath.EPSILON6) {
  12615. return Quaternion.lerp(start, r, t, result);
  12616. }
  12617. var theta = Math.acos(dot);
  12618. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  12619. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  12620. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  12621. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  12622. };
  12623. /**
  12624. * The logarithmic quaternion function.
  12625. *
  12626. * @param {Quaternion} quaternion The unit quaternion.
  12627. * @param {Cartesian3} result The object onto which to store the result.
  12628. * @returns {Cartesian3} The modified result parameter.
  12629. */
  12630. Quaternion.log = function(quaternion, result) {
  12631. if (!defined(quaternion)) {
  12632. throw new DeveloperError('quaternion is required.');
  12633. }
  12634. if (!defined(result)) {
  12635. throw new DeveloperError('result is required');
  12636. }
  12637. var theta = CesiumMath.acosClamped(quaternion.w);
  12638. var thetaOverSinTheta = 0.0;
  12639. if (theta !== 0.0) {
  12640. thetaOverSinTheta = theta / Math.sin(theta);
  12641. }
  12642. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  12643. };
  12644. /**
  12645. * The exponential quaternion function.
  12646. *
  12647. * @param {Cartesian3} cartesian The cartesian.
  12648. * @param {Quaternion} result The object onto which to store the result.
  12649. * @returns {Quaternion} The modified result parameter.
  12650. */
  12651. Quaternion.exp = function(cartesian, result) {
  12652. if (!defined(cartesian)) {
  12653. throw new DeveloperError('cartesian is required.');
  12654. }
  12655. if (!defined(result)) {
  12656. throw new DeveloperError('result is required');
  12657. }
  12658. var theta = Cartesian3.magnitude(cartesian);
  12659. var sinThetaOverTheta = 0.0;
  12660. if (theta !== 0.0) {
  12661. sinThetaOverTheta = Math.sin(theta) / theta;
  12662. }
  12663. result.x = cartesian.x * sinThetaOverTheta;
  12664. result.y = cartesian.y * sinThetaOverTheta;
  12665. result.z = cartesian.z * sinThetaOverTheta;
  12666. result.w = Math.cos(theta);
  12667. return result;
  12668. };
  12669. var squadScratchCartesian0 = new Cartesian3();
  12670. var squadScratchCartesian1 = new Cartesian3();
  12671. var squadScratchQuaternion0 = new Quaternion();
  12672. var squadScratchQuaternion1 = new Quaternion();
  12673. /**
  12674. * Computes an inner quadrangle point.
  12675. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  12676. *
  12677. * @param {Quaternion} q0 The first quaternion.
  12678. * @param {Quaternion} q1 The second quaternion.
  12679. * @param {Quaternion} q2 The third quaternion.
  12680. * @param {Quaternion} result The object onto which to store the result.
  12681. * @returns {Quaternion} The modified result parameter.
  12682. *
  12683. * @see Quaternion#squad
  12684. */
  12685. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  12686. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  12687. throw new DeveloperError('q0, q1, and q2 are required.');
  12688. }
  12689. if (!defined(result)) {
  12690. throw new DeveloperError('result is required');
  12691. }
  12692. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  12693. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  12694. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  12695. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  12696. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  12697. Cartesian3.add(cart0, cart1, cart0);
  12698. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  12699. Cartesian3.negate(cart0, cart0);
  12700. Quaternion.exp(cart0, squadScratchQuaternion0);
  12701. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  12702. };
  12703. /**
  12704. * Computes the spherical quadrangle interpolation between quaternions.
  12705. *
  12706. * @param {Quaternion} q0 The first quaternion.
  12707. * @param {Quaternion} q1 The second quaternion.
  12708. * @param {Quaternion} s0 The first inner quadrangle.
  12709. * @param {Quaternion} s1 The second inner quadrangle.
  12710. * @param {Number} t The time in [0,1] used to interpolate.
  12711. * @param {Quaternion} result The object onto which to store the result.
  12712. * @returns {Quaternion} The modified result parameter.
  12713. *
  12714. *
  12715. * @example
  12716. * // 1. compute the squad interpolation between two quaternions on a curve
  12717. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  12718. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  12719. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  12720. *
  12721. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  12722. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  12723. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  12724. *
  12725. * @see Quaternion#computeInnerQuadrangle
  12726. */
  12727. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  12728. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  12729. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  12730. }
  12731. if (typeof t !== 'number') {
  12732. throw new DeveloperError('t is required and must be a number.');
  12733. }
  12734. if (!defined(result)) {
  12735. throw new DeveloperError('result is required');
  12736. }
  12737. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  12738. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  12739. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  12740. };
  12741. var fastSlerpScratchQuaternion = new Quaternion();
  12742. var opmu = 1.90110745351730037;
  12743. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  12744. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  12745. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  12746. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  12747. for (var i = 0; i < 7; ++i) {
  12748. var s = i + 1.0;
  12749. var t = 2.0 * s + 1.0;
  12750. u[i] = 1.0 / (s * t);
  12751. v[i] = s / t;
  12752. }
  12753. u[7] = opmu / (8.0 * 17.0);
  12754. v[7] = opmu * 8.0 / 17.0;
  12755. /**
  12756. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  12757. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  12758. *
  12759. * @param {Quaternion} start The value corresponding to t at 0.0.
  12760. * @param {Quaternion} end The value corresponding to t at 1.0.
  12761. * @param {Number} t The point along t at which to interpolate.
  12762. * @param {Quaternion} result The object onto which to store the result.
  12763. * @returns {Quaternion} The modified result parameter.
  12764. *
  12765. * @see Quaternion#slerp
  12766. */
  12767. Quaternion.fastSlerp = function(start, end, t, result) {
  12768. if (!defined(start)) {
  12769. throw new DeveloperError('start is required.');
  12770. }
  12771. if (!defined(end)) {
  12772. throw new DeveloperError('end is required.');
  12773. }
  12774. if (typeof t !== 'number') {
  12775. throw new DeveloperError('t is required and must be a number.');
  12776. }
  12777. if (!defined(result)) {
  12778. throw new DeveloperError('result is required');
  12779. }
  12780. var x = Quaternion.dot(start, end);
  12781. var sign;
  12782. if (x >= 0) {
  12783. sign = 1.0;
  12784. } else {
  12785. sign = -1.0;
  12786. x = -x;
  12787. }
  12788. var xm1 = x - 1.0;
  12789. var d = 1.0 - t;
  12790. var sqrT = t * t;
  12791. var sqrD = d * d;
  12792. for (var i = 7; i >= 0; --i) {
  12793. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  12794. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  12795. }
  12796. var cT = sign * t * (
  12797. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  12798. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  12799. var cD = d * (
  12800. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  12801. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  12802. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  12803. Quaternion.multiplyByScalar(end, cT, result);
  12804. return Quaternion.add(temp, result, result);
  12805. };
  12806. /**
  12807. * Computes the spherical quadrangle interpolation between quaternions.
  12808. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  12809. *
  12810. * @param {Quaternion} q0 The first quaternion.
  12811. * @param {Quaternion} q1 The second quaternion.
  12812. * @param {Quaternion} s0 The first inner quadrangle.
  12813. * @param {Quaternion} s1 The second inner quadrangle.
  12814. * @param {Number} t The time in [0,1] used to interpolate.
  12815. * @param {Quaternion} result The object onto which to store the result.
  12816. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  12817. *
  12818. * @see Quaternion#squad
  12819. */
  12820. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  12821. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  12822. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  12823. }
  12824. if (typeof t !== 'number') {
  12825. throw new DeveloperError('t is required and must be a number.');
  12826. }
  12827. if (!defined(result)) {
  12828. throw new DeveloperError('result is required');
  12829. }
  12830. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  12831. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  12832. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  12833. };
  12834. /**
  12835. * Compares the provided quaternions componentwise and returns
  12836. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12837. *
  12838. * @param {Quaternion} [left] The first quaternion.
  12839. * @param {Quaternion} [right] The second quaternion.
  12840. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  12841. */
  12842. Quaternion.equals = function(left, right) {
  12843. return (left === right) ||
  12844. ((defined(left)) &&
  12845. (defined(right)) &&
  12846. (left.x === right.x) &&
  12847. (left.y === right.y) &&
  12848. (left.z === right.z) &&
  12849. (left.w === right.w));
  12850. };
  12851. /**
  12852. * Compares the provided quaternions componentwise and returns
  12853. * <code>true</code> if they are within the provided epsilon,
  12854. * <code>false</code> otherwise.
  12855. *
  12856. * @param {Quaternion} [left] The first quaternion.
  12857. * @param {Quaternion} [right] The second quaternion.
  12858. * @param {Number} epsilon The epsilon to use for equality testing.
  12859. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  12860. */
  12861. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  12862. if (typeof epsilon !== 'number') {
  12863. throw new DeveloperError('epsilon is required and must be a number.');
  12864. }
  12865. return (left === right) ||
  12866. ((defined(left)) &&
  12867. (defined(right)) &&
  12868. (Math.abs(left.x - right.x) <= epsilon) &&
  12869. (Math.abs(left.y - right.y) <= epsilon) &&
  12870. (Math.abs(left.z - right.z) <= epsilon) &&
  12871. (Math.abs(left.w - right.w) <= epsilon));
  12872. };
  12873. /**
  12874. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  12875. *
  12876. * @type {Quaternion}
  12877. * @constant
  12878. */
  12879. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  12880. /**
  12881. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  12882. *
  12883. * @type {Quaternion}
  12884. * @constant
  12885. */
  12886. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  12887. /**
  12888. * Duplicates this Quaternion instance.
  12889. *
  12890. * @param {Quaternion} [result] The object onto which to store the result.
  12891. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  12892. */
  12893. Quaternion.prototype.clone = function(result) {
  12894. return Quaternion.clone(this, result);
  12895. };
  12896. /**
  12897. * Compares this and the provided quaternion componentwise and returns
  12898. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12899. *
  12900. * @param {Quaternion} [right] The right hand side quaternion.
  12901. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  12902. */
  12903. Quaternion.prototype.equals = function(right) {
  12904. return Quaternion.equals(this, right);
  12905. };
  12906. /**
  12907. * Compares this and the provided quaternion componentwise and returns
  12908. * <code>true</code> if they are within the provided epsilon,
  12909. * <code>false</code> otherwise.
  12910. *
  12911. * @param {Quaternion} [right] The right hand side quaternion.
  12912. * @param {Number} epsilon The epsilon to use for equality testing.
  12913. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  12914. */
  12915. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  12916. return Quaternion.equalsEpsilon(this, right, epsilon);
  12917. };
  12918. /**
  12919. * Returns a string representing this quaternion in the format (x, y, z, w).
  12920. *
  12921. * @returns {String} A string representing this Quaternion.
  12922. */
  12923. Quaternion.prototype.toString = function() {
  12924. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  12925. };
  12926. return Quaternion;
  12927. });
  12928. /*global define*/
  12929. define('Core/EllipseGeometryLibrary',[
  12930. './Cartesian3',
  12931. './Math',
  12932. './Matrix3',
  12933. './Quaternion'
  12934. ], function(
  12935. Cartesian3,
  12936. CesiumMath,
  12937. Matrix3,
  12938. Quaternion) {
  12939. 'use strict';
  12940. var EllipseGeometryLibrary = {};
  12941. var rotAxis = new Cartesian3();
  12942. var tempVec = new Cartesian3();
  12943. var unitQuat = new Quaternion();
  12944. var rotMtx = new Matrix3();
  12945. function pointOnEllipsoid(theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, result) {
  12946. var azimuth = theta + rotation;
  12947. Cartesian3.multiplyByScalar(eastVec, Math.cos(azimuth), rotAxis);
  12948. Cartesian3.multiplyByScalar(northVec, Math.sin(azimuth), tempVec);
  12949. Cartesian3.add(rotAxis, tempVec, rotAxis);
  12950. var cosThetaSquared = Math.cos(theta);
  12951. cosThetaSquared = cosThetaSquared * cosThetaSquared;
  12952. var sinThetaSquared = Math.sin(theta);
  12953. sinThetaSquared = sinThetaSquared * sinThetaSquared;
  12954. var radius = ab / Math.sqrt(bSqr * cosThetaSquared + aSqr * sinThetaSquared);
  12955. var angle = radius / mag;
  12956. // Create the quaternion to rotate the position vector to the boundary of the ellipse.
  12957. Quaternion.fromAxisAngle(rotAxis, angle, unitQuat);
  12958. Matrix3.fromQuaternion(unitQuat, rotMtx);
  12959. Matrix3.multiplyByVector(rotMtx, unitPos, result);
  12960. Cartesian3.normalize(result, result);
  12961. Cartesian3.multiplyByScalar(result, mag, result);
  12962. return result;
  12963. }
  12964. var scratchCartesian1 = new Cartesian3();
  12965. var scratchCartesian2 = new Cartesian3();
  12966. var scratchCartesian3 = new Cartesian3();
  12967. var scratchNormal = new Cartesian3();
  12968. /**
  12969. * Returns the positions raised to the given heights
  12970. * @private
  12971. */
  12972. EllipseGeometryLibrary.raisePositionsToHeight = function(positions, options, extrude) {
  12973. var ellipsoid = options.ellipsoid;
  12974. var height = options.height;
  12975. var extrudedHeight = options.extrudedHeight;
  12976. var size = (extrude) ? positions.length / 3 * 2 : positions.length / 3;
  12977. var finalPositions = new Float64Array(size * 3);
  12978. var length = positions.length;
  12979. var bottomOffset = (extrude) ? length : 0;
  12980. for (var i = 0; i < length; i += 3) {
  12981. var i1 = i + 1;
  12982. var i2 = i + 2;
  12983. var position = Cartesian3.fromArray(positions, i, scratchCartesian1);
  12984. ellipsoid.scaleToGeodeticSurface(position, position);
  12985. var extrudedPosition = Cartesian3.clone(position, scratchCartesian2);
  12986. var normal = ellipsoid.geodeticSurfaceNormal(position, scratchNormal);
  12987. var scaledNormal = Cartesian3.multiplyByScalar(normal, height, scratchCartesian3);
  12988. Cartesian3.add(position, scaledNormal, position);
  12989. if (extrude) {
  12990. Cartesian3.multiplyByScalar(normal, extrudedHeight, scaledNormal);
  12991. Cartesian3.add(extrudedPosition, scaledNormal, extrudedPosition);
  12992. finalPositions[i + bottomOffset] = extrudedPosition.x;
  12993. finalPositions[i1 + bottomOffset] = extrudedPosition.y;
  12994. finalPositions[i2 + bottomOffset] = extrudedPosition.z;
  12995. }
  12996. finalPositions[i] = position.x;
  12997. finalPositions[i1] = position.y;
  12998. finalPositions[i2] = position.z;
  12999. }
  13000. return finalPositions;
  13001. };
  13002. var unitPosScratch = new Cartesian3();
  13003. var eastVecScratch = new Cartesian3();
  13004. var northVecScratch = new Cartesian3();
  13005. /**
  13006. * Returns an array of positions that make up the ellipse.
  13007. * @private
  13008. */
  13009. EllipseGeometryLibrary.computeEllipsePositions = function(options, addFillPositions, addEdgePositions) {
  13010. var semiMinorAxis = options.semiMinorAxis;
  13011. var semiMajorAxis = options.semiMajorAxis;
  13012. var rotation = options.rotation;
  13013. var center = options.center;
  13014. // Computing the arc-length of the ellipse is too expensive to be practical. Estimating it using the
  13015. // arc length of the sphere is too inaccurate and creates sharp edges when either the semi-major or
  13016. // semi-minor axis is much bigger than the other. Instead, scale the angle delta to make
  13017. // the distance along the ellipse boundary more closely match the granularity.
  13018. var granularity = options.granularity * 8.0;
  13019. var aSqr = semiMinorAxis * semiMinorAxis;
  13020. var bSqr = semiMajorAxis * semiMajorAxis;
  13021. var ab = semiMajorAxis * semiMinorAxis;
  13022. var mag = Cartesian3.magnitude(center);
  13023. var unitPos = Cartesian3.normalize(center, unitPosScratch);
  13024. var eastVec = Cartesian3.cross(Cartesian3.UNIT_Z, center, eastVecScratch);
  13025. eastVec = Cartesian3.normalize(eastVec, eastVec);
  13026. var northVec = Cartesian3.cross(unitPos, eastVec, northVecScratch);
  13027. // The number of points in the first quadrant
  13028. var numPts = 1 + Math.ceil(CesiumMath.PI_OVER_TWO / granularity);
  13029. var deltaTheta = CesiumMath.PI_OVER_TWO / (numPts - 1);
  13030. var theta = CesiumMath.PI_OVER_TWO - numPts * deltaTheta;
  13031. if (theta < 0.0) {
  13032. numPts -= Math.ceil(Math.abs(theta) / deltaTheta);
  13033. }
  13034. // If the number of points were three, the ellipse
  13035. // would be tessellated like below:
  13036. //
  13037. // *---*
  13038. // / | \ | \
  13039. // *---*---*---*
  13040. // / | \ | \ | \ | \
  13041. // / .*---*---*---*. \
  13042. // * ` | \ | \ | \ | `*
  13043. // \`.*---*---*---*.`/
  13044. // \ | \ | \ | \ | /
  13045. // *---*---*---*
  13046. // \ | \ | /
  13047. // *---*
  13048. // The first and last column have one position and fan to connect to the adjacent column.
  13049. // Each other vertical column contains an even number of positions.
  13050. var size = 2 * (numPts * (numPts + 2));
  13051. var positions = (addFillPositions) ? new Array(size * 3) : undefined;
  13052. var positionIndex = 0;
  13053. var position = scratchCartesian1;
  13054. var reflectedPosition = scratchCartesian2;
  13055. var outerPositionsLength = (numPts * 4) * 3;
  13056. var outerRightIndex = outerPositionsLength - 1;
  13057. var outerLeftIndex = 0;
  13058. var outerPositions = (addEdgePositions) ? new Array(outerPositionsLength) : undefined;
  13059. var i;
  13060. var j;
  13061. var numInterior;
  13062. var t;
  13063. var interiorPosition;
  13064. // Compute points in the 'eastern' half of the ellipse
  13065. theta = CesiumMath.PI_OVER_TWO;
  13066. position = pointOnEllipsoid(theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, position);
  13067. if (addFillPositions) {
  13068. positions[positionIndex++] = position.x;
  13069. positions[positionIndex++] = position.y;
  13070. positions[positionIndex++] = position.z;
  13071. }
  13072. if (addEdgePositions) {
  13073. outerPositions[outerRightIndex--] = position.z;
  13074. outerPositions[outerRightIndex--] = position.y;
  13075. outerPositions[outerRightIndex--] = position.x;
  13076. }
  13077. theta = CesiumMath.PI_OVER_TWO - deltaTheta;
  13078. for (i = 1; i < numPts + 1; ++i) {
  13079. position = pointOnEllipsoid(theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, position);
  13080. reflectedPosition = pointOnEllipsoid(Math.PI - theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, reflectedPosition);
  13081. if (addFillPositions) {
  13082. positions[positionIndex++] = position.x;
  13083. positions[positionIndex++] = position.y;
  13084. positions[positionIndex++] = position.z;
  13085. numInterior = 2 * i + 2;
  13086. for (j = 1; j < numInterior - 1; ++j) {
  13087. t = j / (numInterior - 1);
  13088. interiorPosition = Cartesian3.lerp(position, reflectedPosition, t, scratchCartesian3);
  13089. positions[positionIndex++] = interiorPosition.x;
  13090. positions[positionIndex++] = interiorPosition.y;
  13091. positions[positionIndex++] = interiorPosition.z;
  13092. }
  13093. positions[positionIndex++] = reflectedPosition.x;
  13094. positions[positionIndex++] = reflectedPosition.y;
  13095. positions[positionIndex++] = reflectedPosition.z;
  13096. }
  13097. if (addEdgePositions) {
  13098. outerPositions[outerRightIndex--] = position.z;
  13099. outerPositions[outerRightIndex--] = position.y;
  13100. outerPositions[outerRightIndex--] = position.x;
  13101. outerPositions[outerLeftIndex++] = reflectedPosition.x;
  13102. outerPositions[outerLeftIndex++] = reflectedPosition.y;
  13103. outerPositions[outerLeftIndex++] = reflectedPosition.z;
  13104. }
  13105. theta = CesiumMath.PI_OVER_TWO - (i + 1) * deltaTheta;
  13106. }
  13107. // Compute points in the 'western' half of the ellipse
  13108. for (i = numPts; i > 1; --i) {
  13109. theta = CesiumMath.PI_OVER_TWO - (i - 1) * deltaTheta;
  13110. position = pointOnEllipsoid(-theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, position);
  13111. reflectedPosition = pointOnEllipsoid(theta + Math.PI, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, reflectedPosition);
  13112. if (addFillPositions) {
  13113. positions[positionIndex++] = position.x;
  13114. positions[positionIndex++] = position.y;
  13115. positions[positionIndex++] = position.z;
  13116. numInterior = 2 * (i - 1) + 2;
  13117. for (j = 1; j < numInterior - 1; ++j) {
  13118. t = j / (numInterior - 1);
  13119. interiorPosition = Cartesian3.lerp(position, reflectedPosition, t, scratchCartesian3);
  13120. positions[positionIndex++] = interiorPosition.x;
  13121. positions[positionIndex++] = interiorPosition.y;
  13122. positions[positionIndex++] = interiorPosition.z;
  13123. }
  13124. positions[positionIndex++] = reflectedPosition.x;
  13125. positions[positionIndex++] = reflectedPosition.y;
  13126. positions[positionIndex++] = reflectedPosition.z;
  13127. }
  13128. if (addEdgePositions) {
  13129. outerPositions[outerRightIndex--] = position.z;
  13130. outerPositions[outerRightIndex--] = position.y;
  13131. outerPositions[outerRightIndex--] = position.x;
  13132. outerPositions[outerLeftIndex++] = reflectedPosition.x;
  13133. outerPositions[outerLeftIndex++] = reflectedPosition.y;
  13134. outerPositions[outerLeftIndex++] = reflectedPosition.z;
  13135. }
  13136. }
  13137. theta = CesiumMath.PI_OVER_TWO;
  13138. position = pointOnEllipsoid(-theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, position);
  13139. var r = {};
  13140. if (addFillPositions) {
  13141. positions[positionIndex++] = position.x;
  13142. positions[positionIndex++] = position.y;
  13143. positions[positionIndex++] = position.z;
  13144. r.positions = positions;
  13145. r.numPts = numPts;
  13146. }
  13147. if (addEdgePositions) {
  13148. outerPositions[outerRightIndex--] = position.z;
  13149. outerPositions[outerRightIndex--] = position.y;
  13150. outerPositions[outerRightIndex--] = position.x;
  13151. r.outerPositions = outerPositions;
  13152. }
  13153. return r;
  13154. };
  13155. return EllipseGeometryLibrary;
  13156. });
  13157. /*global define*/
  13158. define('Core/GeometryType',[
  13159. './freezeObject'
  13160. ], function(
  13161. freezeObject) {
  13162. 'use strict';
  13163. /**
  13164. * @private
  13165. */
  13166. var GeometryType = {
  13167. NONE : 0,
  13168. TRIANGLES : 1,
  13169. LINES : 2,
  13170. POLYLINES : 3
  13171. };
  13172. return freezeObject(GeometryType);
  13173. });
  13174. /*global define*/
  13175. define('Core/PrimitiveType',[
  13176. './freezeObject',
  13177. './WebGLConstants'
  13178. ], function(
  13179. freezeObject,
  13180. WebGLConstants) {
  13181. 'use strict';
  13182. /**
  13183. * The type of a geometric primitive, i.e., points, lines, and triangles.
  13184. *
  13185. * @exports PrimitiveType
  13186. */
  13187. var PrimitiveType = {
  13188. /**
  13189. * Points primitive where each vertex (or index) is a separate point.
  13190. *
  13191. * @type {Number}
  13192. * @constant
  13193. */
  13194. POINTS : WebGLConstants.POINTS,
  13195. /**
  13196. * Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
  13197. *
  13198. * @type {Number}
  13199. * @constant
  13200. */
  13201. LINES : WebGLConstants.LINES,
  13202. /**
  13203. * Line loop primitive where each vertex (or index) after the first connects a line to
  13204. * the previous vertex, and the last vertex implicitly connects to the first.
  13205. *
  13206. * @type {Number}
  13207. * @constant
  13208. */
  13209. LINE_LOOP : WebGLConstants.LINE_LOOP,
  13210. /**
  13211. * Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
  13212. *
  13213. * @type {Number}
  13214. * @constant
  13215. */
  13216. LINE_STRIP : WebGLConstants.LINE_STRIP,
  13217. /**
  13218. * Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
  13219. *
  13220. * @type {Number}
  13221. * @constant
  13222. */
  13223. TRIANGLES : WebGLConstants.TRIANGLES,
  13224. /**
  13225. * Triangle strip primitive where each vertex (or index) after the first two connect to
  13226. * the previous two vertices forming a triangle. For example, this can be used to model a wall.
  13227. *
  13228. * @type {Number}
  13229. * @constant
  13230. */
  13231. TRIANGLE_STRIP : WebGLConstants.TRIANGLE_STRIP,
  13232. /**
  13233. * Triangle fan primitive where each vertex (or index) after the first two connect to
  13234. * the previous vertex and the first vertex forming a triangle. For example, this can be used
  13235. * to model a cone or circle.
  13236. *
  13237. * @type {Number}
  13238. * @constant
  13239. */
  13240. TRIANGLE_FAN : WebGLConstants.TRIANGLE_FAN,
  13241. /**
  13242. * @private
  13243. */
  13244. validate : function(primitiveType) {
  13245. return primitiveType === PrimitiveType.POINTS ||
  13246. primitiveType === PrimitiveType.LINES ||
  13247. primitiveType === PrimitiveType.LINE_LOOP ||
  13248. primitiveType === PrimitiveType.LINE_STRIP ||
  13249. primitiveType === PrimitiveType.TRIANGLES ||
  13250. primitiveType === PrimitiveType.TRIANGLE_STRIP ||
  13251. primitiveType === PrimitiveType.TRIANGLE_FAN;
  13252. }
  13253. };
  13254. return freezeObject(PrimitiveType);
  13255. });
  13256. /*global define*/
  13257. define('Core/Geometry',[
  13258. './defaultValue',
  13259. './defined',
  13260. './DeveloperError',
  13261. './GeometryType',
  13262. './PrimitiveType'
  13263. ], function(
  13264. defaultValue,
  13265. defined,
  13266. DeveloperError,
  13267. GeometryType,
  13268. PrimitiveType) {
  13269. 'use strict';
  13270. /**
  13271. * A geometry representation with attributes forming vertices and optional index data
  13272. * defining primitives. Geometries and an {@link Appearance}, which describes the shading,
  13273. * can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
  13274. * be created from many heterogeneous - in many cases - geometries for performance.
  13275. * <p>
  13276. * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
  13277. * </p>
  13278. *
  13279. * @alias Geometry
  13280. * @constructor
  13281. *
  13282. * @param {Object} options Object with the following properties:
  13283. * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
  13284. * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
  13285. * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
  13286. * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
  13287. *
  13288. * @see PolygonGeometry
  13289. * @see RectangleGeometry
  13290. * @see EllipseGeometry
  13291. * @see CircleGeometry
  13292. * @see WallGeometry
  13293. * @see SimplePolylineGeometry
  13294. * @see BoxGeometry
  13295. * @see EllipsoidGeometry
  13296. *
  13297. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
  13298. *
  13299. * @example
  13300. * // Create geometry with a position attribute and indexed lines.
  13301. * var positions = new Float64Array([
  13302. * 0.0, 0.0, 0.0,
  13303. * 7500000.0, 0.0, 0.0,
  13304. * 0.0, 7500000.0, 0.0
  13305. * ]);
  13306. *
  13307. * var geometry = new Cesium.Geometry({
  13308. * attributes : {
  13309. * position : new Cesium.GeometryAttribute({
  13310. * componentDatatype : Cesium.ComponentDatatype.DOUBLE,
  13311. * componentsPerAttribute : 3,
  13312. * values : positions
  13313. * })
  13314. * },
  13315. * indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
  13316. * primitiveType : Cesium.PrimitiveType.LINES,
  13317. * boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
  13318. * });
  13319. */
  13320. function Geometry(options) {
  13321. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  13322. if (!defined(options.attributes)) {
  13323. throw new DeveloperError('options.attributes is required.');
  13324. }
  13325. /**
  13326. * Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
  13327. * {@link GeometryAttribute} containing the attribute's data.
  13328. * <p>
  13329. * Attributes are always stored non-interleaved in a Geometry.
  13330. * </p>
  13331. * <p>
  13332. * There are reserved attribute names with well-known semantics. The following attributes
  13333. * are created by a Geometry (depending on the provided {@link VertexFormat}.
  13334. * <ul>
  13335. * <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
  13336. * <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
  13337. * <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
  13338. * <li><code>binormal</code> - Binormal (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#binormal}.</li>
  13339. * <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#tangent}.</li>
  13340. * </ul>
  13341. * </p>
  13342. * <p>
  13343. * The following attribute names are generally not created by a Geometry, but are added
  13344. * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
  13345. * the geometry for rendering.
  13346. * <ul>
  13347. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  13348. * <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  13349. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  13350. * <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  13351. * <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
  13352. * <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
  13353. * </ul>
  13354. * </p>
  13355. *
  13356. * @type GeometryAttributes
  13357. *
  13358. * @default undefined
  13359. *
  13360. *
  13361. * @example
  13362. * geometry.attributes.position = new Cesium.GeometryAttribute({
  13363. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  13364. * componentsPerAttribute : 3,
  13365. * values : new Float32Array(0)
  13366. * });
  13367. *
  13368. * @see GeometryAttribute
  13369. * @see VertexFormat
  13370. */
  13371. this.attributes = options.attributes;
  13372. /**
  13373. * Optional index data that - along with {@link Geometry#primitiveType} -
  13374. * determines the primitives in the geometry.
  13375. *
  13376. * @type Array
  13377. *
  13378. * @default undefined
  13379. */
  13380. this.indices = options.indices;
  13381. /**
  13382. * The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
  13383. * but can varying based on the specific geometry.
  13384. *
  13385. * @type PrimitiveType
  13386. *
  13387. * @default undefined
  13388. */
  13389. this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
  13390. /**
  13391. * An optional bounding sphere that fully encloses the geometry. This is
  13392. * commonly used for culling.
  13393. *
  13394. * @type BoundingSphere
  13395. *
  13396. * @default undefined
  13397. */
  13398. this.boundingSphere = options.boundingSphere;
  13399. /**
  13400. * @private
  13401. */
  13402. this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
  13403. /**
  13404. * @private
  13405. */
  13406. this.boundingSphereCV = options.boundingSphereCV;
  13407. }
  13408. /**
  13409. * Computes the number of vertices in a geometry. The runtime is linear with
  13410. * respect to the number of attributes in a vertex, not the number of vertices.
  13411. *
  13412. * @param {Geometry} geometry The geometry.
  13413. * @returns {Number} The number of vertices in the geometry.
  13414. *
  13415. * @example
  13416. * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
  13417. */
  13418. Geometry.computeNumberOfVertices = function(geometry) {
  13419. if (!defined(geometry)) {
  13420. throw new DeveloperError('geometry is required.');
  13421. }
  13422. var numberOfVertices = -1;
  13423. for ( var property in geometry.attributes) {
  13424. if (geometry.attributes.hasOwnProperty(property) &&
  13425. defined(geometry.attributes[property]) &&
  13426. defined(geometry.attributes[property].values)) {
  13427. var attribute = geometry.attributes[property];
  13428. var num = attribute.values.length / attribute.componentsPerAttribute;
  13429. if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
  13430. throw new DeveloperError('All attribute lists must have the same number of attributes.');
  13431. }
  13432. numberOfVertices = num;
  13433. }
  13434. }
  13435. return numberOfVertices;
  13436. };
  13437. return Geometry;
  13438. });
  13439. /*global define*/
  13440. define('Core/GeometryAttribute',[
  13441. './defaultValue',
  13442. './defined',
  13443. './DeveloperError'
  13444. ], function(
  13445. defaultValue,
  13446. defined,
  13447. DeveloperError) {
  13448. 'use strict';
  13449. /**
  13450. * Values and type information for geometry attributes. A {@link Geometry}
  13451. * generally contains one or more attributes. All attributes together form
  13452. * the geometry's vertices.
  13453. *
  13454. * @alias GeometryAttribute
  13455. * @constructor
  13456. *
  13457. * @param {Object} [options] Object with the following properties:
  13458. * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
  13459. * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
  13460. * @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  13461. * @param {TypedArray} [options.values] The values for the attributes stored in a typed array.
  13462. *
  13463. * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
  13464. *
  13465. *
  13466. * @example
  13467. * var geometry = new Cesium.Geometry({
  13468. * attributes : {
  13469. * position : new Cesium.GeometryAttribute({
  13470. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  13471. * componentsPerAttribute : 3,
  13472. * values : new Float32Array([
  13473. * 0.0, 0.0, 0.0,
  13474. * 7500000.0, 0.0, 0.0,
  13475. * 0.0, 7500000.0, 0.0
  13476. * ])
  13477. * })
  13478. * },
  13479. * primitiveType : Cesium.PrimitiveType.LINE_LOOP
  13480. * });
  13481. *
  13482. * @see Geometry
  13483. */
  13484. function GeometryAttribute(options) {
  13485. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  13486. if (!defined(options.componentDatatype)) {
  13487. throw new DeveloperError('options.componentDatatype is required.');
  13488. }
  13489. if (!defined(options.componentsPerAttribute)) {
  13490. throw new DeveloperError('options.componentsPerAttribute is required.');
  13491. }
  13492. if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
  13493. throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
  13494. }
  13495. if (!defined(options.values)) {
  13496. throw new DeveloperError('options.values is required.');
  13497. }
  13498. /**
  13499. * The datatype of each component in the attribute, e.g., individual elements in
  13500. * {@link GeometryAttribute#values}.
  13501. *
  13502. * @type ComponentDatatype
  13503. *
  13504. * @default undefined
  13505. */
  13506. this.componentDatatype = options.componentDatatype;
  13507. /**
  13508. * A number between 1 and 4 that defines the number of components in an attributes.
  13509. * For example, a position attribute with x, y, and z components would have 3 as
  13510. * shown in the code example.
  13511. *
  13512. * @type Number
  13513. *
  13514. * @default undefined
  13515. *
  13516. * @example
  13517. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  13518. * attribute.componentsPerAttribute = 3;
  13519. * attribute.values = new Float32Array([
  13520. * 0.0, 0.0, 0.0,
  13521. * 7500000.0, 0.0, 0.0,
  13522. * 0.0, 7500000.0, 0.0
  13523. * ]);
  13524. */
  13525. this.componentsPerAttribute = options.componentsPerAttribute;
  13526. /**
  13527. * When <code>true</code> and <code>componentDatatype</code> is an integer format,
  13528. * indicate that the components should be mapped to the range [0, 1] (unsigned)
  13529. * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  13530. * <p>
  13531. * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
  13532. * </p>
  13533. *
  13534. * @type Boolean
  13535. *
  13536. * @default false
  13537. *
  13538. * @example
  13539. * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
  13540. * attribute.componentsPerAttribute = 4;
  13541. * attribute.normalize = true;
  13542. * attribute.values = new Uint8Array([
  13543. * Cesium.Color.floatToByte(color.red),
  13544. * Cesium.Color.floatToByte(color.green),
  13545. * Cesium.Color.floatToByte(color.blue),
  13546. * Cesium.Color.floatToByte(color.alpha)
  13547. * ]);
  13548. */
  13549. this.normalize = defaultValue(options.normalize, false);
  13550. /**
  13551. * The values for the attributes stored in a typed array. In the code example,
  13552. * every three elements in <code>values</code> defines one attributes since
  13553. * <code>componentsPerAttribute</code> is 3.
  13554. *
  13555. * @type TypedArray
  13556. *
  13557. * @default undefined
  13558. *
  13559. * @example
  13560. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  13561. * attribute.componentsPerAttribute = 3;
  13562. * attribute.values = new Float32Array([
  13563. * 0.0, 0.0, 0.0,
  13564. * 7500000.0, 0.0, 0.0,
  13565. * 0.0, 7500000.0, 0.0
  13566. * ]);
  13567. */
  13568. this.values = options.values;
  13569. }
  13570. return GeometryAttribute;
  13571. });
  13572. /*global define*/
  13573. define('Core/GeometryAttributes',[
  13574. './defaultValue'
  13575. ], function(
  13576. defaultValue) {
  13577. 'use strict';
  13578. /**
  13579. * Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
  13580. * {@link GeometryAttribute} containing the attribute's data.
  13581. * <p>
  13582. * Attributes are always stored non-interleaved in a Geometry.
  13583. * </p>
  13584. *
  13585. * @alias GeometryAttributes
  13586. * @constructor
  13587. */
  13588. function GeometryAttributes(options) {
  13589. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  13590. /**
  13591. * The 3D position attribute.
  13592. * <p>
  13593. * 64-bit floating-point (for precision). 3 components per attribute.
  13594. * </p>
  13595. *
  13596. * @type GeometryAttribute
  13597. *
  13598. * @default undefined
  13599. */
  13600. this.position = options.position;
  13601. /**
  13602. * The normal attribute (normalized), which is commonly used for lighting.
  13603. * <p>
  13604. * 32-bit floating-point. 3 components per attribute.
  13605. * </p>
  13606. *
  13607. * @type GeometryAttribute
  13608. *
  13609. * @default undefined
  13610. */
  13611. this.normal = options.normal;
  13612. /**
  13613. * The 2D texture coordinate attribute.
  13614. * <p>
  13615. * 32-bit floating-point. 2 components per attribute
  13616. * </p>
  13617. *
  13618. * @type GeometryAttribute
  13619. *
  13620. * @default undefined
  13621. */
  13622. this.st = options.st;
  13623. /**
  13624. * The binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  13625. * <p>
  13626. * 32-bit floating-point. 3 components per attribute.
  13627. * </p>
  13628. *
  13629. * @type GeometryAttribute
  13630. *
  13631. * @default undefined
  13632. */
  13633. this.binormal = options.binormal;
  13634. /**
  13635. * The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  13636. * <p>
  13637. * 32-bit floating-point. 3 components per attribute.
  13638. * </p>
  13639. *
  13640. * @type GeometryAttribute
  13641. *
  13642. * @default undefined
  13643. */
  13644. this.tangent = options.tangent;
  13645. /**
  13646. * The color attribute.
  13647. * <p>
  13648. * 8-bit unsigned integer. 4 components per attribute.
  13649. * </p>
  13650. *
  13651. * @type GeometryAttribute
  13652. *
  13653. * @default undefined
  13654. */
  13655. this.color = options.color;
  13656. }
  13657. return GeometryAttributes;
  13658. });
  13659. /*global define*/
  13660. define('Core/GeometryInstance',[
  13661. './defaultValue',
  13662. './defined',
  13663. './DeveloperError',
  13664. './Matrix4'
  13665. ], function(
  13666. defaultValue,
  13667. defined,
  13668. DeveloperError,
  13669. Matrix4) {
  13670. 'use strict';
  13671. /**
  13672. * Geometry instancing allows one {@link Geometry} object to be positions in several
  13673. * different locations and colored uniquely. For example, one {@link BoxGeometry} can
  13674. * be instanced several times, each with a different <code>modelMatrix</code> to change
  13675. * its position, rotation, and scale.
  13676. *
  13677. * @alias GeometryInstance
  13678. * @constructor
  13679. *
  13680. * @param {Object} options Object with the following properties:
  13681. * @param {Geometry} options.geometry The geometry to instance.
  13682. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The model matrix that transforms to transform the geometry from model to world coordinates.
  13683. * @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick} or get/set per-instance attributes with {@link Primitive#getGeometryInstanceAttributes}.
  13684. * @param {Object} [options.attributes] Per-instance attributes like a show or color attribute shown in the example below.
  13685. *
  13686. *
  13687. * @example
  13688. * // Create geometry for a box, and two instances that refer to it.
  13689. * // One instance positions the box on the bottom and colored aqua.
  13690. * // The other instance positions the box on the top and color white.
  13691. * var geometry = Cesium.BoxGeometry.fromDimensions({
  13692. * vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL,
  13693. * dimensions : new Cesium.Cartesian3(1000000.0, 1000000.0, 500000.0)
  13694. * });
  13695. * var instanceBottom = new Cesium.GeometryInstance({
  13696. * geometry : geometry,
  13697. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  13698. * Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
  13699. * attributes : {
  13700. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  13701. * },
  13702. * id : 'bottom'
  13703. * });
  13704. * var instanceTop = new Cesium.GeometryInstance({
  13705. * geometry : geometry,
  13706. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  13707. * Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 3000000.0), new Cesium.Matrix4()),
  13708. * attributes : {
  13709. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  13710. * },
  13711. * id : 'top'
  13712. * });
  13713. *
  13714. * @see Geometry
  13715. */
  13716. function GeometryInstance(options) {
  13717. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  13718. if (!defined(options.geometry)) {
  13719. throw new DeveloperError('options.geometry is required.');
  13720. }
  13721. /**
  13722. * The geometry being instanced.
  13723. *
  13724. * @type Geometry
  13725. *
  13726. * @default undefined
  13727. */
  13728. this.geometry = options.geometry;
  13729. /**
  13730. * The 4x4 transformation matrix that transforms the geometry from model to world coordinates.
  13731. * When this is the identity matrix, the geometry is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
  13732. * Local reference frames can be used by providing a different transformation matrix, like that returned
  13733. * by {@link Transforms.eastNorthUpToFixedFrame}.
  13734. *
  13735. * @type Matrix4
  13736. *
  13737. * @default Matrix4.IDENTITY
  13738. */
  13739. this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
  13740. /**
  13741. * User-defined object returned when the instance is picked or used to get/set per-instance attributes.
  13742. *
  13743. * @type Object
  13744. *
  13745. * @default undefined
  13746. *
  13747. * @see Scene#pick
  13748. * @see Primitive#getGeometryInstanceAttributes
  13749. */
  13750. this.id = options.id;
  13751. /**
  13752. * Used for picking primitives that wrap geometry instances.
  13753. *
  13754. * @private
  13755. */
  13756. this.pickPrimitive = options.pickPrimitive;
  13757. /**
  13758. * Per-instance attributes like {@link ColorGeometryInstanceAttribute} or {@link ShowGeometryInstanceAttribute}.
  13759. * {@link Geometry} attributes varying per vertex; these attributes are constant for the entire instance.
  13760. *
  13761. * @type Object
  13762. *
  13763. * @default undefined
  13764. */
  13765. this.attributes = defaultValue(options.attributes, {});
  13766. /**
  13767. * @private
  13768. */
  13769. this.westHemisphereGeometry = undefined;
  13770. /**
  13771. * @private
  13772. */
  13773. this.eastHemisphereGeometry = undefined;
  13774. }
  13775. return GeometryInstance;
  13776. });
  13777. /*global define*/
  13778. define('Core/AttributeCompression',[
  13779. './Cartesian2',
  13780. './Cartesian3',
  13781. './defined',
  13782. './DeveloperError',
  13783. './Math'
  13784. ], function(
  13785. Cartesian2,
  13786. Cartesian3,
  13787. defined,
  13788. DeveloperError,
  13789. CesiumMath) {
  13790. 'use strict';
  13791. /**
  13792. * Attribute compression and decompression functions.
  13793. *
  13794. * @exports AttributeCompression
  13795. *
  13796. * @private
  13797. */
  13798. var AttributeCompression = {};
  13799. /**
  13800. * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
  13801. *
  13802. * Oct encoding is a compact representation of unit length vectors.
  13803. * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
  13804. * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
  13805. *
  13806. * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
  13807. * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
  13808. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  13809. * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
  13810. *
  13811. * @exception {DeveloperError} vector must be normalized.
  13812. *
  13813. * @see AttributeCompression.octDecodeInRange
  13814. */
  13815. AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
  13816. if (!defined(vector)) {
  13817. throw new DeveloperError('vector is required.');
  13818. }
  13819. if (!defined(result)) {
  13820. throw new DeveloperError('result is required.');
  13821. }
  13822. var magSquared = Cartesian3.magnitudeSquared(vector);
  13823. if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
  13824. throw new DeveloperError('vector must be normalized.');
  13825. }
  13826. result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  13827. result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  13828. if (vector.z < 0) {
  13829. var x = result.x;
  13830. var y = result.y;
  13831. result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
  13832. result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
  13833. }
  13834. result.x = CesiumMath.toSNorm(result.x, rangeMax);
  13835. result.y = CesiumMath.toSNorm(result.y, rangeMax);
  13836. return result;
  13837. };
  13838. /**
  13839. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
  13840. *
  13841. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  13842. * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
  13843. * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
  13844. *
  13845. * @exception {DeveloperError} vector must be normalized.
  13846. *
  13847. * @see AttributeCompression.octEncodeInRange
  13848. * @see AttributeCompression.octDecode
  13849. */
  13850. AttributeCompression.octEncode = function(vector, result) {
  13851. return AttributeCompression.octEncodeInRange(vector, 255, result);
  13852. };
  13853. /**
  13854. * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
  13855. *
  13856. * @param {Number} x The x component of the oct-encoded unit length vector.
  13857. * @param {Number} y The y component of the oct-encoded unit length vector.
  13858. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  13859. * @param {Cartesian3} result The decoded and normalized vector
  13860. * @returns {Cartesian3} The decoded and normalized vector.
  13861. *
  13862. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and rangeMax.
  13863. *
  13864. * @see AttributeCompression.octEncodeInRange
  13865. */
  13866. AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
  13867. if (!defined(result)) {
  13868. throw new DeveloperError('result is required.');
  13869. }
  13870. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  13871. throw new DeveloperError('x and y must be a signed normalized integer between 0 and ' + rangeMax);
  13872. }
  13873. result.x = CesiumMath.fromSNorm(x, rangeMax);
  13874. result.y = CesiumMath.fromSNorm(y, rangeMax);
  13875. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  13876. if (result.z < 0.0)
  13877. {
  13878. var oldVX = result.x;
  13879. result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
  13880. result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
  13881. }
  13882. return Cartesian3.normalize(result, result);
  13883. };
  13884. /**
  13885. * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
  13886. *
  13887. * @param {Number} x The x component of the oct-encoded unit length vector.
  13888. * @param {Number} y The y component of the oct-encoded unit length vector.
  13889. * @param {Cartesian3} result The decoded and normalized vector.
  13890. * @returns {Cartesian3} The decoded and normalized vector.
  13891. *
  13892. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
  13893. *
  13894. * @see AttributeCompression.octDecodeInRange
  13895. */
  13896. AttributeCompression.octDecode = function(x, y, result) {
  13897. return AttributeCompression.octDecodeInRange(x, y, 255, result);
  13898. };
  13899. /**
  13900. * Packs an oct encoded vector into a single floating-point number.
  13901. *
  13902. * @param {Cartesian2} encoded The oct encoded vector.
  13903. * @returns {Number} The oct encoded vector packed into a single float.
  13904. *
  13905. */
  13906. AttributeCompression.octPackFloat = function(encoded) {
  13907. if (!defined(encoded)) {
  13908. throw new DeveloperError('encoded is required.');
  13909. }
  13910. return 256.0 * encoded.x + encoded.y;
  13911. };
  13912. var scratchEncodeCart2 = new Cartesian2();
  13913. /**
  13914. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
  13915. * stores those values in a single float-point number.
  13916. *
  13917. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  13918. * @returns {Number} The 2 byte oct-encoded unit length vector.
  13919. *
  13920. * @exception {DeveloperError} vector must be normalized.
  13921. */
  13922. AttributeCompression.octEncodeFloat = function(vector) {
  13923. AttributeCompression.octEncode(vector, scratchEncodeCart2);
  13924. return AttributeCompression.octPackFloat(scratchEncodeCart2);
  13925. };
  13926. /**
  13927. * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
  13928. *
  13929. * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
  13930. * @param {Cartesian3} result The decoded and normalized vector
  13931. * @returns {Cartesian3} The decoded and normalized vector.
  13932. *
  13933. */
  13934. AttributeCompression.octDecodeFloat = function(value, result) {
  13935. if (!defined(value)) {
  13936. throw new DeveloperError('value is required.');
  13937. }
  13938. var temp = value / 256.0;
  13939. var x = Math.floor(temp);
  13940. var y = (temp - x) * 256.0;
  13941. return AttributeCompression.octDecode(x, y, result);
  13942. };
  13943. /**
  13944. * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
  13945. * packs those into two floating-point numbers.
  13946. *
  13947. * @param {Cartesian3} v1 A normalized vector to be compressed.
  13948. * @param {Cartesian3} v2 A normalized vector to be compressed.
  13949. * @param {Cartesian3} v3 A normalized vector to be compressed.
  13950. * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
  13951. * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
  13952. *
  13953. */
  13954. AttributeCompression.octPack = function(v1, v2, v3, result) {
  13955. if (!defined(v1)) {
  13956. throw new DeveloperError('v1 is required.');
  13957. }
  13958. if (!defined(v2)) {
  13959. throw new DeveloperError('v2 is required.');
  13960. }
  13961. if (!defined(v3)) {
  13962. throw new DeveloperError('v3 is required.');
  13963. }
  13964. if (!defined(result)) {
  13965. throw new DeveloperError('result is required.');
  13966. }
  13967. var encoded1 = AttributeCompression.octEncodeFloat(v1);
  13968. var encoded2 = AttributeCompression.octEncodeFloat(v2);
  13969. var encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
  13970. result.x = 65536.0 * encoded3.x + encoded1;
  13971. result.y = 65536.0 * encoded3.y + encoded2;
  13972. return result;
  13973. };
  13974. /**
  13975. * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
  13976. *
  13977. * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
  13978. * @param {Cartesian3} v1 One decoded and normalized vector.
  13979. * @param {Cartesian3} v2 One decoded and normalized vector.
  13980. * @param {Cartesian3} v3 One decoded and normalized vector.
  13981. */
  13982. AttributeCompression.octUnpack = function(packed, v1, v2, v3) {
  13983. if (!defined(packed)) {
  13984. throw new DeveloperError('packed is required.');
  13985. }
  13986. if (!defined(v1)) {
  13987. throw new DeveloperError('v1 is required.');
  13988. }
  13989. if (!defined(v2)) {
  13990. throw new DeveloperError('v2 is required.');
  13991. }
  13992. if (!defined(v3)) {
  13993. throw new DeveloperError('v3 is required.');
  13994. }
  13995. var temp = packed.x / 65536.0;
  13996. var x = Math.floor(temp);
  13997. var encodedFloat1 = (temp - x) * 65536.0;
  13998. temp = packed.y / 65536.0;
  13999. var y = Math.floor(temp);
  14000. var encodedFloat2 = (temp - y) * 65536.0;
  14001. AttributeCompression.octDecodeFloat(encodedFloat1, v1);
  14002. AttributeCompression.octDecodeFloat(encodedFloat2, v2);
  14003. AttributeCompression.octDecode(x, y, v3);
  14004. };
  14005. /**
  14006. * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
  14007. *
  14008. * @param {Cartesian2} textureCoordinates The texture coordinates to compress. Both coordinates must be in the range 0.0-1.0.
  14009. * @returns {Number} The packed texture coordinates.
  14010. *
  14011. */
  14012. AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
  14013. if (!defined(textureCoordinates)) {
  14014. throw new DeveloperError('textureCoordinates is required.');
  14015. }
  14016. // Move x and y to the range 0-4095;
  14017. var x = (textureCoordinates.x * 4095.0) | 0;
  14018. var y = (textureCoordinates.y * 4095.0) | 0;
  14019. return 4096.0 * x + y;
  14020. };
  14021. /**
  14022. * Decompresses texture coordinates that were packed into a single float.
  14023. *
  14024. * @param {Number} compressed The compressed texture coordinates.
  14025. * @param {Cartesian2} result The decompressed texture coordinates.
  14026. * @returns {Cartesian2} The modified result parameter.
  14027. *
  14028. */
  14029. AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
  14030. if (!defined(compressed)) {
  14031. throw new DeveloperError('compressed is required.');
  14032. }
  14033. if (!defined(result)) {
  14034. throw new DeveloperError('result is required.');
  14035. }
  14036. var temp = compressed / 4096.0;
  14037. var xZeroTo4095 = Math.floor(temp);
  14038. result.x = xZeroTo4095 / 4095.0;
  14039. result.y = (compressed - xZeroTo4095 * 4096) / 4095;
  14040. return result;
  14041. };
  14042. return AttributeCompression;
  14043. });
  14044. /*global define*/
  14045. define('Core/barycentricCoordinates',[
  14046. './Cartesian2',
  14047. './Cartesian3',
  14048. './defined',
  14049. './DeveloperError'
  14050. ], function(
  14051. Cartesian2,
  14052. Cartesian3,
  14053. defined,
  14054. DeveloperError) {
  14055. 'use strict';
  14056. var scratchCartesian1 = new Cartesian3();
  14057. var scratchCartesian2 = new Cartesian3();
  14058. var scratchCartesian3 = new Cartesian3();
  14059. /**
  14060. * Computes the barycentric coordinates for a point with respect to a triangle.
  14061. *
  14062. * @exports barycentricCoordinates
  14063. *
  14064. * @param {Cartesian2|Cartesian3} point The point to test.
  14065. * @param {Cartesian2|Cartesian3} p0 The first point of the triangle, corresponding to the barycentric x-axis.
  14066. * @param {Cartesian2|Cartesian3} p1 The second point of the triangle, corresponding to the barycentric y-axis.
  14067. * @param {Cartesian2|Cartesian3} p2 The third point of the triangle, corresponding to the barycentric z-axis.
  14068. * @param {Cartesian3} [result] The object onto which to store the result.
  14069. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  14070. *
  14071. * @example
  14072. * // Returns Cartesian3.UNIT_X
  14073. * var p = new Cesium.Cartesian3(-1.0, 0.0, 0.0);
  14074. * var b = Cesium.barycentricCoordinates(p,
  14075. * new Cesium.Cartesian3(-1.0, 0.0, 0.0),
  14076. * new Cesium.Cartesian3( 1.0, 0.0, 0.0),
  14077. * new Cesium.Cartesian3( 0.0, 1.0, 1.0));
  14078. */
  14079. function barycentricCoordinates(point, p0, p1, p2, result) {
  14080. if (!defined(point) || !defined(p0) || !defined(p1) || !defined(p2)) {
  14081. throw new DeveloperError('point, p0, p1, and p2 are required.');
  14082. }
  14083. if (!defined(result)) {
  14084. result = new Cartesian3();
  14085. }
  14086. // Implementation based on http://www.blackpawn.com/texts/pointinpoly/default.html.
  14087. var v0, v1, v2;
  14088. var dot00, dot01, dot02, dot11, dot12;
  14089. if(!defined(p0.z)) {
  14090. v0 = Cartesian2.subtract(p1, p0, scratchCartesian1);
  14091. v1 = Cartesian2.subtract(p2, p0, scratchCartesian2);
  14092. v2 = Cartesian2.subtract(point, p0, scratchCartesian3);
  14093. dot00 = Cartesian2.dot(v0, v0);
  14094. dot01 = Cartesian2.dot(v0, v1);
  14095. dot02 = Cartesian2.dot(v0, v2);
  14096. dot11 = Cartesian2.dot(v1, v1);
  14097. dot12 = Cartesian2.dot(v1, v2);
  14098. } else {
  14099. v0 = Cartesian3.subtract(p1, p0, scratchCartesian1);
  14100. v1 = Cartesian3.subtract(p2, p0, scratchCartesian2);
  14101. v2 = Cartesian3.subtract(point, p0, scratchCartesian3);
  14102. dot00 = Cartesian3.dot(v0, v0);
  14103. dot01 = Cartesian3.dot(v0, v1);
  14104. dot02 = Cartesian3.dot(v0, v2);
  14105. dot11 = Cartesian3.dot(v1, v1);
  14106. dot12 = Cartesian3.dot(v1, v2);
  14107. }
  14108. var q = 1.0 / (dot00 * dot11 - dot01 * dot01);
  14109. result.y = (dot11 * dot02 - dot01 * dot12) * q;
  14110. result.z = (dot00 * dot12 - dot01 * dot02) * q;
  14111. result.x = 1.0 - result.y - result.z;
  14112. return result;
  14113. }
  14114. return barycentricCoordinates;
  14115. });
  14116. /*global define*/
  14117. define('Core/EncodedCartesian3',[
  14118. './Cartesian3',
  14119. './defined',
  14120. './DeveloperError'
  14121. ], function(
  14122. Cartesian3,
  14123. defined,
  14124. DeveloperError) {
  14125. 'use strict';
  14126. /**
  14127. * A fixed-point encoding of a {@link Cartesian3} with 64-bit floating-point components, as two {@link Cartesian3}
  14128. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  14129. * <p>
  14130. * This is used to encode positions in vertex buffers for rendering without jittering artifacts
  14131. * as described in {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  14132. * </p>
  14133. *
  14134. * @alias EncodedCartesian3
  14135. * @constructor
  14136. *
  14137. * @private
  14138. */
  14139. function EncodedCartesian3() {
  14140. /**
  14141. * The high bits for each component. Bits 0 to 22 store the whole value. Bits 23 to 31 are not used.
  14142. *
  14143. * @type {Cartesian3}
  14144. * @default {@link Cartesian3.ZERO}
  14145. */
  14146. this.high = Cartesian3.clone(Cartesian3.ZERO);
  14147. /**
  14148. * The low bits for each component. Bits 7 to 22 store the whole value, and bits 0 to 6 store the fraction. Bits 23 to 31 are not used.
  14149. *
  14150. * @type {Cartesian3}
  14151. * @default {@link Cartesian3.ZERO}
  14152. */
  14153. this.low = Cartesian3.clone(Cartesian3.ZERO);
  14154. }
  14155. /**
  14156. * Encodes a 64-bit floating-point value as two floating-point values that, when converted to
  14157. * 32-bit floating-point and added, approximate the original input. The returned object
  14158. * has <code>high</code> and <code>low</code> properties for the high and low bits, respectively.
  14159. * <p>
  14160. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  14161. * </p>
  14162. *
  14163. * @param {Number} value The floating-point value to encode.
  14164. * @param {Object} [result] The object onto which to store the result.
  14165. * @returns {Object} The modified result parameter or a new instance if one was not provided.
  14166. *
  14167. * @example
  14168. * var value = 1234567.1234567;
  14169. * var splitValue = Cesium.EncodedCartesian3.encode(value);
  14170. */
  14171. EncodedCartesian3.encode = function(value, result) {
  14172. if (!defined(value)) {
  14173. throw new DeveloperError('value is required');
  14174. }
  14175. if (!defined(result)) {
  14176. result = {
  14177. high : 0.0,
  14178. low : 0.0
  14179. };
  14180. }
  14181. var doubleHigh;
  14182. if (value >= 0.0) {
  14183. doubleHigh = Math.floor(value / 65536.0) * 65536.0;
  14184. result.high = doubleHigh;
  14185. result.low = value - doubleHigh;
  14186. } else {
  14187. doubleHigh = Math.floor(-value / 65536.0) * 65536.0;
  14188. result.high = -doubleHigh;
  14189. result.low = value + doubleHigh;
  14190. }
  14191. return result;
  14192. };
  14193. var scratchEncode = {
  14194. high : 0.0,
  14195. low : 0.0
  14196. };
  14197. /**
  14198. * Encodes a {@link Cartesian3} with 64-bit floating-point components as two {@link Cartesian3}
  14199. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  14200. * <p>
  14201. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  14202. * </p>
  14203. *
  14204. * @param {Cartesian3} cartesian The cartesian to encode.
  14205. * @param {EncodedCartesian3} [result] The object onto which to store the result.
  14206. * @returns {EncodedCartesian3} The modified result parameter or a new EncodedCartesian3 instance if one was not provided.
  14207. *
  14208. * @example
  14209. * var cart = new Cesium.Cartesian3(-10000000.0, 0.0, 10000000.0);
  14210. * var encoded = Cesium.EncodedCartesian3.fromCartesian(cart);
  14211. */
  14212. EncodedCartesian3.fromCartesian = function(cartesian, result) {
  14213. if (!defined(cartesian)) {
  14214. throw new DeveloperError('cartesian is required');
  14215. }
  14216. if (!defined(result)) {
  14217. result = new EncodedCartesian3();
  14218. }
  14219. var high = result.high;
  14220. var low = result.low;
  14221. EncodedCartesian3.encode(cartesian.x, scratchEncode);
  14222. high.x = scratchEncode.high;
  14223. low.x = scratchEncode.low;
  14224. EncodedCartesian3.encode(cartesian.y, scratchEncode);
  14225. high.y = scratchEncode.high;
  14226. low.y = scratchEncode.low;
  14227. EncodedCartesian3.encode(cartesian.z, scratchEncode);
  14228. high.z = scratchEncode.high;
  14229. low.z = scratchEncode.low;
  14230. return result;
  14231. };
  14232. var encodedP = new EncodedCartesian3();
  14233. /**
  14234. * Encodes the provided <code>cartesian</code>, and writes it to an array with <code>high</code>
  14235. * components followed by <code>low</code> components, i.e. <code>[high.x, high.y, high.z, low.x, low.y, low.z]</code>.
  14236. * <p>
  14237. * This is used to create interleaved high-precision position vertex attributes.
  14238. * </p>
  14239. *
  14240. * @param {Cartesian3} cartesian The cartesian to encode.
  14241. * @param {Number[]} cartesianArray The array to write to.
  14242. * @param {Number} index The index into the array to start writing. Six elements will be written.
  14243. *
  14244. * @exception {DeveloperError} index must be a number greater than or equal to 0.
  14245. *
  14246. * @example
  14247. * var positions = [
  14248. * new Cesium.Cartesian3(),
  14249. * // ...
  14250. * ];
  14251. * var encodedPositions = new Float32Array(2 * 3 * positions.length);
  14252. * var j = 0;
  14253. * for (var i = 0; i < positions.length; ++i) {
  14254. * Cesium.EncodedCartesian3.writeElement(positions[i], encodedPositions, j);
  14255. * j += 6;
  14256. * }
  14257. */
  14258. EncodedCartesian3.writeElements = function(cartesian, cartesianArray, index) {
  14259. if (!defined(cartesian)) {
  14260. throw new DeveloperError('cartesian is required');
  14261. }
  14262. if (!defined(cartesianArray)) {
  14263. throw new DeveloperError('cartesianArray is required');
  14264. }
  14265. if (typeof index !== 'number' || index < 0) {
  14266. throw new DeveloperError('index must be a number greater than or equal to 0.');
  14267. }
  14268. EncodedCartesian3.fromCartesian(cartesian, encodedP);
  14269. var high = encodedP.high;
  14270. var low = encodedP.low;
  14271. cartesianArray[index] = high.x;
  14272. cartesianArray[index + 1] = high.y;
  14273. cartesianArray[index + 2] = high.z;
  14274. cartesianArray[index + 3] = low.x;
  14275. cartesianArray[index + 4] = low.y;
  14276. cartesianArray[index + 5] = low.z;
  14277. };
  14278. return EncodedCartesian3;
  14279. });
  14280. /*global define*/
  14281. define('Core/IndexDatatype',[
  14282. './defined',
  14283. './DeveloperError',
  14284. './freezeObject',
  14285. './Math',
  14286. './WebGLConstants'
  14287. ], function(
  14288. defined,
  14289. DeveloperError,
  14290. freezeObject,
  14291. CesiumMath,
  14292. WebGLConstants) {
  14293. 'use strict';
  14294. /**
  14295. * Constants for WebGL index datatypes. These corresponds to the
  14296. * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
  14297. *
  14298. * @exports IndexDatatype
  14299. */
  14300. var IndexDatatype = {
  14301. /**
  14302. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  14303. * of an element in <code>Uint8Array</code>.
  14304. *
  14305. * @type {Number}
  14306. * @constant
  14307. */
  14308. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  14309. /**
  14310. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  14311. * of an element in <code>Uint16Array</code>.
  14312. *
  14313. * @type {Number}
  14314. * @constant
  14315. */
  14316. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  14317. /**
  14318. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  14319. * of an element in <code>Uint32Array</code>.
  14320. *
  14321. * @type {Number}
  14322. * @constant
  14323. */
  14324. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
  14325. };
  14326. /**
  14327. * Returns the size, in bytes, of the corresponding datatype.
  14328. *
  14329. * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
  14330. * @returns {Number} The size in bytes.
  14331. *
  14332. * @example
  14333. * // Returns 2
  14334. * var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
  14335. */
  14336. IndexDatatype.getSizeInBytes = function(indexDatatype) {
  14337. switch(indexDatatype) {
  14338. case IndexDatatype.UNSIGNED_BYTE:
  14339. return Uint8Array.BYTES_PER_ELEMENT;
  14340. case IndexDatatype.UNSIGNED_SHORT:
  14341. return Uint16Array.BYTES_PER_ELEMENT;
  14342. case IndexDatatype.UNSIGNED_INT:
  14343. return Uint32Array.BYTES_PER_ELEMENT;
  14344. }
  14345. throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
  14346. };
  14347. /**
  14348. * Validates that the provided index datatype is a valid {@link IndexDatatype}.
  14349. *
  14350. * @param {IndexDatatype} indexDatatype The index datatype to validate.
  14351. * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
  14352. *
  14353. * @example
  14354. * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
  14355. * throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
  14356. * }
  14357. */
  14358. IndexDatatype.validate = function(indexDatatype) {
  14359. return defined(indexDatatype) &&
  14360. (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
  14361. indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
  14362. indexDatatype === IndexDatatype.UNSIGNED_INT);
  14363. };
  14364. /**
  14365. * Creates a typed array that will store indices, using either <code><Uint16Array</code>
  14366. * or <code>Uint32Array</code> depending on the number of vertices.
  14367. *
  14368. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  14369. * @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
  14370. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
  14371. *
  14372. * @example
  14373. * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
  14374. */
  14375. IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
  14376. if (!defined(numberOfVertices)) {
  14377. throw new DeveloperError('numberOfVertices is required.');
  14378. }
  14379. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  14380. return new Uint32Array(indicesLengthOrArray);
  14381. }
  14382. return new Uint16Array(indicesLengthOrArray);
  14383. };
  14384. /**
  14385. * Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
  14386. * or <code>Uint32Array</code> depending on the number of vertices.
  14387. *
  14388. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  14389. * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
  14390. * @param {Number} byteOffset Passed through to the typed array constructor.
  14391. * @param {Number} length Passed through to the typed array constructor.
  14392. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
  14393. *
  14394. */
  14395. IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
  14396. if (!defined(numberOfVertices)) {
  14397. throw new DeveloperError('numberOfVertices is required.');
  14398. }
  14399. if (!defined(sourceArray)) {
  14400. throw new DeveloperError('sourceArray is required.');
  14401. }
  14402. if (!defined(byteOffset)) {
  14403. throw new DeveloperError('byteOffset is required.');
  14404. }
  14405. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  14406. return new Uint32Array(sourceArray, byteOffset, length);
  14407. }
  14408. return new Uint16Array(sourceArray, byteOffset, length);
  14409. };
  14410. return freezeObject(IndexDatatype);
  14411. });
  14412. /*global define*/
  14413. define('Core/QuadraticRealPolynomial',[
  14414. './DeveloperError',
  14415. './Math'
  14416. ], function(
  14417. DeveloperError,
  14418. CesiumMath) {
  14419. 'use strict';
  14420. /**
  14421. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  14422. *
  14423. * @exports QuadraticRealPolynomial
  14424. */
  14425. var QuadraticRealPolynomial = {};
  14426. /**
  14427. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  14428. *
  14429. * @param {Number} a The coefficient of the 2nd order monomial.
  14430. * @param {Number} b The coefficient of the 1st order monomial.
  14431. * @param {Number} c The coefficient of the 0th order monomial.
  14432. * @returns {Number} The value of the discriminant.
  14433. */
  14434. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  14435. if (typeof a !== 'number') {
  14436. throw new DeveloperError('a is a required number.');
  14437. }
  14438. if (typeof b !== 'number') {
  14439. throw new DeveloperError('b is a required number.');
  14440. }
  14441. if (typeof c !== 'number') {
  14442. throw new DeveloperError('c is a required number.');
  14443. }
  14444. var discriminant = b * b - 4.0 * a * c;
  14445. return discriminant;
  14446. };
  14447. function addWithCancellationCheck(left, right, tolerance) {
  14448. var difference = left + right;
  14449. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  14450. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  14451. return 0.0;
  14452. }
  14453. return difference;
  14454. }
  14455. /**
  14456. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  14457. *
  14458. * @param {Number} a The coefficient of the 2nd order monomial.
  14459. * @param {Number} b The coefficient of the 1st order monomial.
  14460. * @param {Number} c The coefficient of the 0th order monomial.
  14461. * @returns {Number[]} The real valued roots.
  14462. */
  14463. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  14464. if (typeof a !== 'number') {
  14465. throw new DeveloperError('a is a required number.');
  14466. }
  14467. if (typeof b !== 'number') {
  14468. throw new DeveloperError('b is a required number.');
  14469. }
  14470. if (typeof c !== 'number') {
  14471. throw new DeveloperError('c is a required number.');
  14472. }
  14473. var ratio;
  14474. if (a === 0.0) {
  14475. if (b === 0.0) {
  14476. // Constant function: c = 0.
  14477. return [];
  14478. }
  14479. // Linear function: b * x + c = 0.
  14480. return [-c / b];
  14481. } else if (b === 0.0) {
  14482. if (c === 0.0) {
  14483. // 2nd order monomial: a * x^2 = 0.
  14484. return [0.0, 0.0];
  14485. }
  14486. var cMagnitude = Math.abs(c);
  14487. var aMagnitude = Math.abs(a);
  14488. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  14489. // 2nd order monomial: a * x^2 = 0.
  14490. return [0.0, 0.0];
  14491. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  14492. // Constant function: c = 0.
  14493. return [];
  14494. }
  14495. // a * x^2 + c = 0
  14496. ratio = -c / a;
  14497. if (ratio < 0.0) {
  14498. // Both roots are complex.
  14499. return [];
  14500. }
  14501. // Both roots are real.
  14502. var root = Math.sqrt(ratio);
  14503. return [-root, root];
  14504. } else if (c === 0.0) {
  14505. // a * x^2 + b * x = 0
  14506. ratio = -b / a;
  14507. if (ratio < 0.0) {
  14508. return [ratio, 0.0];
  14509. }
  14510. return [0.0, ratio];
  14511. }
  14512. // a * x^2 + b * x + c = 0
  14513. var b2 = b * b;
  14514. var four_ac = 4.0 * a * c;
  14515. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  14516. if (radicand < 0.0) {
  14517. // Both roots are complex.
  14518. return [];
  14519. }
  14520. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  14521. if (b > 0.0) {
  14522. return [q / a, c / q];
  14523. }
  14524. return [c / q, q / a];
  14525. };
  14526. return QuadraticRealPolynomial;
  14527. });
  14528. /*global define*/
  14529. define('Core/CubicRealPolynomial',[
  14530. './DeveloperError',
  14531. './QuadraticRealPolynomial'
  14532. ], function(
  14533. DeveloperError,
  14534. QuadraticRealPolynomial) {
  14535. 'use strict';
  14536. /**
  14537. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  14538. *
  14539. * @exports CubicRealPolynomial
  14540. */
  14541. var CubicRealPolynomial = {};
  14542. /**
  14543. * Provides the discriminant of the cubic equation from the supplied coefficients.
  14544. *
  14545. * @param {Number} a The coefficient of the 3rd order monomial.
  14546. * @param {Number} b The coefficient of the 2nd order monomial.
  14547. * @param {Number} c The coefficient of the 1st order monomial.
  14548. * @param {Number} d The coefficient of the 0th order monomial.
  14549. * @returns {Number} The value of the discriminant.
  14550. */
  14551. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  14552. if (typeof a !== 'number') {
  14553. throw new DeveloperError('a is a required number.');
  14554. }
  14555. if (typeof b !== 'number') {
  14556. throw new DeveloperError('b is a required number.');
  14557. }
  14558. if (typeof c !== 'number') {
  14559. throw new DeveloperError('c is a required number.');
  14560. }
  14561. if (typeof d !== 'number') {
  14562. throw new DeveloperError('d is a required number.');
  14563. }
  14564. var a2 = a * a;
  14565. var b2 = b * b;
  14566. var c2 = c * c;
  14567. var d2 = d * d;
  14568. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  14569. return discriminant;
  14570. };
  14571. function computeRealRoots(a, b, c, d) {
  14572. var A = a;
  14573. var B = b / 3.0;
  14574. var C = c / 3.0;
  14575. var D = d;
  14576. var AC = A * C;
  14577. var BD = B * D;
  14578. var B2 = B * B;
  14579. var C2 = C * C;
  14580. var delta1 = A * C - B2;
  14581. var delta2 = A * D - B * C;
  14582. var delta3 = B * D - C2;
  14583. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  14584. var temp;
  14585. var temp1;
  14586. if (discriminant < 0.0) {
  14587. var ABar;
  14588. var CBar;
  14589. var DBar;
  14590. if (B2 * BD >= AC * C2) {
  14591. ABar = A;
  14592. CBar = delta1;
  14593. DBar = -2.0 * B * delta1 + A * delta2;
  14594. } else {
  14595. ABar = D;
  14596. CBar = delta3;
  14597. DBar = -D * delta2 + 2.0 * C * delta3;
  14598. }
  14599. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  14600. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  14601. temp1 = -DBar + temp0;
  14602. var x = temp1 / 2.0;
  14603. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  14604. var q = (temp1 === temp0) ? -p : -CBar / p;
  14605. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  14606. if (B2 * BD >= AC * C2) {
  14607. return [(temp - B) / A];
  14608. }
  14609. return [-D / (temp + C)];
  14610. }
  14611. var CBarA = delta1;
  14612. var DBarA = -2.0 * B * delta1 + A * delta2;
  14613. var CBarD = delta3;
  14614. var DBarD = -D * delta2 + 2.0 * C * delta3;
  14615. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  14616. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  14617. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  14618. temp = 2.0 * Math.sqrt(-CBarA);
  14619. var cosine = Math.cos(theta);
  14620. temp1 = temp * cosine;
  14621. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  14622. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  14623. var denominatorLarge = A;
  14624. var root1 = numeratorLarge / denominatorLarge;
  14625. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  14626. temp = 2.0 * Math.sqrt(-CBarD);
  14627. cosine = Math.cos(theta);
  14628. temp1 = temp * cosine;
  14629. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  14630. var numeratorSmall = -D;
  14631. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  14632. var root3 = numeratorSmall / denominatorSmall;
  14633. var E = denominatorLarge * denominatorSmall;
  14634. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  14635. var G = numeratorLarge * numeratorSmall;
  14636. var root2 = (C * F - B * G) / (-B * F + C * E);
  14637. if (root1 <= root2) {
  14638. if (root1 <= root3) {
  14639. if (root2 <= root3) {
  14640. return [root1, root2, root3];
  14641. }
  14642. return [root1, root3, root2];
  14643. }
  14644. return [root3, root1, root2];
  14645. }
  14646. if (root1 <= root3) {
  14647. return [root2, root1, root3];
  14648. }
  14649. if (root2 <= root3) {
  14650. return [root2, root3, root1];
  14651. }
  14652. return [root3, root2, root1];
  14653. }
  14654. /**
  14655. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  14656. *
  14657. * @param {Number} a The coefficient of the 3rd order monomial.
  14658. * @param {Number} b The coefficient of the 2nd order monomial.
  14659. * @param {Number} c The coefficient of the 1st order monomial.
  14660. * @param {Number} d The coefficient of the 0th order monomial.
  14661. * @returns {Number[]} The real valued roots.
  14662. */
  14663. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  14664. if (typeof a !== 'number') {
  14665. throw new DeveloperError('a is a required number.');
  14666. }
  14667. if (typeof b !== 'number') {
  14668. throw new DeveloperError('b is a required number.');
  14669. }
  14670. if (typeof c !== 'number') {
  14671. throw new DeveloperError('c is a required number.');
  14672. }
  14673. if (typeof d !== 'number') {
  14674. throw new DeveloperError('d is a required number.');
  14675. }
  14676. var roots;
  14677. var ratio;
  14678. if (a === 0.0) {
  14679. // Quadratic function: b * x^2 + c * x + d = 0.
  14680. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  14681. } else if (b === 0.0) {
  14682. if (c === 0.0) {
  14683. if (d === 0.0) {
  14684. // 3rd order monomial: a * x^3 = 0.
  14685. return [0.0, 0.0, 0.0];
  14686. }
  14687. // a * x^3 + d = 0
  14688. ratio = -d / a;
  14689. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  14690. return [root, root, root];
  14691. } else if (d === 0.0) {
  14692. // x * (a * x^2 + c) = 0.
  14693. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  14694. // Return the roots in ascending order.
  14695. if (roots.Length === 0) {
  14696. return [0.0];
  14697. }
  14698. return [roots[0], 0.0, roots[1]];
  14699. }
  14700. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  14701. return computeRealRoots(a, 0, c, d);
  14702. } else if (c === 0.0) {
  14703. if (d === 0.0) {
  14704. // x^2 * (a * x + b) = 0.
  14705. ratio = -b / a;
  14706. if (ratio < 0.0) {
  14707. return [ratio, 0.0, 0.0];
  14708. }
  14709. return [0.0, 0.0, ratio];
  14710. }
  14711. // a * x^3 + b * x^2 + d = 0.
  14712. return computeRealRoots(a, b, 0, d);
  14713. } else if (d === 0.0) {
  14714. // x * (a * x^2 + b * x + c) = 0
  14715. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  14716. // Return the roots in ascending order.
  14717. if (roots.length === 0) {
  14718. return [0.0];
  14719. } else if (roots[1] <= 0.0) {
  14720. return [roots[0], roots[1], 0.0];
  14721. } else if (roots[0] >= 0.0) {
  14722. return [0.0, roots[0], roots[1]];
  14723. }
  14724. return [roots[0], 0.0, roots[1]];
  14725. }
  14726. return computeRealRoots(a, b, c, d);
  14727. };
  14728. return CubicRealPolynomial;
  14729. });
  14730. /*global define*/
  14731. define('Core/QuarticRealPolynomial',[
  14732. './CubicRealPolynomial',
  14733. './DeveloperError',
  14734. './Math',
  14735. './QuadraticRealPolynomial'
  14736. ], function(
  14737. CubicRealPolynomial,
  14738. DeveloperError,
  14739. CesiumMath,
  14740. QuadraticRealPolynomial) {
  14741. 'use strict';
  14742. /**
  14743. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  14744. *
  14745. * @exports QuarticRealPolynomial
  14746. */
  14747. var QuarticRealPolynomial = {};
  14748. /**
  14749. * Provides the discriminant of the quartic equation from the supplied coefficients.
  14750. *
  14751. * @param {Number} a The coefficient of the 4th order monomial.
  14752. * @param {Number} b The coefficient of the 3rd order monomial.
  14753. * @param {Number} c The coefficient of the 2nd order monomial.
  14754. * @param {Number} d The coefficient of the 1st order monomial.
  14755. * @param {Number} e The coefficient of the 0th order monomial.
  14756. * @returns {Number} The value of the discriminant.
  14757. */
  14758. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  14759. if (typeof a !== 'number') {
  14760. throw new DeveloperError('a is a required number.');
  14761. }
  14762. if (typeof b !== 'number') {
  14763. throw new DeveloperError('b is a required number.');
  14764. }
  14765. if (typeof c !== 'number') {
  14766. throw new DeveloperError('c is a required number.');
  14767. }
  14768. if (typeof d !== 'number') {
  14769. throw new DeveloperError('d is a required number.');
  14770. }
  14771. if (typeof e !== 'number') {
  14772. throw new DeveloperError('e is a required number.');
  14773. }
  14774. var a2 = a * a;
  14775. var a3 = a2 * a;
  14776. var b2 = b * b;
  14777. var b3 = b2 * b;
  14778. var c2 = c * c;
  14779. var c3 = c2 * c;
  14780. var d2 = d * d;
  14781. var d3 = d2 * d;
  14782. var e2 = e * e;
  14783. var e3 = e2 * e;
  14784. var discriminant = (b2 * c2 * d2 - 4.0 * b3 * d3 - 4.0 * a * c3 * d2 + 18 * a * b * c * d3 - 27.0 * a2 * d2 * d2 + 256.0 * a3 * e3) +
  14785. e * (18.0 * b3 * c * d - 4.0 * b2 * c3 + 16.0 * a * c2 * c2 - 80.0 * a * b * c2 * d - 6.0 * a * b2 * d2 + 144.0 * a2 * c * d2) +
  14786. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  14787. return discriminant;
  14788. };
  14789. function original(a3, a2, a1, a0) {
  14790. var a3Squared = a3 * a3;
  14791. var p = a2 - 3.0 * a3Squared / 8.0;
  14792. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  14793. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  14794. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  14795. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  14796. if (cubicRoots.length > 0) {
  14797. var temp = -a3 / 4.0;
  14798. // Use the largest positive root.
  14799. var hSquared = cubicRoots[cubicRoots.length - 1];
  14800. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  14801. // y^4 + p y^2 + r = 0.
  14802. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  14803. if (roots.length === 2) {
  14804. var root0 = roots[0];
  14805. var root1 = roots[1];
  14806. var y;
  14807. if (root0 >= 0.0 && root1 >= 0.0) {
  14808. var y0 = Math.sqrt(root0);
  14809. var y1 = Math.sqrt(root1);
  14810. return [temp - y1, temp - y0, temp + y0, temp + y1];
  14811. } else if (root0 >= 0.0 && root1 < 0.0) {
  14812. y = Math.sqrt(root0);
  14813. return [temp - y, temp + y];
  14814. } else if (root0 < 0.0 && root1 >= 0.0) {
  14815. y = Math.sqrt(root1);
  14816. return [temp - y, temp + y];
  14817. }
  14818. }
  14819. return [];
  14820. } else if (hSquared > 0.0) {
  14821. var h = Math.sqrt(hSquared);
  14822. var m = (p + hSquared - q / h) / 2.0;
  14823. var n = (p + hSquared + q / h) / 2.0;
  14824. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  14825. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  14826. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  14827. if (roots1.length !== 0) {
  14828. roots1[0] += temp;
  14829. roots1[1] += temp;
  14830. if (roots2.length !== 0) {
  14831. roots2[0] += temp;
  14832. roots2[1] += temp;
  14833. if (roots1[1] <= roots2[0]) {
  14834. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  14835. } else if (roots2[1] <= roots1[0]) {
  14836. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  14837. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  14838. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  14839. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  14840. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  14841. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  14842. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  14843. }
  14844. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  14845. }
  14846. return roots1;
  14847. }
  14848. if (roots2.length !== 0) {
  14849. roots2[0] += temp;
  14850. roots2[1] += temp;
  14851. return roots2;
  14852. }
  14853. return [];
  14854. }
  14855. }
  14856. return [];
  14857. }
  14858. function neumark(a3, a2, a1, a0) {
  14859. var a1Squared = a1 * a1;
  14860. var a2Squared = a2 * a2;
  14861. var a3Squared = a3 * a3;
  14862. var p = -2.0 * a2;
  14863. var q = a1 * a3 + a2Squared - 4.0 * a0;
  14864. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  14865. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  14866. if (cubicRoots.length > 0) {
  14867. // Use the most positive root
  14868. var y = cubicRoots[0];
  14869. var temp = (a2 - y);
  14870. var tempSquared = temp * temp;
  14871. var g1 = a3 / 2.0;
  14872. var h1 = temp / 2.0;
  14873. var m = tempSquared - 4.0 * a0;
  14874. var mError = tempSquared + 4.0 * Math.abs(a0);
  14875. var n = a3Squared - 4.0 * y;
  14876. var nError = a3Squared + 4.0 * Math.abs(y);
  14877. var g2;
  14878. var h2;
  14879. if (y < 0.0 || (m * nError < n * mError)) {
  14880. var squareRootOfN = Math.sqrt(n);
  14881. g2 = squareRootOfN / 2.0;
  14882. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  14883. } else {
  14884. var squareRootOfM = Math.sqrt(m);
  14885. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  14886. h2 = squareRootOfM / 2.0;
  14887. }
  14888. var G;
  14889. var g;
  14890. if (g1 === 0.0 && g2 === 0.0) {
  14891. G = 0.0;
  14892. g = 0.0;
  14893. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  14894. G = g1 + g2;
  14895. g = y / G;
  14896. } else {
  14897. g = g1 - g2;
  14898. G = y / g;
  14899. }
  14900. var H;
  14901. var h;
  14902. if (h1 === 0.0 && h2 === 0.0) {
  14903. H = 0.0;
  14904. h = 0.0;
  14905. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  14906. H = h1 + h2;
  14907. h = a0 / H;
  14908. } else {
  14909. h = h1 - h2;
  14910. H = a0 / h;
  14911. }
  14912. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  14913. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  14914. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  14915. if (roots1.length !== 0) {
  14916. if (roots2.length !== 0) {
  14917. if (roots1[1] <= roots2[0]) {
  14918. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  14919. } else if (roots2[1] <= roots1[0]) {
  14920. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  14921. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  14922. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  14923. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  14924. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  14925. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  14926. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  14927. } else {
  14928. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  14929. }
  14930. }
  14931. return roots1;
  14932. }
  14933. if (roots2.length !== 0) {
  14934. return roots2;
  14935. }
  14936. }
  14937. return [];
  14938. }
  14939. /**
  14940. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  14941. *
  14942. * @param {Number} a The coefficient of the 4th order monomial.
  14943. * @param {Number} b The coefficient of the 3rd order monomial.
  14944. * @param {Number} c The coefficient of the 2nd order monomial.
  14945. * @param {Number} d The coefficient of the 1st order monomial.
  14946. * @param {Number} e The coefficient of the 0th order monomial.
  14947. * @returns {Number[]} The real valued roots.
  14948. */
  14949. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  14950. if (typeof a !== 'number') {
  14951. throw new DeveloperError('a is a required number.');
  14952. }
  14953. if (typeof b !== 'number') {
  14954. throw new DeveloperError('b is a required number.');
  14955. }
  14956. if (typeof c !== 'number') {
  14957. throw new DeveloperError('c is a required number.');
  14958. }
  14959. if (typeof d !== 'number') {
  14960. throw new DeveloperError('d is a required number.');
  14961. }
  14962. if (typeof e !== 'number') {
  14963. throw new DeveloperError('e is a required number.');
  14964. }
  14965. if (Math.abs(a) < CesiumMath.EPSILON15) {
  14966. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  14967. }
  14968. var a3 = b / a;
  14969. var a2 = c / a;
  14970. var a1 = d / a;
  14971. var a0 = e / a;
  14972. var k = (a3 < 0.0) ? 1 : 0;
  14973. k += (a2 < 0.0) ? k + 1 : k;
  14974. k += (a1 < 0.0) ? k + 1 : k;
  14975. k += (a0 < 0.0) ? k + 1 : k;
  14976. switch (k) {
  14977. case 0:
  14978. return original(a3, a2, a1, a0);
  14979. case 1:
  14980. return neumark(a3, a2, a1, a0);
  14981. case 2:
  14982. return neumark(a3, a2, a1, a0);
  14983. case 3:
  14984. return original(a3, a2, a1, a0);
  14985. case 4:
  14986. return original(a3, a2, a1, a0);
  14987. case 5:
  14988. return neumark(a3, a2, a1, a0);
  14989. case 6:
  14990. return original(a3, a2, a1, a0);
  14991. case 7:
  14992. return original(a3, a2, a1, a0);
  14993. case 8:
  14994. return neumark(a3, a2, a1, a0);
  14995. case 9:
  14996. return original(a3, a2, a1, a0);
  14997. case 10:
  14998. return original(a3, a2, a1, a0);
  14999. case 11:
  15000. return neumark(a3, a2, a1, a0);
  15001. case 12:
  15002. return original(a3, a2, a1, a0);
  15003. case 13:
  15004. return original(a3, a2, a1, a0);
  15005. case 14:
  15006. return original(a3, a2, a1, a0);
  15007. case 15:
  15008. return original(a3, a2, a1, a0);
  15009. default:
  15010. return undefined;
  15011. }
  15012. };
  15013. return QuarticRealPolynomial;
  15014. });
  15015. /*global define*/
  15016. define('Core/Ray',[
  15017. './Cartesian3',
  15018. './defaultValue',
  15019. './defined',
  15020. './DeveloperError'
  15021. ], function(
  15022. Cartesian3,
  15023. defaultValue,
  15024. defined,
  15025. DeveloperError) {
  15026. 'use strict';
  15027. /**
  15028. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  15029. * @alias Ray
  15030. * @constructor
  15031. *
  15032. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  15033. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  15034. */
  15035. function Ray(origin, direction) {
  15036. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  15037. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  15038. Cartesian3.normalize(direction, direction);
  15039. }
  15040. /**
  15041. * The origin of the ray.
  15042. * @type {Cartesian3}
  15043. * @default {@link Cartesian3.ZERO}
  15044. */
  15045. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  15046. /**
  15047. * The direction of the ray.
  15048. * @type {Cartesian3}
  15049. */
  15050. this.direction = direction;
  15051. }
  15052. /**
  15053. * Computes the point along the ray given by r(t) = o + t*d,
  15054. * where o is the origin of the ray and d is the direction.
  15055. *
  15056. * @param {Ray} ray The ray.
  15057. * @param {Number} t A scalar value.
  15058. * @param {Cartesian3} [result] The object in which the result will be stored.
  15059. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  15060. *
  15061. * @example
  15062. * //Get the first intersection point of a ray and an ellipsoid.
  15063. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  15064. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  15065. */
  15066. Ray.getPoint = function(ray, t, result) {
  15067. if (!defined(ray)){
  15068. throw new DeveloperError('ray is requred');
  15069. }
  15070. if (typeof t !== 'number') {
  15071. throw new DeveloperError('t is a required number');
  15072. }
  15073. if (!defined(result)) {
  15074. result = new Cartesian3();
  15075. }
  15076. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  15077. return Cartesian3.add(ray.origin, result, result);
  15078. };
  15079. return Ray;
  15080. });
  15081. /*global define*/
  15082. define('Core/IntersectionTests',[
  15083. './Cartesian3',
  15084. './Cartographic',
  15085. './defaultValue',
  15086. './defined',
  15087. './DeveloperError',
  15088. './Math',
  15089. './Matrix3',
  15090. './QuadraticRealPolynomial',
  15091. './QuarticRealPolynomial',
  15092. './Ray'
  15093. ], function(
  15094. Cartesian3,
  15095. Cartographic,
  15096. defaultValue,
  15097. defined,
  15098. DeveloperError,
  15099. CesiumMath,
  15100. Matrix3,
  15101. QuadraticRealPolynomial,
  15102. QuarticRealPolynomial,
  15103. Ray) {
  15104. 'use strict';
  15105. /**
  15106. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  15107. *
  15108. * @exports IntersectionTests
  15109. */
  15110. var IntersectionTests = {};
  15111. /**
  15112. * Computes the intersection of a ray and a plane.
  15113. *
  15114. * @param {Ray} ray The ray.
  15115. * @param {Plane} plane The plane.
  15116. * @param {Cartesian3} [result] The object onto which to store the result.
  15117. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  15118. */
  15119. IntersectionTests.rayPlane = function(ray, plane, result) {
  15120. if (!defined(ray)) {
  15121. throw new DeveloperError('ray is required.');
  15122. }
  15123. if (!defined(plane)) {
  15124. throw new DeveloperError('plane is required.');
  15125. }
  15126. if (!defined(result)) {
  15127. result = new Cartesian3();
  15128. }
  15129. var origin = ray.origin;
  15130. var direction = ray.direction;
  15131. var normal = plane.normal;
  15132. var denominator = Cartesian3.dot(normal, direction);
  15133. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  15134. // Ray is parallel to plane. The ray may be in the polygon's plane.
  15135. return undefined;
  15136. }
  15137. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  15138. if (t < 0) {
  15139. return undefined;
  15140. }
  15141. result = Cartesian3.multiplyByScalar(direction, t, result);
  15142. return Cartesian3.add(origin, result, result);
  15143. };
  15144. var scratchEdge0 = new Cartesian3();
  15145. var scratchEdge1 = new Cartesian3();
  15146. var scratchPVec = new Cartesian3();
  15147. var scratchTVec = new Cartesian3();
  15148. var scratchQVec = new Cartesian3();
  15149. /**
  15150. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  15151. *
  15152. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  15153. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  15154. *
  15155. * @memberof IntersectionTests
  15156. *
  15157. * @param {Ray} ray The ray.
  15158. * @param {Cartesian3} p0 The first vertex of the triangle.
  15159. * @param {Cartesian3} p1 The second vertex of the triangle.
  15160. * @param {Cartesian3} p2 The third vertex of the triangle.
  15161. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  15162. * and return undefined for intersections with the back face.
  15163. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  15164. */
  15165. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  15166. if (!defined(ray)) {
  15167. throw new DeveloperError('ray is required.');
  15168. }
  15169. if (!defined(p0)) {
  15170. throw new DeveloperError('p0 is required.');
  15171. }
  15172. if (!defined(p1)) {
  15173. throw new DeveloperError('p1 is required.');
  15174. }
  15175. if (!defined(p2)) {
  15176. throw new DeveloperError('p2 is required.');
  15177. }
  15178. cullBackFaces = defaultValue(cullBackFaces, false);
  15179. var origin = ray.origin;
  15180. var direction = ray.direction;
  15181. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  15182. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  15183. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  15184. var det = Cartesian3.dot(edge0, p);
  15185. var tvec;
  15186. var q;
  15187. var u;
  15188. var v;
  15189. var t;
  15190. if (cullBackFaces) {
  15191. if (det < CesiumMath.EPSILON6) {
  15192. return undefined;
  15193. }
  15194. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  15195. u = Cartesian3.dot(tvec, p);
  15196. if (u < 0.0 || u > det) {
  15197. return undefined;
  15198. }
  15199. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  15200. v = Cartesian3.dot(direction, q);
  15201. if (v < 0.0 || u + v > det) {
  15202. return undefined;
  15203. }
  15204. t = Cartesian3.dot(edge1, q) / det;
  15205. } else {
  15206. if (Math.abs(det) < CesiumMath.EPSILON6) {
  15207. return undefined;
  15208. }
  15209. var invDet = 1.0 / det;
  15210. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  15211. u = Cartesian3.dot(tvec, p) * invDet;
  15212. if (u < 0.0 || u > 1.0) {
  15213. return undefined;
  15214. }
  15215. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  15216. v = Cartesian3.dot(direction, q) * invDet;
  15217. if (v < 0.0 || u + v > 1.0) {
  15218. return undefined;
  15219. }
  15220. t = Cartesian3.dot(edge1, q) * invDet;
  15221. }
  15222. return t;
  15223. };
  15224. /**
  15225. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  15226. *
  15227. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  15228. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  15229. *
  15230. * @memberof IntersectionTests
  15231. *
  15232. * @param {Ray} ray The ray.
  15233. * @param {Cartesian3} p0 The first vertex of the triangle.
  15234. * @param {Cartesian3} p1 The second vertex of the triangle.
  15235. * @param {Cartesian3} p2 The third vertex of the triangle.
  15236. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  15237. * and return undefined for intersections with the back face.
  15238. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  15239. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  15240. */
  15241. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  15242. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  15243. if (!defined(t) || t < 0.0) {
  15244. return undefined;
  15245. }
  15246. if (!defined(result)) {
  15247. result = new Cartesian3();
  15248. }
  15249. Cartesian3.multiplyByScalar(ray.direction, t, result);
  15250. return Cartesian3.add(ray.origin, result, result);
  15251. };
  15252. var scratchLineSegmentTriangleRay = new Ray();
  15253. /**
  15254. * Computes the intersection of a line segment and a triangle.
  15255. * @memberof IntersectionTests
  15256. *
  15257. * @param {Cartesian3} v0 The an end point of the line segment.
  15258. * @param {Cartesian3} v1 The other end point of the line segment.
  15259. * @param {Cartesian3} p0 The first vertex of the triangle.
  15260. * @param {Cartesian3} p1 The second vertex of the triangle.
  15261. * @param {Cartesian3} p2 The third vertex of the triangle.
  15262. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  15263. * and return undefined for intersections with the back face.
  15264. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  15265. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  15266. */
  15267. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  15268. if (!defined(v0)) {
  15269. throw new DeveloperError('v0 is required.');
  15270. }
  15271. if (!defined(v1)) {
  15272. throw new DeveloperError('v1 is required.');
  15273. }
  15274. if (!defined(p0)) {
  15275. throw new DeveloperError('p0 is required.');
  15276. }
  15277. if (!defined(p1)) {
  15278. throw new DeveloperError('p1 is required.');
  15279. }
  15280. if (!defined(p2)) {
  15281. throw new DeveloperError('p2 is required.');
  15282. }
  15283. var ray = scratchLineSegmentTriangleRay;
  15284. Cartesian3.clone(v0, ray.origin);
  15285. Cartesian3.subtract(v1, v0, ray.direction);
  15286. Cartesian3.normalize(ray.direction, ray.direction);
  15287. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  15288. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  15289. return undefined;
  15290. }
  15291. if (!defined(result)) {
  15292. result = new Cartesian3();
  15293. }
  15294. Cartesian3.multiplyByScalar(ray.direction, t, result);
  15295. return Cartesian3.add(ray.origin, result, result);
  15296. };
  15297. function solveQuadratic(a, b, c, result) {
  15298. var det = b * b - 4.0 * a * c;
  15299. if (det < 0.0) {
  15300. return undefined;
  15301. } else if (det > 0.0) {
  15302. var denom = 1.0 / (2.0 * a);
  15303. var disc = Math.sqrt(det);
  15304. var root0 = (-b + disc) * denom;
  15305. var root1 = (-b - disc) * denom;
  15306. if (root0 < root1) {
  15307. result.root0 = root0;
  15308. result.root1 = root1;
  15309. } else {
  15310. result.root0 = root1;
  15311. result.root1 = root0;
  15312. }
  15313. return result;
  15314. }
  15315. var root = -b / (2.0 * a);
  15316. if (root === 0.0) {
  15317. return undefined;
  15318. }
  15319. result.root0 = result.root1 = root;
  15320. return result;
  15321. }
  15322. var raySphereRoots = {
  15323. root0 : 0.0,
  15324. root1 : 0.0
  15325. };
  15326. function raySphere(ray, sphere, result) {
  15327. if (!defined(result)) {
  15328. result = {};
  15329. }
  15330. var origin = ray.origin;
  15331. var direction = ray.direction;
  15332. var center = sphere.center;
  15333. var radiusSquared = sphere.radius * sphere.radius;
  15334. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  15335. var a = Cartesian3.dot(direction, direction);
  15336. var b = 2.0 * Cartesian3.dot(direction, diff);
  15337. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  15338. var roots = solveQuadratic(a, b, c, raySphereRoots);
  15339. if (!defined(roots)) {
  15340. return undefined;
  15341. }
  15342. result.start = roots.root0;
  15343. result.stop = roots.root1;
  15344. return result;
  15345. }
  15346. /**
  15347. * Computes the intersection points of a ray with a sphere.
  15348. * @memberof IntersectionTests
  15349. *
  15350. * @param {Ray} ray The ray.
  15351. * @param {BoundingSphere} sphere The sphere.
  15352. * @param {Object} [result] The result onto which to store the result.
  15353. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the ray or undefined if there are no intersections.
  15354. */
  15355. IntersectionTests.raySphere = function(ray, sphere, result) {
  15356. if (!defined(ray)) {
  15357. throw new DeveloperError('ray is required.');
  15358. }
  15359. if (!defined(sphere)) {
  15360. throw new DeveloperError('sphere is required.');
  15361. }
  15362. result = raySphere(ray, sphere, result);
  15363. if (!defined(result) || result.stop < 0.0) {
  15364. return undefined;
  15365. }
  15366. result.start = Math.max(result.start, 0.0);
  15367. return result;
  15368. };
  15369. var scratchLineSegmentRay = new Ray();
  15370. /**
  15371. * Computes the intersection points of a line segment with a sphere.
  15372. * @memberof IntersectionTests
  15373. *
  15374. * @param {Cartesian3} p0 An end point of the line segment.
  15375. * @param {Cartesian3} p1 The other end point of the line segment.
  15376. * @param {BoundingSphere} sphere The sphere.
  15377. * @param {Object} [result] The result onto which to store the result.
  15378. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the line segment or undefined if there are no intersections.
  15379. */
  15380. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  15381. if (!defined(p0)) {
  15382. throw new DeveloperError('p0 is required.');
  15383. }
  15384. if (!defined(p1)) {
  15385. throw new DeveloperError('p1 is required.');
  15386. }
  15387. if (!defined(sphere)) {
  15388. throw new DeveloperError('sphere is required.');
  15389. }
  15390. var ray = scratchLineSegmentRay;
  15391. Cartesian3.clone(p0, ray.origin);
  15392. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  15393. var maxT = Cartesian3.magnitude(direction);
  15394. Cartesian3.normalize(direction, direction);
  15395. result = raySphere(ray, sphere, result);
  15396. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  15397. return undefined;
  15398. }
  15399. result.start = Math.max(result.start, 0.0);
  15400. result.stop = Math.min(result.stop, maxT);
  15401. return result;
  15402. };
  15403. var scratchQ = new Cartesian3();
  15404. var scratchW = new Cartesian3();
  15405. /**
  15406. * Computes the intersection points of a ray with an ellipsoid.
  15407. *
  15408. * @param {Ray} ray The ray.
  15409. * @param {Ellipsoid} ellipsoid The ellipsoid.
  15410. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the ray or undefined if there are no intersections.
  15411. */
  15412. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  15413. if (!defined(ray)) {
  15414. throw new DeveloperError('ray is required.');
  15415. }
  15416. if (!defined(ellipsoid)) {
  15417. throw new DeveloperError('ellipsoid is required.');
  15418. }
  15419. var inverseRadii = ellipsoid.oneOverRadii;
  15420. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  15421. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  15422. var q2 = Cartesian3.magnitudeSquared(q);
  15423. var qw = Cartesian3.dot(q, w);
  15424. var difference, w2, product, discriminant, temp;
  15425. if (q2 > 1.0) {
  15426. // Outside ellipsoid.
  15427. if (qw >= 0.0) {
  15428. // Looking outward or tangent (0 intersections).
  15429. return undefined;
  15430. }
  15431. // qw < 0.0.
  15432. var qw2 = qw * qw;
  15433. difference = q2 - 1.0; // Positively valued.
  15434. w2 = Cartesian3.magnitudeSquared(w);
  15435. product = w2 * difference;
  15436. if (qw2 < product) {
  15437. // Imaginary roots (0 intersections).
  15438. return undefined;
  15439. } else if (qw2 > product) {
  15440. // Distinct roots (2 intersections).
  15441. discriminant = qw * qw - product;
  15442. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  15443. var root0 = temp / w2;
  15444. var root1 = difference / temp;
  15445. if (root0 < root1) {
  15446. return {
  15447. start : root0,
  15448. stop : root1
  15449. };
  15450. }
  15451. return {
  15452. start : root1,
  15453. stop : root0
  15454. };
  15455. } else {
  15456. // qw2 == product. Repeated roots (2 intersections).
  15457. var root = Math.sqrt(difference / w2);
  15458. return {
  15459. start : root,
  15460. stop : root
  15461. };
  15462. }
  15463. } else if (q2 < 1.0) {
  15464. // Inside ellipsoid (2 intersections).
  15465. difference = q2 - 1.0; // Negatively valued.
  15466. w2 = Cartesian3.magnitudeSquared(w);
  15467. product = w2 * difference; // Negatively valued.
  15468. discriminant = qw * qw - product;
  15469. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  15470. return {
  15471. start : 0.0,
  15472. stop : temp / w2
  15473. };
  15474. } else {
  15475. // q2 == 1.0. On ellipsoid.
  15476. if (qw < 0.0) {
  15477. // Looking inward.
  15478. w2 = Cartesian3.magnitudeSquared(w);
  15479. return {
  15480. start : 0.0,
  15481. stop : -qw / w2
  15482. };
  15483. }
  15484. // qw >= 0.0. Looking outward or tangent.
  15485. return undefined;
  15486. }
  15487. };
  15488. function addWithCancellationCheck(left, right, tolerance) {
  15489. var difference = left + right;
  15490. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  15491. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  15492. return 0.0;
  15493. }
  15494. return difference;
  15495. }
  15496. function quadraticVectorExpression(A, b, c, x, w) {
  15497. var xSquared = x * x;
  15498. var wSquared = w * w;
  15499. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  15500. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  15501. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  15502. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  15503. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  15504. var cosines;
  15505. var solutions = [];
  15506. if (r0 === 0.0 && r1 === 0.0) {
  15507. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  15508. if (cosines.length === 0) {
  15509. return solutions;
  15510. }
  15511. var cosine0 = cosines[0];
  15512. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  15513. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  15514. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  15515. if (cosines.length === 2) {
  15516. var cosine1 = cosines[1];
  15517. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  15518. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  15519. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  15520. }
  15521. return solutions;
  15522. }
  15523. var r0Squared = r0 * r0;
  15524. var r1Squared = r1 * r1;
  15525. var l2Squared = l2 * l2;
  15526. var r0r1 = r0 * r1;
  15527. var c4 = l2Squared + r1Squared;
  15528. var c3 = 2.0 * (l1 * l2 + r0r1);
  15529. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  15530. var c1 = 2.0 * (l0 * l1 - r0r1);
  15531. var c0 = l0 * l0 - r0Squared;
  15532. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  15533. return solutions;
  15534. }
  15535. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  15536. var length = cosines.length;
  15537. if (length === 0) {
  15538. return solutions;
  15539. }
  15540. for ( var i = 0; i < length; ++i) {
  15541. var cosine = cosines[i];
  15542. var cosineSquared = cosine * cosine;
  15543. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  15544. var sine = Math.sqrt(sineSquared);
  15545. //var left = l2 * cosineSquared + l1 * cosine + l0;
  15546. var left;
  15547. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  15548. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  15549. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  15550. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  15551. } else {
  15552. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  15553. }
  15554. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  15555. var product = left * right;
  15556. if (product < 0.0) {
  15557. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  15558. } else if (product > 0.0) {
  15559. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  15560. } else if (sine !== 0.0) {
  15561. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  15562. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  15563. ++i;
  15564. } else {
  15565. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  15566. }
  15567. }
  15568. return solutions;
  15569. }
  15570. var firstAxisScratch = new Cartesian3();
  15571. var secondAxisScratch = new Cartesian3();
  15572. var thirdAxisScratch = new Cartesian3();
  15573. var referenceScratch = new Cartesian3();
  15574. var bCart = new Cartesian3();
  15575. var bScratch = new Matrix3();
  15576. var btScratch = new Matrix3();
  15577. var diScratch = new Matrix3();
  15578. var dScratch = new Matrix3();
  15579. var cScratch = new Matrix3();
  15580. var tempMatrix = new Matrix3();
  15581. var aScratch = new Matrix3();
  15582. var sScratch = new Cartesian3();
  15583. var closestScratch = new Cartesian3();
  15584. var surfPointScratch = new Cartographic();
  15585. /**
  15586. * Provides the point along the ray which is nearest to the ellipsoid.
  15587. *
  15588. * @param {Ray} ray The ray.
  15589. * @param {Ellipsoid} ellipsoid The ellipsoid.
  15590. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  15591. */
  15592. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  15593. if (!defined(ray)) {
  15594. throw new DeveloperError('ray is required.');
  15595. }
  15596. if (!defined(ellipsoid)) {
  15597. throw new DeveloperError('ellipsoid is required.');
  15598. }
  15599. var position = ray.origin;
  15600. var direction = ray.direction;
  15601. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  15602. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  15603. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  15604. return position;
  15605. }
  15606. }
  15607. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  15608. // Compute the scaled direction vector.
  15609. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  15610. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  15611. var firstAxis = Cartesian3.normalize(f, f);
  15612. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  15613. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  15614. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  15615. var B = bScratch;
  15616. B[0] = firstAxis.x;
  15617. B[1] = firstAxis.y;
  15618. B[2] = firstAxis.z;
  15619. B[3] = secondAxis.x;
  15620. B[4] = secondAxis.y;
  15621. B[5] = secondAxis.z;
  15622. B[6] = thirdAxis.x;
  15623. B[7] = thirdAxis.y;
  15624. B[8] = thirdAxis.z;
  15625. var B_T = Matrix3.transpose(B, btScratch);
  15626. // Get the scaling matrix and its inverse.
  15627. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  15628. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  15629. var C = cScratch;
  15630. C[0] = 0.0;
  15631. C[1] = -direction.z;
  15632. C[2] = direction.y;
  15633. C[3] = direction.z;
  15634. C[4] = 0.0;
  15635. C[5] = -direction.x;
  15636. C[6] = -direction.y;
  15637. C[7] = direction.x;
  15638. C[8] = 0.0;
  15639. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  15640. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  15641. var b = Matrix3.multiplyByVector(temp, position, bCart);
  15642. // Solve for the solutions to the expression in standard form:
  15643. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  15644. var s;
  15645. var altitude;
  15646. var length = solutions.length;
  15647. if (length > 0) {
  15648. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  15649. var maximumValue = Number.NEGATIVE_INFINITY;
  15650. for ( var i = 0; i < length; ++i) {
  15651. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  15652. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  15653. var dotProduct = Cartesian3.dot(v, direction);
  15654. if (dotProduct > maximumValue) {
  15655. maximumValue = dotProduct;
  15656. closest = Cartesian3.clone(s, closest);
  15657. }
  15658. }
  15659. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  15660. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  15661. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  15662. altitude = intersects ? -altitude : altitude;
  15663. surfacePoint.height = altitude;
  15664. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  15665. }
  15666. return undefined;
  15667. };
  15668. var lineSegmentPlaneDifference = new Cartesian3();
  15669. /**
  15670. * Computes the intersection of a line segment and a plane.
  15671. *
  15672. * @param {Cartesian3} endPoint0 An end point of the line segment.
  15673. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  15674. * @param {Plane} plane The plane.
  15675. * @param {Cartesian3} [result] The object onto which to store the result.
  15676. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  15677. *
  15678. * @example
  15679. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  15680. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  15681. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  15682. *
  15683. * var p0 = new Cesium.Cartesian3(...);
  15684. * var p1 = new Cesium.Cartesian3(...);
  15685. *
  15686. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  15687. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  15688. */
  15689. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  15690. if (!defined(endPoint0)) {
  15691. throw new DeveloperError('endPoint0 is required.');
  15692. }
  15693. if (!defined(endPoint1)) {
  15694. throw new DeveloperError('endPoint1 is required.');
  15695. }
  15696. if (!defined(plane)) {
  15697. throw new DeveloperError('plane is required.');
  15698. }
  15699. if (!defined(result)) {
  15700. result = new Cartesian3();
  15701. }
  15702. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  15703. var normal = plane.normal;
  15704. var nDotDiff = Cartesian3.dot(normal, difference);
  15705. // check if the segment and plane are parallel
  15706. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  15707. return undefined;
  15708. }
  15709. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  15710. var t = -(plane.distance + nDotP0) / nDotDiff;
  15711. // intersection only if t is in [0, 1]
  15712. if (t < 0.0 || t > 1.0) {
  15713. return undefined;
  15714. }
  15715. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  15716. Cartesian3.multiplyByScalar(difference, t, result);
  15717. Cartesian3.add(endPoint0, result, result);
  15718. return result;
  15719. };
  15720. /**
  15721. * Computes the intersection of a triangle and a plane
  15722. *
  15723. * @param {Cartesian3} p0 First point of the triangle
  15724. * @param {Cartesian3} p1 Second point of the triangle
  15725. * @param {Cartesian3} p2 Third point of the triangle
  15726. * @param {Plane} plane Intersection plane
  15727. * @returns {Object} An object with properties <code>positions</code> and <code>indices</code>, which are arrays that represent three triangles that do not cross the plane. (Undefined if no intersection exists)
  15728. *
  15729. * @example
  15730. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  15731. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  15732. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  15733. *
  15734. * var p0 = new Cesium.Cartesian3(...);
  15735. * var p1 = new Cesium.Cartesian3(...);
  15736. * var p2 = new Cesium.Cartesian3(...);
  15737. *
  15738. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  15739. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  15740. */
  15741. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  15742. if ((!defined(p0)) ||
  15743. (!defined(p1)) ||
  15744. (!defined(p2)) ||
  15745. (!defined(plane))) {
  15746. throw new DeveloperError('p0, p1, p2, and plane are required.');
  15747. }
  15748. var planeNormal = plane.normal;
  15749. var planeD = plane.distance;
  15750. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  15751. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  15752. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  15753. // Given these dots products, the calls to lineSegmentPlaneIntersection
  15754. // always have defined results.
  15755. var numBehind = 0;
  15756. numBehind += p0Behind ? 1 : 0;
  15757. numBehind += p1Behind ? 1 : 0;
  15758. numBehind += p2Behind ? 1 : 0;
  15759. var u1, u2;
  15760. if (numBehind === 1 || numBehind === 2) {
  15761. u1 = new Cartesian3();
  15762. u2 = new Cartesian3();
  15763. }
  15764. if (numBehind === 1) {
  15765. if (p0Behind) {
  15766. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  15767. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  15768. return {
  15769. positions : [p0, p1, p2, u1, u2 ],
  15770. indices : [
  15771. // Behind
  15772. 0, 3, 4,
  15773. // In front
  15774. 1, 2, 4,
  15775. 1, 4, 3
  15776. ]
  15777. };
  15778. } else if (p1Behind) {
  15779. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  15780. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  15781. return {
  15782. positions : [p0, p1, p2, u1, u2 ],
  15783. indices : [
  15784. // Behind
  15785. 1, 3, 4,
  15786. // In front
  15787. 2, 0, 4,
  15788. 2, 4, 3
  15789. ]
  15790. };
  15791. } else if (p2Behind) {
  15792. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  15793. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  15794. return {
  15795. positions : [p0, p1, p2, u1, u2 ],
  15796. indices : [
  15797. // Behind
  15798. 2, 3, 4,
  15799. // In front
  15800. 0, 1, 4,
  15801. 0, 4, 3
  15802. ]
  15803. };
  15804. }
  15805. } else if (numBehind === 2) {
  15806. if (!p0Behind) {
  15807. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  15808. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  15809. return {
  15810. positions : [p0, p1, p2, u1, u2 ],
  15811. indices : [
  15812. // Behind
  15813. 1, 2, 4,
  15814. 1, 4, 3,
  15815. // In front
  15816. 0, 3, 4
  15817. ]
  15818. };
  15819. } else if (!p1Behind) {
  15820. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  15821. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  15822. return {
  15823. positions : [p0, p1, p2, u1, u2 ],
  15824. indices : [
  15825. // Behind
  15826. 2, 0, 4,
  15827. 2, 4, 3,
  15828. // In front
  15829. 1, 3, 4
  15830. ]
  15831. };
  15832. } else if (!p2Behind) {
  15833. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  15834. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  15835. return {
  15836. positions : [p0, p1, p2, u1, u2 ],
  15837. indices : [
  15838. // Behind
  15839. 0, 1, 4,
  15840. 0, 4, 3,
  15841. // In front
  15842. 2, 3, 4
  15843. ]
  15844. };
  15845. }
  15846. }
  15847. // if numBehind is 3, the triangle is completely behind the plane;
  15848. // otherwise, it is completely in front (numBehind is 0).
  15849. return undefined;
  15850. };
  15851. return IntersectionTests;
  15852. });
  15853. /*global define*/
  15854. define('Core/Plane',[
  15855. './Cartesian3',
  15856. './defined',
  15857. './DeveloperError',
  15858. './freezeObject'
  15859. ], function(
  15860. Cartesian3,
  15861. defined,
  15862. DeveloperError,
  15863. freezeObject) {
  15864. 'use strict';
  15865. /**
  15866. * A plane in Hessian Normal Form defined by
  15867. * <pre>
  15868. * ax + by + cz + d = 0
  15869. * </pre>
  15870. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  15871. * <code>distance</code> to the plane, and (x, y, z) is any point on
  15872. * the plane.
  15873. *
  15874. * @alias Plane
  15875. * @constructor
  15876. *
  15877. * @param {Cartesian3} normal The plane's normal (normalized).
  15878. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  15879. * <code>distance</code> determines which side of the plane the origin
  15880. * is on. If <code>distance</code> is positive, the origin is in the half-space
  15881. * in the direction of the normal; if negative, the origin is in the half-space
  15882. * opposite to the normal; if zero, the plane passes through the origin.
  15883. *
  15884. * @example
  15885. * // The plane x=0
  15886. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  15887. */
  15888. function Plane(normal, distance) {
  15889. if (!defined(normal)) {
  15890. throw new DeveloperError('normal is required.');
  15891. }
  15892. if (!defined(distance)) {
  15893. throw new DeveloperError('distance is required.');
  15894. }
  15895. /**
  15896. * The plane's normal.
  15897. *
  15898. * @type {Cartesian3}
  15899. */
  15900. this.normal = Cartesian3.clone(normal);
  15901. /**
  15902. * The shortest distance from the origin to the plane. The sign of
  15903. * <code>distance</code> determines which side of the plane the origin
  15904. * is on. If <code>distance</code> is positive, the origin is in the half-space
  15905. * in the direction of the normal; if negative, the origin is in the half-space
  15906. * opposite to the normal; if zero, the plane passes through the origin.
  15907. *
  15908. * @type {Number}
  15909. */
  15910. this.distance = distance;
  15911. }
  15912. /**
  15913. * Creates a plane from a normal and a point on the plane.
  15914. *
  15915. * @param {Cartesian3} point The point on the plane.
  15916. * @param {Cartesian3} normal The plane's normal (normalized).
  15917. * @param {Plane} [result] The object onto which to store the result.
  15918. * @returns {Plane} A new plane instance or the modified result parameter.
  15919. *
  15920. * @example
  15921. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  15922. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  15923. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  15924. */
  15925. Plane.fromPointNormal = function(point, normal, result) {
  15926. if (!defined(point)) {
  15927. throw new DeveloperError('point is required.');
  15928. }
  15929. if (!defined(normal)) {
  15930. throw new DeveloperError('normal is required.');
  15931. }
  15932. var distance = -Cartesian3.dot(normal, point);
  15933. if (!defined(result)) {
  15934. return new Plane(normal, distance);
  15935. }
  15936. Cartesian3.clone(normal, result.normal);
  15937. result.distance = distance;
  15938. return result;
  15939. };
  15940. var scratchNormal = new Cartesian3();
  15941. /**
  15942. * Creates a plane from the general equation
  15943. *
  15944. * @param {Cartesian4} coefficients The plane's normal (normalized).
  15945. * @param {Plane} [result] The object onto which to store the result.
  15946. * @returns {Plane} A new plane instance or the modified result parameter.
  15947. */
  15948. Plane.fromCartesian4 = function(coefficients, result) {
  15949. if (!defined(coefficients)) {
  15950. throw new DeveloperError('coefficients is required.');
  15951. }
  15952. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  15953. var distance = coefficients.w;
  15954. if (!defined(result)) {
  15955. return new Plane(normal, distance);
  15956. } else {
  15957. Cartesian3.clone(normal, result.normal);
  15958. result.distance = distance;
  15959. return result;
  15960. }
  15961. };
  15962. /**
  15963. * Computes the signed shortest distance of a point to a plane.
  15964. * The sign of the distance determines which side of the plane the point
  15965. * is on. If the distance is positive, the point is in the half-space
  15966. * in the direction of the normal; if negative, the point is in the half-space
  15967. * opposite to the normal; if zero, the plane passes through the point.
  15968. *
  15969. * @param {Plane} plane The plane.
  15970. * @param {Cartesian3} point The point.
  15971. * @returns {Number} The signed shortest distance of the point to the plane.
  15972. */
  15973. Plane.getPointDistance = function(plane, point) {
  15974. if (!defined(plane)) {
  15975. throw new DeveloperError('plane is required.');
  15976. }
  15977. if (!defined(point)) {
  15978. throw new DeveloperError('point is required.');
  15979. }
  15980. return Cartesian3.dot(plane.normal, point) + plane.distance;
  15981. };
  15982. /**
  15983. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  15984. *
  15985. * @type {Plane}
  15986. * @constant
  15987. */
  15988. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  15989. /**
  15990. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  15991. *
  15992. * @type {Plane}
  15993. * @constant
  15994. */
  15995. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  15996. /**
  15997. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  15998. *
  15999. * @type {Plane}
  16000. * @constant
  16001. */
  16002. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  16003. return Plane;
  16004. });
  16005. /*global define*/
  16006. define('Core/Tipsify',[
  16007. './defaultValue',
  16008. './defined',
  16009. './DeveloperError'
  16010. ], function(
  16011. defaultValue,
  16012. defined,
  16013. DeveloperError) {
  16014. 'use strict';
  16015. /**
  16016. * Encapsulates an algorithm to optimize triangles for the post
  16017. * vertex-shader cache. This is based on the 2007 SIGGRAPH paper
  16018. * 'Fast Triangle Reordering for Vertex Locality and Reduced Overdraw.'
  16019. * The runtime is linear but several passes are made.
  16020. *
  16021. * @exports Tipsify
  16022. *
  16023. * @see <a href='http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf'>
  16024. * Fast Triangle Reordering for Vertex Locality and Reduced Overdraw</a>
  16025. * by Sander, Nehab, and Barczak
  16026. *
  16027. * @private
  16028. */
  16029. var Tipsify = {};
  16030. /**
  16031. * Calculates the average cache miss ratio (ACMR) for a given set of indices.
  16032. *
  16033. * @param {Object} options Object with the following properties:
  16034. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  16035. * in the vertex buffer that define the geometry's triangles.
  16036. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  16037. * If not supplied, this value will be computed.
  16038. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  16039. * @returns {Number} The average cache miss ratio (ACMR).
  16040. *
  16041. * @exception {DeveloperError} indices length must be a multiple of three.
  16042. * @exception {DeveloperError} cacheSize must be greater than two.
  16043. *
  16044. * @example
  16045. * var indices = [0, 1, 2, 3, 4, 5];
  16046. * var maxIndex = 5;
  16047. * var cacheSize = 3;
  16048. * var acmr = Cesium.Tipsify.calculateACMR({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  16049. */
  16050. Tipsify.calculateACMR = function(options) {
  16051. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16052. var indices = options.indices;
  16053. var maximumIndex = options.maximumIndex;
  16054. var cacheSize = defaultValue(options.cacheSize, 24);
  16055. if (!defined(indices)) {
  16056. throw new DeveloperError('indices is required.');
  16057. }
  16058. var numIndices = indices.length;
  16059. if (numIndices < 3 || numIndices % 3 !== 0) {
  16060. throw new DeveloperError('indices length must be a multiple of three.');
  16061. }
  16062. if (maximumIndex <= 0) {
  16063. throw new DeveloperError('maximumIndex must be greater than zero.');
  16064. }
  16065. if (cacheSize < 3) {
  16066. throw new DeveloperError('cacheSize must be greater than two.');
  16067. }
  16068. // Compute the maximumIndex if not given
  16069. if (!defined(maximumIndex)) {
  16070. maximumIndex = 0;
  16071. var currentIndex = 0;
  16072. var intoIndices = indices[currentIndex];
  16073. while (currentIndex < numIndices) {
  16074. if (intoIndices > maximumIndex) {
  16075. maximumIndex = intoIndices;
  16076. }
  16077. ++currentIndex;
  16078. intoIndices = indices[currentIndex];
  16079. }
  16080. }
  16081. // Vertex time stamps
  16082. var vertexTimeStamps = [];
  16083. for ( var i = 0; i < maximumIndex + 1; i++) {
  16084. vertexTimeStamps[i] = 0;
  16085. }
  16086. // Cache processing
  16087. var s = cacheSize + 1;
  16088. for ( var j = 0; j < numIndices; ++j) {
  16089. if ((s - vertexTimeStamps[indices[j]]) > cacheSize) {
  16090. vertexTimeStamps[indices[j]] = s;
  16091. ++s;
  16092. }
  16093. }
  16094. return (s - cacheSize + 1) / (numIndices / 3);
  16095. };
  16096. /**
  16097. * Optimizes triangles for the post-vertex shader cache.
  16098. *
  16099. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  16100. * in the vertex buffer that define the geometry's triangles.
  16101. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  16102. * If not supplied, this value will be computed.
  16103. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  16104. * @returns {Number[]} A list of the input indices in an optimized order.
  16105. *
  16106. * @exception {DeveloperError} indices length must be a multiple of three.
  16107. * @exception {DeveloperError} cacheSize must be greater than two.
  16108. *
  16109. * @example
  16110. * var indices = [0, 1, 2, 3, 4, 5];
  16111. * var maxIndex = 5;
  16112. * var cacheSize = 3;
  16113. * var reorderedIndices = Cesium.Tipsify.tipsify({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  16114. */
  16115. Tipsify.tipsify = function(options) {
  16116. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16117. var indices = options.indices;
  16118. var maximumIndex = options.maximumIndex;
  16119. var cacheSize = defaultValue(options.cacheSize, 24);
  16120. var cursor;
  16121. function skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne) {
  16122. while (deadEnd.length >= 1) {
  16123. // while the stack is not empty
  16124. var d = deadEnd[deadEnd.length - 1]; // top of the stack
  16125. deadEnd.splice(deadEnd.length - 1, 1); // pop the stack
  16126. if (vertices[d].numLiveTriangles > 0) {
  16127. return d;
  16128. }
  16129. }
  16130. while (cursor < maximumIndexPlusOne) {
  16131. if (vertices[cursor].numLiveTriangles > 0) {
  16132. ++cursor;
  16133. return cursor - 1;
  16134. }
  16135. ++cursor;
  16136. }
  16137. return -1;
  16138. }
  16139. function getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne) {
  16140. var n = -1;
  16141. var p;
  16142. var m = -1;
  16143. var itOneRing = 0;
  16144. while (itOneRing < oneRing.length) {
  16145. var index = oneRing[itOneRing];
  16146. if (vertices[index].numLiveTriangles) {
  16147. p = 0;
  16148. if ((s - vertices[index].timeStamp + (2 * vertices[index].numLiveTriangles)) <= cacheSize) {
  16149. p = s - vertices[index].timeStamp;
  16150. }
  16151. if ((p > m) || (m === -1)) {
  16152. m = p;
  16153. n = index;
  16154. }
  16155. }
  16156. ++itOneRing;
  16157. }
  16158. if (n === -1) {
  16159. return skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne);
  16160. }
  16161. return n;
  16162. }
  16163. if (!defined(indices)) {
  16164. throw new DeveloperError('indices is required.');
  16165. }
  16166. var numIndices = indices.length;
  16167. if (numIndices < 3 || numIndices % 3 !== 0) {
  16168. throw new DeveloperError('indices length must be a multiple of three.');
  16169. }
  16170. if (maximumIndex <= 0) {
  16171. throw new DeveloperError('maximumIndex must be greater than zero.');
  16172. }
  16173. if (cacheSize < 3) {
  16174. throw new DeveloperError('cacheSize must be greater than two.');
  16175. }
  16176. // Determine maximum index
  16177. var maximumIndexPlusOne = 0;
  16178. var currentIndex = 0;
  16179. var intoIndices = indices[currentIndex];
  16180. var endIndex = numIndices;
  16181. if (defined(maximumIndex)) {
  16182. maximumIndexPlusOne = maximumIndex + 1;
  16183. } else {
  16184. while (currentIndex < endIndex) {
  16185. if (intoIndices > maximumIndexPlusOne) {
  16186. maximumIndexPlusOne = intoIndices;
  16187. }
  16188. ++currentIndex;
  16189. intoIndices = indices[currentIndex];
  16190. }
  16191. if (maximumIndexPlusOne === -1) {
  16192. return 0;
  16193. }
  16194. ++maximumIndexPlusOne;
  16195. }
  16196. // Vertices
  16197. var vertices = [];
  16198. for ( var i = 0; i < maximumIndexPlusOne; i++) {
  16199. vertices[i] = {
  16200. numLiveTriangles : 0,
  16201. timeStamp : 0,
  16202. vertexTriangles : []
  16203. };
  16204. }
  16205. currentIndex = 0;
  16206. var triangle = 0;
  16207. while (currentIndex < endIndex) {
  16208. vertices[indices[currentIndex]].vertexTriangles.push(triangle);
  16209. ++(vertices[indices[currentIndex]]).numLiveTriangles;
  16210. vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
  16211. ++(vertices[indices[currentIndex + 1]]).numLiveTriangles;
  16212. vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
  16213. ++(vertices[indices[currentIndex + 2]]).numLiveTriangles;
  16214. ++triangle;
  16215. currentIndex += 3;
  16216. }
  16217. // Starting index
  16218. var f = 0;
  16219. // Time Stamp
  16220. var s = cacheSize + 1;
  16221. cursor = 1;
  16222. // Process
  16223. var oneRing = [];
  16224. var deadEnd = []; //Stack
  16225. var vertex;
  16226. var intoVertices;
  16227. var currentOutputIndex = 0;
  16228. var outputIndices = [];
  16229. var numTriangles = numIndices / 3;
  16230. var triangleEmitted = [];
  16231. for (i = 0; i < numTriangles; i++) {
  16232. triangleEmitted[i] = false;
  16233. }
  16234. var index;
  16235. var limit;
  16236. while (f !== -1) {
  16237. oneRing = [];
  16238. intoVertices = vertices[f];
  16239. limit = intoVertices.vertexTriangles.length;
  16240. for ( var k = 0; k < limit; ++k) {
  16241. triangle = intoVertices.vertexTriangles[k];
  16242. if (!triangleEmitted[triangle]) {
  16243. triangleEmitted[triangle] = true;
  16244. currentIndex = triangle + triangle + triangle;
  16245. for ( var j = 0; j < 3; ++j) {
  16246. // Set this index as a possible next index
  16247. index = indices[currentIndex];
  16248. oneRing.push(index);
  16249. deadEnd.push(index);
  16250. // Output index
  16251. outputIndices[currentOutputIndex] = index;
  16252. ++currentOutputIndex;
  16253. // Cache processing
  16254. vertex = vertices[index];
  16255. --vertex.numLiveTriangles;
  16256. if ((s - vertex.timeStamp) > cacheSize) {
  16257. vertex.timeStamp = s;
  16258. ++s;
  16259. }
  16260. ++currentIndex;
  16261. }
  16262. }
  16263. }
  16264. f = getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne);
  16265. }
  16266. return outputIndices;
  16267. };
  16268. return Tipsify;
  16269. });
  16270. /*global define*/
  16271. define('Core/GeometryPipeline',[
  16272. './AttributeCompression',
  16273. './barycentricCoordinates',
  16274. './BoundingSphere',
  16275. './Cartesian2',
  16276. './Cartesian3',
  16277. './Cartesian4',
  16278. './Cartographic',
  16279. './ComponentDatatype',
  16280. './defaultValue',
  16281. './defined',
  16282. './DeveloperError',
  16283. './EncodedCartesian3',
  16284. './GeographicProjection',
  16285. './Geometry',
  16286. './GeometryAttribute',
  16287. './GeometryType',
  16288. './IndexDatatype',
  16289. './Intersect',
  16290. './IntersectionTests',
  16291. './Math',
  16292. './Matrix3',
  16293. './Matrix4',
  16294. './Plane',
  16295. './PrimitiveType',
  16296. './Tipsify'
  16297. ], function(
  16298. AttributeCompression,
  16299. barycentricCoordinates,
  16300. BoundingSphere,
  16301. Cartesian2,
  16302. Cartesian3,
  16303. Cartesian4,
  16304. Cartographic,
  16305. ComponentDatatype,
  16306. defaultValue,
  16307. defined,
  16308. DeveloperError,
  16309. EncodedCartesian3,
  16310. GeographicProjection,
  16311. Geometry,
  16312. GeometryAttribute,
  16313. GeometryType,
  16314. IndexDatatype,
  16315. Intersect,
  16316. IntersectionTests,
  16317. CesiumMath,
  16318. Matrix3,
  16319. Matrix4,
  16320. Plane,
  16321. PrimitiveType,
  16322. Tipsify) {
  16323. 'use strict';
  16324. /**
  16325. * Content pipeline functions for geometries.
  16326. *
  16327. * @exports GeometryPipeline
  16328. *
  16329. * @see Geometry
  16330. */
  16331. var GeometryPipeline = {};
  16332. function addTriangle(lines, index, i0, i1, i2) {
  16333. lines[index++] = i0;
  16334. lines[index++] = i1;
  16335. lines[index++] = i1;
  16336. lines[index++] = i2;
  16337. lines[index++] = i2;
  16338. lines[index] = i0;
  16339. }
  16340. function trianglesToLines(triangles) {
  16341. var count = triangles.length;
  16342. var size = (count / 3) * 6;
  16343. var lines = IndexDatatype.createTypedArray(count, size);
  16344. var index = 0;
  16345. for ( var i = 0; i < count; i += 3, index += 6) {
  16346. addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
  16347. }
  16348. return lines;
  16349. }
  16350. function triangleStripToLines(triangles) {
  16351. var count = triangles.length;
  16352. if (count >= 3) {
  16353. var size = (count - 2) * 6;
  16354. var lines = IndexDatatype.createTypedArray(count, size);
  16355. addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
  16356. var index = 6;
  16357. for ( var i = 3; i < count; ++i, index += 6) {
  16358. addTriangle(lines, index, triangles[i - 1], triangles[i], triangles[i - 2]);
  16359. }
  16360. return lines;
  16361. }
  16362. return new Uint16Array();
  16363. }
  16364. function triangleFanToLines(triangles) {
  16365. if (triangles.length > 0) {
  16366. var count = triangles.length - 1;
  16367. var size = (count - 1) * 6;
  16368. var lines = IndexDatatype.createTypedArray(count, size);
  16369. var base = triangles[0];
  16370. var index = 0;
  16371. for ( var i = 1; i < count; ++i, index += 6) {
  16372. addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
  16373. }
  16374. return lines;
  16375. }
  16376. return new Uint16Array();
  16377. }
  16378. /**
  16379. * Converts a geometry's triangle indices to line indices. If the geometry has an <code>indices</code>
  16380. * and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>,
  16381. * <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed.
  16382. * <p>
  16383. * This is commonly used to create a wireframe geometry for visual debugging.
  16384. * </p>
  16385. *
  16386. * @param {Geometry} geometry The geometry to modify.
  16387. * @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines.
  16388. *
  16389. * @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.
  16390. *
  16391. * @example
  16392. * geometry = Cesium.GeometryPipeline.toWireframe(geometry);
  16393. */
  16394. GeometryPipeline.toWireframe = function(geometry) {
  16395. if (!defined(geometry)) {
  16396. throw new DeveloperError('geometry is required.');
  16397. }
  16398. var indices = geometry.indices;
  16399. if (defined(indices)) {
  16400. switch (geometry.primitiveType) {
  16401. case PrimitiveType.TRIANGLES:
  16402. geometry.indices = trianglesToLines(indices);
  16403. break;
  16404. case PrimitiveType.TRIANGLE_STRIP:
  16405. geometry.indices = triangleStripToLines(indices);
  16406. break;
  16407. case PrimitiveType.TRIANGLE_FAN:
  16408. geometry.indices = triangleFanToLines(indices);
  16409. break;
  16410. default:
  16411. throw new DeveloperError('geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.');
  16412. }
  16413. geometry.primitiveType = PrimitiveType.LINES;
  16414. }
  16415. return geometry;
  16416. };
  16417. /**
  16418. * Creates a new {@link Geometry} with <code>LINES</code> representing the provided
  16419. * attribute (<code>attributeName</code>) for the provided geometry. This is used to
  16420. * visualize vector attributes like normals, binormals, and tangents.
  16421. *
  16422. * @param {Geometry} geometry The <code>Geometry</code> instance with the attribute.
  16423. * @param {String} [attributeName='normal'] The name of the attribute.
  16424. * @param {Number} [length=10000.0] The length of each line segment in meters. This can be negative to point the vector in the opposite direction.
  16425. * @returns {Geometry} A new <code>Geometry</code> instance with line segments for the vector.
  16426. *
  16427. * @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter.
  16428. *
  16429. * @example
  16430. * var geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'binormal', 100000.0);
  16431. */
  16432. GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length) {
  16433. attributeName = defaultValue(attributeName, 'normal');
  16434. if (!defined(geometry)) {
  16435. throw new DeveloperError('geometry is required.');
  16436. }
  16437. if (!defined(geometry.attributes.position)) {
  16438. throw new DeveloperError('geometry.attributes.position is required.');
  16439. }
  16440. if (!defined(geometry.attributes[attributeName])) {
  16441. throw new DeveloperError('geometry.attributes must have an attribute with the same name as the attributeName parameter, ' + attributeName + '.');
  16442. }
  16443. length = defaultValue(length, 10000.0);
  16444. var positions = geometry.attributes.position.values;
  16445. var vectors = geometry.attributes[attributeName].values;
  16446. var positionsLength = positions.length;
  16447. var newPositions = new Float64Array(2 * positionsLength);
  16448. var j = 0;
  16449. for (var i = 0; i < positionsLength; i += 3) {
  16450. newPositions[j++] = positions[i];
  16451. newPositions[j++] = positions[i + 1];
  16452. newPositions[j++] = positions[i + 2];
  16453. newPositions[j++] = positions[i] + (vectors[i] * length);
  16454. newPositions[j++] = positions[i + 1] + (vectors[i + 1] * length);
  16455. newPositions[j++] = positions[i + 2] + (vectors[i + 2] * length);
  16456. }
  16457. var newBoundingSphere;
  16458. var bs = geometry.boundingSphere;
  16459. if (defined(bs)) {
  16460. newBoundingSphere = new BoundingSphere(bs.center, bs.radius + length);
  16461. }
  16462. return new Geometry({
  16463. attributes : {
  16464. position : new GeometryAttribute({
  16465. componentDatatype : ComponentDatatype.DOUBLE,
  16466. componentsPerAttribute : 3,
  16467. values : newPositions
  16468. })
  16469. },
  16470. primitiveType : PrimitiveType.LINES,
  16471. boundingSphere : newBoundingSphere
  16472. });
  16473. };
  16474. /**
  16475. * Creates an object that maps attribute names to unique locations (indices)
  16476. * for matching vertex attributes and shader programs.
  16477. *
  16478. * @param {Geometry} geometry The geometry, which is not modified, to create the object for.
  16479. * @returns {Object} An object with attribute name / index pairs.
  16480. *
  16481. * @example
  16482. * var attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry);
  16483. * // Example output
  16484. * // {
  16485. * // 'position' : 0,
  16486. * // 'normal' : 1
  16487. * // }
  16488. */
  16489. GeometryPipeline.createAttributeLocations = function(geometry) {
  16490. if (!defined(geometry)) {
  16491. throw new DeveloperError('geometry is required.');
  16492. }
  16493. // There can be a WebGL performance hit when attribute 0 is disabled, so
  16494. // assign attribute locations to well-known attributes.
  16495. var semantics = [
  16496. 'position',
  16497. 'positionHigh',
  16498. 'positionLow',
  16499. // From VertexFormat.position - after 2D projection and high-precision encoding
  16500. 'position3DHigh',
  16501. 'position3DLow',
  16502. 'position2DHigh',
  16503. 'position2DLow',
  16504. // From Primitive
  16505. 'pickColor',
  16506. // From VertexFormat
  16507. 'normal',
  16508. 'st',
  16509. 'binormal',
  16510. 'tangent',
  16511. // From compressing texture coordinates and normals
  16512. 'compressedAttributes'
  16513. ];
  16514. var attributes = geometry.attributes;
  16515. var indices = {};
  16516. var j = 0;
  16517. var i;
  16518. var len = semantics.length;
  16519. // Attribute locations for well-known attributes
  16520. for (i = 0; i < len; ++i) {
  16521. var semantic = semantics[i];
  16522. if (defined(attributes[semantic])) {
  16523. indices[semantic] = j++;
  16524. }
  16525. }
  16526. // Locations for custom attributes
  16527. for (var name in attributes) {
  16528. if (attributes.hasOwnProperty(name) && (!defined(indices[name]))) {
  16529. indices[name] = j++;
  16530. }
  16531. }
  16532. return indices;
  16533. };
  16534. /**
  16535. * Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache.
  16536. *
  16537. * @param {Geometry} geometry The geometry to modify.
  16538. * @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache.
  16539. *
  16540. * @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes.
  16541. *
  16542. *
  16543. * @example
  16544. * geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry);
  16545. *
  16546. * @see GeometryPipeline.reorderForPostVertexCache
  16547. */
  16548. GeometryPipeline.reorderForPreVertexCache = function(geometry) {
  16549. if (!defined(geometry)) {
  16550. throw new DeveloperError('geometry is required.');
  16551. }
  16552. var numVertices = Geometry.computeNumberOfVertices(geometry);
  16553. var indices = geometry.indices;
  16554. if (defined(indices)) {
  16555. var indexCrossReferenceOldToNew = new Int32Array(numVertices);
  16556. for ( var i = 0; i < numVertices; i++) {
  16557. indexCrossReferenceOldToNew[i] = -1;
  16558. }
  16559. // Construct cross reference and reorder indices
  16560. var indicesIn = indices;
  16561. var numIndices = indicesIn.length;
  16562. var indicesOut = IndexDatatype.createTypedArray(numVertices, numIndices);
  16563. var intoIndicesIn = 0;
  16564. var intoIndicesOut = 0;
  16565. var nextIndex = 0;
  16566. var tempIndex;
  16567. while (intoIndicesIn < numIndices) {
  16568. tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
  16569. if (tempIndex !== -1) {
  16570. indicesOut[intoIndicesOut] = tempIndex;
  16571. } else {
  16572. tempIndex = indicesIn[intoIndicesIn];
  16573. indexCrossReferenceOldToNew[tempIndex] = nextIndex;
  16574. indicesOut[intoIndicesOut] = nextIndex;
  16575. ++nextIndex;
  16576. }
  16577. ++intoIndicesIn;
  16578. ++intoIndicesOut;
  16579. }
  16580. geometry.indices = indicesOut;
  16581. // Reorder attributes
  16582. var attributes = geometry.attributes;
  16583. for ( var property in attributes) {
  16584. if (attributes.hasOwnProperty(property) &&
  16585. defined(attributes[property]) &&
  16586. defined(attributes[property].values)) {
  16587. var attribute = attributes[property];
  16588. var elementsIn = attribute.values;
  16589. var intoElementsIn = 0;
  16590. var numComponents = attribute.componentsPerAttribute;
  16591. var elementsOut = ComponentDatatype.createTypedArray(attribute.componentDatatype, nextIndex * numComponents);
  16592. while (intoElementsIn < numVertices) {
  16593. var temp = indexCrossReferenceOldToNew[intoElementsIn];
  16594. if (temp !== -1) {
  16595. for (i = 0; i < numComponents; i++) {
  16596. elementsOut[numComponents * temp + i] = elementsIn[numComponents * intoElementsIn + i];
  16597. }
  16598. }
  16599. ++intoElementsIn;
  16600. }
  16601. attribute.values = elementsOut;
  16602. }
  16603. }
  16604. }
  16605. return geometry;
  16606. };
  16607. /**
  16608. * Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's
  16609. * post vertex-shader cache by using the Tipsify algorithm. If the geometry <code>primitiveType</code>
  16610. * is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect.
  16611. *
  16612. * @param {Geometry} geometry The geometry to modify.
  16613. * @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache.
  16614. * @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache.
  16615. *
  16616. * @exception {DeveloperError} cacheCapacity must be greater than two.
  16617. *
  16618. *
  16619. * @example
  16620. * geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry);
  16621. *
  16622. * @see GeometryPipeline.reorderForPreVertexCache
  16623. * @see {@link http://gfx.cs.princ0eton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw}
  16624. * by Sander, Nehab, and Barczak
  16625. */
  16626. GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) {
  16627. if (!defined(geometry)) {
  16628. throw new DeveloperError('geometry is required.');
  16629. }
  16630. var indices = geometry.indices;
  16631. if ((geometry.primitiveType === PrimitiveType.TRIANGLES) && (defined(indices))) {
  16632. var numIndices = indices.length;
  16633. var maximumIndex = 0;
  16634. for ( var j = 0; j < numIndices; j++) {
  16635. if (indices[j] > maximumIndex) {
  16636. maximumIndex = indices[j];
  16637. }
  16638. }
  16639. geometry.indices = Tipsify.tipsify({
  16640. indices : indices,
  16641. maximumIndex : maximumIndex,
  16642. cacheSize : cacheCapacity
  16643. });
  16644. }
  16645. return geometry;
  16646. };
  16647. function copyAttributesDescriptions(attributes) {
  16648. var newAttributes = {};
  16649. for ( var attribute in attributes) {
  16650. if (attributes.hasOwnProperty(attribute) &&
  16651. defined(attributes[attribute]) &&
  16652. defined(attributes[attribute].values)) {
  16653. var attr = attributes[attribute];
  16654. newAttributes[attribute] = new GeometryAttribute({
  16655. componentDatatype : attr.componentDatatype,
  16656. componentsPerAttribute : attr.componentsPerAttribute,
  16657. normalize : attr.normalize,
  16658. values : []
  16659. });
  16660. }
  16661. }
  16662. return newAttributes;
  16663. }
  16664. function copyVertex(destinationAttributes, sourceAttributes, index) {
  16665. for ( var attribute in sourceAttributes) {
  16666. if (sourceAttributes.hasOwnProperty(attribute) &&
  16667. defined(sourceAttributes[attribute]) &&
  16668. defined(sourceAttributes[attribute].values)) {
  16669. var attr = sourceAttributes[attribute];
  16670. for ( var k = 0; k < attr.componentsPerAttribute; ++k) {
  16671. destinationAttributes[attribute].values.push(attr.values[(index * attr.componentsPerAttribute) + k]);
  16672. }
  16673. }
  16674. }
  16675. }
  16676. /**
  16677. * Splits a geometry into multiple geometries, if necessary, to ensure that indices in the
  16678. * <code>indices</code> fit into unsigned shorts. This is used to meet the WebGL requirements
  16679. * when unsigned int indices are not supported.
  16680. * <p>
  16681. * If the geometry does not have any <code>indices</code>, this function has no effect.
  16682. * </p>
  16683. *
  16684. * @param {Geometry} geometry The geometry to be split into multiple geometries.
  16685. * @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts.
  16686. *
  16687. * @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS
  16688. * @exception {DeveloperError} All geometry attribute lists must have the same number of attributes.
  16689. *
  16690. * @example
  16691. * var geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry);
  16692. */
  16693. GeometryPipeline.fitToUnsignedShortIndices = function(geometry) {
  16694. if (!defined(geometry)) {
  16695. throw new DeveloperError('geometry is required.');
  16696. }
  16697. if ((defined(geometry.indices)) &&
  16698. ((geometry.primitiveType !== PrimitiveType.TRIANGLES) &&
  16699. (geometry.primitiveType !== PrimitiveType.LINES) &&
  16700. (geometry.primitiveType !== PrimitiveType.POINTS))) {
  16701. throw new DeveloperError('geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS.');
  16702. }
  16703. var geometries = [];
  16704. // If there's an index list and more than 64K attributes, it is possible that
  16705. // some indices are outside the range of unsigned short [0, 64K - 1]
  16706. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16707. if (defined(geometry.indices) && (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES)) {
  16708. var oldToNewIndex = [];
  16709. var newIndices = [];
  16710. var currentIndex = 0;
  16711. var newAttributes = copyAttributesDescriptions(geometry.attributes);
  16712. var originalIndices = geometry.indices;
  16713. var numberOfIndices = originalIndices.length;
  16714. var indicesPerPrimitive;
  16715. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  16716. indicesPerPrimitive = 3;
  16717. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  16718. indicesPerPrimitive = 2;
  16719. } else if (geometry.primitiveType === PrimitiveType.POINTS) {
  16720. indicesPerPrimitive = 1;
  16721. }
  16722. for ( var j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
  16723. for (var k = 0; k < indicesPerPrimitive; ++k) {
  16724. var x = originalIndices[j + k];
  16725. var i = oldToNewIndex[x];
  16726. if (!defined(i)) {
  16727. i = currentIndex++;
  16728. oldToNewIndex[x] = i;
  16729. copyVertex(newAttributes, geometry.attributes, x);
  16730. }
  16731. newIndices.push(i);
  16732. }
  16733. if (currentIndex + indicesPerPrimitive >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  16734. geometries.push(new Geometry({
  16735. attributes : newAttributes,
  16736. indices : newIndices,
  16737. primitiveType : geometry.primitiveType,
  16738. boundingSphere : geometry.boundingSphere,
  16739. boundingSphereCV : geometry.boundingSphereCV
  16740. }));
  16741. // Reset for next vertex-array
  16742. oldToNewIndex = [];
  16743. newIndices = [];
  16744. currentIndex = 0;
  16745. newAttributes = copyAttributesDescriptions(geometry.attributes);
  16746. }
  16747. }
  16748. if (newIndices.length !== 0) {
  16749. geometries.push(new Geometry({
  16750. attributes : newAttributes,
  16751. indices : newIndices,
  16752. primitiveType : geometry.primitiveType,
  16753. boundingSphere : geometry.boundingSphere,
  16754. boundingSphereCV : geometry.boundingSphereCV
  16755. }));
  16756. }
  16757. } else {
  16758. // No need to split into multiple geometries
  16759. geometries.push(geometry);
  16760. }
  16761. return geometries;
  16762. };
  16763. var scratchProjectTo2DCartesian3 = new Cartesian3();
  16764. var scratchProjectTo2DCartographic = new Cartographic();
  16765. /**
  16766. * Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code>
  16767. * attribute with separate <code>position3D</code> and <code>position2D</code> attributes.
  16768. * <p>
  16769. * If the geometry does not have a <code>position</code>, this function has no effect.
  16770. * </p>
  16771. *
  16772. * @param {Geometry} geometry The geometry to modify.
  16773. * @param {String} attributeName The name of the attribute.
  16774. * @param {String} attributeName3D The name of the attribute in 3D.
  16775. * @param {String} attributeName2D The name of the attribute in 2D.
  16776. * @param {Object} [projection=new GeographicProjection()] The projection to use.
  16777. * @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes.
  16778. *
  16779. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  16780. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  16781. * @exception {DeveloperError} Could not project a point to 2D.
  16782. *
  16783. * @example
  16784. * geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D');
  16785. */
  16786. GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) {
  16787. if (!defined(geometry)) {
  16788. throw new DeveloperError('geometry is required.');
  16789. }
  16790. if (!defined(attributeName)) {
  16791. throw new DeveloperError('attributeName is required.');
  16792. }
  16793. if (!defined(attributeName3D)) {
  16794. throw new DeveloperError('attributeName3D is required.');
  16795. }
  16796. if (!defined(attributeName2D)) {
  16797. throw new DeveloperError('attributeName2D is required.');
  16798. }
  16799. if (!defined(geometry.attributes[attributeName])) {
  16800. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  16801. }
  16802. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  16803. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  16804. }
  16805. var attribute = geometry.attributes[attributeName];
  16806. projection = (defined(projection)) ? projection : new GeographicProjection();
  16807. var ellipsoid = projection.ellipsoid;
  16808. // Project original values to 2D.
  16809. var values3D = attribute.values;
  16810. var projectedValues = new Float64Array(values3D.length);
  16811. var index = 0;
  16812. for ( var i = 0; i < values3D.length; i += 3) {
  16813. var value = Cartesian3.fromArray(values3D, i, scratchProjectTo2DCartesian3);
  16814. var lonLat = ellipsoid.cartesianToCartographic(value, scratchProjectTo2DCartographic);
  16815. if (!defined(lonLat)) {
  16816. throw new DeveloperError('Could not project point (' + value.x + ', ' + value.y + ', ' + value.z + ') to 2D.');
  16817. }
  16818. var projectedLonLat = projection.project(lonLat, scratchProjectTo2DCartesian3);
  16819. projectedValues[index++] = projectedLonLat.x;
  16820. projectedValues[index++] = projectedLonLat.y;
  16821. projectedValues[index++] = projectedLonLat.z;
  16822. }
  16823. // Rename original cartesians to WGS84 cartesians.
  16824. geometry.attributes[attributeName3D] = attribute;
  16825. // Replace original cartesians with 2D projected cartesians
  16826. geometry.attributes[attributeName2D] = new GeometryAttribute({
  16827. componentDatatype : ComponentDatatype.DOUBLE,
  16828. componentsPerAttribute : 3,
  16829. values : projectedValues
  16830. });
  16831. delete geometry.attributes[attributeName];
  16832. return geometry;
  16833. };
  16834. var encodedResult = {
  16835. high : 0.0,
  16836. low : 0.0
  16837. };
  16838. /**
  16839. * Encodes floating-point geometry attribute values as two separate attributes to improve
  16840. * rendering precision.
  16841. * <p>
  16842. * This is commonly used to create high-precision position vertex attributes.
  16843. * </p>
  16844. *
  16845. * @param {Geometry} geometry The geometry to modify.
  16846. * @param {String} attributeName The name of the attribute.
  16847. * @param {String} attributeHighName The name of the attribute for the encoded high bits.
  16848. * @param {String} attributeLowName The name of the attribute for the encoded low bits.
  16849. * @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute.
  16850. *
  16851. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  16852. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  16853. *
  16854. * @example
  16855. * geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow');
  16856. */
  16857. GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) {
  16858. if (!defined(geometry)) {
  16859. throw new DeveloperError('geometry is required.');
  16860. }
  16861. if (!defined(attributeName)) {
  16862. throw new DeveloperError('attributeName is required.');
  16863. }
  16864. if (!defined(attributeHighName)) {
  16865. throw new DeveloperError('attributeHighName is required.');
  16866. }
  16867. if (!defined(attributeLowName)) {
  16868. throw new DeveloperError('attributeLowName is required.');
  16869. }
  16870. if (!defined(geometry.attributes[attributeName])) {
  16871. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  16872. }
  16873. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  16874. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  16875. }
  16876. var attribute = geometry.attributes[attributeName];
  16877. var values = attribute.values;
  16878. var length = values.length;
  16879. var highValues = new Float32Array(length);
  16880. var lowValues = new Float32Array(length);
  16881. for (var i = 0; i < length; ++i) {
  16882. EncodedCartesian3.encode(values[i], encodedResult);
  16883. highValues[i] = encodedResult.high;
  16884. lowValues[i] = encodedResult.low;
  16885. }
  16886. var componentsPerAttribute = attribute.componentsPerAttribute;
  16887. geometry.attributes[attributeHighName] = new GeometryAttribute({
  16888. componentDatatype : ComponentDatatype.FLOAT,
  16889. componentsPerAttribute : componentsPerAttribute,
  16890. values : highValues
  16891. });
  16892. geometry.attributes[attributeLowName] = new GeometryAttribute({
  16893. componentDatatype : ComponentDatatype.FLOAT,
  16894. componentsPerAttribute : componentsPerAttribute,
  16895. values : lowValues
  16896. });
  16897. delete geometry.attributes[attributeName];
  16898. return geometry;
  16899. };
  16900. var scratchCartesian3 = new Cartesian3();
  16901. function transformPoint(matrix, attribute) {
  16902. if (defined(attribute)) {
  16903. var values = attribute.values;
  16904. var length = values.length;
  16905. for (var i = 0; i < length; i += 3) {
  16906. Cartesian3.unpack(values, i, scratchCartesian3);
  16907. Matrix4.multiplyByPoint(matrix, scratchCartesian3, scratchCartesian3);
  16908. Cartesian3.pack(scratchCartesian3, values, i);
  16909. }
  16910. }
  16911. }
  16912. function transformVector(matrix, attribute) {
  16913. if (defined(attribute)) {
  16914. var values = attribute.values;
  16915. var length = values.length;
  16916. for (var i = 0; i < length; i += 3) {
  16917. Cartesian3.unpack(values, i, scratchCartesian3);
  16918. Matrix3.multiplyByVector(matrix, scratchCartesian3, scratchCartesian3);
  16919. scratchCartesian3 = Cartesian3.normalize(scratchCartesian3, scratchCartesian3);
  16920. Cartesian3.pack(scratchCartesian3, values, i);
  16921. }
  16922. }
  16923. }
  16924. var inverseTranspose = new Matrix4();
  16925. var normalMatrix = new Matrix3();
  16926. /**
  16927. * Transforms a geometry instance to world coordinates. This changes
  16928. * the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the
  16929. * following attributes if they are present: <code>position</code>, <code>normal</code>,
  16930. * <code>binormal</code>, and <code>tangent</code>.
  16931. *
  16932. * @param {GeometryInstance} instance The geometry instance to modify.
  16933. * @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates.
  16934. *
  16935. * @example
  16936. * Cesium.GeometryPipeline.transformToWorldCoordinates(instance);
  16937. */
  16938. GeometryPipeline.transformToWorldCoordinates = function(instance) {
  16939. if (!defined(instance)) {
  16940. throw new DeveloperError('instance is required.');
  16941. }
  16942. var modelMatrix = instance.modelMatrix;
  16943. if (Matrix4.equals(modelMatrix, Matrix4.IDENTITY)) {
  16944. // Already in world coordinates
  16945. return instance;
  16946. }
  16947. var attributes = instance.geometry.attributes;
  16948. // Transform attributes in known vertex formats
  16949. transformPoint(modelMatrix, attributes.position);
  16950. transformPoint(modelMatrix, attributes.prevPosition);
  16951. transformPoint(modelMatrix, attributes.nextPosition);
  16952. if ((defined(attributes.normal)) ||
  16953. (defined(attributes.binormal)) ||
  16954. (defined(attributes.tangent))) {
  16955. Matrix4.inverse(modelMatrix, inverseTranspose);
  16956. Matrix4.transpose(inverseTranspose, inverseTranspose);
  16957. Matrix4.getRotation(inverseTranspose, normalMatrix);
  16958. transformVector(normalMatrix, attributes.normal);
  16959. transformVector(normalMatrix, attributes.binormal);
  16960. transformVector(normalMatrix, attributes.tangent);
  16961. }
  16962. var boundingSphere = instance.geometry.boundingSphere;
  16963. if (defined(boundingSphere)) {
  16964. instance.geometry.boundingSphere = BoundingSphere.transform(boundingSphere, modelMatrix, boundingSphere);
  16965. }
  16966. instance.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
  16967. return instance;
  16968. };
  16969. function findAttributesInAllGeometries(instances, propertyName) {
  16970. var length = instances.length;
  16971. var attributesInAllGeometries = {};
  16972. var attributes0 = instances[0][propertyName].attributes;
  16973. var name;
  16974. for (name in attributes0) {
  16975. if (attributes0.hasOwnProperty(name) &&
  16976. defined(attributes0[name]) &&
  16977. defined(attributes0[name].values)) {
  16978. var attribute = attributes0[name];
  16979. var numberOfComponents = attribute.values.length;
  16980. var inAllGeometries = true;
  16981. // Does this same attribute exist in all geometries?
  16982. for (var i = 1; i < length; ++i) {
  16983. var otherAttribute = instances[i][propertyName].attributes[name];
  16984. if ((!defined(otherAttribute)) ||
  16985. (attribute.componentDatatype !== otherAttribute.componentDatatype) ||
  16986. (attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute) ||
  16987. (attribute.normalize !== otherAttribute.normalize)) {
  16988. inAllGeometries = false;
  16989. break;
  16990. }
  16991. numberOfComponents += otherAttribute.values.length;
  16992. }
  16993. if (inAllGeometries) {
  16994. attributesInAllGeometries[name] = new GeometryAttribute({
  16995. componentDatatype : attribute.componentDatatype,
  16996. componentsPerAttribute : attribute.componentsPerAttribute,
  16997. normalize : attribute.normalize,
  16998. values : ComponentDatatype.createTypedArray(attribute.componentDatatype, numberOfComponents)
  16999. });
  17000. }
  17001. }
  17002. }
  17003. return attributesInAllGeometries;
  17004. }
  17005. var tempScratch = new Cartesian3();
  17006. function combineGeometries(instances, propertyName) {
  17007. var length = instances.length;
  17008. var name;
  17009. var i;
  17010. var j;
  17011. var k;
  17012. var m = instances[0].modelMatrix;
  17013. var haveIndices = (defined(instances[0][propertyName].indices));
  17014. var primitiveType = instances[0][propertyName].primitiveType;
  17015. for (i = 1; i < length; ++i) {
  17016. if (!Matrix4.equals(instances[i].modelMatrix, m)) {
  17017. throw new DeveloperError('All instances must have the same modelMatrix.');
  17018. }
  17019. if ((defined(instances[i][propertyName].indices)) !== haveIndices) {
  17020. throw new DeveloperError('All instance geometries must have an indices or not have one.');
  17021. }
  17022. if (instances[i][propertyName].primitiveType !== primitiveType) {
  17023. throw new DeveloperError('All instance geometries must have the same primitiveType.');
  17024. }
  17025. }
  17026. // Find subset of attributes in all geometries
  17027. var attributes = findAttributesInAllGeometries(instances, propertyName);
  17028. var values;
  17029. var sourceValues;
  17030. var sourceValuesLength;
  17031. // Combine attributes from each geometry into a single typed array
  17032. for (name in attributes) {
  17033. if (attributes.hasOwnProperty(name)) {
  17034. values = attributes[name].values;
  17035. k = 0;
  17036. for (i = 0; i < length; ++i) {
  17037. sourceValues = instances[i][propertyName].attributes[name].values;
  17038. sourceValuesLength = sourceValues.length;
  17039. for (j = 0; j < sourceValuesLength; ++j) {
  17040. values[k++] = sourceValues[j];
  17041. }
  17042. }
  17043. }
  17044. }
  17045. // Combine index lists
  17046. var indices;
  17047. if (haveIndices) {
  17048. var numberOfIndices = 0;
  17049. for (i = 0; i < length; ++i) {
  17050. numberOfIndices += instances[i][propertyName].indices.length;
  17051. }
  17052. var numberOfVertices = Geometry.computeNumberOfVertices(new Geometry({
  17053. attributes : attributes,
  17054. primitiveType : PrimitiveType.POINTS
  17055. }));
  17056. var destIndices = IndexDatatype.createTypedArray(numberOfVertices, numberOfIndices);
  17057. var destOffset = 0;
  17058. var offset = 0;
  17059. for (i = 0; i < length; ++i) {
  17060. var sourceIndices = instances[i][propertyName].indices;
  17061. var sourceIndicesLen = sourceIndices.length;
  17062. for (k = 0; k < sourceIndicesLen; ++k) {
  17063. destIndices[destOffset++] = offset + sourceIndices[k];
  17064. }
  17065. offset += Geometry.computeNumberOfVertices(instances[i][propertyName]);
  17066. }
  17067. indices = destIndices;
  17068. }
  17069. // Create bounding sphere that includes all instances
  17070. var center = new Cartesian3();
  17071. var radius = 0.0;
  17072. var bs;
  17073. for (i = 0; i < length; ++i) {
  17074. bs = instances[i][propertyName].boundingSphere;
  17075. if (!defined(bs)) {
  17076. // If any geometries have an undefined bounding sphere, then so does the combined geometry
  17077. center = undefined;
  17078. break;
  17079. }
  17080. Cartesian3.add(bs.center, center, center);
  17081. }
  17082. if (defined(center)) {
  17083. Cartesian3.divideByScalar(center, length, center);
  17084. for (i = 0; i < length; ++i) {
  17085. bs = instances[i][propertyName].boundingSphere;
  17086. var tempRadius = Cartesian3.magnitude(Cartesian3.subtract(bs.center, center, tempScratch)) + bs.radius;
  17087. if (tempRadius > radius) {
  17088. radius = tempRadius;
  17089. }
  17090. }
  17091. }
  17092. return new Geometry({
  17093. attributes : attributes,
  17094. indices : indices,
  17095. primitiveType : primitiveType,
  17096. boundingSphere : (defined(center)) ? new BoundingSphere(center, radius) : undefined
  17097. });
  17098. }
  17099. /**
  17100. * Combines geometry from several {@link GeometryInstance} objects into one geometry.
  17101. * This concatenates the attributes, concatenates and adjusts the indices, and creates
  17102. * a bounding sphere encompassing all instances.
  17103. * <p>
  17104. * If the instances do not have the same attributes, a subset of attributes common
  17105. * to all instances is used, and the others are ignored.
  17106. * </p>
  17107. * <p>
  17108. * This is used by {@link Primitive} to efficiently render a large amount of static data.
  17109. * </p>
  17110. *
  17111. * @private
  17112. *
  17113. * @param {GeometryInstance[]} [instances] The array of {@link GeometryInstance} objects whose geometry will be combined.
  17114. * @returns {Geometry} A single geometry created from the provided geometry instances.
  17115. *
  17116. * @exception {DeveloperError} All instances must have the same modelMatrix.
  17117. * @exception {DeveloperError} All instance geometries must have an indices or not have one.
  17118. * @exception {DeveloperError} All instance geometries must have the same primitiveType.
  17119. *
  17120. *
  17121. * @example
  17122. * for (var i = 0; i < instances.length; ++i) {
  17123. * Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]);
  17124. * }
  17125. * var geometries = Cesium.GeometryPipeline.combineInstances(instances);
  17126. *
  17127. * @see GeometryPipeline.transformToWorldCoordinates
  17128. */
  17129. GeometryPipeline.combineInstances = function(instances) {
  17130. if ((!defined(instances)) || (instances.length < 1)) {
  17131. throw new DeveloperError('instances is required and must have length greater than zero.');
  17132. }
  17133. var instanceGeometry = [];
  17134. var instanceSplitGeometry = [];
  17135. var length = instances.length;
  17136. for (var i = 0; i < length; ++i) {
  17137. var instance = instances[i];
  17138. if (defined(instance.geometry)) {
  17139. instanceGeometry.push(instance);
  17140. } else if (defined(instance.westHemisphereGeometry) && defined(instance.eastHemisphereGeometry)) {
  17141. instanceSplitGeometry.push(instance);
  17142. }
  17143. }
  17144. var geometries = [];
  17145. if (instanceGeometry.length > 0) {
  17146. geometries.push(combineGeometries(instanceGeometry, 'geometry'));
  17147. }
  17148. if (instanceSplitGeometry.length > 0) {
  17149. geometries.push(combineGeometries(instanceSplitGeometry, 'westHemisphereGeometry'));
  17150. geometries.push(combineGeometries(instanceSplitGeometry, 'eastHemisphereGeometry'));
  17151. }
  17152. return geometries;
  17153. };
  17154. var normal = new Cartesian3();
  17155. var v0 = new Cartesian3();
  17156. var v1 = new Cartesian3();
  17157. var v2 = new Cartesian3();
  17158. /**
  17159. * Computes per-vertex normals for a geometry containing <code>TRIANGLES</code> by averaging the normals of
  17160. * all triangles incident to the vertex. The result is a new <code>normal</code> attribute added to the geometry.
  17161. * This assumes a counter-clockwise winding order.
  17162. *
  17163. * @param {Geometry} geometry The geometry to modify.
  17164. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>normal</code> attribute.
  17165. *
  17166. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  17167. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  17168. *
  17169. * @example
  17170. * Cesium.GeometryPipeline.computeNormal(geometry);
  17171. */
  17172. GeometryPipeline.computeNormal = function(geometry) {
  17173. if (!defined(geometry)) {
  17174. throw new DeveloperError('geometry is required.');
  17175. }
  17176. if (!defined(geometry.attributes.position) || !defined(geometry.attributes.position.values)) {
  17177. throw new DeveloperError('geometry.attributes.position.values is required.');
  17178. }
  17179. if (!defined(geometry.indices)) {
  17180. throw new DeveloperError('geometry.indices is required.');
  17181. }
  17182. if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
  17183. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  17184. }
  17185. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  17186. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  17187. }
  17188. var indices = geometry.indices;
  17189. var attributes = geometry.attributes;
  17190. var vertices = attributes.position.values;
  17191. var numVertices = attributes.position.values.length / 3;
  17192. var numIndices = indices.length;
  17193. var normalsPerVertex = new Array(numVertices);
  17194. var normalsPerTriangle = new Array(numIndices / 3);
  17195. var normalIndices = new Array(numIndices);
  17196. for ( var i = 0; i < numVertices; i++) {
  17197. normalsPerVertex[i] = {
  17198. indexOffset : 0,
  17199. count : 0,
  17200. currentCount : 0
  17201. };
  17202. }
  17203. var j = 0;
  17204. for (i = 0; i < numIndices; i += 3) {
  17205. var i0 = indices[i];
  17206. var i1 = indices[i + 1];
  17207. var i2 = indices[i + 2];
  17208. var i03 = i0 * 3;
  17209. var i13 = i1 * 3;
  17210. var i23 = i2 * 3;
  17211. v0.x = vertices[i03];
  17212. v0.y = vertices[i03 + 1];
  17213. v0.z = vertices[i03 + 2];
  17214. v1.x = vertices[i13];
  17215. v1.y = vertices[i13 + 1];
  17216. v1.z = vertices[i13 + 2];
  17217. v2.x = vertices[i23];
  17218. v2.y = vertices[i23 + 1];
  17219. v2.z = vertices[i23 + 2];
  17220. normalsPerVertex[i0].count++;
  17221. normalsPerVertex[i1].count++;
  17222. normalsPerVertex[i2].count++;
  17223. Cartesian3.subtract(v1, v0, v1);
  17224. Cartesian3.subtract(v2, v0, v2);
  17225. normalsPerTriangle[j] = Cartesian3.cross(v1, v2, new Cartesian3());
  17226. j++;
  17227. }
  17228. var indexOffset = 0;
  17229. for (i = 0; i < numVertices; i++) {
  17230. normalsPerVertex[i].indexOffset += indexOffset;
  17231. indexOffset += normalsPerVertex[i].count;
  17232. }
  17233. j = 0;
  17234. var vertexNormalData;
  17235. for (i = 0; i < numIndices; i += 3) {
  17236. vertexNormalData = normalsPerVertex[indices[i]];
  17237. var index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  17238. normalIndices[index] = j;
  17239. vertexNormalData.currentCount++;
  17240. vertexNormalData = normalsPerVertex[indices[i + 1]];
  17241. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  17242. normalIndices[index] = j;
  17243. vertexNormalData.currentCount++;
  17244. vertexNormalData = normalsPerVertex[indices[i + 2]];
  17245. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  17246. normalIndices[index] = j;
  17247. vertexNormalData.currentCount++;
  17248. j++;
  17249. }
  17250. var normalValues = new Float32Array(numVertices * 3);
  17251. for (i = 0; i < numVertices; i++) {
  17252. var i3 = i * 3;
  17253. vertexNormalData = normalsPerVertex[i];
  17254. if (vertexNormalData.count > 0) {
  17255. Cartesian3.clone(Cartesian3.ZERO, normal);
  17256. for (j = 0; j < vertexNormalData.count; j++) {
  17257. Cartesian3.add(normal, normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]], normal);
  17258. }
  17259. Cartesian3.normalize(normal, normal);
  17260. normalValues[i3] = normal.x;
  17261. normalValues[i3 + 1] = normal.y;
  17262. normalValues[i3 + 2] = normal.z;
  17263. } else {
  17264. normalValues[i3] = 0.0;
  17265. normalValues[i3 + 1] = 0.0;
  17266. normalValues[i3 + 2] = 1.0;
  17267. }
  17268. }
  17269. geometry.attributes.normal = new GeometryAttribute({
  17270. componentDatatype : ComponentDatatype.FLOAT,
  17271. componentsPerAttribute : 3,
  17272. values : normalValues
  17273. });
  17274. return geometry;
  17275. };
  17276. var normalScratch = new Cartesian3();
  17277. var normalScale = new Cartesian3();
  17278. var tScratch = new Cartesian3();
  17279. /**
  17280. * Computes per-vertex binormals and tangents for a geometry containing <code>TRIANGLES</code>.
  17281. * The result is new <code>binormal</code> and <code>tangent</code> attributes added to the geometry.
  17282. * This assumes a counter-clockwise winding order.
  17283. * <p>
  17284. * Based on <a href="http://www.terathon.com/code/tangent.html">Computing Tangent Space Basis Vectors
  17285. * for an Arbitrary Mesh</a> by Eric Lengyel.
  17286. * </p>
  17287. *
  17288. * @param {Geometry} geometry The geometry to modify.
  17289. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>binormal</code> and <code>tangent</code> attributes.
  17290. *
  17291. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  17292. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  17293. *
  17294. * @example
  17295. * Cesium.GeometryPipeline.computeBinormalAndTangent(geometry);
  17296. */
  17297. GeometryPipeline.computeBinormalAndTangent = function(geometry) {
  17298. if (!defined(geometry)) {
  17299. throw new DeveloperError('geometry is required.');
  17300. }
  17301. var attributes = geometry.attributes;
  17302. var indices = geometry.indices;
  17303. if (!defined(attributes.position) || !defined(attributes.position.values)) {
  17304. throw new DeveloperError('geometry.attributes.position.values is required.');
  17305. }
  17306. if (!defined(attributes.normal) || !defined(attributes.normal.values)) {
  17307. throw new DeveloperError('geometry.attributes.normal.values is required.');
  17308. }
  17309. if (!defined(attributes.st) || !defined(attributes.st.values)) {
  17310. throw new DeveloperError('geometry.attributes.st.values is required.');
  17311. }
  17312. if (!defined(indices)) {
  17313. throw new DeveloperError('geometry.indices is required.');
  17314. }
  17315. if (indices.length < 2 || indices.length % 3 !== 0) {
  17316. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  17317. }
  17318. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  17319. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  17320. }
  17321. var vertices = geometry.attributes.position.values;
  17322. var normals = geometry.attributes.normal.values;
  17323. var st = geometry.attributes.st.values;
  17324. var numVertices = geometry.attributes.position.values.length / 3;
  17325. var numIndices = indices.length;
  17326. var tan1 = new Array(numVertices * 3);
  17327. for ( var i = 0; i < tan1.length; i++) {
  17328. tan1[i] = 0;
  17329. }
  17330. var i03;
  17331. var i13;
  17332. var i23;
  17333. for (i = 0; i < numIndices; i += 3) {
  17334. var i0 = indices[i];
  17335. var i1 = indices[i + 1];
  17336. var i2 = indices[i + 2];
  17337. i03 = i0 * 3;
  17338. i13 = i1 * 3;
  17339. i23 = i2 * 3;
  17340. var i02 = i0 * 2;
  17341. var i12 = i1 * 2;
  17342. var i22 = i2 * 2;
  17343. var ux = vertices[i03];
  17344. var uy = vertices[i03 + 1];
  17345. var uz = vertices[i03 + 2];
  17346. var wx = st[i02];
  17347. var wy = st[i02 + 1];
  17348. var t1 = st[i12 + 1] - wy;
  17349. var t2 = st[i22 + 1] - wy;
  17350. var r = 1.0 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
  17351. var sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r;
  17352. var sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r;
  17353. var sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r;
  17354. tan1[i03] += sdirx;
  17355. tan1[i03 + 1] += sdiry;
  17356. tan1[i03 + 2] += sdirz;
  17357. tan1[i13] += sdirx;
  17358. tan1[i13 + 1] += sdiry;
  17359. tan1[i13 + 2] += sdirz;
  17360. tan1[i23] += sdirx;
  17361. tan1[i23 + 1] += sdiry;
  17362. tan1[i23 + 2] += sdirz;
  17363. }
  17364. var binormalValues = new Float32Array(numVertices * 3);
  17365. var tangentValues = new Float32Array(numVertices * 3);
  17366. for (i = 0; i < numVertices; i++) {
  17367. i03 = i * 3;
  17368. i13 = i03 + 1;
  17369. i23 = i03 + 2;
  17370. var n = Cartesian3.fromArray(normals, i03, normalScratch);
  17371. var t = Cartesian3.fromArray(tan1, i03, tScratch);
  17372. var scalar = Cartesian3.dot(n, t);
  17373. Cartesian3.multiplyByScalar(n, scalar, normalScale);
  17374. Cartesian3.normalize(Cartesian3.subtract(t, normalScale, t), t);
  17375. tangentValues[i03] = t.x;
  17376. tangentValues[i13] = t.y;
  17377. tangentValues[i23] = t.z;
  17378. Cartesian3.normalize(Cartesian3.cross(n, t, t), t);
  17379. binormalValues[i03] = t.x;
  17380. binormalValues[i13] = t.y;
  17381. binormalValues[i23] = t.z;
  17382. }
  17383. geometry.attributes.tangent = new GeometryAttribute({
  17384. componentDatatype : ComponentDatatype.FLOAT,
  17385. componentsPerAttribute : 3,
  17386. values : tangentValues
  17387. });
  17388. geometry.attributes.binormal = new GeometryAttribute({
  17389. componentDatatype : ComponentDatatype.FLOAT,
  17390. componentsPerAttribute : 3,
  17391. values : binormalValues
  17392. });
  17393. return geometry;
  17394. };
  17395. var scratchCartesian2 = new Cartesian2();
  17396. var toEncode1 = new Cartesian3();
  17397. var toEncode2 = new Cartesian3();
  17398. var toEncode3 = new Cartesian3();
  17399. /**
  17400. * Compresses and packs geometry normal attribute values to save memory.
  17401. *
  17402. * @param {Geometry} geometry The geometry to modify.
  17403. * @returns {Geometry} The modified <code>geometry</code> argument, with its normals compressed and packed.
  17404. *
  17405. * @example
  17406. * geometry = Cesium.GeometryPipeline.compressVertices(geometry);
  17407. */
  17408. GeometryPipeline.compressVertices = function(geometry) {
  17409. if (!defined(geometry)) {
  17410. throw new DeveloperError('geometry is required.');
  17411. }
  17412. var normalAttribute = geometry.attributes.normal;
  17413. var stAttribute = geometry.attributes.st;
  17414. if (!defined(normalAttribute) && !defined(stAttribute)) {
  17415. return geometry;
  17416. }
  17417. var tangentAttribute = geometry.attributes.tangent;
  17418. var binormalAttribute = geometry.attributes.binormal;
  17419. var normals;
  17420. var st;
  17421. var tangents;
  17422. var binormals;
  17423. if (defined(normalAttribute)) {
  17424. normals = normalAttribute.values;
  17425. }
  17426. if (defined(stAttribute)) {
  17427. st = stAttribute.values;
  17428. }
  17429. if (defined(tangentAttribute)) {
  17430. tangents = tangentAttribute.values;
  17431. }
  17432. if (binormalAttribute) {
  17433. binormals = binormalAttribute.values;
  17434. }
  17435. var length = defined(normals) ? normals.length : st.length;
  17436. var numComponents = defined(normals) ? 3.0 : 2.0;
  17437. var numVertices = length / numComponents;
  17438. var compressedLength = numVertices;
  17439. var numCompressedComponents = defined(st) && defined(normals) ? 2.0 : 1.0;
  17440. numCompressedComponents += defined(tangents) || defined(binormals) ? 1.0 : 0.0;
  17441. compressedLength *= numCompressedComponents;
  17442. var compressedAttributes = new Float32Array(compressedLength);
  17443. var normalIndex = 0;
  17444. for (var i = 0; i < numVertices; ++i) {
  17445. if (defined(st)) {
  17446. Cartesian2.fromArray(st, i * 2.0, scratchCartesian2);
  17447. compressedAttributes[normalIndex++] = AttributeCompression.compressTextureCoordinates(scratchCartesian2);
  17448. }
  17449. var index = i * 3.0;
  17450. if (defined(normals) && defined(tangents) && defined(binormals)) {
  17451. Cartesian3.fromArray(normals, index, toEncode1);
  17452. Cartesian3.fromArray(tangents, index, toEncode2);
  17453. Cartesian3.fromArray(binormals, index, toEncode3);
  17454. AttributeCompression.octPack(toEncode1, toEncode2, toEncode3, scratchCartesian2);
  17455. compressedAttributes[normalIndex++] = scratchCartesian2.x;
  17456. compressedAttributes[normalIndex++] = scratchCartesian2.y;
  17457. } else {
  17458. if (defined(normals)) {
  17459. Cartesian3.fromArray(normals, index, toEncode1);
  17460. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  17461. }
  17462. if (defined(tangents)) {
  17463. Cartesian3.fromArray(tangents, index, toEncode1);
  17464. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  17465. }
  17466. if (defined(binormals)) {
  17467. Cartesian3.fromArray(binormals, index, toEncode1);
  17468. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  17469. }
  17470. }
  17471. }
  17472. geometry.attributes.compressedAttributes = new GeometryAttribute({
  17473. componentDatatype : ComponentDatatype.FLOAT,
  17474. componentsPerAttribute : numCompressedComponents,
  17475. values : compressedAttributes
  17476. });
  17477. if (defined(normals)) {
  17478. delete geometry.attributes.normal;
  17479. }
  17480. if (defined(st)) {
  17481. delete geometry.attributes.st;
  17482. }
  17483. if (defined(tangents)) {
  17484. delete geometry.attributes.tangent;
  17485. }
  17486. if (defined(binormals)) {
  17487. delete geometry.attributes.binormal;
  17488. }
  17489. return geometry;
  17490. };
  17491. function indexTriangles(geometry) {
  17492. if (defined(geometry.indices)) {
  17493. return geometry;
  17494. }
  17495. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17496. if (numberOfVertices < 3) {
  17497. throw new DeveloperError('The number of vertices must be at least three.');
  17498. }
  17499. if (numberOfVertices % 3 !== 0) {
  17500. throw new DeveloperError('The number of vertices must be a multiple of three.');
  17501. }
  17502. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  17503. for (var i = 0; i < numberOfVertices; ++i) {
  17504. indices[i] = i;
  17505. }
  17506. geometry.indices = indices;
  17507. return geometry;
  17508. }
  17509. function indexTriangleFan(geometry) {
  17510. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17511. if (numberOfVertices < 3) {
  17512. throw new DeveloperError('The number of vertices must be at least three.');
  17513. }
  17514. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  17515. indices[0] = 1;
  17516. indices[1] = 0;
  17517. indices[2] = 2;
  17518. var indicesIndex = 3;
  17519. for (var i = 3; i < numberOfVertices; ++i) {
  17520. indices[indicesIndex++] = i - 1;
  17521. indices[indicesIndex++] = 0;
  17522. indices[indicesIndex++] = i;
  17523. }
  17524. geometry.indices = indices;
  17525. geometry.primitiveType = PrimitiveType.TRIANGLES;
  17526. return geometry;
  17527. }
  17528. function indexTriangleStrip(geometry) {
  17529. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17530. if (numberOfVertices < 3) {
  17531. throw new DeveloperError('The number of vertices must be at least 3.');
  17532. }
  17533. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  17534. indices[0] = 0;
  17535. indices[1] = 1;
  17536. indices[2] = 2;
  17537. if (numberOfVertices > 3) {
  17538. indices[3] = 0;
  17539. indices[4] = 2;
  17540. indices[5] = 3;
  17541. }
  17542. var indicesIndex = 6;
  17543. for (var i = 3; i < numberOfVertices - 1; i += 2) {
  17544. indices[indicesIndex++] = i;
  17545. indices[indicesIndex++] = i - 1;
  17546. indices[indicesIndex++] = i + 1;
  17547. if (i + 2 < numberOfVertices) {
  17548. indices[indicesIndex++] = i;
  17549. indices[indicesIndex++] = i + 1;
  17550. indices[indicesIndex++] = i + 2;
  17551. }
  17552. }
  17553. geometry.indices = indices;
  17554. geometry.primitiveType = PrimitiveType.TRIANGLES;
  17555. return geometry;
  17556. }
  17557. function indexLines(geometry) {
  17558. if (defined(geometry.indices)) {
  17559. return geometry;
  17560. }
  17561. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17562. if (numberOfVertices < 2) {
  17563. throw new DeveloperError('The number of vertices must be at least two.');
  17564. }
  17565. if (numberOfVertices % 2 !== 0) {
  17566. throw new DeveloperError('The number of vertices must be a multiple of 2.');
  17567. }
  17568. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  17569. for (var i = 0; i < numberOfVertices; ++i) {
  17570. indices[i] = i;
  17571. }
  17572. geometry.indices = indices;
  17573. return geometry;
  17574. }
  17575. function indexLineStrip(geometry) {
  17576. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17577. if (numberOfVertices < 2) {
  17578. throw new DeveloperError('The number of vertices must be at least two.');
  17579. }
  17580. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 1) * 2);
  17581. indices[0] = 0;
  17582. indices[1] = 1;
  17583. var indicesIndex = 2;
  17584. for (var i = 2; i < numberOfVertices; ++i) {
  17585. indices[indicesIndex++] = i - 1;
  17586. indices[indicesIndex++] = i;
  17587. }
  17588. geometry.indices = indices;
  17589. geometry.primitiveType = PrimitiveType.LINES;
  17590. return geometry;
  17591. }
  17592. function indexLineLoop(geometry) {
  17593. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17594. if (numberOfVertices < 2) {
  17595. throw new DeveloperError('The number of vertices must be at least two.');
  17596. }
  17597. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices * 2);
  17598. indices[0] = 0;
  17599. indices[1] = 1;
  17600. var indicesIndex = 2;
  17601. for (var i = 2; i < numberOfVertices; ++i) {
  17602. indices[indicesIndex++] = i - 1;
  17603. indices[indicesIndex++] = i;
  17604. }
  17605. indices[indicesIndex++] = numberOfVertices - 1;
  17606. indices[indicesIndex] = 0;
  17607. geometry.indices = indices;
  17608. geometry.primitiveType = PrimitiveType.LINES;
  17609. return geometry;
  17610. }
  17611. function indexPrimitive(geometry) {
  17612. switch (geometry.primitiveType) {
  17613. case PrimitiveType.TRIANGLE_FAN:
  17614. return indexTriangleFan(geometry);
  17615. case PrimitiveType.TRIANGLE_STRIP:
  17616. return indexTriangleStrip(geometry);
  17617. case PrimitiveType.TRIANGLES:
  17618. return indexTriangles(geometry);
  17619. case PrimitiveType.LINE_STRIP:
  17620. return indexLineStrip(geometry);
  17621. case PrimitiveType.LINE_LOOP:
  17622. return indexLineLoop(geometry);
  17623. case PrimitiveType.LINES:
  17624. return indexLines(geometry);
  17625. }
  17626. return geometry;
  17627. }
  17628. function offsetPointFromXZPlane(p, isBehind) {
  17629. if (Math.abs(p.y) < CesiumMath.EPSILON6){
  17630. if (isBehind) {
  17631. p.y = -CesiumMath.EPSILON6;
  17632. } else {
  17633. p.y = CesiumMath.EPSILON6;
  17634. }
  17635. }
  17636. }
  17637. function offsetTriangleFromXZPlane(p0, p1, p2) {
  17638. if (p0.y !== 0.0 && p1.y !== 0.0 && p2.y !== 0.0) {
  17639. offsetPointFromXZPlane(p0, p0.y < 0.0);
  17640. offsetPointFromXZPlane(p1, p1.y < 0.0);
  17641. offsetPointFromXZPlane(p2, p2.y < 0.0);
  17642. return;
  17643. }
  17644. var p0y = Math.abs(p0.y);
  17645. var p1y = Math.abs(p1.y);
  17646. var p2y = Math.abs(p2.y);
  17647. var sign;
  17648. if (p0y > p1y) {
  17649. if (p0y > p2y) {
  17650. sign = CesiumMath.sign(p0.y);
  17651. } else {
  17652. sign = CesiumMath.sign(p2.y);
  17653. }
  17654. } else if (p1y > p2y) {
  17655. sign = CesiumMath.sign(p1.y);
  17656. } else {
  17657. sign = CesiumMath.sign(p2.y);
  17658. }
  17659. var isBehind = sign < 0.0;
  17660. offsetPointFromXZPlane(p0, isBehind);
  17661. offsetPointFromXZPlane(p1, isBehind);
  17662. offsetPointFromXZPlane(p2, isBehind);
  17663. }
  17664. var c3 = new Cartesian3();
  17665. function getXZIntersectionOffsetPoints(p, p1, u1, v1) {
  17666. Cartesian3.add(p, Cartesian3.multiplyByScalar(Cartesian3.subtract(p1, p, c3), p.y/(p.y-p1.y), c3), u1);
  17667. Cartesian3.clone(u1, v1);
  17668. offsetPointFromXZPlane(u1, true);
  17669. offsetPointFromXZPlane(v1, false);
  17670. }
  17671. var u1 = new Cartesian3();
  17672. var u2 = new Cartesian3();
  17673. var q1 = new Cartesian3();
  17674. var q2 = new Cartesian3();
  17675. var splitTriangleResult = {
  17676. positions : new Array(7),
  17677. indices : new Array(3 * 3)
  17678. };
  17679. function splitTriangle(p0, p1, p2) {
  17680. // In WGS84 coordinates, for a triangle approximately on the
  17681. // ellipsoid to cross the IDL, first it needs to be on the
  17682. // negative side of the plane x = 0.
  17683. if ((p0.x >= 0.0) || (p1.x >= 0.0) || (p2.x >= 0.0)) {
  17684. return undefined;
  17685. }
  17686. offsetTriangleFromXZPlane(p0, p1, p2);
  17687. var p0Behind = p0.y < 0.0;
  17688. var p1Behind = p1.y < 0.0;
  17689. var p2Behind = p2.y < 0.0;
  17690. var numBehind = 0;
  17691. numBehind += p0Behind ? 1 : 0;
  17692. numBehind += p1Behind ? 1 : 0;
  17693. numBehind += p2Behind ? 1 : 0;
  17694. var indices = splitTriangleResult.indices;
  17695. if (numBehind === 1) {
  17696. indices[1] = 3;
  17697. indices[2] = 4;
  17698. indices[5] = 6;
  17699. indices[7] = 6;
  17700. indices[8] = 5;
  17701. if (p0Behind) {
  17702. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  17703. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  17704. indices[0] = 0;
  17705. indices[3] = 1;
  17706. indices[4] = 2;
  17707. indices[6] = 1;
  17708. } else if (p1Behind) {
  17709. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  17710. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  17711. indices[0] = 1;
  17712. indices[3] = 2;
  17713. indices[4] = 0;
  17714. indices[6] = 2;
  17715. } else if (p2Behind) {
  17716. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  17717. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  17718. indices[0] = 2;
  17719. indices[3] = 0;
  17720. indices[4] = 1;
  17721. indices[6] = 0;
  17722. }
  17723. } else if (numBehind === 2) {
  17724. indices[2] = 4;
  17725. indices[4] = 4;
  17726. indices[5] = 3;
  17727. indices[7] = 5;
  17728. indices[8] = 6;
  17729. if (!p0Behind) {
  17730. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  17731. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  17732. indices[0] = 1;
  17733. indices[1] = 2;
  17734. indices[3] = 1;
  17735. indices[6] = 0;
  17736. } else if (!p1Behind) {
  17737. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  17738. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  17739. indices[0] = 2;
  17740. indices[1] = 0;
  17741. indices[3] = 2;
  17742. indices[6] = 1;
  17743. } else if (!p2Behind) {
  17744. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  17745. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  17746. indices[0] = 0;
  17747. indices[1] = 1;
  17748. indices[3] = 0;
  17749. indices[6] = 2;
  17750. }
  17751. }
  17752. var positions = splitTriangleResult.positions;
  17753. positions[0] = p0;
  17754. positions[1] = p1;
  17755. positions[2] = p2;
  17756. positions.length = 3;
  17757. if (numBehind === 1 || numBehind === 2) {
  17758. positions[3] = u1;
  17759. positions[4] = u2;
  17760. positions[5] = q1;
  17761. positions[6] = q2;
  17762. positions.length = 7;
  17763. }
  17764. return splitTriangleResult;
  17765. }
  17766. function updateGeometryAfterSplit(geometry, computeBoundingSphere) {
  17767. var attributes = geometry.attributes;
  17768. if (attributes.position.values.length === 0) {
  17769. return undefined;
  17770. }
  17771. for (var property in attributes) {
  17772. if (attributes.hasOwnProperty(property) &&
  17773. defined(attributes[property]) &&
  17774. defined(attributes[property].values)) {
  17775. var attribute = attributes[property];
  17776. attribute.values = ComponentDatatype.createTypedArray(attribute.componentDatatype, attribute.values);
  17777. }
  17778. }
  17779. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  17780. geometry.indices = IndexDatatype.createTypedArray(numberOfVertices, geometry.indices);
  17781. if (computeBoundingSphere) {
  17782. geometry.boundingSphere = BoundingSphere.fromVertices(attributes.position.values);
  17783. }
  17784. return geometry;
  17785. }
  17786. function copyGeometryForSplit(geometry) {
  17787. var attributes = geometry.attributes;
  17788. var copiedAttributes = {};
  17789. for (var property in attributes) {
  17790. if (attributes.hasOwnProperty(property) &&
  17791. defined(attributes[property]) &&
  17792. defined(attributes[property].values)) {
  17793. var attribute = attributes[property];
  17794. copiedAttributes[property] = new GeometryAttribute({
  17795. componentDatatype : attribute.componentDatatype,
  17796. componentsPerAttribute : attribute.componentsPerAttribute,
  17797. normalize : attribute.normalize,
  17798. values : []
  17799. });
  17800. }
  17801. }
  17802. return new Geometry({
  17803. attributes : copiedAttributes,
  17804. indices : [],
  17805. primitiveType : geometry.primitiveType
  17806. });
  17807. }
  17808. function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
  17809. var computeBoundingSphere = defined(instance.geometry.boundingSphere);
  17810. westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
  17811. eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);
  17812. if (defined(eastGeometry) && !defined(westGeometry)) {
  17813. instance.geometry = eastGeometry;
  17814. } else if (!defined(eastGeometry) && defined(westGeometry)) {
  17815. instance.geometry = westGeometry;
  17816. } else {
  17817. instance.westHemisphereGeometry = westGeometry;
  17818. instance.eastHemisphereGeometry = eastGeometry;
  17819. instance.geometry = undefined;
  17820. }
  17821. }
  17822. var p0Scratch = new Cartesian3();
  17823. var p1Scratch = new Cartesian3();
  17824. var p2Scratch = new Cartesian3();
  17825. var barycentricScratch = new Cartesian3();
  17826. var s0Scratch = new Cartesian2();
  17827. var s1Scratch = new Cartesian2();
  17828. var s2Scratch = new Cartesian2();
  17829. function computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex) {
  17830. if (!defined(normals) && !defined(binormals) && !defined(tangents) && !defined(texCoords)) {
  17831. return;
  17832. }
  17833. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  17834. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  17835. var p2 = Cartesian3.fromArray(positions, i2 * 3, p2Scratch);
  17836. var coords = barycentricCoordinates(point, p0, p1, p2, barycentricScratch);
  17837. if (defined(normals)) {
  17838. var n0 = Cartesian3.fromArray(normals, i0 * 3, p0Scratch);
  17839. var n1 = Cartesian3.fromArray(normals, i1 * 3, p1Scratch);
  17840. var n2 = Cartesian3.fromArray(normals, i2 * 3, p2Scratch);
  17841. Cartesian3.multiplyByScalar(n0, coords.x, n0);
  17842. Cartesian3.multiplyByScalar(n1, coords.y, n1);
  17843. Cartesian3.multiplyByScalar(n2, coords.z, n2);
  17844. var normal = Cartesian3.add(n0, n1, n0);
  17845. Cartesian3.add(normal, n2, normal);
  17846. Cartesian3.normalize(normal, normal);
  17847. Cartesian3.pack(normal, currentAttributes.normal.values, insertedIndex * 3);
  17848. }
  17849. if (defined(binormals)) {
  17850. var b0 = Cartesian3.fromArray(binormals, i0 * 3, p0Scratch);
  17851. var b1 = Cartesian3.fromArray(binormals, i1 * 3, p1Scratch);
  17852. var b2 = Cartesian3.fromArray(binormals, i2 * 3, p2Scratch);
  17853. Cartesian3.multiplyByScalar(b0, coords.x, b0);
  17854. Cartesian3.multiplyByScalar(b1, coords.y, b1);
  17855. Cartesian3.multiplyByScalar(b2, coords.z, b2);
  17856. var binormal = Cartesian3.add(b0, b1, b0);
  17857. Cartesian3.add(binormal, b2, binormal);
  17858. Cartesian3.normalize(binormal, binormal);
  17859. Cartesian3.pack(binormal, currentAttributes.binormal.values, insertedIndex * 3);
  17860. }
  17861. if (defined(tangents)) {
  17862. var t0 = Cartesian3.fromArray(tangents, i0 * 3, p0Scratch);
  17863. var t1 = Cartesian3.fromArray(tangents, i1 * 3, p1Scratch);
  17864. var t2 = Cartesian3.fromArray(tangents, i2 * 3, p2Scratch);
  17865. Cartesian3.multiplyByScalar(t0, coords.x, t0);
  17866. Cartesian3.multiplyByScalar(t1, coords.y, t1);
  17867. Cartesian3.multiplyByScalar(t2, coords.z, t2);
  17868. var tangent = Cartesian3.add(t0, t1, t0);
  17869. Cartesian3.add(tangent, t2, tangent);
  17870. Cartesian3.normalize(tangent, tangent);
  17871. Cartesian3.pack(tangent, currentAttributes.tangent.values, insertedIndex * 3);
  17872. }
  17873. if (defined(texCoords)) {
  17874. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, s0Scratch);
  17875. var s1 = Cartesian2.fromArray(texCoords, i1 * 2, s1Scratch);
  17876. var s2 = Cartesian2.fromArray(texCoords, i2 * 2, s2Scratch);
  17877. Cartesian2.multiplyByScalar(s0, coords.x, s0);
  17878. Cartesian2.multiplyByScalar(s1, coords.y, s1);
  17879. Cartesian2.multiplyByScalar(s2, coords.z, s2);
  17880. var texCoord = Cartesian2.add(s0, s1, s0);
  17881. Cartesian2.add(texCoord, s2, texCoord);
  17882. Cartesian2.pack(texCoord, currentAttributes.st.values, insertedIndex * 2);
  17883. }
  17884. }
  17885. function insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, currentIndex, point) {
  17886. var insertIndex = currentAttributes.position.values.length / 3;
  17887. if (currentIndex !== -1) {
  17888. var prevIndex = indices[currentIndex];
  17889. var newIndex = currentIndexMap[prevIndex];
  17890. if (newIndex === -1) {
  17891. currentIndexMap[prevIndex] = insertIndex;
  17892. currentAttributes.position.values.push(point.x, point.y, point.z);
  17893. currentIndices.push(insertIndex);
  17894. return insertIndex;
  17895. }
  17896. currentIndices.push(newIndex);
  17897. return newIndex;
  17898. }
  17899. currentAttributes.position.values.push(point.x, point.y, point.z);
  17900. currentIndices.push(insertIndex);
  17901. return insertIndex;
  17902. }
  17903. function splitLongitudeTriangles(instance) {
  17904. var geometry = instance.geometry;
  17905. var attributes = geometry.attributes;
  17906. var positions = attributes.position.values;
  17907. var normals = (defined(attributes.normal)) ? attributes.normal.values : undefined;
  17908. var binormals = (defined(attributes.binormal)) ? attributes.binormal.values : undefined;
  17909. var tangents = (defined(attributes.tangent)) ? attributes.tangent.values : undefined;
  17910. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  17911. var indices = geometry.indices;
  17912. var eastGeometry = copyGeometryForSplit(geometry);
  17913. var westGeometry = copyGeometryForSplit(geometry);
  17914. var currentAttributes;
  17915. var currentIndices;
  17916. var currentIndexMap;
  17917. var insertedIndex;
  17918. var i;
  17919. var westGeometryIndexMap = [];
  17920. westGeometryIndexMap.length = positions.length / 3;
  17921. var eastGeometryIndexMap = [];
  17922. eastGeometryIndexMap.length = positions.length / 3;
  17923. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  17924. westGeometryIndexMap[i] = -1;
  17925. eastGeometryIndexMap[i] = -1;
  17926. }
  17927. var len = indices.length;
  17928. for (i = 0; i < len; i += 3) {
  17929. var i0 = indices[i];
  17930. var i1 = indices[i + 1];
  17931. var i2 = indices[i + 2];
  17932. var p0 = Cartesian3.fromArray(positions, i0 * 3);
  17933. var p1 = Cartesian3.fromArray(positions, i1 * 3);
  17934. var p2 = Cartesian3.fromArray(positions, i2 * 3);
  17935. var result = splitTriangle(p0, p1, p2);
  17936. if (defined(result) && result.positions.length > 3) {
  17937. var resultPositions = result.positions;
  17938. var resultIndices = result.indices;
  17939. var resultLength = resultIndices.length;
  17940. for (var j = 0; j < resultLength; ++j) {
  17941. var resultIndex = resultIndices[j];
  17942. var point = resultPositions[resultIndex];
  17943. if (point.y < 0.0) {
  17944. currentAttributes = westGeometry.attributes;
  17945. currentIndices = westGeometry.indices;
  17946. currentIndexMap = westGeometryIndexMap;
  17947. } else {
  17948. currentAttributes = eastGeometry.attributes;
  17949. currentIndices = eastGeometry.indices;
  17950. currentIndexMap = eastGeometryIndexMap;
  17951. }
  17952. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, resultIndex < 3 ? i + resultIndex : -1, point);
  17953. computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17954. }
  17955. } else {
  17956. if (defined(result)) {
  17957. p0 = result.positions[0];
  17958. p1 = result.positions[1];
  17959. p2 = result.positions[2];
  17960. }
  17961. if (p0.y < 0.0) {
  17962. currentAttributes = westGeometry.attributes;
  17963. currentIndices = westGeometry.indices;
  17964. currentIndexMap = westGeometryIndexMap;
  17965. } else {
  17966. currentAttributes = eastGeometry.attributes;
  17967. currentIndices = eastGeometry.indices;
  17968. currentIndexMap = eastGeometryIndexMap;
  17969. }
  17970. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  17971. computeTriangleAttributes(i0, i1, i2, p0, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17972. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  17973. computeTriangleAttributes(i0, i1, i2, p1, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17974. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 2, p2);
  17975. computeTriangleAttributes(i0, i1, i2, p2, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17976. }
  17977. }
  17978. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  17979. }
  17980. var xzPlane = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y);
  17981. var offsetScratch = new Cartesian3();
  17982. var offsetPointScratch = new Cartesian3();
  17983. function splitLongitudeLines(instance) {
  17984. var geometry = instance.geometry;
  17985. var attributes = geometry.attributes;
  17986. var positions = attributes.position.values;
  17987. var indices = geometry.indices;
  17988. var eastGeometry = copyGeometryForSplit(geometry);
  17989. var westGeometry = copyGeometryForSplit(geometry);
  17990. var i;
  17991. var length = indices.length;
  17992. var westGeometryIndexMap = [];
  17993. westGeometryIndexMap.length = positions.length / 3;
  17994. var eastGeometryIndexMap = [];
  17995. eastGeometryIndexMap.length = positions.length / 3;
  17996. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  17997. westGeometryIndexMap[i] = -1;
  17998. eastGeometryIndexMap[i] = -1;
  17999. }
  18000. for (i = 0; i < length; i += 2) {
  18001. var i0 = indices[i];
  18002. var i1 = indices[i + 1];
  18003. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  18004. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  18005. if (Math.abs(p0.y) < CesiumMath.EPSILON6){
  18006. if (p0.y < 0.0) {
  18007. p0.y = -CesiumMath.EPSILON6;
  18008. } else {
  18009. p0.y = CesiumMath.EPSILON6;
  18010. }
  18011. }
  18012. if (Math.abs(p1.y) < CesiumMath.EPSILON6){
  18013. if (p1.y < 0.0) {
  18014. p1.y = -CesiumMath.EPSILON6;
  18015. } else {
  18016. p1.y = CesiumMath.EPSILON6;
  18017. }
  18018. }
  18019. var p0Attributes = eastGeometry.attributes;
  18020. var p0Indices = eastGeometry.indices;
  18021. var p0IndexMap = eastGeometryIndexMap;
  18022. var p1Attributes = westGeometry.attributes;
  18023. var p1Indices = westGeometry.indices;
  18024. var p1IndexMap = westGeometryIndexMap;
  18025. var intersection = IntersectionTests.lineSegmentPlane(p0, p1, xzPlane, p2Scratch);
  18026. if (defined(intersection)) {
  18027. // move point on the xz-plane slightly away from the plane
  18028. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, 5.0 * CesiumMath.EPSILON9, offsetScratch);
  18029. if (p0.y < 0.0) {
  18030. Cartesian3.negate(offset, offset);
  18031. p0Attributes = westGeometry.attributes;
  18032. p0Indices = westGeometry.indices;
  18033. p0IndexMap = westGeometryIndexMap;
  18034. p1Attributes = eastGeometry.attributes;
  18035. p1Indices = eastGeometry.indices;
  18036. p1IndexMap = eastGeometryIndexMap;
  18037. }
  18038. var offsetPoint = Cartesian3.add(intersection, offset, offsetPointScratch);
  18039. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, i, p0);
  18040. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, -1, offsetPoint);
  18041. Cartesian3.negate(offset, offset);
  18042. Cartesian3.add(intersection, offset, offsetPoint);
  18043. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, -1, offsetPoint);
  18044. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, i + 1, p1);
  18045. } else {
  18046. var currentAttributes;
  18047. var currentIndices;
  18048. var currentIndexMap;
  18049. if (p0.y < 0.0) {
  18050. currentAttributes = westGeometry.attributes;
  18051. currentIndices = westGeometry.indices;
  18052. currentIndexMap = westGeometryIndexMap;
  18053. } else {
  18054. currentAttributes = eastGeometry.attributes;
  18055. currentIndices = eastGeometry.indices;
  18056. currentIndexMap = eastGeometryIndexMap;
  18057. }
  18058. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  18059. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  18060. }
  18061. }
  18062. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  18063. }
  18064. var cartesian2Scratch0 = new Cartesian2();
  18065. var cartesian2Scratch1 = new Cartesian2();
  18066. var cartesian3Scratch0 = new Cartesian3();
  18067. var cartesian3Scratch2 = new Cartesian3();
  18068. var cartesian3Scratch3 = new Cartesian3();
  18069. var cartesian3Scratch4 = new Cartesian3();
  18070. var cartesian3Scratch5 = new Cartesian3();
  18071. var cartesian3Scratch6 = new Cartesian3();
  18072. var cartesian4Scratch0 = new Cartesian4();
  18073. function updateAdjacencyAfterSplit(geometry) {
  18074. var attributes = geometry.attributes;
  18075. var positions = attributes.position.values;
  18076. var prevPositions = attributes.prevPosition.values;
  18077. var nextPositions = attributes.nextPosition.values;
  18078. var length = positions.length;
  18079. for (var j = 0; j < length; j += 3) {
  18080. var position = Cartesian3.unpack(positions, j, cartesian3Scratch0);
  18081. if (position.x > 0.0) {
  18082. continue;
  18083. }
  18084. var prevPosition = Cartesian3.unpack(prevPositions, j, cartesian3Scratch2);
  18085. if ((position.y < 0.0 && prevPosition.y > 0.0) || (position.y > 0.0 && prevPosition.y < 0.0)) {
  18086. if (j - 3 > 0) {
  18087. prevPositions[j] = positions[j - 3];
  18088. prevPositions[j + 1] = positions[j - 2];
  18089. prevPositions[j + 2] = positions[j - 1];
  18090. } else {
  18091. Cartesian3.pack(position, prevPositions, j);
  18092. }
  18093. }
  18094. var nextPosition = Cartesian3.unpack(nextPositions, j, cartesian3Scratch3);
  18095. if ((position.y < 0.0 && nextPosition.y > 0.0) || (position.y > 0.0 && nextPosition.y < 0.0)) {
  18096. if (j + 3 < length) {
  18097. nextPositions[j] = positions[j + 3];
  18098. nextPositions[j + 1] = positions[j + 4];
  18099. nextPositions[j + 2] = positions[j + 5];
  18100. } else {
  18101. Cartesian3.pack(position, nextPositions, j);
  18102. }
  18103. }
  18104. }
  18105. }
  18106. var offsetScalar = 5.0 * CesiumMath.EPSILON9;
  18107. var coplanarOffset = CesiumMath.EPSILON6;
  18108. function splitLongitudePolyline(instance) {
  18109. var geometry = instance.geometry;
  18110. var attributes = geometry.attributes;
  18111. var positions = attributes.position.values;
  18112. var prevPositions = attributes.prevPosition.values;
  18113. var nextPositions = attributes.nextPosition.values;
  18114. var expandAndWidths = attributes.expandAndWidth.values;
  18115. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  18116. var colors = (defined(attributes.color)) ? attributes.color.values : undefined;
  18117. var eastGeometry = copyGeometryForSplit(geometry);
  18118. var westGeometry = copyGeometryForSplit(geometry);
  18119. var i;
  18120. var j;
  18121. var index;
  18122. var intersectionFound = false;
  18123. var length = positions.length / 3;
  18124. for (i = 0; i < length; i += 4) {
  18125. var i0 = i;
  18126. var i2 = i + 2;
  18127. var p0 = Cartesian3.fromArray(positions, i0 * 3, cartesian3Scratch0);
  18128. var p2 = Cartesian3.fromArray(positions, i2 * 3, cartesian3Scratch2);
  18129. // Offset points that are close to the 180 longitude and change the previous/next point
  18130. // to be the same offset point so it can be projected to 2D. There is special handling in the
  18131. // shader for when position == prevPosition || position == nextPosition.
  18132. if (Math.abs(p0.y) < coplanarOffset) {
  18133. p0.y = coplanarOffset * (p2.y < 0.0 ? -1.0 : 1.0);
  18134. positions[i * 3 + 1] = p0.y;
  18135. positions[(i + 1) * 3 + 1] = p0.y;
  18136. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  18137. prevPositions[j] = positions[i * 3];
  18138. prevPositions[j + 1] = positions[i * 3 + 1];
  18139. prevPositions[j + 2] = positions[i * 3 + 2];
  18140. }
  18141. }
  18142. // Do the same but for when the line crosses 180 longitude in the opposite direction.
  18143. if (Math.abs(p2.y) < coplanarOffset) {
  18144. p2.y = coplanarOffset * (p0.y < 0.0 ? -1.0 : 1.0);
  18145. positions[(i + 2) * 3 + 1] = p2.y;
  18146. positions[(i + 3) * 3 + 1] = p2.y;
  18147. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  18148. nextPositions[j] = positions[(i + 2) * 3];
  18149. nextPositions[j + 1] = positions[(i + 2) * 3 + 1];
  18150. nextPositions[j + 2] = positions[(i + 2) * 3 + 2];
  18151. }
  18152. }
  18153. var p0Attributes = eastGeometry.attributes;
  18154. var p0Indices = eastGeometry.indices;
  18155. var p2Attributes = westGeometry.attributes;
  18156. var p2Indices = westGeometry.indices;
  18157. var intersection = IntersectionTests.lineSegmentPlane(p0, p2, xzPlane, cartesian3Scratch4);
  18158. if (defined(intersection)) {
  18159. intersectionFound = true;
  18160. // move point on the xz-plane slightly away from the plane
  18161. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, offsetScalar, cartesian3Scratch5);
  18162. if (p0.y < 0.0) {
  18163. Cartesian3.negate(offset, offset);
  18164. p0Attributes = westGeometry.attributes;
  18165. p0Indices = westGeometry.indices;
  18166. p2Attributes = eastGeometry.attributes;
  18167. p2Indices = eastGeometry.indices;
  18168. }
  18169. var offsetPoint = Cartesian3.add(intersection, offset, cartesian3Scratch6);
  18170. p0Attributes.position.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  18171. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18172. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18173. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3], prevPositions[i0 * 3 + 1], prevPositions[i0 * 3 + 2]);
  18174. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3 + 3], prevPositions[i0 * 3 + 4], prevPositions[i0 * 3 + 5]);
  18175. p0Attributes.prevPosition.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  18176. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18177. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18178. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18179. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18180. Cartesian3.negate(offset, offset);
  18181. Cartesian3.add(intersection, offset, offsetPoint);
  18182. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18183. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18184. p2Attributes.position.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  18185. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18186. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18187. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18188. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  18189. p2Attributes.nextPosition.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  18190. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3], nextPositions[i2 * 3 + 1], nextPositions[i2 * 3 + 2]);
  18191. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3 + 3], nextPositions[i2 * 3 + 4], nextPositions[i2 * 3 + 5]);
  18192. var ew0 = Cartesian2.fromArray(expandAndWidths, i0 * 2, cartesian2Scratch0);
  18193. var width = Math.abs(ew0.y);
  18194. p0Attributes.expandAndWidth.values.push(-1, width, 1, width);
  18195. p0Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  18196. p2Attributes.expandAndWidth.values.push(-1, width, 1, width);
  18197. p2Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  18198. var t = Cartesian3.magnitudeSquared(Cartesian3.subtract(intersection, p0, cartesian3Scratch3));
  18199. t /= Cartesian3.magnitudeSquared(Cartesian3.subtract(p2, p0, cartesian3Scratch3));
  18200. if (defined(colors)) {
  18201. var c0 = Cartesian4.fromArray(colors, i0 * 4, cartesian4Scratch0);
  18202. var c2 = Cartesian4.fromArray(colors, i2 * 4, cartesian4Scratch0);
  18203. var r = CesiumMath.lerp(c0.x, c2.x, t);
  18204. var g = CesiumMath.lerp(c0.y, c2.y, t);
  18205. var b = CesiumMath.lerp(c0.z, c2.z, t);
  18206. var a = CesiumMath.lerp(c0.w, c2.w, t);
  18207. for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
  18208. p0Attributes.color.values.push(colors[j]);
  18209. }
  18210. p0Attributes.color.values.push(r, g, b, a);
  18211. p0Attributes.color.values.push(r, g, b, a);
  18212. p2Attributes.color.values.push(r, g, b, a);
  18213. p2Attributes.color.values.push(r, g, b, a);
  18214. for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
  18215. p2Attributes.color.values.push(colors[j]);
  18216. }
  18217. }
  18218. if (defined(texCoords)) {
  18219. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
  18220. var s3 = Cartesian2.fromArray(texCoords, (i + 3) * 2, cartesian2Scratch1);
  18221. var sx = CesiumMath.lerp(s0.x, s3.x, t);
  18222. for (j = i0 * 2; j < i0 * 2 + 2 * 2; ++j) {
  18223. p0Attributes.st.values.push(texCoords[j]);
  18224. }
  18225. p0Attributes.st.values.push(sx, s0.y);
  18226. p0Attributes.st.values.push(sx, s3.y);
  18227. p2Attributes.st.values.push(sx, s0.y);
  18228. p2Attributes.st.values.push(sx, s3.y);
  18229. for (j = i2 * 2; j < i2 * 2 + 2 * 2; ++j) {
  18230. p2Attributes.st.values.push(texCoords[j]);
  18231. }
  18232. }
  18233. index = p0Attributes.position.values.length / 3 - 4;
  18234. p0Indices.push(index, index + 2, index + 1);
  18235. p0Indices.push(index + 1, index + 2, index + 3);
  18236. index = p2Attributes.position.values.length / 3 - 4;
  18237. p2Indices.push(index, index + 2, index + 1);
  18238. p2Indices.push(index + 1, index + 2, index + 3);
  18239. } else {
  18240. var currentAttributes;
  18241. var currentIndices;
  18242. if (p0.y < 0.0) {
  18243. currentAttributes = westGeometry.attributes;
  18244. currentIndices = westGeometry.indices;
  18245. } else {
  18246. currentAttributes = eastGeometry.attributes;
  18247. currentIndices = eastGeometry.indices;
  18248. }
  18249. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  18250. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  18251. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  18252. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  18253. for (j = i * 3; j < i * 3 + 4 * 3; ++j) {
  18254. currentAttributes.prevPosition.values.push(prevPositions[j]);
  18255. currentAttributes.nextPosition.values.push(nextPositions[j]);
  18256. }
  18257. for (j = i * 2; j < i * 2 + 4 * 2; ++j) {
  18258. currentAttributes.expandAndWidth.values.push(expandAndWidths[j]);
  18259. if (defined(texCoords)) {
  18260. currentAttributes.st.values.push(texCoords[j]);
  18261. }
  18262. }
  18263. if (defined(colors)) {
  18264. for (j = i * 4; j < i * 4 + 4 * 4; ++j) {
  18265. currentAttributes.color.values.push(colors[j]);
  18266. }
  18267. }
  18268. index = currentAttributes.position.values.length / 3 - 4;
  18269. currentIndices.push(index, index + 2, index + 1);
  18270. currentIndices.push(index + 1, index + 2, index + 3);
  18271. }
  18272. }
  18273. if (intersectionFound) {
  18274. updateAdjacencyAfterSplit(westGeometry);
  18275. updateAdjacencyAfterSplit(eastGeometry);
  18276. }
  18277. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  18278. }
  18279. /**
  18280. * Splits the instances's geometry, by introducing new vertices and indices,that
  18281. * intersect the International Date Line and Prime Meridian so that no primitives cross longitude
  18282. * -180/180 degrees. This is not required for 3D drawing, but is required for
  18283. * correcting drawing in 2D and Columbus view.
  18284. *
  18285. * @private
  18286. *
  18287. * @param {GeometryInstance} instance The instance to modify.
  18288. * @returns {GeometryInstance} The modified <code>instance</code> argument, with it's geometry split at the International Date Line.
  18289. *
  18290. * @example
  18291. * instance = Cesium.GeometryPipeline.splitLongitude(instance);
  18292. */
  18293. GeometryPipeline.splitLongitude = function(instance) {
  18294. if (!defined(instance)) {
  18295. throw new DeveloperError('instance is required.');
  18296. }
  18297. var geometry = instance.geometry;
  18298. var boundingSphere = geometry.boundingSphere;
  18299. if (defined(boundingSphere)) {
  18300. var minX = boundingSphere.center.x - boundingSphere.radius;
  18301. if (minX > 0 || BoundingSphere.intersectPlane(boundingSphere, Plane.ORIGIN_ZX_PLANE) !== Intersect.INTERSECTING) {
  18302. return instance;
  18303. }
  18304. }
  18305. if (geometry.geometryType !== GeometryType.NONE) {
  18306. switch (geometry.geometryType) {
  18307. case GeometryType.POLYLINES:
  18308. splitLongitudePolyline(instance);
  18309. break;
  18310. case GeometryType.TRIANGLES:
  18311. splitLongitudeTriangles(instance);
  18312. break;
  18313. case GeometryType.LINES:
  18314. splitLongitudeLines(instance);
  18315. break;
  18316. }
  18317. } else {
  18318. indexPrimitive(geometry);
  18319. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  18320. splitLongitudeTriangles(instance);
  18321. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  18322. splitLongitudeLines(instance);
  18323. }
  18324. }
  18325. return instance;
  18326. };
  18327. return GeometryPipeline;
  18328. });
  18329. /**
  18330. @license
  18331. when.js - https://github.com/cujojs/when
  18332. MIT License (c) copyright B Cavalier & J Hann
  18333. * A lightweight CommonJS Promises/A and when() implementation
  18334. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  18335. *
  18336. * Licensed under the MIT License at:
  18337. * http://www.opensource.org/licenses/mit-license.php
  18338. *
  18339. * @version 1.7.1
  18340. */
  18341. (function(define) { 'use strict';
  18342. define('ThirdParty/when',[],function () {
  18343. var reduceArray, slice, undef;
  18344. //
  18345. // Public API
  18346. //
  18347. when.defer = defer; // Create a deferred
  18348. when.resolve = resolve; // Create a resolved promise
  18349. when.reject = reject; // Create a rejected promise
  18350. when.join = join; // Join 2 or more promises
  18351. when.all = all; // Resolve a list of promises
  18352. when.map = map; // Array.map() for promises
  18353. when.reduce = reduce; // Array.reduce() for promises
  18354. when.any = any; // One-winner race
  18355. when.some = some; // Multi-winner race
  18356. when.chain = chain; // Make a promise trigger another resolver
  18357. when.isPromise = isPromise; // Determine if a thing is a promise
  18358. /**
  18359. * Register an observer for a promise or immediate value.
  18360. *
  18361. * @param {*} promiseOrValue
  18362. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  18363. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  18364. * will be invoked immediately.
  18365. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  18366. * rejected.
  18367. * @param {function?} [onProgress] callback to be called when progress updates
  18368. * are issued for promiseOrValue.
  18369. * @returns {Promise} a new {@link Promise} that will complete with the return
  18370. * value of callback or errback or the completion value of promiseOrValue if
  18371. * callback and/or errback is not supplied.
  18372. */
  18373. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  18374. // Get a trusted promise for the input promiseOrValue, and then
  18375. // register promise handlers
  18376. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  18377. }
  18378. /**
  18379. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  18380. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  18381. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  18382. *
  18383. * @param {*} promiseOrValue
  18384. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  18385. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  18386. * whose resolution value is:
  18387. * * the resolution value of promiseOrValue if it's a foreign promise, or
  18388. * * promiseOrValue if it's a value
  18389. */
  18390. function resolve(promiseOrValue) {
  18391. var promise, deferred;
  18392. if(promiseOrValue instanceof Promise) {
  18393. // It's a when.js promise, so we trust it
  18394. promise = promiseOrValue;
  18395. } else {
  18396. // It's not a when.js promise. See if it's a foreign promise or a value.
  18397. if(isPromise(promiseOrValue)) {
  18398. // It's a thenable, but we don't know where it came from, so don't trust
  18399. // its implementation entirely. Introduce a trusted middleman when.js promise
  18400. deferred = defer();
  18401. // IMPORTANT: This is the only place when.js should ever call .then() on an
  18402. // untrusted promise. Don't expose the return value to the untrusted promise
  18403. promiseOrValue.then(
  18404. function(value) { deferred.resolve(value); },
  18405. function(reason) { deferred.reject(reason); },
  18406. function(update) { deferred.progress(update); }
  18407. );
  18408. promise = deferred.promise;
  18409. } else {
  18410. // It's a value, not a promise. Create a resolved promise for it.
  18411. promise = fulfilled(promiseOrValue);
  18412. }
  18413. }
  18414. return promise;
  18415. }
  18416. /**
  18417. * Returns a rejected promise for the supplied promiseOrValue. The returned
  18418. * promise will be rejected with:
  18419. * - promiseOrValue, if it is a value, or
  18420. * - if promiseOrValue is a promise
  18421. * - promiseOrValue's value after it is fulfilled
  18422. * - promiseOrValue's reason after it is rejected
  18423. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  18424. * @returns {Promise} rejected {@link Promise}
  18425. */
  18426. function reject(promiseOrValue) {
  18427. return when(promiseOrValue, rejected);
  18428. }
  18429. /**
  18430. * Trusted Promise constructor. A Promise created from this constructor is
  18431. * a trusted when.js promise. Any other duck-typed promise is considered
  18432. * untrusted.
  18433. * @constructor
  18434. * @name Promise
  18435. */
  18436. function Promise(then) {
  18437. this.then = then;
  18438. }
  18439. Promise.prototype = {
  18440. /**
  18441. * Register a callback that will be called when a promise is
  18442. * fulfilled or rejected. Optionally also register a progress handler.
  18443. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  18444. * @param {function?} [onFulfilledOrRejected]
  18445. * @param {function?} [onProgress]
  18446. * @returns {Promise}
  18447. */
  18448. always: function(onFulfilledOrRejected, onProgress) {
  18449. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  18450. },
  18451. /**
  18452. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  18453. * @param {function?} onRejected
  18454. * @returns {Promise}
  18455. */
  18456. otherwise: function(onRejected) {
  18457. return this.then(undef, onRejected);
  18458. },
  18459. /**
  18460. * Shortcut for .then(function() { return value; })
  18461. * @param {*} value
  18462. * @returns {Promise} a promise that:
  18463. * - is fulfilled if value is not a promise, or
  18464. * - if value is a promise, will fulfill with its value, or reject
  18465. * with its reason.
  18466. */
  18467. yield: function(value) {
  18468. return this.then(function() {
  18469. return value;
  18470. });
  18471. },
  18472. /**
  18473. * Assumes that this promise will fulfill with an array, and arranges
  18474. * for the onFulfilled to be called with the array as its argument list
  18475. * i.e. onFulfilled.spread(undefined, array).
  18476. * @param {function} onFulfilled function to receive spread arguments
  18477. * @returns {Promise}
  18478. */
  18479. spread: function(onFulfilled) {
  18480. return this.then(function(array) {
  18481. // array may contain promises, so resolve its contents.
  18482. return all(array, function(array) {
  18483. return onFulfilled.apply(undef, array);
  18484. });
  18485. });
  18486. }
  18487. };
  18488. /**
  18489. * Create an already-resolved promise for the supplied value
  18490. * @private
  18491. *
  18492. * @param {*} value
  18493. * @returns {Promise} fulfilled promise
  18494. */
  18495. function fulfilled(value) {
  18496. var p = new Promise(function(onFulfilled) {
  18497. // TODO: Promises/A+ check typeof onFulfilled
  18498. try {
  18499. return resolve(onFulfilled ? onFulfilled(value) : value);
  18500. } catch(e) {
  18501. return rejected(e);
  18502. }
  18503. });
  18504. return p;
  18505. }
  18506. /**
  18507. * Create an already-rejected {@link Promise} with the supplied
  18508. * rejection reason.
  18509. * @private
  18510. *
  18511. * @param {*} reason
  18512. * @returns {Promise} rejected promise
  18513. */
  18514. function rejected(reason) {
  18515. var p = new Promise(function(_, onRejected) {
  18516. // TODO: Promises/A+ check typeof onRejected
  18517. try {
  18518. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  18519. } catch(e) {
  18520. return rejected(e);
  18521. }
  18522. });
  18523. return p;
  18524. }
  18525. /**
  18526. * Creates a new, Deferred with fully isolated resolver and promise parts,
  18527. * either or both of which may be given out safely to consumers.
  18528. * The Deferred itself has the full API: resolve, reject, progress, and
  18529. * then. The resolver has resolve, reject, and progress. The promise
  18530. * only has then.
  18531. *
  18532. * @returns {Deferred}
  18533. */
  18534. function defer() {
  18535. var deferred, promise, handlers, progressHandlers,
  18536. _then, _progress, _resolve;
  18537. /**
  18538. * The promise for the new deferred
  18539. * @type {Promise}
  18540. */
  18541. promise = new Promise(then);
  18542. /**
  18543. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  18544. * @class Deferred
  18545. * @name Deferred
  18546. */
  18547. deferred = {
  18548. then: then, // DEPRECATED: use deferred.promise.then
  18549. resolve: promiseResolve,
  18550. reject: promiseReject,
  18551. // TODO: Consider renaming progress() to notify()
  18552. progress: promiseProgress,
  18553. promise: promise,
  18554. resolver: {
  18555. resolve: promiseResolve,
  18556. reject: promiseReject,
  18557. progress: promiseProgress
  18558. }
  18559. };
  18560. handlers = [];
  18561. progressHandlers = [];
  18562. /**
  18563. * Pre-resolution then() that adds the supplied callback, errback, and progback
  18564. * functions to the registered listeners
  18565. * @private
  18566. *
  18567. * @param {function?} [onFulfilled] resolution handler
  18568. * @param {function?} [onRejected] rejection handler
  18569. * @param {function?} [onProgress] progress handler
  18570. */
  18571. _then = function(onFulfilled, onRejected, onProgress) {
  18572. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  18573. var deferred, progressHandler;
  18574. deferred = defer();
  18575. progressHandler = typeof onProgress === 'function'
  18576. ? function(update) {
  18577. try {
  18578. // Allow progress handler to transform progress event
  18579. deferred.progress(onProgress(update));
  18580. } catch(e) {
  18581. // Use caught value as progress
  18582. deferred.progress(e);
  18583. }
  18584. }
  18585. : function(update) { deferred.progress(update); };
  18586. handlers.push(function(promise) {
  18587. promise.then(onFulfilled, onRejected)
  18588. .then(deferred.resolve, deferred.reject, progressHandler);
  18589. });
  18590. progressHandlers.push(progressHandler);
  18591. return deferred.promise;
  18592. };
  18593. /**
  18594. * Issue a progress event, notifying all progress listeners
  18595. * @private
  18596. * @param {*} update progress event payload to pass to all listeners
  18597. */
  18598. _progress = function(update) {
  18599. processQueue(progressHandlers, update);
  18600. return update;
  18601. };
  18602. /**
  18603. * Transition from pre-resolution state to post-resolution state, notifying
  18604. * all listeners of the resolution or rejection
  18605. * @private
  18606. * @param {*} value the value of this deferred
  18607. */
  18608. _resolve = function(value) {
  18609. value = resolve(value);
  18610. // Replace _then with one that directly notifies with the result.
  18611. _then = value.then;
  18612. // Replace _resolve so that this Deferred can only be resolved once
  18613. _resolve = resolve;
  18614. // Make _progress a noop, to disallow progress for the resolved promise.
  18615. _progress = noop;
  18616. // Notify handlers
  18617. processQueue(handlers, value);
  18618. // Free progressHandlers array since we'll never issue progress events
  18619. progressHandlers = handlers = undef;
  18620. return value;
  18621. };
  18622. return deferred;
  18623. /**
  18624. * Wrapper to allow _then to be replaced safely
  18625. * @param {function?} [onFulfilled] resolution handler
  18626. * @param {function?} [onRejected] rejection handler
  18627. * @param {function?} [onProgress] progress handler
  18628. * @returns {Promise} new promise
  18629. */
  18630. function then(onFulfilled, onRejected, onProgress) {
  18631. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  18632. return _then(onFulfilled, onRejected, onProgress);
  18633. }
  18634. /**
  18635. * Wrapper to allow _resolve to be replaced
  18636. */
  18637. function promiseResolve(val) {
  18638. return _resolve(val);
  18639. }
  18640. /**
  18641. * Wrapper to allow _reject to be replaced
  18642. */
  18643. function promiseReject(err) {
  18644. return _resolve(rejected(err));
  18645. }
  18646. /**
  18647. * Wrapper to allow _progress to be replaced
  18648. */
  18649. function promiseProgress(update) {
  18650. return _progress(update);
  18651. }
  18652. }
  18653. /**
  18654. * Determines if promiseOrValue is a promise or not. Uses the feature
  18655. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  18656. * promiseOrValue is a promise.
  18657. *
  18658. * @param {*} promiseOrValue anything
  18659. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  18660. */
  18661. function isPromise(promiseOrValue) {
  18662. return promiseOrValue && typeof promiseOrValue.then === 'function';
  18663. }
  18664. /**
  18665. * Initiates a competitive race, returning a promise that will resolve when
  18666. * howMany of the supplied promisesOrValues have resolved, or will reject when
  18667. * it becomes impossible for howMany to resolve, for example, when
  18668. * (promisesOrValues.length - howMany) + 1 input promises reject.
  18669. *
  18670. * @param {Array} promisesOrValues array of anything, may contain a mix
  18671. * of promises and values
  18672. * @param howMany {number} number of promisesOrValues to resolve
  18673. * @param {function?} [onFulfilled] resolution handler
  18674. * @param {function?} [onRejected] rejection handler
  18675. * @param {function?} [onProgress] progress handler
  18676. * @returns {Promise} promise that will resolve to an array of howMany values that
  18677. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  18678. * rejection reasons.
  18679. */
  18680. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  18681. checkCallbacks(2, arguments);
  18682. return when(promisesOrValues, function(promisesOrValues) {
  18683. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  18684. len = promisesOrValues.length >>> 0;
  18685. toResolve = Math.max(0, Math.min(howMany, len));
  18686. values = [];
  18687. toReject = (len - toResolve) + 1;
  18688. reasons = [];
  18689. deferred = defer();
  18690. // No items in the input, resolve immediately
  18691. if (!toResolve) {
  18692. deferred.resolve(values);
  18693. } else {
  18694. progress = deferred.progress;
  18695. rejectOne = function(reason) {
  18696. reasons.push(reason);
  18697. if(!--toReject) {
  18698. fulfillOne = rejectOne = noop;
  18699. deferred.reject(reasons);
  18700. }
  18701. };
  18702. fulfillOne = function(val) {
  18703. // This orders the values based on promise resolution order
  18704. // Another strategy would be to use the original position of
  18705. // the corresponding promise.
  18706. values.push(val);
  18707. if (!--toResolve) {
  18708. fulfillOne = rejectOne = noop;
  18709. deferred.resolve(values);
  18710. }
  18711. };
  18712. for(i = 0; i < len; ++i) {
  18713. if(i in promisesOrValues) {
  18714. when(promisesOrValues[i], fulfiller, rejecter, progress);
  18715. }
  18716. }
  18717. }
  18718. return deferred.then(onFulfilled, onRejected, onProgress);
  18719. function rejecter(reason) {
  18720. rejectOne(reason);
  18721. }
  18722. function fulfiller(val) {
  18723. fulfillOne(val);
  18724. }
  18725. });
  18726. }
  18727. /**
  18728. * Initiates a competitive race, returning a promise that will resolve when
  18729. * any one of the supplied promisesOrValues has resolved or will reject when
  18730. * *all* promisesOrValues have rejected.
  18731. *
  18732. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  18733. * of {@link Promise}s and values
  18734. * @param {function?} [onFulfilled] resolution handler
  18735. * @param {function?} [onRejected] rejection handler
  18736. * @param {function?} [onProgress] progress handler
  18737. * @returns {Promise} promise that will resolve to the value that resolved first, or
  18738. * will reject with an array of all rejected inputs.
  18739. */
  18740. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  18741. function unwrapSingleResult(val) {
  18742. return onFulfilled ? onFulfilled(val[0]) : val[0];
  18743. }
  18744. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  18745. }
  18746. /**
  18747. * Return a promise that will resolve only once all the supplied promisesOrValues
  18748. * have resolved. The resolution value of the returned promise will be an array
  18749. * containing the resolution values of each of the promisesOrValues.
  18750. * @memberOf when
  18751. *
  18752. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  18753. * of {@link Promise}s and values
  18754. * @param {function?} [onFulfilled] resolution handler
  18755. * @param {function?} [onRejected] rejection handler
  18756. * @param {function?} [onProgress] progress handler
  18757. * @returns {Promise}
  18758. */
  18759. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  18760. checkCallbacks(1, arguments);
  18761. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  18762. }
  18763. /**
  18764. * Joins multiple promises into a single returned promise.
  18765. * @returns {Promise} a promise that will fulfill when *all* the input promises
  18766. * have fulfilled, or will reject when *any one* of the input promises rejects.
  18767. */
  18768. function join(/* ...promises */) {
  18769. return map(arguments, identity);
  18770. }
  18771. /**
  18772. * Traditional map function, similar to `Array.prototype.map()`, but allows
  18773. * input to contain {@link Promise}s and/or values, and mapFunc may return
  18774. * either a value or a {@link Promise}
  18775. *
  18776. * @param {Array|Promise} promise array of anything, may contain a mix
  18777. * of {@link Promise}s and values
  18778. * @param {function} mapFunc mapping function mapFunc(value) which may return
  18779. * either a {@link Promise} or value
  18780. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  18781. * the mapped output values.
  18782. */
  18783. function map(promise, mapFunc) {
  18784. return when(promise, function(array) {
  18785. var results, len, toResolve, resolve, i, d;
  18786. // Since we know the resulting length, we can preallocate the results
  18787. // array to avoid array expansions.
  18788. toResolve = len = array.length >>> 0;
  18789. results = [];
  18790. d = defer();
  18791. if(!toResolve) {
  18792. d.resolve(results);
  18793. } else {
  18794. resolve = function resolveOne(item, i) {
  18795. when(item, mapFunc).then(function(mapped) {
  18796. results[i] = mapped;
  18797. if(!--toResolve) {
  18798. d.resolve(results);
  18799. }
  18800. }, d.reject);
  18801. };
  18802. // Since mapFunc may be async, get all invocations of it into flight
  18803. for(i = 0; i < len; i++) {
  18804. if(i in array) {
  18805. resolve(array[i], i);
  18806. } else {
  18807. --toResolve;
  18808. }
  18809. }
  18810. }
  18811. return d.promise;
  18812. });
  18813. }
  18814. /**
  18815. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  18816. * input may contain promises and/or values, and reduceFunc
  18817. * may return either a value or a promise, *and* initialValue may
  18818. * be a promise for the starting value.
  18819. *
  18820. * @param {Array|Promise} promise array or promise for an array of anything,
  18821. * may contain a mix of promises and values.
  18822. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  18823. * where total is the total number of items being reduced, and will be the same
  18824. * in each call to reduceFunc.
  18825. * @returns {Promise} that will resolve to the final reduced value
  18826. */
  18827. function reduce(promise, reduceFunc /*, initialValue */) {
  18828. var args = slice.call(arguments, 1);
  18829. return when(promise, function(array) {
  18830. var total;
  18831. total = array.length;
  18832. // Wrap the supplied reduceFunc with one that handles promises and then
  18833. // delegates to the supplied.
  18834. args[0] = function (current, val, i) {
  18835. return when(current, function (c) {
  18836. return when(val, function (value) {
  18837. return reduceFunc(c, value, i, total);
  18838. });
  18839. });
  18840. };
  18841. return reduceArray.apply(array, args);
  18842. });
  18843. }
  18844. /**
  18845. * Ensure that resolution of promiseOrValue will trigger resolver with the
  18846. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  18847. *
  18848. * @param promiseOrValue
  18849. * @param {Object} resolver
  18850. * @param {function} resolver.resolve
  18851. * @param {function} resolver.reject
  18852. * @param {*} [resolveValue]
  18853. * @returns {Promise}
  18854. */
  18855. function chain(promiseOrValue, resolver, resolveValue) {
  18856. var useResolveValue = arguments.length > 2;
  18857. return when(promiseOrValue,
  18858. function(val) {
  18859. val = useResolveValue ? resolveValue : val;
  18860. resolver.resolve(val);
  18861. return val;
  18862. },
  18863. function(reason) {
  18864. resolver.reject(reason);
  18865. return rejected(reason);
  18866. },
  18867. resolver.progress
  18868. );
  18869. }
  18870. //
  18871. // Utility functions
  18872. //
  18873. /**
  18874. * Apply all functions in queue to value
  18875. * @param {Array} queue array of functions to execute
  18876. * @param {*} value argument passed to each function
  18877. */
  18878. function processQueue(queue, value) {
  18879. var handler, i = 0;
  18880. while (handler = queue[i++]) {
  18881. handler(value);
  18882. }
  18883. }
  18884. /**
  18885. * Helper that checks arrayOfCallbacks to ensure that each element is either
  18886. * a function, or null or undefined.
  18887. * @private
  18888. * @param {number} start index at which to start checking items in arrayOfCallbacks
  18889. * @param {Array} arrayOfCallbacks array to check
  18890. * @throws {Error} if any element of arrayOfCallbacks is something other than
  18891. * a functions, null, or undefined.
  18892. */
  18893. function checkCallbacks(start, arrayOfCallbacks) {
  18894. // TODO: Promises/A+ update type checking and docs
  18895. var arg, i = arrayOfCallbacks.length;
  18896. while(i > start) {
  18897. arg = arrayOfCallbacks[--i];
  18898. if (arg != null && typeof arg != 'function') {
  18899. throw new Error('arg '+i+' must be a function');
  18900. }
  18901. }
  18902. }
  18903. /**
  18904. * No-Op function used in method replacement
  18905. * @private
  18906. */
  18907. function noop() {}
  18908. slice = [].slice;
  18909. // ES5 reduce implementation if native not available
  18910. // See: http://es5.github.com/#x15.4.4.21 as there are many
  18911. // specifics and edge cases.
  18912. reduceArray = [].reduce ||
  18913. function(reduceFunc /*, initialValue */) {
  18914. /*jshint maxcomplexity: 7*/
  18915. // ES5 dictates that reduce.length === 1
  18916. // This implementation deviates from ES5 spec in the following ways:
  18917. // 1. It does not check if reduceFunc is a Callable
  18918. var arr, args, reduced, len, i;
  18919. i = 0;
  18920. // This generates a jshint warning, despite being valid
  18921. // "Missing 'new' prefix when invoking a constructor."
  18922. // See https://github.com/jshint/jshint/issues/392
  18923. arr = Object(this);
  18924. len = arr.length >>> 0;
  18925. args = arguments;
  18926. // If no initialValue, use first item of array (we know length !== 0 here)
  18927. // and adjust i to start at second item
  18928. if(args.length <= 1) {
  18929. // Skip to the first real element in the array
  18930. for(;;) {
  18931. if(i in arr) {
  18932. reduced = arr[i++];
  18933. break;
  18934. }
  18935. // If we reached the end of the array without finding any real
  18936. // elements, it's a TypeError
  18937. if(++i >= len) {
  18938. throw new TypeError();
  18939. }
  18940. }
  18941. } else {
  18942. // If initialValue provided, use it
  18943. reduced = args[1];
  18944. }
  18945. // Do the actual reduce
  18946. for(;i < len; ++i) {
  18947. // Skip holes
  18948. if(i in arr) {
  18949. reduced = reduceFunc(reduced, arr[i], i, arr);
  18950. }
  18951. }
  18952. return reduced;
  18953. };
  18954. function identity(x) {
  18955. return x;
  18956. }
  18957. return when;
  18958. });
  18959. })(typeof define == 'function' && define.amd
  18960. ? define
  18961. : function (factory) { typeof exports === 'object'
  18962. ? (module.exports = factory())
  18963. : (this.when = factory());
  18964. }
  18965. // Boilerplate for AMD, Node, and browser global
  18966. );
  18967. /*global define*/
  18968. define('Core/oneTimeWarning',[
  18969. './defaultValue',
  18970. './defined',
  18971. './DeveloperError'
  18972. ], function(
  18973. defaultValue,
  18974. defined,
  18975. DeveloperError) {
  18976. "use strict";
  18977. var warnings = {};
  18978. /**
  18979. * Logs a one time message to the console. Use this function instead of
  18980. * <code>console.log</code> directly since this does not log duplicate messages
  18981. * unless it is called from multiple workers.
  18982. *
  18983. * @exports oneTimeWarning
  18984. *
  18985. * @param {String} identifier The unique identifier for this warning.
  18986. * @param {String} [message=identifier] The message to log to the console.
  18987. *
  18988. * @example
  18989. * for(var i=0;i<foo.length;++i) {
  18990. * if (!defined(foo[i].bar)) {
  18991. * // Something that can be recovered from but may happen a lot
  18992. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  18993. * foo[i].bar = 0;
  18994. * // ...
  18995. * }
  18996. * }
  18997. *
  18998. * @private
  18999. */
  19000. function oneTimeWarning(identifier, message) {
  19001. if (!defined(identifier)) {
  19002. throw new DeveloperError('identifier is required.');
  19003. }
  19004. if (!defined(warnings[identifier])) {
  19005. warnings[identifier] = true;
  19006. console.log(defaultValue(message, identifier));
  19007. }
  19008. }
  19009. 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.';
  19010. return oneTimeWarning;
  19011. });
  19012. /*global define*/
  19013. define('Core/deprecationWarning',[
  19014. './defined',
  19015. './DeveloperError',
  19016. './oneTimeWarning'
  19017. ], function(
  19018. defined,
  19019. DeveloperError,
  19020. oneTimeWarning) {
  19021. 'use strict';
  19022. /**
  19023. * Logs a deprecation message to the console. Use this function instead of
  19024. * <code>console.log</code> directly since this does not log duplicate messages
  19025. * unless it is called from multiple workers.
  19026. *
  19027. * @exports deprecationWarning
  19028. *
  19029. * @param {String} identifier The unique identifier for this deprecated API.
  19030. * @param {String} message The message to log to the console.
  19031. *
  19032. * @example
  19033. * // Deprecated function or class
  19034. * function Foo() {
  19035. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  19036. * // ...
  19037. * }
  19038. *
  19039. * // Deprecated function
  19040. * Bar.prototype.func = function() {
  19041. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  19042. * // ...
  19043. * };
  19044. *
  19045. * // Deprecated property
  19046. * defineProperties(Bar.prototype, {
  19047. * prop : {
  19048. * get : function() {
  19049. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  19050. * // ...
  19051. * },
  19052. * set : function(value) {
  19053. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  19054. * // ...
  19055. * }
  19056. * }
  19057. * });
  19058. *
  19059. * @private
  19060. */
  19061. function deprecationWarning(identifier, message) {
  19062. if (!defined(identifier) || !defined(message)) {
  19063. throw new DeveloperError('identifier and message are required.');
  19064. }
  19065. oneTimeWarning(identifier, message);
  19066. }
  19067. return deprecationWarning;
  19068. });
  19069. /*global define*/
  19070. define('Core/binarySearch',[
  19071. './defined',
  19072. './DeveloperError'
  19073. ], function(
  19074. defined,
  19075. DeveloperError) {
  19076. 'use strict';
  19077. /**
  19078. * Finds an item in a sorted array.
  19079. *
  19080. * @exports binarySearch
  19081. *
  19082. * @param {Array} array The sorted array to search.
  19083. * @param {Object} itemToFind The item to find in the array.
  19084. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  19085. * elements in the array.
  19086. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  19087. * does not exist, the return value is a negative number which is the bitwise complement (~)
  19088. * of the index before which the itemToFind should be inserted in order to maintain the
  19089. * sorted order of the array.
  19090. *
  19091. * @example
  19092. * // Create a comparator function to search through an array of numbers.
  19093. * function comparator(a, b) {
  19094. * return a - b;
  19095. * };
  19096. * var numbers = [0, 2, 4, 6, 8];
  19097. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  19098. */
  19099. function binarySearch(array, itemToFind, comparator) {
  19100. if (!defined(array)) {
  19101. throw new DeveloperError('array is required.');
  19102. }
  19103. if (!defined(itemToFind)) {
  19104. throw new DeveloperError('itemToFind is required.');
  19105. }
  19106. if (!defined(comparator)) {
  19107. throw new DeveloperError('comparator is required.');
  19108. }
  19109. var low = 0;
  19110. var high = array.length - 1;
  19111. var i;
  19112. var comparison;
  19113. while (low <= high) {
  19114. i = ~~((low + high) / 2);
  19115. comparison = comparator(array[i], itemToFind);
  19116. if (comparison < 0) {
  19117. low = i + 1;
  19118. continue;
  19119. }
  19120. if (comparison > 0) {
  19121. high = i - 1;
  19122. continue;
  19123. }
  19124. return i;
  19125. }
  19126. return ~(high + 1);
  19127. }
  19128. /**
  19129. * A function used to compare two items while performing a binary search.
  19130. * @callback binarySearch~Comparator
  19131. *
  19132. * @param {Object} a An item in the array.
  19133. * @param {Object} b The item being searched for.
  19134. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  19135. * a positive value if <code>a</code> is greater than <code>b</code>, or
  19136. * 0 if <code>a</code> is equal to <code>b</code>.
  19137. *
  19138. * @example
  19139. * function compareNumbers(a, b) {
  19140. * return a - b;
  19141. * }
  19142. */
  19143. return binarySearch;
  19144. });
  19145. /*global define*/
  19146. define('Core/EarthOrientationParametersSample',[],function() {
  19147. 'use strict';
  19148. /**
  19149. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  19150. *
  19151. * @alias EarthOrientationParametersSample
  19152. * @constructor
  19153. *
  19154. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  19155. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  19156. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  19157. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  19158. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  19159. *
  19160. * @private
  19161. */
  19162. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  19163. /**
  19164. * The pole wander about the X axis, in radians.
  19165. * @type {Number}
  19166. */
  19167. this.xPoleWander = xPoleWander;
  19168. /**
  19169. * The pole wander about the Y axis, in radians.
  19170. * @type {Number}
  19171. */
  19172. this.yPoleWander = yPoleWander;
  19173. /**
  19174. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  19175. * @type {Number}
  19176. */
  19177. this.xPoleOffset = xPoleOffset;
  19178. /**
  19179. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  19180. * @type {Number}
  19181. */
  19182. this.yPoleOffset = yPoleOffset;
  19183. /**
  19184. * The difference in time standards, UT1 - UTC, in seconds.
  19185. * @type {Number}
  19186. */
  19187. this.ut1MinusUtc = ut1MinusUtc;
  19188. }
  19189. return EarthOrientationParametersSample;
  19190. });
  19191. /**
  19192. @license
  19193. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  19194. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  19195. php.js is copyright 2012 Kevin van Zonneveld.
  19196. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  19197. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  19198. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  19199. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  19200. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  19201. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  19202. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  19203. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  19204. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  19205. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  19206. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  19207. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  19208. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  19209. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  19210. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  19211. (http://geekfg.blogspot.com), Andrea Giammarchi
  19212. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  19213. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  19214. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  19215. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  19216. Marc Palau, Martin
  19217. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  19218. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  19219. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  19220. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  19221. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  19222. Ariede (http://caioariede.com), Robin, Kankrelune
  19223. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  19224. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  19225. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  19226. David, Aman Gupta, Michael White, Public Domain
  19227. (http://www.json.org/json2.js), Steven Levithan
  19228. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  19229. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  19230. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  19231. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  19232. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  19233. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  19234. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  19235. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  19236. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  19237. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  19238. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  19239. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  19240. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  19241. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  19242. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  19243. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  19244. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  19245. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  19246. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  19247. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  19248. (http://yass.meetcweb.com), Peter-Paul Koch
  19249. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  19250. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  19251. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  19252. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  19253. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  19254. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  19255. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  19256. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  19257. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  19258. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  19259. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  19260. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  19261. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  19262. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  19263. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  19264. (http://www.premasolutions.com/), Philippe Jausions
  19265. (http://pear.php.net/user/jausions), Aidan Lister
  19266. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  19267. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  19268. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  19269. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  19270. (http://www.pedrotainha.com), James, Arnout Kazemier
  19271. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  19272. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  19273. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  19274. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  19275. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  19276. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  19277. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  19278. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  19279. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  19280. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  19281. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  19282. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  19283. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  19284. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  19285. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  19286. (http://benblume.co.uk/), DtTvB
  19287. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  19288. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  19289. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  19290. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  19291. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  19292. Bryan
  19293. Licensed under the MIT (MIT-LICENSE.txt) license.
  19294. Permission is hereby granted, free of charge, to any person obtaining a
  19295. copy of this software and associated documentation files (the
  19296. "Software"), to deal in the Software without restriction, including
  19297. without limitation the rights to use, copy, modify, merge, publish,
  19298. distribute, sublicense, and/or sell copies of the Software, and to
  19299. permit persons to whom the Software is furnished to do so, subject to
  19300. the following conditions:
  19301. The above copyright notice and this permission notice shall be included
  19302. in all copies or substantial portions of the Software.
  19303. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19304. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19305. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19306. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  19307. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  19308. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  19309. OTHER DEALINGS IN THE SOFTWARE.
  19310. */
  19311. /*global define*/
  19312. define('ThirdParty/sprintf',[],function() {
  19313. function sprintf () {
  19314. // http://kevin.vanzonneveld.net
  19315. // + original by: Ash Searle (http://hexmen.com/blog/)
  19316. // + namespaced by: Michael White (http://getsprink.com)
  19317. // + tweaked by: Jack
  19318. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  19319. // + input by: Paulo Freitas
  19320. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  19321. // + input by: Brett Zamir (http://brett-zamir.me)
  19322. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  19323. // + improved by: Dj
  19324. // + improved by: Allidylls
  19325. // * example 1: sprintf("%01.2f", 123.1);
  19326. // * returns 1: 123.10
  19327. // * example 2: sprintf("[%10s]", 'monkey');
  19328. // * returns 2: '[ monkey]'
  19329. // * example 3: sprintf("[%'#10s]", 'monkey');
  19330. // * returns 3: '[####monkey]'
  19331. // * example 4: sprintf("%d", 123456789012345);
  19332. // * returns 4: '123456789012345'
  19333. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  19334. var a = arguments,
  19335. i = 0,
  19336. format = a[i++];
  19337. // pad()
  19338. var pad = function (str, len, chr, leftJustify) {
  19339. if (!chr) {
  19340. chr = ' ';
  19341. }
  19342. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  19343. return leftJustify ? str + padding : padding + str;
  19344. };
  19345. // justify()
  19346. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  19347. var diff = minWidth - value.length;
  19348. if (diff > 0) {
  19349. if (leftJustify || !zeroPad) {
  19350. value = pad(value, minWidth, customPadChar, leftJustify);
  19351. } else {
  19352. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  19353. }
  19354. }
  19355. return value;
  19356. };
  19357. // formatBaseX()
  19358. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  19359. // Note: casts negative numbers to positive ones
  19360. var number = value >>> 0;
  19361. prefix = prefix && number && {
  19362. '2': '0b',
  19363. '8': '0',
  19364. '16': '0x'
  19365. }[base] || '';
  19366. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  19367. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  19368. };
  19369. // formatString()
  19370. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  19371. if (precision != null) {
  19372. value = value.slice(0, precision);
  19373. }
  19374. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  19375. };
  19376. // doFormat()
  19377. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  19378. var number;
  19379. var prefix;
  19380. var method;
  19381. var textTransform;
  19382. var value;
  19383. if (substring == '%%') {
  19384. return '%';
  19385. }
  19386. // parse flags
  19387. var leftJustify = false,
  19388. positivePrefix = '',
  19389. zeroPad = false,
  19390. prefixBaseX = false,
  19391. customPadChar = ' ';
  19392. var flagsl = flags.length;
  19393. for (var j = 0; flags && j < flagsl; j++) {
  19394. switch (flags.charAt(j)) {
  19395. case ' ':
  19396. positivePrefix = ' ';
  19397. break;
  19398. case '+':
  19399. positivePrefix = '+';
  19400. break;
  19401. case '-':
  19402. leftJustify = true;
  19403. break;
  19404. case "'":
  19405. customPadChar = flags.charAt(j + 1);
  19406. break;
  19407. case '0':
  19408. zeroPad = true;
  19409. break;
  19410. case '#':
  19411. prefixBaseX = true;
  19412. break;
  19413. }
  19414. }
  19415. // parameters may be null, undefined, empty-string or real valued
  19416. // we want to ignore null, undefined and empty-string values
  19417. if (!minWidth) {
  19418. minWidth = 0;
  19419. } else if (minWidth == '*') {
  19420. minWidth = +a[i++];
  19421. } else if (minWidth.charAt(0) == '*') {
  19422. minWidth = +a[minWidth.slice(1, -1)];
  19423. } else {
  19424. minWidth = +minWidth;
  19425. }
  19426. // Note: undocumented perl feature:
  19427. if (minWidth < 0) {
  19428. minWidth = -minWidth;
  19429. leftJustify = true;
  19430. }
  19431. if (!isFinite(minWidth)) {
  19432. throw new Error('sprintf: (minimum-)width must be finite');
  19433. }
  19434. if (!precision) {
  19435. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  19436. } else if (precision == '*') {
  19437. precision = +a[i++];
  19438. } else if (precision.charAt(0) == '*') {
  19439. precision = +a[precision.slice(1, -1)];
  19440. } else {
  19441. precision = +precision;
  19442. }
  19443. // grab value using valueIndex if required?
  19444. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  19445. switch (type) {
  19446. case 's':
  19447. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  19448. case 'c':
  19449. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  19450. case 'b':
  19451. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19452. case 'o':
  19453. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19454. case 'x':
  19455. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19456. case 'X':
  19457. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  19458. case 'u':
  19459. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19460. case 'i':
  19461. case 'd':
  19462. number = +value || 0;
  19463. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  19464. prefix = number < 0 ? '-' : positivePrefix;
  19465. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  19466. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  19467. case 'e':
  19468. case 'E':
  19469. case 'f': // Should handle locales (as per setlocale)
  19470. case 'F':
  19471. case 'g':
  19472. case 'G':
  19473. number = +value;
  19474. prefix = number < 0 ? '-' : positivePrefix;
  19475. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  19476. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  19477. value = prefix + Math.abs(number)[method](precision);
  19478. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  19479. default:
  19480. return substring;
  19481. }
  19482. };
  19483. return format.replace(regex, doFormat);
  19484. }
  19485. return sprintf;
  19486. });
  19487. /*global define*/
  19488. define('Core/GregorianDate',[],function() {
  19489. 'use strict';
  19490. /**
  19491. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  19492. * In addition to submillisecond precision, this object can also represent leap seconds.
  19493. * @alias GregorianDate
  19494. * @constructor
  19495. *
  19496. * @see JulianDate#toGregorianDate
  19497. */
  19498. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  19499. /**
  19500. * Gets or sets the year as a whole number.
  19501. * @type {Number}
  19502. */
  19503. this.year = year;
  19504. /**
  19505. * Gets or sets the month as a whole number with range [1, 12].
  19506. * @type {Number}
  19507. */
  19508. this.month = month;
  19509. /**
  19510. * Gets or sets the day of the month as a whole number starting at 1.
  19511. * @type {Number}
  19512. */
  19513. this.day = day;
  19514. /**
  19515. * Gets or sets the hour as a whole number with range [0, 23].
  19516. * @type {Number}
  19517. */
  19518. this.hour = hour;
  19519. /**
  19520. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  19521. * @type {Number}
  19522. */
  19523. this.minute = minute;
  19524. /**
  19525. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  19526. * @type {Number}
  19527. */
  19528. this.second = second;
  19529. /**
  19530. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  19531. * @type {Number}
  19532. */
  19533. this.millisecond = millisecond;
  19534. /**
  19535. * Gets or sets whether this time is during a leap second.
  19536. * @type {Boolean}
  19537. */
  19538. this.isLeapSecond = isLeapSecond;
  19539. }
  19540. return GregorianDate;
  19541. });
  19542. /*global define*/
  19543. define('Core/isLeapYear',[
  19544. './DeveloperError'
  19545. ], function(
  19546. DeveloperError) {
  19547. 'use strict';
  19548. /**
  19549. * Determines if a given date is a leap year.
  19550. *
  19551. * @exports isLeapYear
  19552. *
  19553. * @param {Number} year The year to be tested.
  19554. * @returns {Boolean} True if <code>year</code> is a leap year.
  19555. *
  19556. * @example
  19557. * var leapYear = Cesium.isLeapYear(2000); // true
  19558. */
  19559. function isLeapYear(year) {
  19560. if (year === null || isNaN(year)) {
  19561. throw new DeveloperError('year is required and must be a number.');
  19562. }
  19563. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  19564. }
  19565. return isLeapYear;
  19566. });
  19567. /*global define*/
  19568. define('Core/LeapSecond',[],function() {
  19569. 'use strict';
  19570. /**
  19571. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  19572. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  19573. * @alias LeapSecond
  19574. * @constructor
  19575. *
  19576. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  19577. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  19578. */
  19579. function LeapSecond(date, offset) {
  19580. /**
  19581. * Gets or sets the date at which this leap second occurs.
  19582. * @type {JulianDate}
  19583. */
  19584. this.julianDate = date;
  19585. /**
  19586. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  19587. * of this leap second.
  19588. * @type {Number}
  19589. */
  19590. this.offset = offset;
  19591. }
  19592. return LeapSecond;
  19593. });
  19594. /*global define*/
  19595. define('Core/TimeConstants',[
  19596. './freezeObject'
  19597. ], function(
  19598. freezeObject) {
  19599. 'use strict';
  19600. /**
  19601. * Constants for time conversions like those done by {@link JulianDate}.
  19602. *
  19603. * @exports TimeConstants
  19604. *
  19605. * @see JulianDate
  19606. *
  19607. * @private
  19608. */
  19609. var TimeConstants = {
  19610. /**
  19611. * The number of seconds in one millisecond: <code>0.001</code>
  19612. * @type {Number}
  19613. * @constant
  19614. */
  19615. SECONDS_PER_MILLISECOND : 0.001,
  19616. /**
  19617. * The number of seconds in one minute: <code>60</code>.
  19618. * @type {Number}
  19619. * @constant
  19620. */
  19621. SECONDS_PER_MINUTE : 60.0,
  19622. /**
  19623. * The number of minutes in one hour: <code>60</code>.
  19624. * @type {Number}
  19625. * @constant
  19626. */
  19627. MINUTES_PER_HOUR : 60.0,
  19628. /**
  19629. * The number of hours in one day: <code>24</code>.
  19630. * @type {Number}
  19631. * @constant
  19632. */
  19633. HOURS_PER_DAY : 24.0,
  19634. /**
  19635. * The number of seconds in one hour: <code>3600</code>.
  19636. * @type {Number}
  19637. * @constant
  19638. */
  19639. SECONDS_PER_HOUR : 3600.0,
  19640. /**
  19641. * The number of minutes in one day: <code>1440</code>.
  19642. * @type {Number}
  19643. * @constant
  19644. */
  19645. MINUTES_PER_DAY : 1440.0,
  19646. /**
  19647. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  19648. * @type {Number}
  19649. * @constant
  19650. */
  19651. SECONDS_PER_DAY : 86400.0,
  19652. /**
  19653. * The number of days in one Julian century: <code>36525</code>.
  19654. * @type {Number}
  19655. * @constant
  19656. */
  19657. DAYS_PER_JULIAN_CENTURY : 36525.0,
  19658. /**
  19659. * One trillionth of a second.
  19660. * @type {Number}
  19661. * @constant
  19662. */
  19663. PICOSECOND : 0.000000001,
  19664. /**
  19665. * The number of days to subtract from a Julian date to determine the
  19666. * modified Julian date, which gives the number of days since midnight
  19667. * on November 17, 1858.
  19668. * @type {Number}
  19669. * @constant
  19670. */
  19671. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  19672. };
  19673. return freezeObject(TimeConstants);
  19674. });
  19675. /*global define*/
  19676. define('Core/TimeStandard',[
  19677. './freezeObject'
  19678. ], function(
  19679. freezeObject) {
  19680. 'use strict';
  19681. /**
  19682. * Provides the type of time standards which JulianDate can take as input.
  19683. *
  19684. * @exports TimeStandard
  19685. *
  19686. * @see JulianDate
  19687. */
  19688. var TimeStandard = {
  19689. /**
  19690. * Represents the coordinated Universal Time (UTC) time standard.
  19691. *
  19692. * UTC is related to TAI according to the relationship
  19693. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  19694. * seconds which have been introduced as of the time in TAI.
  19695. *
  19696. */
  19697. UTC : 0,
  19698. /**
  19699. * Represents the International Atomic Time (TAI) time standard.
  19700. * TAI is the principal time standard to which the other time standards are related.
  19701. */
  19702. TAI : 1
  19703. };
  19704. return freezeObject(TimeStandard);
  19705. });
  19706. /*global define*/
  19707. define('Core/JulianDate',[
  19708. '../ThirdParty/sprintf',
  19709. './binarySearch',
  19710. './defaultValue',
  19711. './defined',
  19712. './DeveloperError',
  19713. './GregorianDate',
  19714. './isLeapYear',
  19715. './LeapSecond',
  19716. './TimeConstants',
  19717. './TimeStandard'
  19718. ], function(
  19719. sprintf,
  19720. binarySearch,
  19721. defaultValue,
  19722. defined,
  19723. DeveloperError,
  19724. GregorianDate,
  19725. isLeapYear,
  19726. LeapSecond,
  19727. TimeConstants,
  19728. TimeStandard) {
  19729. 'use strict';
  19730. var gregorianDateScratch = new GregorianDate();
  19731. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  19732. var daysInLeapFeburary = 29;
  19733. function compareLeapSecondDates(leapSecond, dateToFind) {
  19734. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  19735. }
  19736. // we don't really need a leap second instance, anything with a julianDate property will do
  19737. var binarySearchScratchLeapSecond = new LeapSecond();
  19738. function convertUtcToTai(julianDate) {
  19739. //Even though julianDate is in UTC, we'll treat it as TAI and
  19740. //search the leap second table for it.
  19741. binarySearchScratchLeapSecond.julianDate = julianDate;
  19742. var leapSeconds = JulianDate.leapSeconds;
  19743. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  19744. if (index < 0) {
  19745. index = ~index;
  19746. }
  19747. if (index >= leapSeconds.length) {
  19748. index = leapSeconds.length - 1;
  19749. }
  19750. var offset = leapSeconds[index].offset;
  19751. if (index > 0) {
  19752. //Now we have the index of the closest leap second that comes on or after our UTC time.
  19753. //However, if the difference between the UTC date being converted and the TAI
  19754. //defined leap second is greater than the offset, we are off by one and need to use
  19755. //the previous leap second.
  19756. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  19757. if (difference > offset) {
  19758. index--;
  19759. offset = leapSeconds[index].offset;
  19760. }
  19761. }
  19762. JulianDate.addSeconds(julianDate, offset, julianDate);
  19763. }
  19764. function convertTaiToUtc(julianDate, result) {
  19765. binarySearchScratchLeapSecond.julianDate = julianDate;
  19766. var leapSeconds = JulianDate.leapSeconds;
  19767. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  19768. if (index < 0) {
  19769. index = ~index;
  19770. }
  19771. //All times before our first leap second get the first offset.
  19772. if (index === 0) {
  19773. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  19774. }
  19775. //All times after our leap second get the last offset.
  19776. if (index >= leapSeconds.length) {
  19777. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  19778. }
  19779. //Compute the difference between the found leap second and the time we are converting.
  19780. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  19781. if (difference === 0) {
  19782. //The date is in our leap second table.
  19783. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  19784. }
  19785. if (difference <= 1.0) {
  19786. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  19787. return undefined;
  19788. }
  19789. //The time is in between two leap seconds, index is the leap second after the date
  19790. //we're converting, so we subtract one to get the correct LeapSecond instance.
  19791. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  19792. }
  19793. function setComponents(wholeDays, secondsOfDay, julianDate) {
  19794. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  19795. wholeDays += extraDays;
  19796. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  19797. if (secondsOfDay < 0) {
  19798. wholeDays--;
  19799. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  19800. }
  19801. julianDate.dayNumber = wholeDays;
  19802. julianDate.secondsOfDay = secondsOfDay;
  19803. return julianDate;
  19804. }
  19805. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  19806. // Algorithm from page 604 of the Explanatory Supplement to the
  19807. // Astronomical Almanac (Seidelmann 1992).
  19808. var a = ((month - 14) / 12) | 0;
  19809. var b = year + 4800 + a;
  19810. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  19811. // JulianDates are noon-based
  19812. hour = hour - 12;
  19813. if (hour < 0) {
  19814. hour += 24;
  19815. }
  19816. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  19817. if (secondsOfDay >= 43200.0) {
  19818. dayNumber -= 1;
  19819. }
  19820. return [dayNumber, secondsOfDay];
  19821. }
  19822. //Regular expressions used for ISO8601 date parsing.
  19823. //YYYY
  19824. var matchCalendarYear = /^(\d{4})$/;
  19825. //YYYY-MM (YYYYMM is invalid)
  19826. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  19827. //YYYY-DDD or YYYYDDD
  19828. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  19829. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  19830. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  19831. //YYYY-MM-DD or YYYYMMDD
  19832. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  19833. // Match utc offset
  19834. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  19835. // Match hours HH or HH.xxxxx
  19836. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  19837. // Match hours/minutes HH:MM HHMM.xxxxx
  19838. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  19839. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  19840. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  19841. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  19842. /**
  19843. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  19844. * For increased precision, this class stores the whole number part of the date and the seconds
  19845. * part of the date in separate components. In order to be safe for arithmetic and represent
  19846. * leap seconds, the date is always stored in the International Atomic Time standard
  19847. * {@link TimeStandard.TAI}.
  19848. * @alias JulianDate
  19849. * @constructor
  19850. *
  19851. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  19852. * @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.
  19853. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  19854. */
  19855. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  19856. /**
  19857. * Gets or sets the number of whole days.
  19858. * @type {Number}
  19859. */
  19860. this.dayNumber = undefined;
  19861. /**
  19862. * Gets or sets the number of seconds into the current day.
  19863. * @type {Number}
  19864. */
  19865. this.secondsOfDay = undefined;
  19866. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  19867. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  19868. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  19869. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  19870. var wholeDays = julianDayNumber | 0;
  19871. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  19872. setComponents(wholeDays, secondsOfDay, this);
  19873. if (timeStandard === TimeStandard.UTC) {
  19874. convertUtcToTai(this);
  19875. }
  19876. }
  19877. /**
  19878. * Creates a new instance from a JavaScript Date.
  19879. *
  19880. * @param {Date} date A JavaScript Date.
  19881. * @param {JulianDate} [result] An existing instance to use for the result.
  19882. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  19883. *
  19884. * @exception {DeveloperError} date must be a valid JavaScript Date.
  19885. */
  19886. JulianDate.fromDate = function(date, result) {
  19887. if (!(date instanceof Date) || isNaN(date.getTime())) {
  19888. throw new DeveloperError('date must be a valid JavaScript Date.');
  19889. }
  19890. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  19891. if (!defined(result)) {
  19892. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  19893. }
  19894. setComponents(components[0], components[1], result);
  19895. convertUtcToTai(result);
  19896. return result;
  19897. };
  19898. /**
  19899. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  19900. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  19901. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  19902. *
  19903. * @param {String} iso8601String An ISO 8601 date.
  19904. * @param {JulianDate} [result] An existing instance to use for the result.
  19905. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  19906. *
  19907. * @exception {DeveloperError} Invalid ISO 8601 date.
  19908. */
  19909. JulianDate.fromIso8601 = function(iso8601String, result) {
  19910. if (typeof iso8601String !== 'string') {
  19911. throw new DeveloperError(iso8601ErrorMessage);
  19912. }
  19913. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  19914. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  19915. iso8601String = iso8601String.replace(',', '.');
  19916. //Split the string into its date and time components, denoted by a mandatory T
  19917. var tokens = iso8601String.split('T');
  19918. var year;
  19919. var month = 1;
  19920. var day = 1;
  19921. var hour = 0;
  19922. var minute = 0;
  19923. var second = 0;
  19924. var millisecond = 0;
  19925. //Lacking a time is okay, but a missing date is illegal.
  19926. var date = tokens[0];
  19927. var time = tokens[1];
  19928. var tmp;
  19929. var inLeapYear;
  19930. if (!defined(date)) {
  19931. throw new DeveloperError(iso8601ErrorMessage);
  19932. }
  19933. var dashCount;
  19934. //First match the date against possible regular expressions.
  19935. tokens = date.match(matchCalendarDate);
  19936. if (tokens !== null) {
  19937. dashCount = date.split('-').length - 1;
  19938. if (dashCount > 0 && dashCount !== 2) {
  19939. throw new DeveloperError(iso8601ErrorMessage);
  19940. }
  19941. year = +tokens[1];
  19942. month = +tokens[2];
  19943. day = +tokens[3];
  19944. } else {
  19945. tokens = date.match(matchCalendarMonth);
  19946. if (tokens !== null) {
  19947. year = +tokens[1];
  19948. month = +tokens[2];
  19949. } else {
  19950. tokens = date.match(matchCalendarYear);
  19951. if (tokens !== null) {
  19952. year = +tokens[1];
  19953. } else {
  19954. //Not a year/month/day so it must be an ordinal date.
  19955. var dayOfYear;
  19956. tokens = date.match(matchOrdinalDate);
  19957. if (tokens !== null) {
  19958. year = +tokens[1];
  19959. dayOfYear = +tokens[2];
  19960. inLeapYear = isLeapYear(year);
  19961. //This validation is only applicable for this format.
  19962. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  19963. throw new DeveloperError(iso8601ErrorMessage);
  19964. }
  19965. } else {
  19966. tokens = date.match(matchWeekDate);
  19967. if (tokens !== null) {
  19968. //ISO week date to ordinal date from
  19969. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  19970. year = +tokens[1];
  19971. var weekNumber = +tokens[2];
  19972. var dayOfWeek = +tokens[3] || 0;
  19973. dashCount = date.split('-').length - 1;
  19974. if (dashCount > 0 &&
  19975. ((!defined(tokens[3]) && dashCount !== 1) ||
  19976. (defined(tokens[3]) && dashCount !== 2))) {
  19977. throw new DeveloperError(iso8601ErrorMessage);
  19978. }
  19979. var january4 = new Date(Date.UTC(year, 0, 4));
  19980. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  19981. } else {
  19982. //None of our regular expressions succeeded in parsing the date properly.
  19983. throw new DeveloperError(iso8601ErrorMessage);
  19984. }
  19985. }
  19986. //Split an ordinal date into month/day.
  19987. tmp = new Date(Date.UTC(year, 0, 1));
  19988. tmp.setUTCDate(dayOfYear);
  19989. month = tmp.getUTCMonth() + 1;
  19990. day = tmp.getUTCDate();
  19991. }
  19992. }
  19993. }
  19994. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  19995. inLeapYear = isLeapYear(year);
  19996. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  19997. throw new DeveloperError(iso8601ErrorMessage);
  19998. }
  19999. //Not move onto the time string, which is much simpler.
  20000. var offsetIndex;
  20001. if (defined(time)) {
  20002. tokens = time.match(matchHoursMinutesSeconds);
  20003. if (tokens !== null) {
  20004. dashCount = time.split(':').length - 1;
  20005. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  20006. throw new DeveloperError(iso8601ErrorMessage);
  20007. }
  20008. hour = +tokens[1];
  20009. minute = +tokens[2];
  20010. second = +tokens[3];
  20011. millisecond = +(tokens[4] || 0) * 1000.0;
  20012. offsetIndex = 5;
  20013. } else {
  20014. tokens = time.match(matchHoursMinutes);
  20015. if (tokens !== null) {
  20016. dashCount = time.split(':').length - 1;
  20017. if (dashCount > 2) {
  20018. throw new DeveloperError(iso8601ErrorMessage);
  20019. }
  20020. hour = +tokens[1];
  20021. minute = +tokens[2];
  20022. second = +(tokens[3] || 0) * 60.0;
  20023. offsetIndex = 4;
  20024. } else {
  20025. tokens = time.match(matchHours);
  20026. if (tokens !== null) {
  20027. hour = +tokens[1];
  20028. minute = +(tokens[2] || 0) * 60.0;
  20029. offsetIndex = 3;
  20030. } else {
  20031. throw new DeveloperError(iso8601ErrorMessage);
  20032. }
  20033. }
  20034. }
  20035. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  20036. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  20037. throw new DeveloperError(iso8601ErrorMessage);
  20038. }
  20039. //Check the UTC offset value, if no value exists, use local time
  20040. //a Z indicates UTC, + or - are offsets.
  20041. var offset = tokens[offsetIndex];
  20042. var offsetHours = +(tokens[offsetIndex + 1]);
  20043. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  20044. switch (offset) {
  20045. case '+':
  20046. hour = hour - offsetHours;
  20047. minute = minute - offsetMinutes;
  20048. break;
  20049. case '-':
  20050. hour = hour + offsetHours;
  20051. minute = minute + offsetMinutes;
  20052. break;
  20053. case 'Z':
  20054. break;
  20055. default:
  20056. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  20057. break;
  20058. }
  20059. } else {
  20060. //If no time is specified, it is considered the beginning of the day, local time.
  20061. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  20062. }
  20063. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  20064. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  20065. //Then we add it back in after converting to TAI.
  20066. var isLeapSecond = second === 60;
  20067. if (isLeapSecond) {
  20068. second--;
  20069. }
  20070. //Even if we successfully parsed the string into its components, after applying UTC offset or
  20071. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  20072. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  20073. while (minute >= 60) {
  20074. minute -= 60;
  20075. hour++;
  20076. }
  20077. while (hour >= 24) {
  20078. hour -= 24;
  20079. day++;
  20080. }
  20081. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  20082. while (day > tmp) {
  20083. day -= tmp;
  20084. month++;
  20085. if (month > 12) {
  20086. month -= 12;
  20087. year++;
  20088. }
  20089. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  20090. }
  20091. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  20092. while (minute < 0) {
  20093. minute += 60;
  20094. hour--;
  20095. }
  20096. while (hour < 0) {
  20097. hour += 24;
  20098. day--;
  20099. }
  20100. while (day < 1) {
  20101. month--;
  20102. if (month < 1) {
  20103. month += 12;
  20104. year--;
  20105. }
  20106. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  20107. day += tmp;
  20108. }
  20109. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  20110. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  20111. if (!defined(result)) {
  20112. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  20113. } else {
  20114. setComponents(components[0], components[1], result);
  20115. convertUtcToTai(result);
  20116. }
  20117. //If we were on a leap second, add it back.
  20118. if (isLeapSecond) {
  20119. JulianDate.addSeconds(result, 1, result);
  20120. }
  20121. return result;
  20122. };
  20123. /**
  20124. * Creates a new instance that represents the current system time.
  20125. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  20126. *
  20127. * @param {JulianDate} [result] An existing instance to use for the result.
  20128. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  20129. */
  20130. JulianDate.now = function(result) {
  20131. return JulianDate.fromDate(new Date(), result);
  20132. };
  20133. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  20134. /**
  20135. * Creates a {@link GregorianDate} from the provided instance.
  20136. *
  20137. * @param {JulianDate} julianDate The date to be converted.
  20138. * @param {GregorianDate} [result] An existing instance to use for the result.
  20139. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  20140. */
  20141. JulianDate.toGregorianDate = function(julianDate, result) {
  20142. if (!defined(julianDate)) {
  20143. throw new DeveloperError('julianDate is required.');
  20144. }
  20145. var isLeapSecond = false;
  20146. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  20147. if (!defined(thisUtc)) {
  20148. //Conversion to UTC will fail if we are during a leap second.
  20149. //If that's the case, subtract a second and convert again.
  20150. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  20151. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  20152. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  20153. isLeapSecond = true;
  20154. }
  20155. var julianDayNumber = thisUtc.dayNumber;
  20156. var secondsOfDay = thisUtc.secondsOfDay;
  20157. if (secondsOfDay >= 43200.0) {
  20158. julianDayNumber += 1;
  20159. }
  20160. // Algorithm from page 604 of the Explanatory Supplement to the
  20161. // Astronomical Almanac (Seidelmann 1992).
  20162. var L = (julianDayNumber + 68569) | 0;
  20163. var N = (4 * L / 146097) | 0;
  20164. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  20165. var I = ((4000 * (L + 1)) / 1461001) | 0;
  20166. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  20167. var J = ((80 * L) / 2447) | 0;
  20168. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  20169. L = (J / 11) | 0;
  20170. var month = (J + 2 - 12 * L) | 0;
  20171. var year = (100 * (N - 49) + I + L) | 0;
  20172. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  20173. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  20174. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  20175. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  20176. var second = remainingSeconds | 0;
  20177. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  20178. // JulianDates are noon-based
  20179. hour += 12;
  20180. if (hour > 23) {
  20181. hour -= 24;
  20182. }
  20183. //If we were on a leap second, add it back.
  20184. if (isLeapSecond) {
  20185. second += 1;
  20186. }
  20187. if (!defined(result)) {
  20188. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  20189. }
  20190. result.year = year;
  20191. result.month = month;
  20192. result.day = day;
  20193. result.hour = hour;
  20194. result.minute = minute;
  20195. result.second = second;
  20196. result.millisecond = millisecond;
  20197. result.isLeapSecond = isLeapSecond;
  20198. return result;
  20199. };
  20200. /**
  20201. * Creates a JavaScript Date from the provided instance.
  20202. * Since JavaScript dates are only accurate to the nearest millisecond and
  20203. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  20204. * If the provided JulianDate is during a leap second, the previous second is used.
  20205. *
  20206. * @param {JulianDate} julianDate The date to be converted.
  20207. * @returns {Date} A new instance representing the provided date.
  20208. */
  20209. JulianDate.toDate = function(julianDate) {
  20210. if (!defined(julianDate)) {
  20211. throw new DeveloperError('julianDate is required.');
  20212. }
  20213. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  20214. var second = gDate.second;
  20215. if (gDate.isLeapSecond) {
  20216. second -= 1;
  20217. }
  20218. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  20219. };
  20220. /**
  20221. * Creates an ISO8601 representation of the provided date.
  20222. *
  20223. * @param {JulianDate} julianDate The date to be converted.
  20224. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  20225. * @returns {String} The ISO8601 representation of the provided date.
  20226. */
  20227. JulianDate.toIso8601 = function(julianDate, precision) {
  20228. if (!defined(julianDate)) {
  20229. throw new DeveloperError('julianDate is required.');
  20230. }
  20231. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  20232. var millisecondStr;
  20233. if (!defined(precision) && gDate.millisecond !== 0) {
  20234. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  20235. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  20236. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  20237. }
  20238. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  20239. if (!defined(precision) || precision === 0) {
  20240. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  20241. }
  20242. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  20243. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  20244. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  20245. };
  20246. /**
  20247. * Duplicates a JulianDate instance.
  20248. *
  20249. * @param {JulianDate} julianDate The date to duplicate.
  20250. * @param {JulianDate} [result] An existing instance to use for the result.
  20251. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  20252. */
  20253. JulianDate.clone = function(julianDate, result) {
  20254. if (!defined(julianDate)) {
  20255. return undefined;
  20256. }
  20257. if (!defined(result)) {
  20258. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  20259. }
  20260. result.dayNumber = julianDate.dayNumber;
  20261. result.secondsOfDay = julianDate.secondsOfDay;
  20262. return result;
  20263. };
  20264. /**
  20265. * Compares two instances.
  20266. *
  20267. * @param {JulianDate} left The first instance.
  20268. * @param {JulianDate} right The second instance.
  20269. * @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.
  20270. */
  20271. JulianDate.compare = function(left, right) {
  20272. if (!defined(left)) {
  20273. throw new DeveloperError('left is required.');
  20274. }
  20275. if (!defined(right)) {
  20276. throw new DeveloperError('right is required.');
  20277. }
  20278. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  20279. if (julianDayNumberDifference !== 0) {
  20280. return julianDayNumberDifference;
  20281. }
  20282. return left.secondsOfDay - right.secondsOfDay;
  20283. };
  20284. /**
  20285. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  20286. *
  20287. * @param {JulianDate} [left] The first instance.
  20288. * @param {JulianDate} [right] The second instance.
  20289. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  20290. */
  20291. JulianDate.equals = function(left, right) {
  20292. return (left === right) ||
  20293. (defined(left) &&
  20294. defined(right) &&
  20295. left.dayNumber === right.dayNumber &&
  20296. left.secondsOfDay === right.secondsOfDay);
  20297. };
  20298. /**
  20299. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  20300. * each other. That is, in order for the dates to be considered equal (and for
  20301. * this function to return <code>true</code>), the absolute value of the difference between them, in
  20302. * seconds, must be less than <code>epsilon</code>.
  20303. *
  20304. * @param {JulianDate} [left] The first instance.
  20305. * @param {JulianDate} [right] The second instance.
  20306. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  20307. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  20308. */
  20309. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  20310. if (!defined(epsilon)) {
  20311. throw new DeveloperError('epsilon is required.');
  20312. }
  20313. return (left === right) ||
  20314. (defined(left) &&
  20315. defined(right) &&
  20316. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  20317. };
  20318. /**
  20319. * Computes the total number of whole and fractional days represented by the provided instance.
  20320. *
  20321. * @param {JulianDate} julianDate The date.
  20322. * @returns {Number} The Julian date as single floating point number.
  20323. */
  20324. JulianDate.totalDays = function(julianDate) {
  20325. if (!defined(julianDate)) {
  20326. throw new DeveloperError('julianDate is required.');
  20327. }
  20328. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  20329. };
  20330. /**
  20331. * Computes the difference in seconds between the provided instance.
  20332. *
  20333. * @param {JulianDate} left The first instance.
  20334. * @param {JulianDate} right The second instance.
  20335. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  20336. */
  20337. JulianDate.secondsDifference = function(left, right) {
  20338. if (!defined(left)) {
  20339. throw new DeveloperError('left is required.');
  20340. }
  20341. if (!defined(right)) {
  20342. throw new DeveloperError('right is required.');
  20343. }
  20344. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  20345. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  20346. };
  20347. /**
  20348. * Computes the difference in days between the provided instance.
  20349. *
  20350. * @param {JulianDate} left The first instance.
  20351. * @param {JulianDate} right The second instance.
  20352. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  20353. */
  20354. JulianDate.daysDifference = function(left, right) {
  20355. if (!defined(left)) {
  20356. throw new DeveloperError('left is required.');
  20357. }
  20358. if (!defined(right)) {
  20359. throw new DeveloperError('right is required.');
  20360. }
  20361. var dayDifference = (left.dayNumber - right.dayNumber);
  20362. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  20363. return dayDifference + secondDifference;
  20364. };
  20365. /**
  20366. * Computes the number of seconds the provided instance is ahead of UTC.
  20367. *
  20368. * @param {JulianDate} julianDate The date.
  20369. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  20370. */
  20371. JulianDate.computeTaiMinusUtc = function(julianDate) {
  20372. binarySearchScratchLeapSecond.julianDate = julianDate;
  20373. var leapSeconds = JulianDate.leapSeconds;
  20374. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  20375. if (index < 0) {
  20376. index = ~index;
  20377. --index;
  20378. if (index < 0) {
  20379. index = 0;
  20380. }
  20381. }
  20382. return leapSeconds[index].offset;
  20383. };
  20384. /**
  20385. * Adds the provided number of seconds to the provided date instance.
  20386. *
  20387. * @param {JulianDate} julianDate The date.
  20388. * @param {Number} seconds The number of seconds to add or subtract.
  20389. * @param {JulianDate} result An existing instance to use for the result.
  20390. * @returns {JulianDate} The modified result parameter.
  20391. */
  20392. JulianDate.addSeconds = function(julianDate, seconds, result) {
  20393. if (!defined(julianDate)) {
  20394. throw new DeveloperError('julianDate is required.');
  20395. }
  20396. if (!defined(seconds)) {
  20397. throw new DeveloperError('seconds is required.');
  20398. }
  20399. if (!defined(result)) {
  20400. throw new DeveloperError('result is required.');
  20401. }
  20402. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  20403. };
  20404. /**
  20405. * Adds the provided number of minutes to the provided date instance.
  20406. *
  20407. * @param {JulianDate} julianDate The date.
  20408. * @param {Number} minutes The number of minutes to add or subtract.
  20409. * @param {JulianDate} result An existing instance to use for the result.
  20410. * @returns {JulianDate} The modified result parameter.
  20411. */
  20412. JulianDate.addMinutes = function(julianDate, minutes, result) {
  20413. if (!defined(julianDate)) {
  20414. throw new DeveloperError('julianDate is required.');
  20415. }
  20416. if (!defined(minutes)) {
  20417. throw new DeveloperError('minutes is required.');
  20418. }
  20419. if (!defined(result)) {
  20420. throw new DeveloperError('result is required.');
  20421. }
  20422. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  20423. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  20424. };
  20425. /**
  20426. * Adds the provided number of hours to the provided date instance.
  20427. *
  20428. * @param {JulianDate} julianDate The date.
  20429. * @param {Number} hours The number of hours to add or subtract.
  20430. * @param {JulianDate} result An existing instance to use for the result.
  20431. * @returns {JulianDate} The modified result parameter.
  20432. */
  20433. JulianDate.addHours = function(julianDate, hours, result) {
  20434. if (!defined(julianDate)) {
  20435. throw new DeveloperError('julianDate is required.');
  20436. }
  20437. if (!defined(hours)) {
  20438. throw new DeveloperError('hours is required.');
  20439. }
  20440. if (!defined(result)) {
  20441. throw new DeveloperError('result is required.');
  20442. }
  20443. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  20444. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  20445. };
  20446. /**
  20447. * Adds the provided number of days to the provided date instance.
  20448. *
  20449. * @param {JulianDate} julianDate The date.
  20450. * @param {Number} days The number of days to add or subtract.
  20451. * @param {JulianDate} result An existing instance to use for the result.
  20452. * @returns {JulianDate} The modified result parameter.
  20453. */
  20454. JulianDate.addDays = function(julianDate, days, result) {
  20455. if (!defined(julianDate)) {
  20456. throw new DeveloperError('julianDate is required.');
  20457. }
  20458. if (!defined(days)) {
  20459. throw new DeveloperError('days is required.');
  20460. }
  20461. if (!defined(result)) {
  20462. throw new DeveloperError('result is required.');
  20463. }
  20464. var newJulianDayNumber = julianDate.dayNumber + days;
  20465. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  20466. };
  20467. /**
  20468. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  20469. *
  20470. * @param {JulianDate} left The first instance.
  20471. * @param {JulianDate} right The second instance.
  20472. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  20473. */
  20474. JulianDate.lessThan = function(left, right) {
  20475. return JulianDate.compare(left, right) < 0;
  20476. };
  20477. /**
  20478. * 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.
  20479. *
  20480. * @param {JulianDate} left The first instance.
  20481. * @param {JulianDate} right The second instance.
  20482. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  20483. */
  20484. JulianDate.lessThanOrEquals = function(left, right) {
  20485. return JulianDate.compare(left, right) <= 0;
  20486. };
  20487. /**
  20488. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  20489. *
  20490. * @param {JulianDate} left The first instance.
  20491. * @param {JulianDate} right The second instance.
  20492. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  20493. */
  20494. JulianDate.greaterThan = function(left, right) {
  20495. return JulianDate.compare(left, right) > 0;
  20496. };
  20497. /**
  20498. * 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.
  20499. *
  20500. * @param {JulianDate} left The first instance.
  20501. * @param {JulianDate} right The second instance.
  20502. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  20503. */
  20504. JulianDate.greaterThanOrEquals = function(left, right) {
  20505. return JulianDate.compare(left, right) >= 0;
  20506. };
  20507. /**
  20508. * Duplicates this instance.
  20509. *
  20510. * @param {JulianDate} [result] An existing instance to use for the result.
  20511. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  20512. */
  20513. JulianDate.prototype.clone = function(result) {
  20514. return JulianDate.clone(this, result);
  20515. };
  20516. /**
  20517. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  20518. *
  20519. * @param {JulianDate} [right] The second instance.
  20520. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  20521. */
  20522. JulianDate.prototype.equals = function(right) {
  20523. return JulianDate.equals(this, right);
  20524. };
  20525. /**
  20526. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  20527. * each other. That is, in order for the dates to be considered equal (and for
  20528. * this function to return <code>true</code>), the absolute value of the difference between them, in
  20529. * seconds, must be less than <code>epsilon</code>.
  20530. *
  20531. * @param {JulianDate} [right] The second instance.
  20532. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  20533. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  20534. */
  20535. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  20536. return JulianDate.equalsEpsilon(this, right, epsilon);
  20537. };
  20538. /**
  20539. * Creates a string representing this date in ISO8601 format.
  20540. *
  20541. * @returns {String} A string representing this date in ISO8601 format.
  20542. */
  20543. JulianDate.prototype.toString = function() {
  20544. return JulianDate.toIso8601(this);
  20545. };
  20546. /**
  20547. * Gets or sets the list of leap seconds used throughout Cesium.
  20548. * @memberof JulianDate
  20549. * @type {LeapSecond[]}
  20550. */
  20551. JulianDate.leapSeconds = [
  20552. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  20553. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  20554. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  20555. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  20556. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  20557. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  20558. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  20559. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  20560. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  20561. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  20562. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  20563. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  20564. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  20565. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  20566. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  20567. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  20568. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  20569. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  20570. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  20571. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  20572. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  20573. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  20574. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  20575. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  20576. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  20577. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  20578. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  20579. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  20580. ];
  20581. return JulianDate;
  20582. });
  20583. /*global define*/
  20584. define('Core/clone',[
  20585. './defaultValue'
  20586. ], function(
  20587. defaultValue) {
  20588. 'use strict';
  20589. /**
  20590. * Clones an object, returning a new object containing the same properties.
  20591. *
  20592. * @exports clone
  20593. *
  20594. * @param {Object} object The object to clone.
  20595. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  20596. * @returns {Object} The cloned object.
  20597. */
  20598. function clone(object, deep) {
  20599. if (object === null || typeof object !== 'object') {
  20600. return object;
  20601. }
  20602. deep = defaultValue(deep, false);
  20603. var result = new object.constructor();
  20604. for ( var propertyName in object) {
  20605. if (object.hasOwnProperty(propertyName)) {
  20606. var value = object[propertyName];
  20607. if (deep) {
  20608. value = clone(value, deep);
  20609. }
  20610. result[propertyName] = value;
  20611. }
  20612. }
  20613. return result;
  20614. }
  20615. return clone;
  20616. });
  20617. /*global define*/
  20618. define('Core/parseResponseHeaders',[], function() {
  20619. 'use strict';
  20620. /**
  20621. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  20622. * a dictionary.
  20623. *
  20624. * @exports parseResponseHeaders
  20625. *
  20626. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  20627. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  20628. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  20629. * is that header's value.
  20630. *
  20631. * @private
  20632. */
  20633. function parseResponseHeaders(headerString) {
  20634. var headers = {};
  20635. if (!headerString) {
  20636. return headers;
  20637. }
  20638. var headerPairs = headerString.split('\u000d\u000a');
  20639. for (var i = 0; i < headerPairs.length; ++i) {
  20640. var headerPair = headerPairs[i];
  20641. // Can't use split() here because it does the wrong thing
  20642. // if the header value has the string ": " in it.
  20643. var index = headerPair.indexOf('\u003a\u0020');
  20644. if (index > 0) {
  20645. var key = headerPair.substring(0, index);
  20646. var val = headerPair.substring(index + 2);
  20647. headers[key] = val;
  20648. }
  20649. }
  20650. return headers;
  20651. }
  20652. return parseResponseHeaders;
  20653. });
  20654. /*global define*/
  20655. define('Core/RequestErrorEvent',[
  20656. './defined',
  20657. './parseResponseHeaders'
  20658. ], function(
  20659. defined,
  20660. parseResponseHeaders) {
  20661. 'use strict';
  20662. /**
  20663. * An event that is raised when a request encounters an error.
  20664. *
  20665. * @constructor
  20666. * @alias RequestErrorEvent
  20667. *
  20668. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  20669. * @param {Object} [response] The response included along with the error.
  20670. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  20671. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  20672. */
  20673. function RequestErrorEvent(statusCode, response, responseHeaders) {
  20674. /**
  20675. * The HTTP error status code, such as 404. If the error does not have a particular
  20676. * HTTP code, this property will be undefined.
  20677. *
  20678. * @type {Number}
  20679. */
  20680. this.statusCode = statusCode;
  20681. /**
  20682. * The response included along with the error. If the error does not include a response,
  20683. * this property will be undefined.
  20684. *
  20685. * @type {Object}
  20686. */
  20687. this.response = response;
  20688. /**
  20689. * The headers included in the response, represented as an object literal of key/value pairs.
  20690. * If the error does not include any headers, this property will be undefined.
  20691. *
  20692. * @type {Object}
  20693. */
  20694. this.responseHeaders = responseHeaders;
  20695. if (typeof this.responseHeaders === 'string') {
  20696. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  20697. }
  20698. }
  20699. /**
  20700. * Creates a string representing this RequestErrorEvent.
  20701. * @memberof RequestErrorEvent
  20702. *
  20703. * @returns {String} A string representing the provided RequestErrorEvent.
  20704. */
  20705. RequestErrorEvent.prototype.toString = function() {
  20706. var str = 'Request has failed.';
  20707. if (defined(this.statusCode)) {
  20708. str += ' Status Code: ' + this.statusCode;
  20709. }
  20710. return str;
  20711. };
  20712. return RequestErrorEvent;
  20713. });
  20714. /**
  20715. * @license
  20716. *
  20717. * Grauw URI utilities
  20718. *
  20719. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  20720. *
  20721. * @author Laurens Holst (http://www.grauw.nl/)
  20722. *
  20723. * Copyright 2012 Laurens Holst
  20724. *
  20725. * Licensed under the Apache License, Version 2.0 (the "License");
  20726. * you may not use this file except in compliance with the License.
  20727. * You may obtain a copy of the License at
  20728. *
  20729. * http://www.apache.org/licenses/LICENSE-2.0
  20730. *
  20731. * Unless required by applicable law or agreed to in writing, software
  20732. * distributed under the License is distributed on an "AS IS" BASIS,
  20733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20734. * See the License for the specific language governing permissions and
  20735. * limitations under the License.
  20736. *
  20737. */
  20738. /*global define*/
  20739. define('ThirdParty/Uri',[],function() {
  20740. /**
  20741. * Constructs a URI object.
  20742. * @constructor
  20743. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  20744. * @param {string|URI} uri A string or URI object to create the object from.
  20745. */
  20746. function URI(uri) {
  20747. if (uri instanceof URI) { // copy constructor
  20748. this.scheme = uri.scheme;
  20749. this.authority = uri.authority;
  20750. this.path = uri.path;
  20751. this.query = uri.query;
  20752. this.fragment = uri.fragment;
  20753. } else if (uri) { // uri is URI string or cast to string
  20754. var c = parseRegex.exec(uri);
  20755. this.scheme = c[1];
  20756. this.authority = c[2];
  20757. this.path = c[3];
  20758. this.query = c[4];
  20759. this.fragment = c[5];
  20760. }
  20761. }
  20762. // Initial values on the prototype
  20763. URI.prototype.scheme = null;
  20764. URI.prototype.authority = null;
  20765. URI.prototype.path = '';
  20766. URI.prototype.query = null;
  20767. URI.prototype.fragment = null;
  20768. // Regular expression from RFC 3986 appendix B
  20769. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  20770. /**
  20771. * Returns the scheme part of the URI.
  20772. * In "http://example.com:80/a/b?x#y" this is "http".
  20773. */
  20774. URI.prototype.getScheme = function() {
  20775. return this.scheme;
  20776. };
  20777. /**
  20778. * Returns the authority part of the URI.
  20779. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  20780. */
  20781. URI.prototype.getAuthority = function() {
  20782. return this.authority;
  20783. };
  20784. /**
  20785. * Returns the path part of the URI.
  20786. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  20787. * In "mailto:mike@example.com" this is "mike@example.com".
  20788. */
  20789. URI.prototype.getPath = function() {
  20790. return this.path;
  20791. };
  20792. /**
  20793. * Returns the query part of the URI.
  20794. * In "http://example.com:80/a/b?x#y" this is "x".
  20795. */
  20796. URI.prototype.getQuery = function() {
  20797. return this.query;
  20798. };
  20799. /**
  20800. * Returns the fragment part of the URI.
  20801. * In "http://example.com:80/a/b?x#y" this is "y".
  20802. */
  20803. URI.prototype.getFragment = function() {
  20804. return this.fragment;
  20805. };
  20806. /**
  20807. * Tests whether the URI is an absolute URI.
  20808. * See RFC 3986 section 4.3.
  20809. */
  20810. URI.prototype.isAbsolute = function() {
  20811. return !!this.scheme && !this.fragment;
  20812. };
  20813. ///**
  20814. //* Extensive validation of the URI against the ABNF in RFC 3986
  20815. //*/
  20816. //URI.prototype.validate
  20817. /**
  20818. * Tests whether the URI is a same-document reference.
  20819. * See RFC 3986 section 4.4.
  20820. *
  20821. * To perform more thorough comparison, you can normalise the URI objects.
  20822. */
  20823. URI.prototype.isSameDocumentAs = function(uri) {
  20824. return uri.scheme == this.scheme &&
  20825. uri.authority == this.authority &&
  20826. uri.path == this.path &&
  20827. uri.query == this.query;
  20828. };
  20829. /**
  20830. * Simple String Comparison of two URIs.
  20831. * See RFC 3986 section 6.2.1.
  20832. *
  20833. * To perform more thorough comparison, you can normalise the URI objects.
  20834. */
  20835. URI.prototype.equals = function(uri) {
  20836. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  20837. };
  20838. /**
  20839. * Normalizes the URI using syntax-based normalization.
  20840. * This includes case normalization, percent-encoding normalization and path segment normalization.
  20841. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  20842. * (Although that would not be a valid URI in the first place. See validate().)
  20843. * See RFC 3986 section 6.2.2.
  20844. */
  20845. URI.prototype.normalize = function() {
  20846. this.removeDotSegments();
  20847. if (this.scheme)
  20848. this.scheme = this.scheme.toLowerCase();
  20849. if (this.authority)
  20850. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  20851. replace(caseRegex, replaceCase);
  20852. if (this.path)
  20853. this.path = this.path.replace(caseRegex, replaceCase);
  20854. if (this.query)
  20855. this.query = this.query.replace(caseRegex, replaceCase);
  20856. if (this.fragment)
  20857. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  20858. };
  20859. var caseRegex = /%[0-9a-z]{2}/gi;
  20860. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  20861. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  20862. function replaceCase(str) {
  20863. var dec = unescape(str);
  20864. return percentRegex.test(dec) ? dec : str.toUpperCase();
  20865. }
  20866. function replaceAuthority(str, p1, p2, p3) {
  20867. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  20868. }
  20869. /**
  20870. * Resolve a relative URI (this) against a base URI.
  20871. * The base URI must be an absolute URI.
  20872. * See RFC 3986 section 5.2
  20873. */
  20874. URI.prototype.resolve = function(baseURI) {
  20875. var uri = new URI();
  20876. if (this.scheme) {
  20877. uri.scheme = this.scheme;
  20878. uri.authority = this.authority;
  20879. uri.path = this.path;
  20880. uri.query = this.query;
  20881. } else {
  20882. uri.scheme = baseURI.scheme;
  20883. if (this.authority) {
  20884. uri.authority = this.authority;
  20885. uri.path = this.path;
  20886. uri.query = this.query;
  20887. } else {
  20888. uri.authority = baseURI.authority;
  20889. if (this.path == '') {
  20890. uri.path = baseURI.path;
  20891. uri.query = this.query || baseURI.query;
  20892. } else {
  20893. if (this.path.charAt(0) == '/') {
  20894. uri.path = this.path;
  20895. uri.removeDotSegments();
  20896. } else {
  20897. if (baseURI.authority && baseURI.path == '') {
  20898. uri.path = '/' + this.path;
  20899. } else {
  20900. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  20901. }
  20902. uri.removeDotSegments();
  20903. }
  20904. uri.query = this.query;
  20905. }
  20906. }
  20907. }
  20908. uri.fragment = this.fragment;
  20909. return uri;
  20910. };
  20911. /**
  20912. * Remove dot segments from path.
  20913. * See RFC 3986 section 5.2.4
  20914. * @private
  20915. */
  20916. URI.prototype.removeDotSegments = function() {
  20917. var input = this.path.split('/'),
  20918. output = [],
  20919. segment,
  20920. absPath = input[0] == '';
  20921. if (absPath)
  20922. input.shift();
  20923. var sFirst = input[0] == '' ? input.shift() : null;
  20924. while (input.length) {
  20925. segment = input.shift();
  20926. if (segment == '..') {
  20927. output.pop();
  20928. } else if (segment != '.') {
  20929. output.push(segment);
  20930. }
  20931. }
  20932. if (segment == '.' || segment == '..')
  20933. output.push('');
  20934. if (absPath)
  20935. output.unshift('');
  20936. this.path = output.join('/');
  20937. };
  20938. // We don't like this function because it builds up a cache that is never cleared.
  20939. // /**
  20940. // * Resolves a relative URI against an absolute base URI.
  20941. // * Convenience method.
  20942. // * @param {String} uri the relative URI to resolve
  20943. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  20944. // */
  20945. // URI.resolve = function(sURI, sBaseURI) {
  20946. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  20947. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  20948. // return uri.resolve(baseURI).toString();
  20949. // };
  20950. // var cache = {};
  20951. /**
  20952. * Serialises the URI to a string.
  20953. */
  20954. URI.prototype.toString = function() {
  20955. var result = '';
  20956. if (this.scheme)
  20957. result += this.scheme + ':';
  20958. if (this.authority)
  20959. result += '//' + this.authority;
  20960. result += this.path;
  20961. if (this.query)
  20962. result += '?' + this.query;
  20963. if (this.fragment)
  20964. result += '#' + this.fragment;
  20965. return result;
  20966. };
  20967. return URI;
  20968. });
  20969. /*global define*/
  20970. define('Core/TrustedServers',[
  20971. '../ThirdParty/Uri',
  20972. './defined',
  20973. './DeveloperError'
  20974. ], function(
  20975. Uri,
  20976. defined,
  20977. DeveloperError) {
  20978. 'use strict';
  20979. /**
  20980. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  20981. * any requests to these servers.
  20982. *
  20983. * @exports TrustedServers
  20984. *
  20985. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  20986. */
  20987. var TrustedServers = {};
  20988. var _servers = {};
  20989. /**
  20990. * Adds a trusted server to the registry
  20991. *
  20992. * @param {String} host The host to be added.
  20993. * @param {Number} port The port used to access the host.
  20994. *
  20995. * @example
  20996. * // Add a trusted server
  20997. * TrustedServers.add('my.server.com', 80);
  20998. */
  20999. TrustedServers.add = function(host, port) {
  21000. if (!defined(host)) {
  21001. throw new DeveloperError('host is required.');
  21002. }
  21003. if (!defined(port) || port <= 0) {
  21004. throw new DeveloperError('port is required to be greater than 0.');
  21005. }
  21006. var authority = host.toLowerCase() + ':' + port;
  21007. if (!defined(_servers[authority])) {
  21008. _servers[authority] = true;
  21009. }
  21010. };
  21011. /**
  21012. * Removes a trusted server from the registry
  21013. *
  21014. * @param {String} host The host to be removed.
  21015. * @param {Number} port The port used to access the host.
  21016. *
  21017. * @example
  21018. * // Remove a trusted server
  21019. * TrustedServers.remove('my.server.com', 80);
  21020. */
  21021. TrustedServers.remove = function(host, port) {
  21022. if (!defined(host)) {
  21023. throw new DeveloperError('host is required.');
  21024. }
  21025. if (!defined(port) || port <= 0) {
  21026. throw new DeveloperError('port is required to be greater than 0.');
  21027. }
  21028. var authority = host.toLowerCase() + ':' + port;
  21029. if (defined(_servers[authority])) {
  21030. delete _servers[authority];
  21031. }
  21032. };
  21033. function getAuthority(url) {
  21034. var uri = new Uri(url);
  21035. uri.normalize();
  21036. // Removes username:password@ so we just have host[:port]
  21037. var authority = uri.getAuthority();
  21038. if (!defined(authority)) {
  21039. return undefined; // Relative URL
  21040. }
  21041. if (authority.indexOf('@') !== -1) {
  21042. var parts = authority.split('@');
  21043. authority = parts[1];
  21044. }
  21045. // If the port is missing add one based on the scheme
  21046. if (authority.indexOf(':') === -1) {
  21047. var scheme = uri.getScheme();
  21048. if (!defined(scheme)) {
  21049. scheme = window.location.protocol;
  21050. scheme = scheme.substring(0, scheme.length-1);
  21051. }
  21052. if (scheme === 'http') {
  21053. authority += ':80';
  21054. } else if (scheme === 'https') {
  21055. authority += ':443';
  21056. } else {
  21057. return undefined;
  21058. }
  21059. }
  21060. return authority;
  21061. }
  21062. /**
  21063. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  21064. *
  21065. * @param {String} url The url to be tested against the trusted list
  21066. *
  21067. * @returns {boolean} Returns true if url is trusted, false otherwise.
  21068. *
  21069. * @example
  21070. * // Add server
  21071. * TrustedServers.add('my.server.com', 81);
  21072. *
  21073. * // Check if server is trusted
  21074. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  21075. * // my.server.com:81 is trusted
  21076. * }
  21077. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  21078. * // my.server.com isn't trusted
  21079. * }
  21080. */
  21081. TrustedServers.contains = function(url) {
  21082. if (!defined(url)) {
  21083. throw new DeveloperError('url is required.');
  21084. }
  21085. var authority = getAuthority(url);
  21086. if (defined(authority) && defined(_servers[authority])) {
  21087. return true;
  21088. }
  21089. return false;
  21090. };
  21091. /**
  21092. * Clears the registry
  21093. *
  21094. * @example
  21095. * // Remove a trusted server
  21096. * TrustedServers.clear();
  21097. */
  21098. TrustedServers.clear = function() {
  21099. _servers = {};
  21100. };
  21101. return TrustedServers;
  21102. });
  21103. /*global define*/
  21104. define('Core/loadWithXhr',[
  21105. '../ThirdParty/when',
  21106. './defaultValue',
  21107. './defined',
  21108. './DeveloperError',
  21109. './RequestErrorEvent',
  21110. './RuntimeError',
  21111. './TrustedServers'
  21112. ], function(
  21113. when,
  21114. defaultValue,
  21115. defined,
  21116. DeveloperError,
  21117. RequestErrorEvent,
  21118. RuntimeError,
  21119. TrustedServers) {
  21120. 'use strict';
  21121. /**
  21122. * Asynchronously loads the given URL. Returns a promise that will resolve to
  21123. * the result once loaded, or reject if the URL failed to load. The data is loaded
  21124. * using XMLHttpRequest, which means that in order to make requests to another origin,
  21125. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  21126. *
  21127. * @exports loadWithXhr
  21128. *
  21129. * @param {Object} options Object with the following properties:
  21130. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  21131. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  21132. * @param {String} [options.method='GET'] The HTTP method to use.
  21133. * @param {String} [options.data] The data to send with the request, if any.
  21134. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  21135. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  21136. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  21137. *
  21138. *
  21139. * @example
  21140. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  21141. * Cesium.loadWithXhr({
  21142. * url : 'some/url',
  21143. * responseType : 'blob'
  21144. * }).then(function(blob) {
  21145. * // use the data
  21146. * }).otherwise(function(error) {
  21147. * // an error occurred
  21148. * });
  21149. *
  21150. * @see loadArrayBuffer
  21151. * @see loadBlob
  21152. * @see loadJson
  21153. * @see loadText
  21154. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21155. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  21156. */
  21157. function loadWithXhr(options) {
  21158. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21159. if (!defined(options.url)) {
  21160. throw new DeveloperError('options.url is required.');
  21161. }
  21162. var responseType = options.responseType;
  21163. var method = defaultValue(options.method, 'GET');
  21164. var data = options.data;
  21165. var headers = options.headers;
  21166. var overrideMimeType = options.overrideMimeType;
  21167. return when(options.url, function(url) {
  21168. var deferred = when.defer();
  21169. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  21170. return deferred.promise;
  21171. });
  21172. }
  21173. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21174. function decodeDataUriText(isBase64, data) {
  21175. var result = decodeURIComponent(data);
  21176. if (isBase64) {
  21177. return atob(result);
  21178. }
  21179. return result;
  21180. }
  21181. function decodeDataUriArrayBuffer(isBase64, data) {
  21182. var byteString = decodeDataUriText(isBase64, data);
  21183. var buffer = new ArrayBuffer(byteString.length);
  21184. var view = new Uint8Array(buffer);
  21185. for (var i = 0; i < byteString.length; i++) {
  21186. view[i] = byteString.charCodeAt(i);
  21187. }
  21188. return buffer;
  21189. }
  21190. function decodeDataUri(dataUriRegexResult, responseType) {
  21191. responseType = defaultValue(responseType, '');
  21192. var mimeType = dataUriRegexResult[1];
  21193. var isBase64 = !!dataUriRegexResult[2];
  21194. var data = dataUriRegexResult[3];
  21195. switch (responseType) {
  21196. case '':
  21197. case 'text':
  21198. return decodeDataUriText(isBase64, data);
  21199. case 'arraybuffer':
  21200. return decodeDataUriArrayBuffer(isBase64, data);
  21201. case 'blob':
  21202. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  21203. return new Blob([buffer], {
  21204. type : mimeType
  21205. });
  21206. case 'document':
  21207. var parser = new DOMParser();
  21208. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  21209. case 'json':
  21210. return JSON.parse(decodeDataUriText(isBase64, data));
  21211. default:
  21212. throw new DeveloperError('Unhandled responseType: ' + responseType);
  21213. }
  21214. }
  21215. // This is broken out into a separate function so that it can be mocked for testing purposes.
  21216. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  21217. var dataUriRegexResult = dataUriRegex.exec(url);
  21218. if (dataUriRegexResult !== null) {
  21219. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  21220. return;
  21221. }
  21222. var xhr = new XMLHttpRequest();
  21223. if (TrustedServers.contains(url)) {
  21224. xhr.withCredentials = true;
  21225. }
  21226. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  21227. xhr.overrideMimeType(overrideMimeType);
  21228. }
  21229. xhr.open(method, url, true);
  21230. if (defined(headers)) {
  21231. for (var key in headers) {
  21232. if (headers.hasOwnProperty(key)) {
  21233. xhr.setRequestHeader(key, headers[key]);
  21234. }
  21235. }
  21236. }
  21237. if (defined(responseType)) {
  21238. xhr.responseType = responseType;
  21239. }
  21240. xhr.onload = function() {
  21241. if (xhr.status < 200 || xhr.status >= 300) {
  21242. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  21243. return;
  21244. }
  21245. var response = xhr.response;
  21246. var browserResponseType = xhr.responseType;
  21247. //All modern browsers will go into either the first if block or last else block.
  21248. //Other code paths support older browsers that either do not support the supplied responseType
  21249. //or do not support the xhr.response property.
  21250. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  21251. deferred.resolve(response);
  21252. } else if ((responseType === 'json') && typeof response === 'string') {
  21253. try {
  21254. deferred.resolve(JSON.parse(response));
  21255. } catch (e) {
  21256. deferred.reject(e);
  21257. }
  21258. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  21259. deferred.resolve(xhr.responseXML);
  21260. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  21261. deferred.resolve(xhr.responseText);
  21262. } else {
  21263. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  21264. }
  21265. };
  21266. xhr.onerror = function(e) {
  21267. deferred.reject(new RequestErrorEvent());
  21268. };
  21269. xhr.send(data);
  21270. };
  21271. loadWithXhr.defaultLoad = loadWithXhr.load;
  21272. return loadWithXhr;
  21273. });
  21274. /*global define*/
  21275. define('Core/loadText',[
  21276. './loadWithXhr'
  21277. ], function(
  21278. loadWithXhr) {
  21279. 'use strict';
  21280. /**
  21281. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  21282. * a String once loaded, or reject if the URL failed to load. The data is loaded
  21283. * using XMLHttpRequest, which means that in order to make requests to another origin,
  21284. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  21285. *
  21286. * @exports loadText
  21287. *
  21288. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  21289. * @param {Object} [headers] HTTP headers to send with the request.
  21290. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  21291. *
  21292. *
  21293. * @example
  21294. * // load text from a URL, setting a custom header
  21295. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  21296. * 'X-Custom-Header' : 'some value'
  21297. * }).then(function(text) {
  21298. * // Do something with the text
  21299. * }).otherwise(function(error) {
  21300. * // an error occurred
  21301. * });
  21302. *
  21303. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  21304. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21305. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  21306. */
  21307. function loadText(url, headers) {
  21308. return loadWithXhr({
  21309. url : url,
  21310. headers : headers
  21311. });
  21312. }
  21313. return loadText;
  21314. });
  21315. /*global define*/
  21316. define('Core/loadJson',[
  21317. './clone',
  21318. './defined',
  21319. './DeveloperError',
  21320. './loadText'
  21321. ], function(
  21322. clone,
  21323. defined,
  21324. DeveloperError,
  21325. loadText) {
  21326. 'use strict';
  21327. var defaultHeaders = {
  21328. Accept : 'application/json,*/*;q=0.01'
  21329. };
  21330. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  21331. /**
  21332. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  21333. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  21334. * using XMLHttpRequest, which means that in order to make requests to another origin,
  21335. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  21336. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  21337. * already specified.
  21338. *
  21339. * @exports loadJson
  21340. *
  21341. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  21342. * @param {Object} [headers] HTTP headers to send with the request.
  21343. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  21344. * if not specified.
  21345. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  21346. *
  21347. *
  21348. * @example
  21349. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  21350. * // Do something with the JSON object
  21351. * }).otherwise(function(error) {
  21352. * // an error occurred
  21353. * });
  21354. *
  21355. * @see loadText
  21356. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21357. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  21358. */
  21359. function loadJson(url, headers) {
  21360. if (!defined(url)) {
  21361. throw new DeveloperError('url is required.');
  21362. }
  21363. if (!defined(headers)) {
  21364. headers = defaultHeaders;
  21365. } else if (!defined(headers.Accept)) {
  21366. // clone before adding the Accept header
  21367. headers = clone(headers);
  21368. headers.Accept = defaultHeaders.Accept;
  21369. }
  21370. return loadText(url, headers).then(function(value) {
  21371. return JSON.parse(value);
  21372. });
  21373. }
  21374. return loadJson;
  21375. });
  21376. /*global define*/
  21377. define('Core/EarthOrientationParameters',[
  21378. '../ThirdParty/when',
  21379. './binarySearch',
  21380. './defaultValue',
  21381. './defined',
  21382. './EarthOrientationParametersSample',
  21383. './freezeObject',
  21384. './JulianDate',
  21385. './LeapSecond',
  21386. './loadJson',
  21387. './RuntimeError',
  21388. './TimeConstants',
  21389. './TimeStandard'
  21390. ], function(
  21391. when,
  21392. binarySearch,
  21393. defaultValue,
  21394. defined,
  21395. EarthOrientationParametersSample,
  21396. freezeObject,
  21397. JulianDate,
  21398. LeapSecond,
  21399. loadJson,
  21400. RuntimeError,
  21401. TimeConstants,
  21402. TimeStandard) {
  21403. 'use strict';
  21404. /**
  21405. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  21406. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  21407. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  21408. * Reference Frame (ITRF).
  21409. *
  21410. * @alias EarthOrientationParameters
  21411. * @constructor
  21412. *
  21413. * @param {Object} [options] Object with the following properties:
  21414. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  21415. * parameter nor options.data is specified, all EOP values are assumed
  21416. * to be 0.0. If options.data is specified, this parameter is
  21417. * ignored.
  21418. * @param {Object} [options.data] The actual EOP data. If neither this
  21419. * parameter nor options.data is specified, all EOP values are assumed
  21420. * to be 0.0.
  21421. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  21422. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  21423. * should be added to {@link JulianDate.leapSeconds}. False if
  21424. * new leap seconds should be handled correctly in the context
  21425. * of the EOP data but otherwise ignored.
  21426. *
  21427. * @example
  21428. * // An example EOP data file, EOP.json:
  21429. * {
  21430. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  21431. * "samples" : [
  21432. * "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,
  21433. * "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,
  21434. * "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
  21435. * ]
  21436. * }
  21437. *
  21438. * @example
  21439. * // Loading the EOP data
  21440. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  21441. * Cesium.Transforms.earthOrientationParameters = eop;
  21442. *
  21443. * @private
  21444. */
  21445. function EarthOrientationParameters(options) {
  21446. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21447. this._dates = undefined;
  21448. this._samples = undefined;
  21449. this._dateColumn = -1;
  21450. this._xPoleWanderRadiansColumn = -1;
  21451. this._yPoleWanderRadiansColumn = -1;
  21452. this._ut1MinusUtcSecondsColumn = -1;
  21453. this._xCelestialPoleOffsetRadiansColumn = -1;
  21454. this._yCelestialPoleOffsetRadiansColumn = -1;
  21455. this._taiMinusUtcSecondsColumn = -1;
  21456. this._columnCount = 0;
  21457. this._lastIndex = -1;
  21458. this._downloadPromise = undefined;
  21459. this._dataError = undefined;
  21460. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  21461. if (defined(options.data)) {
  21462. // Use supplied EOP data.
  21463. onDataReady(this, options.data);
  21464. } else if (defined(options.url)) {
  21465. // Download EOP data.
  21466. var that = this;
  21467. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  21468. onDataReady(that, eopData);
  21469. }, function() {
  21470. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  21471. });
  21472. } else {
  21473. // Use all zeros for EOP data.
  21474. onDataReady(this, {
  21475. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  21476. 'samples' : []
  21477. });
  21478. }
  21479. }
  21480. /**
  21481. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  21482. */
  21483. EarthOrientationParameters.NONE = freezeObject({
  21484. getPromiseToLoad : function() {
  21485. return when();
  21486. },
  21487. compute : function(date, result) {
  21488. if (!defined(result)) {
  21489. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  21490. } else {
  21491. result.xPoleWander = 0.0;
  21492. result.yPoleWander = 0.0;
  21493. result.xPoleOffset = 0.0;
  21494. result.yPoleOffset = 0.0;
  21495. result.ut1MinusUtc = 0.0;
  21496. }
  21497. return result;
  21498. }
  21499. });
  21500. /**
  21501. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  21502. * ready to use.
  21503. *
  21504. * @returns {Promise.<undefined>} The promise.
  21505. *
  21506. * @see when
  21507. */
  21508. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  21509. return when(this._downloadPromise);
  21510. };
  21511. /**
  21512. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  21513. * If the EOP data has not yet been download, this method returns undefined.
  21514. *
  21515. * @param {JulianDate} date The date for each to evaluate the EOP.
  21516. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  21517. * If this parameter is undefined, a new instance is created and returned.
  21518. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  21519. * undefined if the data necessary to evaluate EOP at the date has not yet been
  21520. * downloaded.
  21521. *
  21522. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  21523. *
  21524. * @see EarthOrientationParameters#getPromiseToLoad
  21525. */
  21526. EarthOrientationParameters.prototype.compute = function(date, result) {
  21527. // We cannot compute until the samples are available.
  21528. if (!defined(this._samples)) {
  21529. if (defined(this._dataError)) {
  21530. throw new RuntimeError(this._dataError);
  21531. }
  21532. return undefined;
  21533. }
  21534. if (!defined(result)) {
  21535. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  21536. }
  21537. if (this._samples.length === 0) {
  21538. result.xPoleWander = 0.0;
  21539. result.yPoleWander = 0.0;
  21540. result.xPoleOffset = 0.0;
  21541. result.yPoleOffset = 0.0;
  21542. result.ut1MinusUtc = 0.0;
  21543. return result;
  21544. }
  21545. var dates = this._dates;
  21546. var lastIndex = this._lastIndex;
  21547. var before = 0;
  21548. var after = 0;
  21549. if (defined(lastIndex)) {
  21550. var previousIndexDate = dates[lastIndex];
  21551. var nextIndexDate = dates[lastIndex + 1];
  21552. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  21553. var isAfterLastSample = !defined(nextIndexDate);
  21554. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  21555. if (isAfterPrevious && isBeforeNext) {
  21556. before = lastIndex;
  21557. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  21558. ++before;
  21559. }
  21560. after = before + 1;
  21561. interpolate(this, dates, this._samples, date, before, after, result);
  21562. return result;
  21563. }
  21564. }
  21565. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  21566. if (index >= 0) {
  21567. // If the next entry is the same date, use the later entry. This way, if two entries
  21568. // describe the same moment, one before a leap second and the other after, then we will use
  21569. // the post-leap second data.
  21570. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  21571. ++index;
  21572. }
  21573. before = index;
  21574. after = index;
  21575. } else {
  21576. after = ~index;
  21577. before = after - 1;
  21578. // Use the first entry if the date requested is before the beginning of the data.
  21579. if (before < 0) {
  21580. before = 0;
  21581. }
  21582. }
  21583. this._lastIndex = before;
  21584. interpolate(this, dates, this._samples, date, before, after, result);
  21585. return result;
  21586. };
  21587. function compareLeapSecondDates(leapSecond, dateToFind) {
  21588. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  21589. }
  21590. function onDataReady(eop, eopData) {
  21591. if (!defined(eopData.columnNames)) {
  21592. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  21593. return;
  21594. }
  21595. if (!defined(eopData.samples)) {
  21596. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  21597. return;
  21598. }
  21599. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  21600. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  21601. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  21602. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  21603. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  21604. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  21605. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  21606. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  21607. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  21608. return;
  21609. }
  21610. var samples = eop._samples = eopData.samples;
  21611. var dates = eop._dates = [];
  21612. eop._dateColumn = dateColumn;
  21613. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  21614. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  21615. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  21616. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  21617. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  21618. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  21619. eop._columnCount = eopData.columnNames.length;
  21620. eop._lastIndex = undefined;
  21621. var lastTaiMinusUtc;
  21622. var addNewLeapSeconds = eop._addNewLeapSeconds;
  21623. // Convert the ISO8601 dates to JulianDates.
  21624. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  21625. var mjd = samples[i + dateColumn];
  21626. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  21627. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  21628. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  21629. dates.push(date);
  21630. if (addNewLeapSeconds) {
  21631. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  21632. // We crossed a leap second boundary, so add the leap second
  21633. // if it does not already exist.
  21634. var leapSeconds = JulianDate.leapSeconds;
  21635. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  21636. if (leapSecondIndex < 0) {
  21637. var leapSecond = new LeapSecond(date, taiMinusUtc);
  21638. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  21639. }
  21640. }
  21641. lastTaiMinusUtc = taiMinusUtc;
  21642. }
  21643. }
  21644. }
  21645. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  21646. var start = index * columnCount;
  21647. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  21648. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  21649. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  21650. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  21651. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  21652. }
  21653. function linearInterp(dx, y1, y2) {
  21654. return y1 + dx * (y2 - y1);
  21655. }
  21656. function interpolate(eop, dates, samples, date, before, after, result) {
  21657. var columnCount = eop._columnCount;
  21658. // First check the bounds on the EOP data
  21659. // If we are after the bounds of the data, return zeros.
  21660. // The 'before' index should never be less than zero.
  21661. if (after > dates.length - 1) {
  21662. result.xPoleWander = 0;
  21663. result.yPoleWander = 0;
  21664. result.xPoleOffset = 0;
  21665. result.yPoleOffset = 0;
  21666. result.ut1MinusUtc = 0;
  21667. return result;
  21668. }
  21669. var beforeDate = dates[before];
  21670. var afterDate = dates[after];
  21671. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  21672. fillResultFromIndex(eop, samples, before, columnCount, result);
  21673. return result;
  21674. } else if (date.equals(afterDate)) {
  21675. fillResultFromIndex(eop, samples, after, columnCount, result);
  21676. return result;
  21677. }
  21678. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  21679. var startBefore = before * columnCount;
  21680. var startAfter = after * columnCount;
  21681. // Handle UT1 leap second edge case
  21682. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  21683. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  21684. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  21685. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  21686. // The absolute difference between the values is more than 0.5, so we may have
  21687. // crossed a leap second. Check if this is the case and, if so, adjust the
  21688. // afterValue to account for the leap second. This way, our interpolation will
  21689. // produce reasonable results.
  21690. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  21691. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  21692. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  21693. if (afterDate.equals(date)) {
  21694. // If we are at the end of the leap second interval, take the second value
  21695. // Otherwise, the interpolation below will yield the wrong side of the
  21696. // discontinuity
  21697. // At the end of the leap second, we need to start accounting for the jump
  21698. beforeUt1MinusUtc = afterUt1MinusUtc;
  21699. } else {
  21700. // Otherwise, remove the leap second so that the interpolation is correct
  21701. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  21702. }
  21703. }
  21704. }
  21705. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  21706. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  21707. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  21708. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  21709. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  21710. return result;
  21711. }
  21712. return EarthOrientationParameters;
  21713. });
  21714. /*global define*/
  21715. define('Core/HeadingPitchRoll',[
  21716. './defaultValue',
  21717. './defined',
  21718. './DeveloperError',
  21719. './Math'
  21720. ], function(
  21721. defaultValue,
  21722. defined,
  21723. DeveloperError,
  21724. CesiumMath) {
  21725. "use strict";
  21726. /**
  21727. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  21728. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  21729. * the positive x axis.
  21730. * @alias HeadingPitchRoll
  21731. * @constructor
  21732. *
  21733. * @param {Number} [heading=0.0] The heading component in radians.
  21734. * @param {Number} [pitch=0.0] The pitch component in radians.
  21735. * @param {Number} [roll=0.0] The roll component in radians.
  21736. */
  21737. function HeadingPitchRoll(heading, pitch, roll) {
  21738. this.heading = defaultValue(heading, 0.0);
  21739. this.pitch = defaultValue(pitch, 0.0);
  21740. this.roll = defaultValue(roll, 0.0);
  21741. }
  21742. /**
  21743. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  21744. *
  21745. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  21746. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  21747. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  21748. */
  21749. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  21750. if (!defined(quaternion)) {
  21751. throw new DeveloperError('quaternion is required');
  21752. }
  21753. if (!defined(result)) {
  21754. result = new HeadingPitchRoll();
  21755. }
  21756. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  21757. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  21758. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  21759. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  21760. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  21761. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  21762. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  21763. result.pitch = -Math.asin(test);
  21764. return result;
  21765. };
  21766. /**
  21767. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  21768. *
  21769. * @param {Number} heading the heading in degrees
  21770. * @param {Number} pitch the pitch in degrees
  21771. * @param {Number} roll the heading in degrees
  21772. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  21773. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  21774. */
  21775. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  21776. if (!defined(heading)) {
  21777. throw new DeveloperError('heading is required');
  21778. }
  21779. if (!defined(pitch)) {
  21780. throw new DeveloperError('pitch is required');
  21781. }
  21782. if (!defined(roll)) {
  21783. throw new DeveloperError('roll is required');
  21784. }
  21785. if (!defined(result)) {
  21786. result = new HeadingPitchRoll();
  21787. }
  21788. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  21789. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  21790. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  21791. return result;
  21792. };
  21793. /**
  21794. * Duplicates a HeadingPitchRoll instance.
  21795. *
  21796. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  21797. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  21798. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  21799. */
  21800. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  21801. if (!defined(headingPitchRoll)) {
  21802. return undefined;
  21803. }
  21804. if (!defined(result)) {
  21805. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  21806. }
  21807. result.heading = headingPitchRoll.heading;
  21808. result.pitch = headingPitchRoll.pitch;
  21809. result.roll = headingPitchRoll.roll;
  21810. return result;
  21811. };
  21812. /**
  21813. * Compares the provided HeadingPitchRolls componentwise and returns
  21814. * <code>true</code> if they are equal, <code>false</code> otherwise.
  21815. *
  21816. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  21817. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  21818. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  21819. */
  21820. HeadingPitchRoll.equals = function(left, right) {
  21821. return (left === right) ||
  21822. ((defined(left)) &&
  21823. (defined(right)) &&
  21824. (left.heading === right.heading) &&
  21825. (left.pitch === right.pitch) &&
  21826. (left.roll === right.roll));
  21827. };
  21828. /**
  21829. * Compares the provided HeadingPitchRolls componentwise and returns
  21830. * <code>true</code> if they pass an absolute or relative tolerance test,
  21831. * <code>false</code> otherwise.
  21832. *
  21833. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  21834. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  21835. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  21836. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  21837. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  21838. */
  21839. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  21840. return (left === right) ||
  21841. (defined(left) &&
  21842. defined(right) &&
  21843. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  21844. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  21845. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  21846. };
  21847. /**
  21848. * Duplicates this HeadingPitchRoll instance.
  21849. *
  21850. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  21851. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  21852. */
  21853. HeadingPitchRoll.prototype.clone = function(result) {
  21854. return HeadingPitchRoll.clone(this, result);
  21855. };
  21856. /**
  21857. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  21858. * <code>true</code> if they are equal, <code>false</code> otherwise.
  21859. *
  21860. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  21861. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  21862. */
  21863. HeadingPitchRoll.prototype.equals = function(right) {
  21864. return HeadingPitchRoll.equals(this, right);
  21865. };
  21866. /**
  21867. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  21868. * <code>true</code> if they pass an absolute or relative tolerance test,
  21869. * <code>false</code> otherwise.
  21870. *
  21871. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  21872. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  21873. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  21874. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  21875. */
  21876. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  21877. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  21878. };
  21879. /**
  21880. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  21881. *
  21882. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  21883. */
  21884. HeadingPitchRoll.prototype.toString = function() {
  21885. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  21886. };
  21887. return HeadingPitchRoll;
  21888. });
  21889. /*global define*/
  21890. define('Core/getAbsoluteUri',[
  21891. '../ThirdParty/Uri',
  21892. './defaultValue',
  21893. './defined',
  21894. './DeveloperError'
  21895. ], function(
  21896. Uri,
  21897. defaultValue,
  21898. defined,
  21899. DeveloperError) {
  21900. 'use strict';
  21901. /**
  21902. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  21903. * @exports getAbsoluteUri
  21904. *
  21905. * @param {String} relative The relative Uri.
  21906. * @param {String} [base] The base Uri.
  21907. * @returns {String} The absolute Uri of the given relative Uri.
  21908. *
  21909. * @example
  21910. * //absolute Uri will be "https://test.com/awesome.png";
  21911. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  21912. */
  21913. function getAbsoluteUri(relative, base) {
  21914. if (!defined(relative)) {
  21915. throw new DeveloperError('relative uri is required.');
  21916. }
  21917. base = defaultValue(base, document.location.href);
  21918. var baseUri = new Uri(base);
  21919. var relativeUri = new Uri(relative);
  21920. return relativeUri.resolve(baseUri).toString();
  21921. }
  21922. return getAbsoluteUri;
  21923. });
  21924. /*global define*/
  21925. define('Core/joinUrls',[
  21926. '../ThirdParty/Uri',
  21927. './defaultValue',
  21928. './defined',
  21929. './DeveloperError'
  21930. ], function(
  21931. Uri,
  21932. defaultValue,
  21933. defined,
  21934. DeveloperError) {
  21935. 'use strict';
  21936. /**
  21937. * Function for joining URLs in a manner that is aware of query strings and fragments.
  21938. * This is useful when the base URL has a query string that needs to be maintained
  21939. * (e.g. a presigned base URL).
  21940. * @param {String|Uri} first The base URL.
  21941. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  21942. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  21943. * @private
  21944. */
  21945. function joinUrls(first, second, appendSlash) {
  21946. if (!defined(first)) {
  21947. throw new DeveloperError('first is required');
  21948. }
  21949. if (!defined(second)) {
  21950. throw new DeveloperError('second is required');
  21951. }
  21952. appendSlash = defaultValue(appendSlash, true);
  21953. if (!(first instanceof Uri)) {
  21954. first = new Uri(first);
  21955. }
  21956. if (!(second instanceof Uri)) {
  21957. second = new Uri(second);
  21958. }
  21959. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  21960. // not a scheme, add a scheme matching the page's scheme.
  21961. if (defined(second.authority) && !defined(second.scheme)) {
  21962. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  21963. second.scheme = new Uri(document.location.href).scheme;
  21964. } else {
  21965. // Not in a browser? Use the first URL's scheme instead.
  21966. second.scheme = first.scheme;
  21967. }
  21968. }
  21969. // If the second URL is absolute, use it for the scheme, authority, and path.
  21970. var baseUri = first;
  21971. if (second.isAbsolute()) {
  21972. baseUri = second;
  21973. }
  21974. var url = '';
  21975. if (defined(baseUri.scheme)) {
  21976. url += baseUri.scheme + ':';
  21977. }
  21978. if (defined(baseUri.authority)) {
  21979. url += '//' + baseUri.authority;
  21980. if (baseUri.path !== '' && baseUri.path !== '/') {
  21981. url = url.replace(/\/?$/, '/');
  21982. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  21983. }
  21984. }
  21985. // Combine the paths (only if second is relative).
  21986. if (baseUri === first) {
  21987. if (appendSlash) {
  21988. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  21989. } else {
  21990. url += first.path + second.path;
  21991. }
  21992. } else {
  21993. url += second.path;
  21994. }
  21995. // Combine the queries and fragments.
  21996. var hasFirstQuery = defined(first.query);
  21997. var hasSecondQuery = defined(second.query);
  21998. if (hasFirstQuery && hasSecondQuery) {
  21999. url += '?' + first.query + '&' + second.query;
  22000. } else if (hasFirstQuery && !hasSecondQuery) {
  22001. url += '?' + first.query;
  22002. } else if (!hasFirstQuery && hasSecondQuery) {
  22003. url += '?' + second.query;
  22004. }
  22005. var hasSecondFragment = defined(second.fragment);
  22006. if (defined(first.fragment) && !hasSecondFragment) {
  22007. url += '#' + first.fragment;
  22008. } else if (hasSecondFragment) {
  22009. url += '#' + second.fragment;
  22010. }
  22011. return url;
  22012. }
  22013. return joinUrls;
  22014. });
  22015. /*global define*/
  22016. define('Core/buildModuleUrl',[
  22017. '../ThirdParty/Uri',
  22018. './defined',
  22019. './DeveloperError',
  22020. './getAbsoluteUri',
  22021. './joinUrls',
  22022. 'require'
  22023. ], function(
  22024. Uri,
  22025. defined,
  22026. DeveloperError,
  22027. getAbsoluteUri,
  22028. joinUrls,
  22029. require) {
  22030. 'use strict';
  22031. /*global CESIUM_BASE_URL*/
  22032. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  22033. function getBaseUrlFromCesiumScript() {
  22034. var scripts = document.getElementsByTagName('script');
  22035. for ( var i = 0, len = scripts.length; i < len; ++i) {
  22036. var src = scripts[i].getAttribute('src');
  22037. var result = cesiumScriptRegex.exec(src);
  22038. if (result !== null) {
  22039. return result[1];
  22040. }
  22041. }
  22042. return undefined;
  22043. }
  22044. var baseUrl;
  22045. function getCesiumBaseUrl() {
  22046. if (defined(baseUrl)) {
  22047. return baseUrl;
  22048. }
  22049. var baseUrlString;
  22050. if (typeof CESIUM_BASE_URL !== 'undefined') {
  22051. baseUrlString = CESIUM_BASE_URL;
  22052. } else {
  22053. baseUrlString = getBaseUrlFromCesiumScript();
  22054. }
  22055. if (!defined(baseUrlString)) {
  22056. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  22057. }
  22058. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  22059. return baseUrl;
  22060. }
  22061. function buildModuleUrlFromRequireToUrl(moduleID) {
  22062. //moduleID will be non-relative, so require it relative to this module, in Core.
  22063. return require.toUrl('../' + moduleID);
  22064. }
  22065. function buildModuleUrlFromBaseUrl(moduleID) {
  22066. return joinUrls(getCesiumBaseUrl(), moduleID);
  22067. }
  22068. var implementation;
  22069. var a;
  22070. /**
  22071. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  22072. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  22073. * the base URL of the Cesium.js script.
  22074. *
  22075. * @private
  22076. */
  22077. function buildModuleUrl(moduleID) {
  22078. if (!defined(implementation)) {
  22079. //select implementation
  22080. if (defined(require.toUrl)) {
  22081. implementation = buildModuleUrlFromRequireToUrl;
  22082. } else {
  22083. implementation = buildModuleUrlFromBaseUrl;
  22084. }
  22085. }
  22086. if (!defined(a)) {
  22087. a = document.createElement('a');
  22088. }
  22089. var url = implementation(moduleID);
  22090. a.href = url;
  22091. a.href = a.href; // IE only absolutizes href on get, not set
  22092. return a.href;
  22093. }
  22094. // exposed for testing
  22095. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  22096. /**
  22097. * Sets the base URL for resolving modules.
  22098. * @param {String} value The new base URL.
  22099. */
  22100. buildModuleUrl.setBaseUrl = function(value) {
  22101. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  22102. };
  22103. return buildModuleUrl;
  22104. });
  22105. /*global define*/
  22106. define('Core/Iau2006XysSample',[],function() {
  22107. 'use strict';
  22108. /**
  22109. * An IAU 2006 XYS value sampled at a particular time.
  22110. *
  22111. * @alias Iau2006XysSample
  22112. * @constructor
  22113. *
  22114. * @param {Number} x The X value.
  22115. * @param {Number} y The Y value.
  22116. * @param {Number} s The S value.
  22117. *
  22118. * @private
  22119. */
  22120. function Iau2006XysSample(x, y, s) {
  22121. /**
  22122. * The X value.
  22123. * @type {Number}
  22124. */
  22125. this.x = x;
  22126. /**
  22127. * The Y value.
  22128. * @type {Number}
  22129. */
  22130. this.y = y;
  22131. /**
  22132. * The S value.
  22133. * @type {Number}
  22134. */
  22135. this.s = s;
  22136. }
  22137. return Iau2006XysSample;
  22138. });
  22139. /*global define*/
  22140. define('Core/Iau2006XysData',[
  22141. '../ThirdParty/when',
  22142. './buildModuleUrl',
  22143. './defaultValue',
  22144. './defined',
  22145. './Iau2006XysSample',
  22146. './JulianDate',
  22147. './loadJson',
  22148. './TimeStandard'
  22149. ], function(
  22150. when,
  22151. buildModuleUrl,
  22152. defaultValue,
  22153. defined,
  22154. Iau2006XysSample,
  22155. JulianDate,
  22156. loadJson,
  22157. TimeStandard) {
  22158. 'use strict';
  22159. /**
  22160. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  22161. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  22162. *
  22163. * @alias Iau2006XysData
  22164. * @constructor
  22165. *
  22166. * @param {Object} [options] Object with the following properties:
  22167. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  22168. * `{0}` will be replaced with the file index.
  22169. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  22170. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  22171. * first XYS sample.
  22172. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  22173. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  22174. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  22175. *
  22176. * @private
  22177. */
  22178. function Iau2006XysData(options) {
  22179. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  22180. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  22181. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  22182. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  22183. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  22184. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  22185. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  22186. this._totalSamples = defaultValue(options.totalSamples, 27426);
  22187. this._samples = new Array(this._totalSamples * 3);
  22188. this._chunkDownloadsInProgress = [];
  22189. var order = this._interpolationOrder;
  22190. // Compute denominators and X values for interpolation.
  22191. var denom = this._denominators = new Array(order + 1);
  22192. var xTable = this._xTable = new Array(order + 1);
  22193. var stepN = Math.pow(this._stepSizeDays, order);
  22194. for ( var i = 0; i <= order; ++i) {
  22195. denom[i] = stepN;
  22196. xTable[i] = i * this._stepSizeDays;
  22197. for ( var j = 0; j <= order; ++j) {
  22198. if (j !== i) {
  22199. denom[i] *= (i - j);
  22200. }
  22201. }
  22202. denom[i] = 1.0 / denom[i];
  22203. }
  22204. // Allocate scratch arrays for interpolation.
  22205. this._work = new Array(order + 1);
  22206. this._coef = new Array(order + 1);
  22207. }
  22208. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  22209. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  22210. var dateTT = julianDateScratch;
  22211. dateTT.dayNumber = dayTT;
  22212. dateTT.secondsOfDay = secondTT;
  22213. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  22214. }
  22215. /**
  22216. * Preloads XYS data for a specified date range.
  22217. *
  22218. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  22219. * the Terrestrial Time (TT) time standard.
  22220. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  22221. * the Terrestrial Time (TT) time standard.
  22222. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  22223. * the Terrestrial Time (TT) time standard.
  22224. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  22225. * the Terrestrial Time (TT) time standard.
  22226. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  22227. * preloaded.
  22228. */
  22229. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  22230. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  22231. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  22232. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  22233. if (startIndex < 0) {
  22234. startIndex = 0;
  22235. }
  22236. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  22237. if (stopIndex >= this._totalSamples) {
  22238. stopIndex = this._totalSamples - 1;
  22239. }
  22240. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  22241. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  22242. var promises = [];
  22243. for ( var i = startChunk; i <= stopChunk; ++i) {
  22244. promises.push(requestXysChunk(this, i));
  22245. }
  22246. return when.all(promises);
  22247. };
  22248. /**
  22249. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  22250. * this method will return undefined.
  22251. *
  22252. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  22253. * the Terrestrial Time (TT) time standard.
  22254. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  22255. * the Terrestrial Time (TT) time standard.
  22256. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  22257. * is undefined, a new instance is allocated and returned.
  22258. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  22259. * computation has not yet been downloaded.
  22260. *
  22261. * @see Iau2006XysData#preload
  22262. */
  22263. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  22264. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  22265. if (daysSinceEpoch < 0.0) {
  22266. // Can't evaluate prior to the epoch of the data.
  22267. return undefined;
  22268. }
  22269. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  22270. if (centerIndex >= this._totalSamples) {
  22271. // Can't evaluate after the last sample in the data.
  22272. return undefined;
  22273. }
  22274. var degree = this._interpolationOrder;
  22275. var firstIndex = centerIndex - ((degree / 2) | 0);
  22276. if (firstIndex < 0) {
  22277. firstIndex = 0;
  22278. }
  22279. var lastIndex = firstIndex + degree;
  22280. if (lastIndex >= this._totalSamples) {
  22281. lastIndex = this._totalSamples - 1;
  22282. firstIndex = lastIndex - degree;
  22283. if (firstIndex < 0) {
  22284. firstIndex = 0;
  22285. }
  22286. }
  22287. // Are all the samples we need present?
  22288. // We can assume so if the first and last are present
  22289. var isDataMissing = false;
  22290. var samples = this._samples;
  22291. if (!defined(samples[firstIndex * 3])) {
  22292. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  22293. isDataMissing = true;
  22294. }
  22295. if (!defined(samples[lastIndex * 3])) {
  22296. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  22297. isDataMissing = true;
  22298. }
  22299. if (isDataMissing) {
  22300. return undefined;
  22301. }
  22302. if (!defined(result)) {
  22303. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  22304. } else {
  22305. result.x = 0.0;
  22306. result.y = 0.0;
  22307. result.s = 0.0;
  22308. }
  22309. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  22310. var work = this._work;
  22311. var denom = this._denominators;
  22312. var coef = this._coef;
  22313. var xTable = this._xTable;
  22314. var i, j;
  22315. for (i = 0; i <= degree; ++i) {
  22316. work[i] = x - xTable[i];
  22317. }
  22318. for (i = 0; i <= degree; ++i) {
  22319. coef[i] = 1.0;
  22320. for (j = 0; j <= degree; ++j) {
  22321. if (j !== i) {
  22322. coef[i] *= work[j];
  22323. }
  22324. }
  22325. coef[i] *= denom[i];
  22326. var sampleIndex = (firstIndex + i) * 3;
  22327. result.x += coef[i] * samples[sampleIndex++];
  22328. result.y += coef[i] * samples[sampleIndex++];
  22329. result.s += coef[i] * samples[sampleIndex];
  22330. }
  22331. return result;
  22332. };
  22333. function requestXysChunk(xysData, chunkIndex) {
  22334. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  22335. // Chunk has already been requested.
  22336. return xysData._chunkDownloadsInProgress[chunkIndex];
  22337. }
  22338. var deferred = when.defer();
  22339. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  22340. var chunkUrl;
  22341. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  22342. if (defined(xysFileUrlTemplate)) {
  22343. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  22344. } else {
  22345. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  22346. }
  22347. when(loadJson(chunkUrl), function(chunk) {
  22348. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  22349. var samples = xysData._samples;
  22350. var newSamples = chunk.samples;
  22351. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  22352. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  22353. samples[startIndex + i] = newSamples[i];
  22354. }
  22355. deferred.resolve();
  22356. });
  22357. return deferred.promise;
  22358. }
  22359. return Iau2006XysData;
  22360. });
  22361. /*global define*/
  22362. define('Core/Transforms',[
  22363. '../ThirdParty/when',
  22364. './Cartesian2',
  22365. './Cartesian3',
  22366. './Cartesian4',
  22367. './Cartographic',
  22368. './defaultValue',
  22369. './defined',
  22370. './deprecationWarning',
  22371. './DeveloperError',
  22372. './EarthOrientationParameters',
  22373. './EarthOrientationParametersSample',
  22374. './Ellipsoid',
  22375. './HeadingPitchRoll',
  22376. './Iau2006XysData',
  22377. './Iau2006XysSample',
  22378. './JulianDate',
  22379. './Math',
  22380. './Matrix3',
  22381. './Matrix4',
  22382. './Quaternion',
  22383. './TimeConstants'
  22384. ], function(
  22385. when,
  22386. Cartesian2,
  22387. Cartesian3,
  22388. Cartesian4,
  22389. Cartographic,
  22390. defaultValue,
  22391. defined,
  22392. deprecationWarning,
  22393. DeveloperError,
  22394. EarthOrientationParameters,
  22395. EarthOrientationParametersSample,
  22396. Ellipsoid,
  22397. HeadingPitchRoll,
  22398. Iau2006XysData,
  22399. Iau2006XysSample,
  22400. JulianDate,
  22401. CesiumMath,
  22402. Matrix3,
  22403. Matrix4,
  22404. Quaternion,
  22405. TimeConstants) {
  22406. 'use strict';
  22407. /**
  22408. * Contains functions for transforming positions to various reference frames.
  22409. *
  22410. * @exports Transforms
  22411. */
  22412. var Transforms = {};
  22413. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  22414. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  22415. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  22416. /**
  22417. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  22418. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  22419. * The local axes are defined as:
  22420. * <ul>
  22421. * <li>The <code>x</code> axis points in the local east direction.</li>
  22422. * <li>The <code>y</code> axis points in the local north direction.</li>
  22423. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  22424. * </ul>
  22425. *
  22426. * @param {Cartesian3} origin The center point of the local reference frame.
  22427. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  22428. * @param {Matrix4} [result] The object onto which to store the result.
  22429. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  22430. *
  22431. * @example
  22432. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  22433. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  22434. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  22435. */
  22436. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  22437. if (!defined(origin)) {
  22438. throw new DeveloperError('origin is required.');
  22439. }
  22440. // If x and y are zero, assume origin is at a pole, which is a special case.
  22441. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  22442. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  22443. var sign = CesiumMath.sign(origin.z);
  22444. if (!defined(result)) {
  22445. return new Matrix4(
  22446. 0.0, -sign, 0.0, origin.x,
  22447. 1.0, 0.0, 0.0, origin.y,
  22448. 0.0, 0.0, sign, origin.z,
  22449. 0.0, 0.0, 0.0, 1.0);
  22450. }
  22451. result[0] = 0.0;
  22452. result[1] = 1.0;
  22453. result[2] = 0.0;
  22454. result[3] = 0.0;
  22455. result[4] = -sign;
  22456. result[5] = 0.0;
  22457. result[6] = 0.0;
  22458. result[7] = 0.0;
  22459. result[8] = 0.0;
  22460. result[9] = 0.0;
  22461. result[10] = sign;
  22462. result[11] = 0.0;
  22463. result[12] = origin.x;
  22464. result[13] = origin.y;
  22465. result[14] = origin.z;
  22466. result[15] = 1.0;
  22467. return result;
  22468. }
  22469. var normal = eastNorthUpToFixedFrameNormal;
  22470. var tangent = eastNorthUpToFixedFrameTangent;
  22471. var bitangent = eastNorthUpToFixedFrameBitangent;
  22472. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  22473. ellipsoid.geodeticSurfaceNormal(origin, normal);
  22474. tangent.x = -origin.y;
  22475. tangent.y = origin.x;
  22476. tangent.z = 0.0;
  22477. Cartesian3.normalize(tangent, tangent);
  22478. Cartesian3.cross(normal, tangent, bitangent);
  22479. if (!defined(result)) {
  22480. return new Matrix4(
  22481. tangent.x, bitangent.x, normal.x, origin.x,
  22482. tangent.y, bitangent.y, normal.y, origin.y,
  22483. tangent.z, bitangent.z, normal.z, origin.z,
  22484. 0.0, 0.0, 0.0, 1.0);
  22485. }
  22486. result[0] = tangent.x;
  22487. result[1] = tangent.y;
  22488. result[2] = tangent.z;
  22489. result[3] = 0.0;
  22490. result[4] = bitangent.x;
  22491. result[5] = bitangent.y;
  22492. result[6] = bitangent.z;
  22493. result[7] = 0.0;
  22494. result[8] = normal.x;
  22495. result[9] = normal.y;
  22496. result[10] = normal.z;
  22497. result[11] = 0.0;
  22498. result[12] = origin.x;
  22499. result[13] = origin.y;
  22500. result[14] = origin.z;
  22501. result[15] = 1.0;
  22502. return result;
  22503. };
  22504. var northEastDownToFixedFrameNormal = new Cartesian3();
  22505. var northEastDownToFixedFrameTangent = new Cartesian3();
  22506. var northEastDownToFixedFrameBitangent = new Cartesian3();
  22507. /**
  22508. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  22509. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  22510. * The local axes are defined as:
  22511. * <ul>
  22512. * <li>The <code>x</code> axis points in the local north direction.</li>
  22513. * <li>The <code>y</code> axis points in the local east direction.</li>
  22514. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  22515. * </ul>
  22516. *
  22517. * @param {Cartesian3} origin The center point of the local reference frame.
  22518. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  22519. * @param {Matrix4} [result] The object onto which to store the result.
  22520. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  22521. *
  22522. * @example
  22523. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  22524. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  22525. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  22526. */
  22527. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  22528. if (!defined(origin)) {
  22529. throw new DeveloperError('origin is required.');
  22530. }
  22531. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  22532. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  22533. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  22534. var sign = CesiumMath.sign(origin.z);
  22535. if (!defined(result)) {
  22536. return new Matrix4(
  22537. -sign, 0.0, 0.0, origin.x,
  22538. 0.0, 1.0, 0.0, origin.y,
  22539. 0.0, 0.0, -sign, origin.z,
  22540. 0.0, 0.0, 0.0, 1.0);
  22541. }
  22542. result[0] = -sign;
  22543. result[1] = 0.0;
  22544. result[2] = 0.0;
  22545. result[3] = 0.0;
  22546. result[4] = 0.0;
  22547. result[5] = 1.0;
  22548. result[6] = 0.0;
  22549. result[7] = 0.0;
  22550. result[8] = 0.0;
  22551. result[9] = 0.0;
  22552. result[10] = -sign;
  22553. result[11] = 0.0;
  22554. result[12] = origin.x;
  22555. result[13] = origin.y;
  22556. result[14] = origin.z;
  22557. result[15] = 1.0;
  22558. return result;
  22559. }
  22560. var normal = northEastDownToFixedFrameNormal;
  22561. var tangent = northEastDownToFixedFrameTangent;
  22562. var bitangent = northEastDownToFixedFrameBitangent;
  22563. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  22564. ellipsoid.geodeticSurfaceNormal(origin, normal);
  22565. tangent.x = -origin.y;
  22566. tangent.y = origin.x;
  22567. tangent.z = 0.0;
  22568. Cartesian3.normalize(tangent, tangent);
  22569. Cartesian3.cross(normal, tangent, bitangent);
  22570. if (!defined(result)) {
  22571. return new Matrix4(
  22572. bitangent.x, tangent.x, -normal.x, origin.x,
  22573. bitangent.y, tangent.y, -normal.y, origin.y,
  22574. bitangent.z, tangent.z, -normal.z, origin.z,
  22575. 0.0, 0.0, 0.0, 1.0);
  22576. }
  22577. result[0] = bitangent.x;
  22578. result[1] = bitangent.y;
  22579. result[2] = bitangent.z;
  22580. result[3] = 0.0;
  22581. result[4] = tangent.x;
  22582. result[5] = tangent.y;
  22583. result[6] = tangent.z;
  22584. result[7] = 0.0;
  22585. result[8] = -normal.x;
  22586. result[9] = -normal.y;
  22587. result[10] = -normal.z;
  22588. result[11] = 0.0;
  22589. result[12] = origin.x;
  22590. result[13] = origin.y;
  22591. result[14] = origin.z;
  22592. result[15] = 1.0;
  22593. return result;
  22594. };
  22595. /**
  22596. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  22597. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  22598. * The local axes are defined as:
  22599. * <ul>
  22600. * <li>The <code>x</code> axis points in the local north direction.</li>
  22601. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  22602. * <li>The <code>z</code> axis points in the local east direction.</li>
  22603. * </ul>
  22604. *
  22605. * @param {Cartesian3} origin The center point of the local reference frame.
  22606. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  22607. * @param {Matrix4} [result] The object onto which to store the result.
  22608. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  22609. *
  22610. * @example
  22611. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  22612. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  22613. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  22614. */
  22615. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  22616. if (!defined(origin)) {
  22617. throw new DeveloperError('origin is required.');
  22618. }
  22619. // If x and y are zero, assume origin is at a pole, which is a special case.
  22620. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  22621. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  22622. var sign = CesiumMath.sign(origin.z);
  22623. if (!defined(result)) {
  22624. return new Matrix4(
  22625. -sign, 0.0, 0.0, origin.x,
  22626. 0.0, 0.0, 1.0, origin.y,
  22627. 0.0, sign, 0.0, origin.z,
  22628. 0.0, 0.0, 0.0, 1.0);
  22629. }
  22630. result[0] = -sign;
  22631. result[1] = 0.0;
  22632. result[2] = 0.0;
  22633. result[3] = 0.0;
  22634. result[4] = 0.0;
  22635. result[5] = 0.0;
  22636. result[6] = sign;
  22637. result[7] = 0.0;
  22638. result[8] = 0.0;
  22639. result[9] = 1.0;
  22640. result[10] = 0.0;
  22641. result[11] = 0.0;
  22642. result[12] = origin.x;
  22643. result[13] = origin.y;
  22644. result[14] = origin.z;
  22645. result[15] = 1.0;
  22646. return result;
  22647. }
  22648. var normal = eastNorthUpToFixedFrameNormal;
  22649. var tangent = eastNorthUpToFixedFrameTangent;
  22650. var bitangent = eastNorthUpToFixedFrameBitangent;
  22651. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  22652. ellipsoid.geodeticSurfaceNormal(origin, normal);
  22653. tangent.x = -origin.y;
  22654. tangent.y = origin.x;
  22655. tangent.z = 0.0;
  22656. Cartesian3.normalize(tangent, tangent);
  22657. Cartesian3.cross(normal, tangent, bitangent);
  22658. if (!defined(result)) {
  22659. return new Matrix4(
  22660. bitangent.x, normal.x, tangent.x, origin.x,
  22661. bitangent.y, normal.y, tangent.y, origin.y,
  22662. bitangent.z, normal.z, tangent.z, origin.z,
  22663. 0.0, 0.0, 0.0, 1.0);
  22664. }
  22665. result[0] = bitangent.x;
  22666. result[1] = bitangent.y;
  22667. result[2] = bitangent.z;
  22668. result[3] = 0.0;
  22669. result[4] = normal.x;
  22670. result[5] = normal.y;
  22671. result[6] = normal.z;
  22672. result[7] = 0.0;
  22673. result[8] = tangent.x;
  22674. result[9] = tangent.y;
  22675. result[10] = tangent.z;
  22676. result[11] = 0.0;
  22677. result[12] = origin.x;
  22678. result[13] = origin.y;
  22679. result[14] = origin.z;
  22680. result[15] = 1.0;
  22681. return result;
  22682. };
  22683. /**
  22684. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  22685. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  22686. * The local axes are defined as:
  22687. * <ul>
  22688. * <li>The <code>x</code> axis points in the local north direction.</li>
  22689. * <li>The <code>y</code> axis points in the local west direction.</li>
  22690. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  22691. * </ul>
  22692. *
  22693. * @param {Cartesian3} origin The center point of the local reference frame.
  22694. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  22695. * @param {Matrix4} [result] The object onto which to store the result.
  22696. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  22697. *
  22698. * @example
  22699. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  22700. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  22701. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  22702. */
  22703. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  22704. if (!defined(origin)) {
  22705. throw new DeveloperError('origin is required.');
  22706. }
  22707. // If x and y are zero, assume origin is at a pole, which is a special case.
  22708. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  22709. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  22710. var sign = CesiumMath.sign(origin.z);
  22711. if (!defined(result)) {
  22712. return new Matrix4(
  22713. -sign, 0.0, 0.0, origin.x,
  22714. 0.0, -1.0, 0.0, origin.y,
  22715. 0.0, 0.0, sign, origin.z,
  22716. 0.0, 0.0, 0.0, 1.0);
  22717. }
  22718. result[0] = -sign;
  22719. result[1] = 0.0;
  22720. result[2] = 0.0;
  22721. result[3] = 0.0;
  22722. result[4] = 0.0;
  22723. result[5] = -1.0;
  22724. result[6] = 0.0;
  22725. result[7] = 0.0;
  22726. result[8] = 0.0;
  22727. result[9] = 0.0;
  22728. result[10] = sign;
  22729. result[11] = 0.0;
  22730. result[12] = origin.x;
  22731. result[13] = origin.y;
  22732. result[14] = origin.z;
  22733. result[15] = 1.0;
  22734. return result;
  22735. }
  22736. var normal = eastNorthUpToFixedFrameNormal;//Up
  22737. var tangent = eastNorthUpToFixedFrameTangent;//East
  22738. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  22739. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  22740. ellipsoid.geodeticSurfaceNormal(origin, normal);
  22741. tangent.x = -origin.y;
  22742. tangent.y = origin.x;
  22743. tangent.z = 0.0;
  22744. Cartesian3.normalize(tangent, tangent);
  22745. Cartesian3.cross(normal, tangent, bitangent);
  22746. if (!defined(result)) {
  22747. return new Matrix4(
  22748. bitangent.x, -tangent.x, normal.x, origin.x,
  22749. bitangent.y, -tangent.y, normal.y, origin.y,
  22750. bitangent.z, -tangent.z, normal.z, origin.z,
  22751. 0.0, 0.0, 0.0, 1.0);
  22752. }
  22753. result[0] = bitangent.x;
  22754. result[1] = bitangent.y;
  22755. result[2] = bitangent.z;
  22756. result[3] = 0.0;
  22757. result[4] = -tangent.x;
  22758. result[5] = -tangent.y;
  22759. result[6] = -tangent.z;
  22760. result[7] = 0.0;
  22761. result[8] = normal.x;
  22762. result[9] = normal.y;
  22763. result[10] = normal.z;
  22764. result[11] = 0.0;
  22765. result[12] = origin.x;
  22766. result[13] = origin.y;
  22767. result[14] = origin.z;
  22768. result[15] = 1.0;
  22769. return result;
  22770. };
  22771. var scratchHPRQuaternion = new Quaternion();
  22772. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  22773. var scratchHPRMatrix4 = new Matrix4();
  22774. /**
  22775. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  22776. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  22777. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  22778. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  22779. *
  22780. * @param {Cartesian3} origin The center point of the local reference frame.
  22781. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  22782. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  22783. * @param {Matrix4} [result] The object onto which to store the result.
  22784. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  22785. *
  22786. * @example
  22787. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  22788. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  22789. * var heading = -Cesium.Math.PI_OVER_TWO;
  22790. * var pitch = Cesium.Math.PI_OVER_FOUR;
  22791. * var roll = 0.0;
  22792. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  22793. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  22794. */
  22795. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  22796. var heading;
  22797. if (typeof headingPitchRoll === 'object') {
  22798. // Shift arguments using assignments to encourage JIT optimization.
  22799. ellipsoid = pitch;
  22800. result = roll;
  22801. heading = headingPitchRoll.heading;
  22802. pitch = headingPitchRoll.pitch;
  22803. roll = headingPitchRoll.roll;
  22804. } else {
  22805. deprecationWarning('headingPitchRollToFixedFrame', 'headingPitchRollToFixedFrame with separate heading, pitch, and roll arguments was deprecated in 1.27. It will be removed in 1.30. Use a HeadingPitchRoll object.');
  22806. heading = headingPitchRoll;
  22807. }
  22808. // checks for required parameters happen in the called functions
  22809. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  22810. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  22811. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  22812. return Matrix4.multiply(result, hprMatrix, result);
  22813. };
  22814. var scratchHPR = new HeadingPitchRoll();
  22815. var scratchENUMatrix4 = new Matrix4();
  22816. var scratchHPRMatrix3 = new Matrix3();
  22817. /**
  22818. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  22819. * centered at the provided origin. Heading is the rotation from the local north
  22820. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  22821. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  22822. *
  22823. * @param {Cartesian3} origin The center point of the local reference frame.
  22824. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  22825. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  22826. * @param {Quaternion} [result] The object onto which to store the result.
  22827. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  22828. *
  22829. * @example
  22830. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  22831. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  22832. * var heading = -Cesium.Math.PI_OVER_TWO;
  22833. * var pitch = Cesium.Math.PI_OVER_FOUR;
  22834. * var roll = 0.0;
  22835. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  22836. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  22837. */
  22838. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  22839. var hpr;
  22840. if (typeof headingPitchRoll === 'object') {
  22841. // Shift arguments using assignment to encourage JIT optimization.
  22842. hpr = headingPitchRoll;
  22843. ellipsoid = pitch;
  22844. result = roll;
  22845. } else {
  22846. deprecationWarning('headingPitchRollQuaternion', 'headingPitchRollQuaternion with separate heading, pitch, and roll arguments was deprecated in 1.27. It will be removed in 1.30. Use a HeadingPitchRoll object.');
  22847. scratchHPR.heading = headingPitchRoll;
  22848. scratchHPR.pitch = pitch;
  22849. scratchHPR.roll = roll;
  22850. hpr = scratchHPR;
  22851. }
  22852. // checks for required parameters happen in the called functions
  22853. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  22854. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  22855. return Quaternion.fromRotationMatrix(rotation, result);
  22856. };
  22857. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  22858. var gmstConstant1 = 8640184.812866;
  22859. var gmstConstant2 = 0.093104;
  22860. var gmstConstant3 = -6.2E-6;
  22861. var rateCoef = 1.1772758384668e-19;
  22862. var wgs84WRPrecessing = 7.2921158553E-5;
  22863. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  22864. var dateInUtc = new JulianDate();
  22865. /**
  22866. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  22867. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  22868. *
  22869. * @param {JulianDate} date The time at which to compute the rotation matrix.
  22870. * @param {Matrix3} [result] The object onto which to store the result.
  22871. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  22872. *
  22873. * @example
  22874. * //Set the view to in the inertial frame.
  22875. * scene.preRender.addEventListener(function(scene, time) {
  22876. * var now = Cesium.JulianDate.now();
  22877. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  22878. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  22879. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  22880. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  22881. * camera.lookAtTransform(transform, offset);
  22882. * });
  22883. */
  22884. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  22885. if (!defined(date)) {
  22886. throw new DeveloperError('date is required.');
  22887. }
  22888. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  22889. // We do not want to use the function like convertTaiToUtc in JulianDate because
  22890. // we explicitly do not want to fail when inside the leap second.
  22891. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  22892. var utcDayNumber = dateInUtc.dayNumber;
  22893. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  22894. var t;
  22895. var diffDays = utcDayNumber - 2451545;
  22896. if (utcSecondsIntoDay >= 43200.0) {
  22897. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  22898. } else {
  22899. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  22900. }
  22901. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  22902. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  22903. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  22904. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  22905. var gha = angle + (ratio * secondsSinceMidnight);
  22906. var cosGha = Math.cos(gha);
  22907. var sinGha = Math.sin(gha);
  22908. if (!defined(result)) {
  22909. return new Matrix3(cosGha, sinGha, 0.0,
  22910. -sinGha, cosGha, 0.0,
  22911. 0.0, 0.0, 1.0);
  22912. }
  22913. result[0] = cosGha;
  22914. result[1] = -sinGha;
  22915. result[2] = 0.0;
  22916. result[3] = sinGha;
  22917. result[4] = cosGha;
  22918. result[5] = 0.0;
  22919. result[6] = 0.0;
  22920. result[7] = 0.0;
  22921. result[8] = 1.0;
  22922. return result;
  22923. };
  22924. /**
  22925. * The source of IAU 2006 XYS data, used for computing the transformation between the
  22926. * Fixed and ICRF axes.
  22927. * @type {Iau2006XysData}
  22928. *
  22929. * @see Transforms.computeIcrfToFixedMatrix
  22930. * @see Transforms.computeFixedToIcrfMatrix
  22931. *
  22932. * @private
  22933. */
  22934. Transforms.iau2006XysData = new Iau2006XysData();
  22935. /**
  22936. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  22937. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  22938. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  22939. * @type {EarthOrientationParameters}
  22940. *
  22941. * @see Transforms.computeIcrfToFixedMatrix
  22942. * @see Transforms.computeFixedToIcrfMatrix
  22943. *
  22944. * @private
  22945. */
  22946. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  22947. var ttMinusTai = 32.184;
  22948. var j2000ttDays = 2451545.0;
  22949. /**
  22950. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  22951. * direction, over a given interval. This function returns a promise that, when resolved,
  22952. * indicates that the preload has completed.
  22953. *
  22954. * @param {TimeInterval} timeInterval The interval to preload.
  22955. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  22956. * and evaluation of the transformation between the fixed and ICRF axes will
  22957. * no longer return undefined for a time inside the interval.
  22958. *
  22959. *
  22960. * @example
  22961. * var interval = new Cesium.TimeInterval(...);
  22962. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  22963. * // the data is now loaded
  22964. * });
  22965. *
  22966. * @see Transforms.computeIcrfToFixedMatrix
  22967. * @see Transforms.computeFixedToIcrfMatrix
  22968. * @see when
  22969. */
  22970. Transforms.preloadIcrfFixed = function(timeInterval) {
  22971. var startDayTT = timeInterval.start.dayNumber;
  22972. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  22973. var stopDayTT = timeInterval.stop.dayNumber;
  22974. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  22975. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  22976. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  22977. return when.all([xysPromise, eopPromise]);
  22978. };
  22979. /**
  22980. * Computes a rotation matrix to transform a point or vector from the International Celestial
  22981. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  22982. * at a given time. This function may return undefined if the data necessary to
  22983. * do the transformation is not yet loaded.
  22984. *
  22985. * @param {JulianDate} date The time at which to compute the rotation matrix.
  22986. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  22987. * not specified, a new instance is created and returned.
  22988. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  22989. * transformation is not yet loaded.
  22990. *
  22991. *
  22992. * @example
  22993. * scene.preRender.addEventListener(function(scene, time) {
  22994. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  22995. * if (Cesium.defined(icrfToFixed)) {
  22996. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  22997. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  22998. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  22999. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  23000. * camera.lookAtTransform(transform, offset);
  23001. * }
  23002. * });
  23003. *
  23004. * @see Transforms.preloadIcrfFixed
  23005. */
  23006. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  23007. if (!defined(date)) {
  23008. throw new DeveloperError('date is required.');
  23009. }
  23010. if (!defined(result)) {
  23011. result = new Matrix3();
  23012. }
  23013. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  23014. if (!defined(fixedToIcrfMtx)) {
  23015. return undefined;
  23016. }
  23017. return Matrix3.transpose(fixedToIcrfMtx, result);
  23018. };
  23019. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  23020. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  23021. var rotation1Scratch = new Matrix3();
  23022. var rotation2Scratch = new Matrix3();
  23023. /**
  23024. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  23025. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  23026. * at a given time. This function may return undefined if the data necessary to
  23027. * do the transformation is not yet loaded.
  23028. *
  23029. * @param {JulianDate} date The time at which to compute the rotation matrix.
  23030. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  23031. * not specified, a new instance is created and returned.
  23032. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  23033. * transformation is not yet loaded.
  23034. *
  23035. *
  23036. * @example
  23037. * // Transform a point from the ICRF axes to the Fixed axes.
  23038. * var now = Cesium.JulianDate.now();
  23039. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23040. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  23041. * var pointInInertial = new Cesium.Cartesian3();
  23042. * if (Cesium.defined(fixedToIcrf)) {
  23043. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  23044. * }
  23045. *
  23046. * @see Transforms.preloadIcrfFixed
  23047. */
  23048. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  23049. if (!defined(date)) {
  23050. throw new DeveloperError('date is required.');
  23051. }
  23052. if (!defined(result)) {
  23053. result = new Matrix3();
  23054. }
  23055. // Compute pole wander
  23056. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  23057. if (!defined(eop)) {
  23058. return undefined;
  23059. }
  23060. // There is no external conversion to Terrestrial Time (TT).
  23061. // So use International Atomic Time (TAI) and convert using offsets.
  23062. // Here we are assuming that dayTT and secondTT are positive
  23063. var dayTT = date.dayNumber;
  23064. // It's possible here that secondTT could roll over 86400
  23065. // This does not seem to affect the precision (unit tests check for this)
  23066. var secondTT = date.secondsOfDay + ttMinusTai;
  23067. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  23068. if (!defined(xys)) {
  23069. return undefined;
  23070. }
  23071. var x = xys.x + eop.xPoleOffset;
  23072. var y = xys.y + eop.yPoleOffset;
  23073. // Compute XYS rotation
  23074. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  23075. var rotation1 = rotation1Scratch;
  23076. rotation1[0] = 1.0 - a * x * x;
  23077. rotation1[3] = -a * x * y;
  23078. rotation1[6] = x;
  23079. rotation1[1] = -a * x * y;
  23080. rotation1[4] = 1 - a * y * y;
  23081. rotation1[7] = y;
  23082. rotation1[2] = -x;
  23083. rotation1[5] = -y;
  23084. rotation1[8] = 1 - a * (x * x + y * y);
  23085. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  23086. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  23087. // Similar to TT conversions above
  23088. // It's possible here that secondTT could roll over 86400
  23089. // This does not seem to affect the precision (unit tests check for this)
  23090. var dateUt1day = date.dayNumber;
  23091. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  23092. // Compute Earth rotation angle
  23093. // The IERS standard for era is
  23094. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  23095. // where
  23096. // Tu = JulianDateInUt1 - 2451545.0
  23097. // However, you get much more precision if you make the following simplification
  23098. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  23099. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  23100. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  23101. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  23102. var daysSinceJ2000 = dateUt1day - 2451545;
  23103. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  23104. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  23105. era = (era % 1.0) * CesiumMath.TWO_PI;
  23106. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  23107. // pseudoFixed to ICRF
  23108. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  23109. // Compute pole wander matrix
  23110. var cosxp = Math.cos(eop.xPoleWander);
  23111. var cosyp = Math.cos(eop.yPoleWander);
  23112. var sinxp = Math.sin(eop.xPoleWander);
  23113. var sinyp = Math.sin(eop.yPoleWander);
  23114. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  23115. ttt /= 36525.0;
  23116. // approximate sp value in rad
  23117. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  23118. var cossp = Math.cos(sp);
  23119. var sinsp = Math.sin(sp);
  23120. var fToPfMtx = rotation2Scratch;
  23121. fToPfMtx[0] = cosxp * cossp;
  23122. fToPfMtx[1] = cosxp * sinsp;
  23123. fToPfMtx[2] = sinxp;
  23124. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  23125. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  23126. fToPfMtx[5] = -sinyp * cosxp;
  23127. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  23128. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  23129. fToPfMtx[8] = cosyp * cosxp;
  23130. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  23131. };
  23132. var pointToWindowCoordinatesTemp = new Cartesian4();
  23133. /**
  23134. * Transform a point from model coordinates to window coordinates.
  23135. *
  23136. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  23137. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  23138. * @param {Cartesian3} point The point to transform.
  23139. * @param {Cartesian2} [result] The object onto which to store the result.
  23140. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  23141. */
  23142. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  23143. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  23144. result.y = 2.0 * viewportTransformation[5] - result.y;
  23145. return result;
  23146. };
  23147. /**
  23148. * @private
  23149. */
  23150. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  23151. if (!defined(modelViewProjectionMatrix)) {
  23152. throw new DeveloperError('modelViewProjectionMatrix is required.');
  23153. }
  23154. if (!defined(viewportTransformation)) {
  23155. throw new DeveloperError('viewportTransformation is required.');
  23156. }
  23157. if (!defined(point)) {
  23158. throw new DeveloperError('point is required.');
  23159. }
  23160. if (!defined(result)) {
  23161. result = new Cartesian2();
  23162. }
  23163. var tmp = pointToWindowCoordinatesTemp;
  23164. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  23165. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  23166. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  23167. return Cartesian2.fromCartesian4(tmp, result);
  23168. };
  23169. var normalScratch = new Cartesian3();
  23170. var rightScratch = new Cartesian3();
  23171. var upScratch = new Cartesian3();
  23172. /**
  23173. * @private
  23174. */
  23175. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  23176. if (!defined(position)) {
  23177. throw new DeveloperError('position is required.');
  23178. }
  23179. if (!defined(velocity)) {
  23180. throw new DeveloperError('velocity is required.');
  23181. }
  23182. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  23183. var right = Cartesian3.cross(velocity, normal, rightScratch);
  23184. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  23185. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  23186. }
  23187. var up = Cartesian3.cross(right, velocity, upScratch);
  23188. Cartesian3.cross(velocity, up, right);
  23189. Cartesian3.negate(right, right);
  23190. if (!defined(result)) {
  23191. result = new Matrix3();
  23192. }
  23193. result[0] = velocity.x;
  23194. result[1] = velocity.y;
  23195. result[2] = velocity.z;
  23196. result[3] = right.x;
  23197. result[4] = right.y;
  23198. result[5] = right.z;
  23199. result[6] = up.x;
  23200. result[7] = up.y;
  23201. result[8] = up.z;
  23202. return result;
  23203. };
  23204. var scratchCartographic = new Cartographic();
  23205. var scratchCartesian3Projection = new Cartesian3();
  23206. var scratchCartesian3 = new Cartesian3();
  23207. var scratchCartesian4Origin = new Cartesian4();
  23208. var scratchCartesian4NewOrigin = new Cartesian4();
  23209. var scratchCartesian4NewXAxis = new Cartesian4();
  23210. var scratchCartesian4NewYAxis = new Cartesian4();
  23211. var scratchCartesian4NewZAxis = new Cartesian4();
  23212. var scratchFromENU = new Matrix4();
  23213. var scratchToENU = new Matrix4();
  23214. /**
  23215. * @private
  23216. */
  23217. Transforms.basisTo2D = function(projection, matrix, result) {
  23218. if (!defined(projection)) {
  23219. throw new DeveloperError('projection is required.');
  23220. }
  23221. if (!defined(matrix)) {
  23222. throw new DeveloperError('matrix is required.');
  23223. }
  23224. if (!defined(result)) {
  23225. throw new DeveloperError('result is required.');
  23226. }
  23227. var ellipsoid = projection.ellipsoid;
  23228. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  23229. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  23230. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  23231. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  23232. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  23233. var newOrigin = scratchCartesian4NewOrigin;
  23234. newOrigin.x = projectedPosition.z;
  23235. newOrigin.y = projectedPosition.x;
  23236. newOrigin.z = projectedPosition.y;
  23237. newOrigin.w = 1.0;
  23238. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  23239. var xScale = Cartesian3.magnitude(xAxis);
  23240. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  23241. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  23242. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  23243. var yScale = Cartesian3.magnitude(yAxis);
  23244. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  23245. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  23246. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  23247. var zScale = Cartesian3.magnitude(zAxis);
  23248. var newZAxis = scratchCartesian4NewZAxis;
  23249. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  23250. Cartesian3.normalize(newZAxis, newZAxis);
  23251. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  23252. Cartesian3.normalize(newXAxis, newXAxis);
  23253. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  23254. Cartesian3.normalize(newYAxis, newYAxis);
  23255. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  23256. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  23257. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  23258. Matrix4.setColumn(result, 0, newXAxis, result);
  23259. Matrix4.setColumn(result, 1, newYAxis, result);
  23260. Matrix4.setColumn(result, 2, newZAxis, result);
  23261. Matrix4.setColumn(result, 3, newOrigin, result);
  23262. return result;
  23263. };
  23264. return Transforms;
  23265. });
  23266. /*global define*/
  23267. define('Core/VertexFormat',[
  23268. './defaultValue',
  23269. './defined',
  23270. './DeveloperError',
  23271. './freezeObject'
  23272. ], function(
  23273. defaultValue,
  23274. defined,
  23275. DeveloperError,
  23276. freezeObject) {
  23277. 'use strict';
  23278. /**
  23279. * A vertex format defines what attributes make up a vertex. A VertexFormat can be provided
  23280. * to a {@link Geometry} to request that certain properties be computed, e.g., just position,
  23281. * position and normal, etc.
  23282. *
  23283. * @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example.
  23284. *
  23285. * @alias VertexFormat
  23286. * @constructor
  23287. *
  23288. * @example
  23289. * // Create a vertex format with position and 2D texture coordinate attributes.
  23290. * var format = new Cesium.VertexFormat({
  23291. * position : true,
  23292. * st : true
  23293. * });
  23294. *
  23295. * @see Geometry#attributes
  23296. * @see Packable
  23297. */
  23298. function VertexFormat(options) {
  23299. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  23300. /**
  23301. * When <code>true</code>, the vertex has a 3D position attribute.
  23302. * <p>
  23303. * 64-bit floating-point (for precision). 3 components per attribute.
  23304. * </p>
  23305. *
  23306. * @type Boolean
  23307. *
  23308. * @default false
  23309. */
  23310. this.position = defaultValue(options.position, false);
  23311. /**
  23312. * When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting.
  23313. * <p>
  23314. * 32-bit floating-point. 3 components per attribute.
  23315. * </p>
  23316. *
  23317. * @type Boolean
  23318. *
  23319. * @default false
  23320. */
  23321. this.normal = defaultValue(options.normal, false);
  23322. /**
  23323. * When <code>true</code>, the vertex has a 2D texture coordinate attribute.
  23324. * <p>
  23325. * 32-bit floating-point. 2 components per attribute
  23326. * </p>
  23327. *
  23328. * @type Boolean
  23329. *
  23330. * @default false
  23331. */
  23332. this.st = defaultValue(options.st, false);
  23333. /**
  23334. * When <code>true</code>, the vertex has a binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  23335. * <p>
  23336. * 32-bit floating-point. 3 components per attribute.
  23337. * </p>
  23338. *
  23339. * @type Boolean
  23340. *
  23341. * @default false
  23342. */
  23343. this.binormal = defaultValue(options.binormal, false);
  23344. /**
  23345. * When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  23346. * <p>
  23347. * 32-bit floating-point. 3 components per attribute.
  23348. * </p>
  23349. *
  23350. * @type Boolean
  23351. *
  23352. * @default false
  23353. */
  23354. this.tangent = defaultValue(options.tangent, false);
  23355. /**
  23356. * When <code>true</code>, the vertex has an RGB color attribute.
  23357. * <p>
  23358. * 8-bit unsigned byte. 3 components per attribute.
  23359. * </p>
  23360. *
  23361. * @type Boolean
  23362. *
  23363. * @default false
  23364. */
  23365. this.color = defaultValue(options.color, false);
  23366. }
  23367. /**
  23368. * An immutable vertex format with only a position attribute.
  23369. *
  23370. * @type {VertexFormat}
  23371. * @constant
  23372. *
  23373. * @see VertexFormat#position
  23374. */
  23375. VertexFormat.POSITION_ONLY = freezeObject(new VertexFormat({
  23376. position : true
  23377. }));
  23378. /**
  23379. * An immutable vertex format with position and normal attributes.
  23380. * This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}.
  23381. *
  23382. * @type {VertexFormat}
  23383. * @constant
  23384. *
  23385. * @see VertexFormat#position
  23386. * @see VertexFormat#normal
  23387. */
  23388. VertexFormat.POSITION_AND_NORMAL = freezeObject(new VertexFormat({
  23389. position : true,
  23390. normal : true
  23391. }));
  23392. /**
  23393. * An immutable vertex format with position, normal, and st attributes.
  23394. * This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport}
  23395. * is <code>TEXTURED/code>.
  23396. *
  23397. * @type {VertexFormat}
  23398. * @constant
  23399. *
  23400. * @see VertexFormat#position
  23401. * @see VertexFormat#normal
  23402. * @see VertexFormat#st
  23403. */
  23404. VertexFormat.POSITION_NORMAL_AND_ST = freezeObject(new VertexFormat({
  23405. position : true,
  23406. normal : true,
  23407. st : true
  23408. }));
  23409. /**
  23410. * An immutable vertex format with position and st attributes.
  23411. * This is compatible with {@link EllipsoidSurfaceAppearance}.
  23412. *
  23413. * @type {VertexFormat}
  23414. * @constant
  23415. *
  23416. * @see VertexFormat#position
  23417. * @see VertexFormat#st
  23418. */
  23419. VertexFormat.POSITION_AND_ST = freezeObject(new VertexFormat({
  23420. position : true,
  23421. st : true
  23422. }));
  23423. /**
  23424. * An immutable vertex format with position and color attributes.
  23425. *
  23426. * @type {VertexFormat}
  23427. * @constant
  23428. *
  23429. * @see VertexFormat#position
  23430. * @see VertexFormat#color
  23431. */
  23432. VertexFormat.POSITION_AND_COLOR = freezeObject(new VertexFormat({
  23433. position : true,
  23434. color : true
  23435. }));
  23436. /**
  23437. * An immutable vertex format with well-known attributes: position, normal, st, binormal, and tangent.
  23438. *
  23439. * @type {VertexFormat}
  23440. * @constant
  23441. *
  23442. * @see VertexFormat#position
  23443. * @see VertexFormat#normal
  23444. * @see VertexFormat#st
  23445. * @see VertexFormat#binormal
  23446. * @see VertexFormat#tangent
  23447. */
  23448. VertexFormat.ALL = freezeObject(new VertexFormat({
  23449. position : true,
  23450. normal : true,
  23451. st : true,
  23452. binormal : true,
  23453. tangent : true
  23454. }));
  23455. /**
  23456. * An immutable vertex format with position, normal, and st attributes.
  23457. * This is compatible with most appearances and materials; however
  23458. * normal and st attributes are not always required. When this is
  23459. * known in advance, another <code>VertexFormat</code> should be used.
  23460. *
  23461. * @type {VertexFormat}
  23462. * @constant
  23463. *
  23464. * @see VertexFormat#position
  23465. * @see VertexFormat#normal
  23466. */
  23467. VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
  23468. /**
  23469. * The number of elements used to pack the object into an array.
  23470. * @type {Number}
  23471. */
  23472. VertexFormat.packedLength = 6;
  23473. /**
  23474. * Stores the provided instance into the provided array.
  23475. *
  23476. * @param {VertexFormat} value The value to pack.
  23477. * @param {Number[]} array The array to pack into.
  23478. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  23479. *
  23480. * @returns {Number[]} The array that was packed into
  23481. */
  23482. VertexFormat.pack = function(value, array, startingIndex) {
  23483. if (!defined(value)) {
  23484. throw new DeveloperError('value is required');
  23485. }
  23486. if (!defined(array)) {
  23487. throw new DeveloperError('array is required');
  23488. }
  23489. startingIndex = defaultValue(startingIndex, 0);
  23490. array[startingIndex++] = value.position ? 1.0 : 0.0;
  23491. array[startingIndex++] = value.normal ? 1.0 : 0.0;
  23492. array[startingIndex++] = value.st ? 1.0 : 0.0;
  23493. array[startingIndex++] = value.binormal ? 1.0 : 0.0;
  23494. array[startingIndex++] = value.tangent ? 1.0 : 0.0;
  23495. array[startingIndex++] = value.color ? 1.0 : 0.0;
  23496. return array;
  23497. };
  23498. /**
  23499. * Retrieves an instance from a packed array.
  23500. *
  23501. * @param {Number[]} array The packed array.
  23502. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  23503. * @param {VertexFormat} [result] The object into which to store the result.
  23504. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided.
  23505. */
  23506. VertexFormat.unpack = function(array, startingIndex, result) {
  23507. if (!defined(array)) {
  23508. throw new DeveloperError('array is required');
  23509. }
  23510. startingIndex = defaultValue(startingIndex, 0);
  23511. if (!defined(result)) {
  23512. result = new VertexFormat();
  23513. }
  23514. result.position = array[startingIndex++] === 1.0;
  23515. result.normal = array[startingIndex++] === 1.0;
  23516. result.st = array[startingIndex++] === 1.0;
  23517. result.binormal = array[startingIndex++] === 1.0;
  23518. result.tangent = array[startingIndex++] === 1.0;
  23519. result.color = array[startingIndex++] === 1.0;
  23520. return result;
  23521. };
  23522. /**
  23523. * Duplicates a VertexFormat instance.
  23524. *
  23525. * @param {VertexFormat} cartesian The vertex format to duplicate.
  23526. * @param {VertexFormat} [result] The object onto which to store the result.
  23527. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined)
  23528. */
  23529. VertexFormat.clone = function(vertexFormat, result) {
  23530. if (!defined(vertexFormat)) {
  23531. return undefined;
  23532. }
  23533. if (!defined(result)) {
  23534. result = new VertexFormat();
  23535. }
  23536. result.position = vertexFormat.position;
  23537. result.normal = vertexFormat.normal;
  23538. result.st = vertexFormat.st;
  23539. result.binormal = vertexFormat.binormal;
  23540. result.tangent = vertexFormat.tangent;
  23541. result.color = vertexFormat.color;
  23542. return result;
  23543. };
  23544. return VertexFormat;
  23545. });
  23546. /*global define*/
  23547. define('Core/EllipseGeometry',[
  23548. './BoundingSphere',
  23549. './Cartesian2',
  23550. './Cartesian3',
  23551. './Cartographic',
  23552. './ComponentDatatype',
  23553. './defaultValue',
  23554. './defined',
  23555. './defineProperties',
  23556. './DeveloperError',
  23557. './EllipseGeometryLibrary',
  23558. './Ellipsoid',
  23559. './GeographicProjection',
  23560. './Geometry',
  23561. './GeometryAttribute',
  23562. './GeometryAttributes',
  23563. './GeometryInstance',
  23564. './GeometryPipeline',
  23565. './IndexDatatype',
  23566. './Math',
  23567. './Matrix3',
  23568. './Matrix4',
  23569. './PrimitiveType',
  23570. './Quaternion',
  23571. './Rectangle',
  23572. './Transforms',
  23573. './VertexFormat'
  23574. ], function(
  23575. BoundingSphere,
  23576. Cartesian2,
  23577. Cartesian3,
  23578. Cartographic,
  23579. ComponentDatatype,
  23580. defaultValue,
  23581. defined,
  23582. defineProperties,
  23583. DeveloperError,
  23584. EllipseGeometryLibrary,
  23585. Ellipsoid,
  23586. GeographicProjection,
  23587. Geometry,
  23588. GeometryAttribute,
  23589. GeometryAttributes,
  23590. GeometryInstance,
  23591. GeometryPipeline,
  23592. IndexDatatype,
  23593. CesiumMath,
  23594. Matrix3,
  23595. Matrix4,
  23596. PrimitiveType,
  23597. Quaternion,
  23598. Rectangle,
  23599. Transforms,
  23600. VertexFormat) {
  23601. 'use strict';
  23602. var scratchCartesian1 = new Cartesian3();
  23603. var scratchCartesian2 = new Cartesian3();
  23604. var scratchCartesian3 = new Cartesian3();
  23605. var scratchCartesian4 = new Cartesian3();
  23606. var texCoordScratch = new Cartesian2();
  23607. var textureMatrixScratch = new Matrix3();
  23608. var quaternionScratch = new Quaternion();
  23609. var scratchNormal = new Cartesian3();
  23610. var scratchTangent = new Cartesian3();
  23611. var scratchBinormal = new Cartesian3();
  23612. var scratchCartographic = new Cartographic();
  23613. var projectedCenterScratch = new Cartesian3();
  23614. var scratchMinTexCoord = new Cartesian2();
  23615. var scratchMaxTexCoord = new Cartesian2();
  23616. function computeTopBottomAttributes(positions, options, extrude) {
  23617. var vertexFormat = options.vertexFormat;
  23618. var center = options.center;
  23619. var semiMajorAxis = options.semiMajorAxis;
  23620. var semiMinorAxis = options.semiMinorAxis;
  23621. var ellipsoid = options.ellipsoid;
  23622. var stRotation = options.stRotation;
  23623. var size = (extrude) ? positions.length / 3 * 2 : positions.length / 3;
  23624. var textureCoordinates = (vertexFormat.st) ? new Float32Array(size * 2) : undefined;
  23625. var normals = (vertexFormat.normal) ? new Float32Array(size * 3) : undefined;
  23626. var tangents = (vertexFormat.tangent) ? new Float32Array(size * 3) : undefined;
  23627. var binormals = (vertexFormat.binormal) ? new Float32Array(size * 3) : undefined;
  23628. var textureCoordIndex = 0;
  23629. // Raise positions to a height above the ellipsoid and compute the
  23630. // texture coordinates, normals, tangents, and binormals.
  23631. var normal = scratchNormal;
  23632. var tangent = scratchTangent;
  23633. var binormal = scratchBinormal;
  23634. var projection = new GeographicProjection(ellipsoid);
  23635. var projectedCenter = projection.project(ellipsoid.cartesianToCartographic(center, scratchCartographic), projectedCenterScratch);
  23636. var geodeticNormal = ellipsoid.scaleToGeodeticSurface(center, scratchCartesian1);
  23637. ellipsoid.geodeticSurfaceNormal(geodeticNormal, geodeticNormal);
  23638. var rotation = Quaternion.fromAxisAngle(geodeticNormal, stRotation, quaternionScratch);
  23639. var textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrixScratch);
  23640. var minTexCoord = Cartesian2.fromElements(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, scratchMinTexCoord);
  23641. var maxTexCoord = Cartesian2.fromElements(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, scratchMaxTexCoord);
  23642. var length = positions.length;
  23643. var bottomOffset = (extrude) ? length : 0;
  23644. var stOffset = bottomOffset / 3 * 2;
  23645. for (var i = 0; i < length; i += 3) {
  23646. var i1 = i + 1;
  23647. var i2 = i + 2;
  23648. var position = Cartesian3.fromArray(positions, i, scratchCartesian1);
  23649. if (vertexFormat.st) {
  23650. var rotatedPoint = Matrix3.multiplyByVector(textureMatrix, position, scratchCartesian2);
  23651. var projectedPoint = projection.project(ellipsoid.cartesianToCartographic(rotatedPoint, scratchCartographic), scratchCartesian3);
  23652. Cartesian3.subtract(projectedPoint, projectedCenter, projectedPoint);
  23653. texCoordScratch.x = (projectedPoint.x + semiMajorAxis) / (2.0 * semiMajorAxis);
  23654. texCoordScratch.y = (projectedPoint.y + semiMinorAxis) / (2.0 * semiMinorAxis);
  23655. minTexCoord.x = Math.min(texCoordScratch.x, minTexCoord.x);
  23656. minTexCoord.y = Math.min(texCoordScratch.y, minTexCoord.y);
  23657. maxTexCoord.x = Math.max(texCoordScratch.x, maxTexCoord.x);
  23658. maxTexCoord.y = Math.max(texCoordScratch.y, maxTexCoord.y);
  23659. if (extrude) {
  23660. textureCoordinates[textureCoordIndex + stOffset] = texCoordScratch.x;
  23661. textureCoordinates[textureCoordIndex + 1 + stOffset] = texCoordScratch.y;
  23662. }
  23663. textureCoordinates[textureCoordIndex++] = texCoordScratch.x;
  23664. textureCoordinates[textureCoordIndex++] = texCoordScratch.y;
  23665. }
  23666. normal = ellipsoid.geodeticSurfaceNormal(position, normal);
  23667. if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.binormal) {
  23668. if (vertexFormat.tangent || vertexFormat.binormal) {
  23669. tangent = Cartesian3.normalize(Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent), tangent);
  23670. Matrix3.multiplyByVector(textureMatrix, tangent, tangent);
  23671. }
  23672. if (vertexFormat.normal) {
  23673. normals[i] = normal.x;
  23674. normals[i1] = normal.y;
  23675. normals[i2] = normal.z;
  23676. if (extrude) {
  23677. normals[i + bottomOffset] = -normal.x;
  23678. normals[i1 + bottomOffset] = -normal.y;
  23679. normals[i2 + bottomOffset] = -normal.z;
  23680. }
  23681. }
  23682. if (vertexFormat.tangent) {
  23683. tangents[i] = tangent.x;
  23684. tangents[i1] = tangent.y;
  23685. tangents[i2] = tangent.z;
  23686. if (extrude) {
  23687. tangents[i + bottomOffset] = -tangent.x;
  23688. tangents[i1 + bottomOffset] = -tangent.y;
  23689. tangents[i2 + bottomOffset] = -tangent.z;
  23690. }
  23691. }
  23692. if (vertexFormat.binormal) {
  23693. binormal = Cartesian3.normalize(Cartesian3.cross(normal, tangent, binormal), binormal);
  23694. binormals[i] = binormal.x;
  23695. binormals[i1] = binormal.y;
  23696. binormals[i2] = binormal.z;
  23697. if (extrude) {
  23698. binormals[i + bottomOffset] = binormal.x;
  23699. binormals[i1 + bottomOffset] = binormal.y;
  23700. binormals[i2 + bottomOffset] = binormal.z;
  23701. }
  23702. }
  23703. }
  23704. }
  23705. if (vertexFormat.st) {
  23706. length = textureCoordinates.length;
  23707. for (var k = 0; k < length; k += 2) {
  23708. textureCoordinates[k] = (textureCoordinates[k] - minTexCoord.x) / (maxTexCoord.x - minTexCoord.x);
  23709. textureCoordinates[k + 1] = (textureCoordinates[k + 1] - minTexCoord.y) / (maxTexCoord.y - minTexCoord.y);
  23710. }
  23711. }
  23712. var attributes = new GeometryAttributes();
  23713. if (vertexFormat.position) {
  23714. var finalPositions = EllipseGeometryLibrary.raisePositionsToHeight(positions, options, extrude);
  23715. attributes.position = new GeometryAttribute({
  23716. componentDatatype : ComponentDatatype.DOUBLE,
  23717. componentsPerAttribute : 3,
  23718. values : finalPositions
  23719. });
  23720. }
  23721. if (vertexFormat.st) {
  23722. attributes.st = new GeometryAttribute({
  23723. componentDatatype : ComponentDatatype.FLOAT,
  23724. componentsPerAttribute : 2,
  23725. values : textureCoordinates
  23726. });
  23727. }
  23728. if (vertexFormat.normal) {
  23729. attributes.normal = new GeometryAttribute({
  23730. componentDatatype : ComponentDatatype.FLOAT,
  23731. componentsPerAttribute : 3,
  23732. values : normals
  23733. });
  23734. }
  23735. if (vertexFormat.tangent) {
  23736. attributes.tangent = new GeometryAttribute({
  23737. componentDatatype : ComponentDatatype.FLOAT,
  23738. componentsPerAttribute : 3,
  23739. values : tangents
  23740. });
  23741. }
  23742. if (vertexFormat.binormal) {
  23743. attributes.binormal = new GeometryAttribute({
  23744. componentDatatype : ComponentDatatype.FLOAT,
  23745. componentsPerAttribute : 3,
  23746. values : binormals
  23747. });
  23748. }
  23749. return attributes;
  23750. }
  23751. function topIndices(numPts) {
  23752. // numTriangles in half = 3 + 8 + 12 + ... = -1 + 4 + (4 + 4) + (4 + 4 + 4) + ... = -1 + 4 * (1 + 2 + 3 + ...)
  23753. // = -1 + 4 * ((n * ( n + 1)) / 2)
  23754. // total triangles = 2 * numTrangles in half
  23755. // indices = total triangles * 3;
  23756. // Substitute numPts for n above
  23757. var indices = new Array(12 * (numPts * ( numPts + 1)) - 6);
  23758. var indicesIndex = 0;
  23759. var prevIndex;
  23760. var numInterior;
  23761. var positionIndex;
  23762. var i;
  23763. var j;
  23764. // Indices triangles to the 'right' of the north vector
  23765. prevIndex = 0;
  23766. positionIndex = 1;
  23767. for (i = 0; i < 3; i++) {
  23768. indices[indicesIndex++] = positionIndex++;
  23769. indices[indicesIndex++] = prevIndex;
  23770. indices[indicesIndex++] = positionIndex;
  23771. }
  23772. for (i = 2; i < numPts + 1; ++i) {
  23773. positionIndex = i * (i + 1) - 1;
  23774. prevIndex = (i - 1) * i - 1;
  23775. indices[indicesIndex++] = positionIndex++;
  23776. indices[indicesIndex++] = prevIndex;
  23777. indices[indicesIndex++] = positionIndex;
  23778. numInterior = 2 * i;
  23779. for (j = 0; j < numInterior - 1; ++j) {
  23780. indices[indicesIndex++] = positionIndex;
  23781. indices[indicesIndex++] = prevIndex++;
  23782. indices[indicesIndex++] = prevIndex;
  23783. indices[indicesIndex++] = positionIndex++;
  23784. indices[indicesIndex++] = prevIndex;
  23785. indices[indicesIndex++] = positionIndex;
  23786. }
  23787. indices[indicesIndex++] = positionIndex++;
  23788. indices[indicesIndex++] = prevIndex;
  23789. indices[indicesIndex++] = positionIndex;
  23790. }
  23791. // Indices for center column of triangles
  23792. numInterior = numPts * 2;
  23793. ++positionIndex;
  23794. ++prevIndex;
  23795. for (i = 0; i < numInterior - 1; ++i) {
  23796. indices[indicesIndex++] = positionIndex;
  23797. indices[indicesIndex++] = prevIndex++;
  23798. indices[indicesIndex++] = prevIndex;
  23799. indices[indicesIndex++] = positionIndex++;
  23800. indices[indicesIndex++] = prevIndex;
  23801. indices[indicesIndex++] = positionIndex;
  23802. }
  23803. indices[indicesIndex++] = positionIndex;
  23804. indices[indicesIndex++] = prevIndex++;
  23805. indices[indicesIndex++] = prevIndex;
  23806. indices[indicesIndex++] = positionIndex++;
  23807. indices[indicesIndex++] = prevIndex++;
  23808. indices[indicesIndex++] = prevIndex;
  23809. // Reverse the process creating indices to the 'left' of the north vector
  23810. ++prevIndex;
  23811. for (i = numPts - 1; i > 1; --i) {
  23812. indices[indicesIndex++] = prevIndex++;
  23813. indices[indicesIndex++] = prevIndex;
  23814. indices[indicesIndex++] = positionIndex;
  23815. numInterior = 2 * i;
  23816. for (j = 0; j < numInterior - 1; ++j) {
  23817. indices[indicesIndex++] = positionIndex;
  23818. indices[indicesIndex++] = prevIndex++;
  23819. indices[indicesIndex++] = prevIndex;
  23820. indices[indicesIndex++] = positionIndex++;
  23821. indices[indicesIndex++] = prevIndex;
  23822. indices[indicesIndex++] = positionIndex;
  23823. }
  23824. indices[indicesIndex++] = prevIndex++;
  23825. indices[indicesIndex++] = prevIndex++;
  23826. indices[indicesIndex++] = positionIndex++;
  23827. }
  23828. for (i = 0; i < 3; i++) {
  23829. indices[indicesIndex++] = prevIndex++;
  23830. indices[indicesIndex++] = prevIndex;
  23831. indices[indicesIndex++] = positionIndex;
  23832. }
  23833. return indices;
  23834. }
  23835. var boundingSphereCenter = new Cartesian3();
  23836. function computeEllipse(options) {
  23837. var center = options.center;
  23838. boundingSphereCenter = Cartesian3.multiplyByScalar(options.ellipsoid.geodeticSurfaceNormal(center, boundingSphereCenter), options.height, boundingSphereCenter);
  23839. boundingSphereCenter = Cartesian3.add(center, boundingSphereCenter, boundingSphereCenter);
  23840. var boundingSphere = new BoundingSphere(boundingSphereCenter, options.semiMajorAxis);
  23841. var cep = EllipseGeometryLibrary.computeEllipsePositions(options, true, false);
  23842. var positions = cep.positions;
  23843. var numPts = cep.numPts;
  23844. var attributes = computeTopBottomAttributes(positions, options, false);
  23845. var indices = topIndices(numPts);
  23846. indices = IndexDatatype.createTypedArray(positions.length / 3, indices);
  23847. return {
  23848. boundingSphere : boundingSphere,
  23849. attributes : attributes,
  23850. indices : indices
  23851. };
  23852. }
  23853. function computeWallAttributes(positions, options) {
  23854. var vertexFormat = options.vertexFormat;
  23855. var center = options.center;
  23856. var semiMajorAxis = options.semiMajorAxis;
  23857. var semiMinorAxis = options.semiMinorAxis;
  23858. var ellipsoid = options.ellipsoid;
  23859. var height = options.height;
  23860. var extrudedHeight = options.extrudedHeight;
  23861. var stRotation = options.stRotation;
  23862. var size = positions.length / 3 * 2;
  23863. var finalPositions = new Float64Array(size * 3);
  23864. var textureCoordinates = (vertexFormat.st) ? new Float32Array(size * 2) : undefined;
  23865. var normals = (vertexFormat.normal) ? new Float32Array(size * 3) : undefined;
  23866. var tangents = (vertexFormat.tangent) ? new Float32Array(size * 3) : undefined;
  23867. var binormals = (vertexFormat.binormal) ? new Float32Array(size * 3) : undefined;
  23868. var textureCoordIndex = 0;
  23869. // Raise positions to a height above the ellipsoid and compute the
  23870. // texture coordinates, normals, tangents, and binormals.
  23871. var normal = scratchNormal;
  23872. var tangent = scratchTangent;
  23873. var binormal = scratchBinormal;
  23874. var projection = new GeographicProjection(ellipsoid);
  23875. var projectedCenter = projection.project(ellipsoid.cartesianToCartographic(center, scratchCartographic), projectedCenterScratch);
  23876. var geodeticNormal = ellipsoid.scaleToGeodeticSurface(center, scratchCartesian1);
  23877. ellipsoid.geodeticSurfaceNormal(geodeticNormal, geodeticNormal);
  23878. var rotation = Quaternion.fromAxisAngle(geodeticNormal, stRotation, quaternionScratch);
  23879. var textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrixScratch);
  23880. var minTexCoord = Cartesian2.fromElements(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, scratchMinTexCoord);
  23881. var maxTexCoord = Cartesian2.fromElements(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, scratchMaxTexCoord);
  23882. var length = positions.length;
  23883. var stOffset = length / 3 * 2;
  23884. for (var i = 0; i < length; i += 3) {
  23885. var i1 = i + 1;
  23886. var i2 = i + 2;
  23887. var position = Cartesian3.fromArray(positions, i, scratchCartesian1);
  23888. var extrudedPosition;
  23889. if (vertexFormat.st) {
  23890. var rotatedPoint = Matrix3.multiplyByVector(textureMatrix, position, scratchCartesian2);
  23891. var projectedPoint = projection.project(ellipsoid.cartesianToCartographic(rotatedPoint, scratchCartographic), scratchCartesian3);
  23892. Cartesian3.subtract(projectedPoint, projectedCenter, projectedPoint);
  23893. texCoordScratch.x = (projectedPoint.x + semiMajorAxis) / (2.0 * semiMajorAxis);
  23894. texCoordScratch.y = (projectedPoint.y + semiMinorAxis) / (2.0 * semiMinorAxis);
  23895. minTexCoord.x = Math.min(texCoordScratch.x, minTexCoord.x);
  23896. minTexCoord.y = Math.min(texCoordScratch.y, minTexCoord.y);
  23897. maxTexCoord.x = Math.max(texCoordScratch.x, maxTexCoord.x);
  23898. maxTexCoord.y = Math.max(texCoordScratch.y, maxTexCoord.y);
  23899. textureCoordinates[textureCoordIndex + stOffset] = texCoordScratch.x;
  23900. textureCoordinates[textureCoordIndex + 1 + stOffset] = texCoordScratch.y;
  23901. textureCoordinates[textureCoordIndex++] = texCoordScratch.x;
  23902. textureCoordinates[textureCoordIndex++] = texCoordScratch.y;
  23903. }
  23904. position = ellipsoid.scaleToGeodeticSurface(position, position);
  23905. extrudedPosition = Cartesian3.clone(position, scratchCartesian2);
  23906. normal = ellipsoid.geodeticSurfaceNormal(position, normal);
  23907. var scaledNormal = Cartesian3.multiplyByScalar(normal, height, scratchCartesian4);
  23908. position = Cartesian3.add(position, scaledNormal, position);
  23909. scaledNormal = Cartesian3.multiplyByScalar(normal, extrudedHeight, scaledNormal);
  23910. extrudedPosition = Cartesian3.add(extrudedPosition, scaledNormal, extrudedPosition);
  23911. if (vertexFormat.position) {
  23912. finalPositions[i + length] = extrudedPosition.x;
  23913. finalPositions[i1 + length] = extrudedPosition.y;
  23914. finalPositions[i2 + length] = extrudedPosition.z;
  23915. finalPositions[i] = position.x;
  23916. finalPositions[i1] = position.y;
  23917. finalPositions[i2] = position.z;
  23918. }
  23919. if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.binormal) {
  23920. binormal = Cartesian3.clone(normal, binormal);
  23921. var next = Cartesian3.fromArray(positions, (i + 3) % length, scratchCartesian4);
  23922. Cartesian3.subtract(next, position, next);
  23923. var bottom = Cartesian3.subtract(extrudedPosition, position, scratchCartesian3);
  23924. normal = Cartesian3.normalize(Cartesian3.cross(bottom, next, normal), normal);
  23925. if (vertexFormat.normal) {
  23926. normals[i] = normal.x;
  23927. normals[i1] = normal.y;
  23928. normals[i2] = normal.z;
  23929. normals[i + length] = normal.x;
  23930. normals[i1 + length] = normal.y;
  23931. normals[i2 + length] = normal.z;
  23932. }
  23933. if (vertexFormat.tangent) {
  23934. tangent = Cartesian3.normalize(Cartesian3.cross(binormal, normal, tangent), tangent);
  23935. tangents[i] = tangent.x;
  23936. tangents[i1] = tangent.y;
  23937. tangents[i2] = tangent.z;
  23938. tangents[i + length] = tangent.x;
  23939. tangents[i + 1 + length] = tangent.y;
  23940. tangents[i + 2 + length] = tangent.z;
  23941. }
  23942. if (vertexFormat.binormal) {
  23943. binormals[i] = binormal.x;
  23944. binormals[i1] = binormal.y;
  23945. binormals[i2] = binormal.z;
  23946. binormals[i + length] = binormal.x;
  23947. binormals[i1 + length] = binormal.y;
  23948. binormals[i2 + length] = binormal.z;
  23949. }
  23950. }
  23951. }
  23952. if (vertexFormat.st) {
  23953. length = textureCoordinates.length;
  23954. for (var k = 0; k < length; k += 2) {
  23955. textureCoordinates[k] = (textureCoordinates[k] - minTexCoord.x) / (maxTexCoord.x - minTexCoord.x);
  23956. textureCoordinates[k + 1] = (textureCoordinates[k + 1] - minTexCoord.y) / (maxTexCoord.y - minTexCoord.y);
  23957. }
  23958. }
  23959. var attributes = new GeometryAttributes();
  23960. if (vertexFormat.position) {
  23961. attributes.position = new GeometryAttribute({
  23962. componentDatatype : ComponentDatatype.DOUBLE,
  23963. componentsPerAttribute : 3,
  23964. values : finalPositions
  23965. });
  23966. }
  23967. if (vertexFormat.st) {
  23968. attributes.st = new GeometryAttribute({
  23969. componentDatatype : ComponentDatatype.FLOAT,
  23970. componentsPerAttribute : 2,
  23971. values : textureCoordinates
  23972. });
  23973. }
  23974. if (vertexFormat.normal) {
  23975. attributes.normal = new GeometryAttribute({
  23976. componentDatatype : ComponentDatatype.FLOAT,
  23977. componentsPerAttribute : 3,
  23978. values : normals
  23979. });
  23980. }
  23981. if (vertexFormat.tangent) {
  23982. attributes.tangent = new GeometryAttribute({
  23983. componentDatatype : ComponentDatatype.FLOAT,
  23984. componentsPerAttribute : 3,
  23985. values : tangents
  23986. });
  23987. }
  23988. if (vertexFormat.binormal) {
  23989. attributes.binormal = new GeometryAttribute({
  23990. componentDatatype : ComponentDatatype.FLOAT,
  23991. componentsPerAttribute : 3,
  23992. values : binormals
  23993. });
  23994. }
  23995. return attributes;
  23996. }
  23997. function computeWallIndices(positions) {
  23998. var length = positions.length / 3;
  23999. var indices = IndexDatatype.createTypedArray(length, length * 6);
  24000. var index = 0;
  24001. for (var i = 0; i < length; i++) {
  24002. var UL = i;
  24003. var LL = i + length;
  24004. var UR = (UL + 1) % length;
  24005. var LR = UR + length;
  24006. indices[index++] = UL;
  24007. indices[index++] = LL;
  24008. indices[index++] = UR;
  24009. indices[index++] = UR;
  24010. indices[index++] = LL;
  24011. indices[index++] = LR;
  24012. }
  24013. return indices;
  24014. }
  24015. var topBoundingSphere = new BoundingSphere();
  24016. var bottomBoundingSphere = new BoundingSphere();
  24017. function computeExtrudedEllipse(options) {
  24018. var center = options.center;
  24019. var ellipsoid = options.ellipsoid;
  24020. var semiMajorAxis = options.semiMajorAxis;
  24021. var scaledNormal = Cartesian3.multiplyByScalar(ellipsoid.geodeticSurfaceNormal(center, scratchCartesian1), options.height, scratchCartesian1);
  24022. topBoundingSphere.center = Cartesian3.add(center, scaledNormal, topBoundingSphere.center);
  24023. topBoundingSphere.radius = semiMajorAxis;
  24024. scaledNormal = Cartesian3.multiplyByScalar(ellipsoid.geodeticSurfaceNormal(center, scaledNormal), options.extrudedHeight, scaledNormal);
  24025. bottomBoundingSphere.center = Cartesian3.add(center, scaledNormal, bottomBoundingSphere.center);
  24026. bottomBoundingSphere.radius = semiMajorAxis;
  24027. var cep = EllipseGeometryLibrary.computeEllipsePositions(options, true, true);
  24028. var positions = cep.positions;
  24029. var numPts = cep.numPts;
  24030. var outerPositions = cep.outerPositions;
  24031. var boundingSphere = BoundingSphere.union(topBoundingSphere, bottomBoundingSphere);
  24032. var topBottomAttributes = computeTopBottomAttributes(positions, options, true);
  24033. var indices = topIndices(numPts);
  24034. var length = indices.length;
  24035. indices.length = length * 2;
  24036. var posLength = positions.length / 3;
  24037. for (var i = 0; i < length; i += 3) {
  24038. indices[i + length] = indices[i + 2] + posLength;
  24039. indices[i + 1 + length] = indices[i + 1] + posLength;
  24040. indices[i + 2 + length] = indices[i] + posLength;
  24041. }
  24042. var topBottomIndices = IndexDatatype.createTypedArray(posLength * 2 / 3, indices);
  24043. var topBottomGeo = new Geometry({
  24044. attributes : topBottomAttributes,
  24045. indices : topBottomIndices,
  24046. primitiveType : PrimitiveType.TRIANGLES
  24047. });
  24048. var wallAttributes = computeWallAttributes(outerPositions, options);
  24049. indices = computeWallIndices(outerPositions);
  24050. var wallIndices = IndexDatatype.createTypedArray(outerPositions.length * 2 / 3, indices);
  24051. var wallGeo = new Geometry({
  24052. attributes : wallAttributes,
  24053. indices : wallIndices,
  24054. primitiveType : PrimitiveType.TRIANGLES
  24055. });
  24056. var geo = GeometryPipeline.combineInstances([
  24057. new GeometryInstance({
  24058. geometry : topBottomGeo
  24059. }),
  24060. new GeometryInstance({
  24061. geometry : wallGeo
  24062. })
  24063. ]);
  24064. return {
  24065. boundingSphere : boundingSphere,
  24066. attributes : geo[0].attributes,
  24067. indices : geo[0].indices
  24068. };
  24069. }
  24070. var scratchEnuToFixedMatrix = new Matrix4();
  24071. var scratchFixedToEnuMatrix = new Matrix4();
  24072. var scratchRotationMatrix = new Matrix3();
  24073. var scratchRectanglePoints = [new Cartesian3(), new Cartesian3(), new Cartesian3(), new Cartesian3()];
  24074. var scratchCartographicPoints = [new Cartographic(), new Cartographic(), new Cartographic(), new Cartographic()];
  24075. function computeRectangle(center, ellipsoid, semiMajorAxis, semiMinorAxis, rotation) {
  24076. Transforms.eastNorthUpToFixedFrame(center, ellipsoid, scratchEnuToFixedMatrix);
  24077. Matrix4.inverseTransformation(scratchEnuToFixedMatrix, scratchFixedToEnuMatrix);
  24078. // Find the 4 extreme points of the ellipse in ENU
  24079. for (var i = 0; i < 4; ++i) {
  24080. Cartesian3.clone(Cartesian3.ZERO, scratchRectanglePoints[i]);
  24081. }
  24082. scratchRectanglePoints[0].x += semiMajorAxis;
  24083. scratchRectanglePoints[1].x -= semiMajorAxis;
  24084. scratchRectanglePoints[2].y += semiMinorAxis;
  24085. scratchRectanglePoints[3].y -= semiMinorAxis;
  24086. Matrix3.fromRotationZ(rotation, scratchRotationMatrix);
  24087. for (i = 0; i < 4; ++i) {
  24088. // Apply the rotation
  24089. Matrix3.multiplyByVector(scratchRotationMatrix, scratchRectanglePoints[i], scratchRectanglePoints[i]);
  24090. // Convert back to fixed and then to cartographic
  24091. Matrix4.multiplyByPoint(scratchEnuToFixedMatrix, scratchRectanglePoints[i], scratchRectanglePoints[i]);
  24092. ellipsoid.cartesianToCartographic(scratchRectanglePoints[i], scratchCartographicPoints[i]);
  24093. }
  24094. return Rectangle.fromCartographicArray(scratchCartographicPoints);
  24095. }
  24096. /**
  24097. * A description of an ellipse on an ellipsoid. Ellipse geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
  24098. *
  24099. * @alias EllipseGeometry
  24100. * @constructor
  24101. *
  24102. * @param {Object} options Object with the following properties:
  24103. * @param {Cartesian3} options.center The ellipse's center point in the fixed frame.
  24104. * @param {Number} options.semiMajorAxis The length of the ellipse's semi-major axis in meters.
  24105. * @param {Number} options.semiMinorAxis The length of the ellipse's semi-minor axis in meters.
  24106. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the ellipse will be on.
  24107. * @param {Number} [options.height=0.0] The distance in meters between the ellipse and the ellipsoid surface.
  24108. * @param {Number} [options.extrudedHeight] The distance in meters between the ellipse's extruded face and the ellipsoid surface.
  24109. * @param {Number} [options.rotation=0.0] The angle of rotation counter-clockwise from north.
  24110. * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates counter-clockwise from north.
  24111. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The angular distance between points on the ellipse in radians.
  24112. * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
  24113. *
  24114. * @exception {DeveloperError} semiMajorAxis and semiMinorAxis must be greater than zero.
  24115. * @exception {DeveloperError} semiMajorAxis must be greater than or equal to the semiMinorAxis.
  24116. * @exception {DeveloperError} granularity must be greater than zero.
  24117. *
  24118. *
  24119. * @example
  24120. * // Create an ellipse.
  24121. * var ellipse = new Cesium.EllipseGeometry({
  24122. * center : Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
  24123. * semiMajorAxis : 500000.0,
  24124. * semiMinorAxis : 300000.0,
  24125. * rotation : Cesium.Math.toRadians(60.0)
  24126. * });
  24127. * var geometry = Cesium.EllipseGeometry.createGeometry(ellipse);
  24128. *
  24129. * @see EllipseGeometry.createGeometry
  24130. */
  24131. function EllipseGeometry(options) {
  24132. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  24133. var center = options.center;
  24134. var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  24135. var semiMajorAxis = options.semiMajorAxis;
  24136. var semiMinorAxis = options.semiMinorAxis;
  24137. var granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  24138. var height = defaultValue(options.height, 0.0);
  24139. var extrudedHeight = options.extrudedHeight;
  24140. var extrude = (defined(extrudedHeight) && Math.abs(height - extrudedHeight) > 1.0);
  24141. var vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
  24142. if (!defined(center)) {
  24143. throw new DeveloperError('center is required.');
  24144. }
  24145. if (!defined(semiMajorAxis)) {
  24146. throw new DeveloperError('semiMajorAxis is required.');
  24147. }
  24148. if (!defined(semiMinorAxis)) {
  24149. throw new DeveloperError('semiMinorAxis is required.');
  24150. }
  24151. if (semiMajorAxis < semiMinorAxis) {
  24152. throw new DeveloperError('semiMajorAxis must be greater than or equal to the semiMinorAxis.');
  24153. }
  24154. if (granularity <= 0.0) {
  24155. throw new DeveloperError('granularity must be greater than zero.');
  24156. }
  24157. this._center = Cartesian3.clone(center);
  24158. this._semiMajorAxis = semiMajorAxis;
  24159. this._semiMinorAxis = semiMinorAxis;
  24160. this._ellipsoid = Ellipsoid.clone(ellipsoid);
  24161. this._rotation = defaultValue(options.rotation, 0.0);
  24162. this._stRotation = defaultValue(options.stRotation, 0.0);
  24163. this._height = height;
  24164. this._granularity = granularity;
  24165. this._vertexFormat = VertexFormat.clone(vertexFormat);
  24166. this._extrudedHeight = defaultValue(extrudedHeight, height);
  24167. this._extrude = extrude;
  24168. this._workerName = 'createEllipseGeometry';
  24169. this._rectangle = computeRectangle(this._center, this._ellipsoid, semiMajorAxis, semiMinorAxis, this._rotation);
  24170. }
  24171. /**
  24172. * The number of elements used to pack the object into an array.
  24173. * @type {Number}
  24174. */
  24175. EllipseGeometry.packedLength = Cartesian3.packedLength + Ellipsoid.packedLength + VertexFormat.packedLength + Rectangle.packedLength + 8;
  24176. /**
  24177. * Stores the provided instance into the provided array.
  24178. *
  24179. * @param {EllipseGeometry} value The value to pack.
  24180. * @param {Number[]} array The array to pack into.
  24181. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  24182. *
  24183. * @returns {Number[]} The array that was packed into
  24184. */
  24185. EllipseGeometry.pack = function(value, array, startingIndex) {
  24186. if (!defined(value)) {
  24187. throw new DeveloperError('value is required');
  24188. }
  24189. if (!defined(array)) {
  24190. throw new DeveloperError('array is required');
  24191. }
  24192. startingIndex = defaultValue(startingIndex, 0);
  24193. Cartesian3.pack(value._center, array, startingIndex);
  24194. startingIndex += Cartesian3.packedLength;
  24195. Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  24196. startingIndex += Ellipsoid.packedLength;
  24197. VertexFormat.pack(value._vertexFormat, array, startingIndex);
  24198. startingIndex += VertexFormat.packedLength;
  24199. Rectangle.pack(value._rectangle, array, startingIndex);
  24200. startingIndex += Rectangle.packedLength;
  24201. array[startingIndex++] = value._semiMajorAxis;
  24202. array[startingIndex++] = value._semiMinorAxis;
  24203. array[startingIndex++] = value._rotation;
  24204. array[startingIndex++] = value._stRotation;
  24205. array[startingIndex++] = value._height;
  24206. array[startingIndex++] = value._granularity;
  24207. array[startingIndex++] = value._extrudedHeight;
  24208. array[startingIndex] = value._extrude ? 1.0 : 0.0;
  24209. return array;
  24210. };
  24211. var scratchCenter = new Cartesian3();
  24212. var scratchEllipsoid = new Ellipsoid();
  24213. var scratchVertexFormat = new VertexFormat();
  24214. var scratchRectangle = new Rectangle();
  24215. var scratchOptions = {
  24216. center : scratchCenter,
  24217. ellipsoid : scratchEllipsoid,
  24218. vertexFormat : scratchVertexFormat,
  24219. semiMajorAxis : undefined,
  24220. semiMinorAxis : undefined,
  24221. rotation : undefined,
  24222. stRotation : undefined,
  24223. height : undefined,
  24224. granularity : undefined,
  24225. extrudedHeight : undefined
  24226. };
  24227. /**
  24228. * Retrieves an instance from a packed array.
  24229. *
  24230. * @param {Number[]} array The packed array.
  24231. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  24232. * @param {EllipseGeometry} [result] The object into which to store the result.
  24233. * @returns {EllipseGeometry} The modified result parameter or a new EllipseGeometry instance if one was not provided.
  24234. */
  24235. EllipseGeometry.unpack = function(array, startingIndex, result) {
  24236. if (!defined(array)) {
  24237. throw new DeveloperError('array is required');
  24238. }
  24239. startingIndex = defaultValue(startingIndex, 0);
  24240. var center = Cartesian3.unpack(array, startingIndex, scratchCenter);
  24241. startingIndex += Cartesian3.packedLength;
  24242. var ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  24243. startingIndex += Ellipsoid.packedLength;
  24244. var vertexFormat = VertexFormat.unpack(array, startingIndex, scratchVertexFormat);
  24245. startingIndex += VertexFormat.packedLength;
  24246. var rectangle = Rectangle.unpack(array, startingIndex, scratchRectangle);
  24247. startingIndex += Rectangle.packedLength;
  24248. var semiMajorAxis = array[startingIndex++];
  24249. var semiMinorAxis = array[startingIndex++];
  24250. var rotation = array[startingIndex++];
  24251. var stRotation = array[startingIndex++];
  24252. var height = array[startingIndex++];
  24253. var granularity = array[startingIndex++];
  24254. var extrudedHeight = array[startingIndex++];
  24255. var extrude = array[startingIndex] === 1.0;
  24256. if (!defined(result)) {
  24257. scratchOptions.height = height;
  24258. scratchOptions.extrudedHeight = extrudedHeight;
  24259. scratchOptions.granularity = granularity;
  24260. scratchOptions.stRotation = stRotation;
  24261. scratchOptions.rotation = rotation;
  24262. scratchOptions.semiMajorAxis = semiMajorAxis;
  24263. scratchOptions.semiMinorAxis = semiMinorAxis;
  24264. return new EllipseGeometry(scratchOptions);
  24265. }
  24266. result._center = Cartesian3.clone(center, result._center);
  24267. result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  24268. result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
  24269. result._semiMajorAxis = semiMajorAxis;
  24270. result._semiMinorAxis = semiMinorAxis;
  24271. result._rotation = rotation;
  24272. result._stRotation = stRotation;
  24273. result._height = height;
  24274. result._granularity = granularity;
  24275. result._extrudedHeight = extrudedHeight;
  24276. result._extrude = extrude;
  24277. result._rectangle = Rectangle.clone(rectangle);
  24278. return result;
  24279. };
  24280. /**
  24281. * Computes the geometric representation of a ellipse on an ellipsoid, including its vertices, indices, and a bounding sphere.
  24282. *
  24283. * @param {EllipseGeometry} ellipseGeometry A description of the ellipse.
  24284. * @returns {Geometry|undefined} The computed vertices and indices.
  24285. */
  24286. EllipseGeometry.createGeometry = function(ellipseGeometry) {
  24287. if ((ellipseGeometry._semiMajorAxis <= 0.0) || (ellipseGeometry._semiMinorAxis <= 0.0)) {
  24288. return;
  24289. }
  24290. ellipseGeometry._center = ellipseGeometry._ellipsoid.scaleToGeodeticSurface(ellipseGeometry._center, ellipseGeometry._center);
  24291. var options = {
  24292. center : ellipseGeometry._center,
  24293. semiMajorAxis : ellipseGeometry._semiMajorAxis,
  24294. semiMinorAxis : ellipseGeometry._semiMinorAxis,
  24295. ellipsoid : ellipseGeometry._ellipsoid,
  24296. rotation : ellipseGeometry._rotation,
  24297. height : ellipseGeometry._height,
  24298. extrudedHeight : ellipseGeometry._extrudedHeight,
  24299. granularity : ellipseGeometry._granularity,
  24300. vertexFormat : ellipseGeometry._vertexFormat,
  24301. stRotation : ellipseGeometry._stRotation
  24302. };
  24303. var geometry;
  24304. if (ellipseGeometry._extrude) {
  24305. options.extrudedHeight = Math.min(ellipseGeometry._extrudedHeight, ellipseGeometry._height);
  24306. options.height = Math.max(ellipseGeometry._extrudedHeight, ellipseGeometry._height);
  24307. geometry = computeExtrudedEllipse(options);
  24308. } else {
  24309. geometry = computeEllipse(options);
  24310. }
  24311. return new Geometry({
  24312. attributes : geometry.attributes,
  24313. indices : geometry.indices,
  24314. primitiveType : PrimitiveType.TRIANGLES,
  24315. boundingSphere : geometry.boundingSphere
  24316. });
  24317. };
  24318. /**
  24319. * @private
  24320. */
  24321. EllipseGeometry.createShadowVolume = function(ellipseGeometry, minHeightFunc, maxHeightFunc) {
  24322. var granularity = ellipseGeometry._granularity;
  24323. var ellipsoid = ellipseGeometry._ellipsoid;
  24324. var minHeight = minHeightFunc(granularity, ellipsoid);
  24325. var maxHeight = maxHeightFunc(granularity, ellipsoid);
  24326. return new EllipseGeometry({
  24327. center : ellipseGeometry._center,
  24328. semiMajorAxis : ellipseGeometry._semiMajorAxis,
  24329. semiMinorAxis : ellipseGeometry._semiMinorAxis,
  24330. ellipsoid : ellipsoid,
  24331. rotation : ellipseGeometry._rotation,
  24332. stRotation : ellipseGeometry._stRotation,
  24333. granularity : granularity,
  24334. extrudedHeight : minHeight,
  24335. height : maxHeight,
  24336. vertexFormat : VertexFormat.POSITION_ONLY
  24337. });
  24338. };
  24339. defineProperties(EllipseGeometry.prototype, {
  24340. /**
  24341. * @private
  24342. */
  24343. rectangle : {
  24344. get : function() {
  24345. return this._rectangle;
  24346. }
  24347. }
  24348. });
  24349. return EllipseGeometry;
  24350. });
  24351. /*global define*/
  24352. define('Workers/createEllipseGeometry',[
  24353. '../Core/Cartesian3',
  24354. '../Core/defined',
  24355. '../Core/EllipseGeometry',
  24356. '../Core/Ellipsoid'
  24357. ], function(
  24358. Cartesian3,
  24359. defined,
  24360. EllipseGeometry,
  24361. Ellipsoid) {
  24362. 'use strict';
  24363. function createEllipseGeometry(ellipseGeometry, offset) {
  24364. if (defined(offset)) {
  24365. ellipseGeometry = EllipseGeometry.unpack(ellipseGeometry, offset);
  24366. }
  24367. ellipseGeometry._center = Cartesian3.clone(ellipseGeometry._center);
  24368. ellipseGeometry._ellipsoid = Ellipsoid.clone(ellipseGeometry._ellipsoid);
  24369. return EllipseGeometry.createGeometry(ellipseGeometry);
  24370. }
  24371. return createEllipseGeometry;
  24372. });
  24373. }());