createPolygonGeometry.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821
  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/Cartesian2',[
  3058. './defaultValue',
  3059. './defined',
  3060. './DeveloperError',
  3061. './freezeObject',
  3062. './Math'
  3063. ], function(
  3064. defaultValue,
  3065. defined,
  3066. DeveloperError,
  3067. freezeObject,
  3068. CesiumMath) {
  3069. 'use strict';
  3070. /**
  3071. * A 2D Cartesian point.
  3072. * @alias Cartesian2
  3073. * @constructor
  3074. *
  3075. * @param {Number} [x=0.0] The X component.
  3076. * @param {Number} [y=0.0] The Y component.
  3077. *
  3078. * @see Cartesian3
  3079. * @see Cartesian4
  3080. * @see Packable
  3081. */
  3082. function Cartesian2(x, y) {
  3083. /**
  3084. * The X component.
  3085. * @type {Number}
  3086. * @default 0.0
  3087. */
  3088. this.x = defaultValue(x, 0.0);
  3089. /**
  3090. * The Y component.
  3091. * @type {Number}
  3092. * @default 0.0
  3093. */
  3094. this.y = defaultValue(y, 0.0);
  3095. }
  3096. /**
  3097. * Creates a Cartesian2 instance from x and y coordinates.
  3098. *
  3099. * @param {Number} x The x coordinate.
  3100. * @param {Number} y The y coordinate.
  3101. * @param {Cartesian2} [result] The object onto which to store the result.
  3102. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3103. */
  3104. Cartesian2.fromElements = function(x, y, result) {
  3105. if (!defined(result)) {
  3106. return new Cartesian2(x, y);
  3107. }
  3108. result.x = x;
  3109. result.y = y;
  3110. return result;
  3111. };
  3112. /**
  3113. * Duplicates a Cartesian2 instance.
  3114. *
  3115. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  3116. * @param {Cartesian2} [result] The object onto which to store the result.
  3117. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  3118. */
  3119. Cartesian2.clone = function(cartesian, result) {
  3120. if (!defined(cartesian)) {
  3121. return undefined;
  3122. }
  3123. if (!defined(result)) {
  3124. return new Cartesian2(cartesian.x, cartesian.y);
  3125. }
  3126. result.x = cartesian.x;
  3127. result.y = cartesian.y;
  3128. return result;
  3129. };
  3130. /**
  3131. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  3132. * x and y properties of the Cartesian3 and drops z.
  3133. * @function
  3134. *
  3135. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  3136. * @param {Cartesian2} [result] The object onto which to store the result.
  3137. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3138. */
  3139. Cartesian2.fromCartesian3 = Cartesian2.clone;
  3140. /**
  3141. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  3142. * x and y properties of the Cartesian4 and drops z and w.
  3143. * @function
  3144. *
  3145. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  3146. * @param {Cartesian2} [result] The object onto which to store the result.
  3147. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3148. */
  3149. Cartesian2.fromCartesian4 = Cartesian2.clone;
  3150. /**
  3151. * The number of elements used to pack the object into an array.
  3152. * @type {Number}
  3153. */
  3154. Cartesian2.packedLength = 2;
  3155. /**
  3156. * Stores the provided instance into the provided array.
  3157. *
  3158. * @param {Cartesian2} value The value to pack.
  3159. * @param {Number[]} array The array to pack into.
  3160. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3161. *
  3162. * @returns {Number[]} The array that was packed into
  3163. */
  3164. Cartesian2.pack = function(value, array, startingIndex) {
  3165. if (!defined(value)) {
  3166. throw new DeveloperError('value is required');
  3167. }
  3168. if (!defined(array)) {
  3169. throw new DeveloperError('array is required');
  3170. }
  3171. startingIndex = defaultValue(startingIndex, 0);
  3172. array[startingIndex++] = value.x;
  3173. array[startingIndex] = value.y;
  3174. return array;
  3175. };
  3176. /**
  3177. * Retrieves an instance from a packed array.
  3178. *
  3179. * @param {Number[]} array The packed array.
  3180. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3181. * @param {Cartesian2} [result] The object into which to store the result.
  3182. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3183. */
  3184. Cartesian2.unpack = function(array, startingIndex, result) {
  3185. if (!defined(array)) {
  3186. throw new DeveloperError('array is required');
  3187. }
  3188. startingIndex = defaultValue(startingIndex, 0);
  3189. if (!defined(result)) {
  3190. result = new Cartesian2();
  3191. }
  3192. result.x = array[startingIndex++];
  3193. result.y = array[startingIndex];
  3194. return result;
  3195. };
  3196. /**
  3197. * Flattens an array of Cartesian2s into and array of components.
  3198. *
  3199. * @param {Cartesian2[]} array The array of cartesians to pack.
  3200. * @param {Number[]} result The array onto which to store the result.
  3201. * @returns {Number[]} The packed array.
  3202. */
  3203. Cartesian2.packArray = function(array, result) {
  3204. if (!defined(array)) {
  3205. throw new DeveloperError('array is required');
  3206. }
  3207. var length = array.length;
  3208. if (!defined(result)) {
  3209. result = new Array(length * 2);
  3210. } else {
  3211. result.length = length * 2;
  3212. }
  3213. for (var i = 0; i < length; ++i) {
  3214. Cartesian2.pack(array[i], result, i * 2);
  3215. }
  3216. return result;
  3217. };
  3218. /**
  3219. * Unpacks an array of cartesian components into and array of Cartesian2s.
  3220. *
  3221. * @param {Number[]} array The array of components to unpack.
  3222. * @param {Cartesian2[]} result The array onto which to store the result.
  3223. * @returns {Cartesian2[]} The unpacked array.
  3224. */
  3225. Cartesian2.unpackArray = function(array, result) {
  3226. if (!defined(array)) {
  3227. throw new DeveloperError('array is required');
  3228. }
  3229. var length = array.length;
  3230. if (!defined(result)) {
  3231. result = new Array(length / 2);
  3232. } else {
  3233. result.length = length / 2;
  3234. }
  3235. for (var i = 0; i < length; i += 2) {
  3236. var index = i / 2;
  3237. result[index] = Cartesian2.unpack(array, i, result[index]);
  3238. }
  3239. return result;
  3240. };
  3241. /**
  3242. * Creates a Cartesian2 from two consecutive elements in an array.
  3243. * @function
  3244. *
  3245. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  3246. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  3247. * @param {Cartesian2} [result] The object onto which to store the result.
  3248. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3249. *
  3250. * @example
  3251. * // Create a Cartesian2 with (1.0, 2.0)
  3252. * var v = [1.0, 2.0];
  3253. * var p = Cesium.Cartesian2.fromArray(v);
  3254. *
  3255. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  3256. * var v2 = [0.0, 0.0, 1.0, 2.0];
  3257. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  3258. */
  3259. Cartesian2.fromArray = Cartesian2.unpack;
  3260. /**
  3261. * Computes the value of the maximum component for the supplied Cartesian.
  3262. *
  3263. * @param {Cartesian2} cartesian The cartesian to use.
  3264. * @returns {Number} The value of the maximum component.
  3265. */
  3266. Cartesian2.maximumComponent = function(cartesian) {
  3267. if (!defined(cartesian)) {
  3268. throw new DeveloperError('cartesian is required');
  3269. }
  3270. return Math.max(cartesian.x, cartesian.y);
  3271. };
  3272. /**
  3273. * Computes the value of the minimum component for the supplied Cartesian.
  3274. *
  3275. * @param {Cartesian2} cartesian The cartesian to use.
  3276. * @returns {Number} The value of the minimum component.
  3277. */
  3278. Cartesian2.minimumComponent = function(cartesian) {
  3279. if (!defined(cartesian)) {
  3280. throw new DeveloperError('cartesian is required');
  3281. }
  3282. return Math.min(cartesian.x, cartesian.y);
  3283. };
  3284. /**
  3285. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  3286. *
  3287. * @param {Cartesian2} first A cartesian to compare.
  3288. * @param {Cartesian2} second A cartesian to compare.
  3289. * @param {Cartesian2} result The object into which to store the result.
  3290. * @returns {Cartesian2} A cartesian with the minimum components.
  3291. */
  3292. Cartesian2.minimumByComponent = function(first, second, result) {
  3293. if (!defined(first)) {
  3294. throw new DeveloperError('first is required.');
  3295. }
  3296. if (!defined(second)) {
  3297. throw new DeveloperError('second is required.');
  3298. }
  3299. if (!defined(result)) {
  3300. throw new DeveloperError('result is required.');
  3301. }
  3302. result.x = Math.min(first.x, second.x);
  3303. result.y = Math.min(first.y, second.y);
  3304. return result;
  3305. };
  3306. /**
  3307. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  3308. *
  3309. * @param {Cartesian2} first A cartesian to compare.
  3310. * @param {Cartesian2} second A cartesian to compare.
  3311. * @param {Cartesian2} result The object into which to store the result.
  3312. * @returns {Cartesian2} A cartesian with the maximum components.
  3313. */
  3314. Cartesian2.maximumByComponent = function(first, second, result) {
  3315. if (!defined(first)) {
  3316. throw new DeveloperError('first is required.');
  3317. }
  3318. if (!defined(second)) {
  3319. throw new DeveloperError('second is required.');
  3320. }
  3321. if (!defined(result)) {
  3322. throw new DeveloperError('result is required.');
  3323. }
  3324. result.x = Math.max(first.x, second.x);
  3325. result.y = Math.max(first.y, second.y);
  3326. return result;
  3327. };
  3328. /**
  3329. * Computes the provided Cartesian's squared magnitude.
  3330. *
  3331. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  3332. * @returns {Number} The squared magnitude.
  3333. */
  3334. Cartesian2.magnitudeSquared = function(cartesian) {
  3335. if (!defined(cartesian)) {
  3336. throw new DeveloperError('cartesian is required');
  3337. }
  3338. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  3339. };
  3340. /**
  3341. * Computes the Cartesian's magnitude (length).
  3342. *
  3343. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  3344. * @returns {Number} The magnitude.
  3345. */
  3346. Cartesian2.magnitude = function(cartesian) {
  3347. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  3348. };
  3349. var distanceScratch = new Cartesian2();
  3350. /**
  3351. * Computes the distance between two points.
  3352. *
  3353. * @param {Cartesian2} left The first point to compute the distance from.
  3354. * @param {Cartesian2} right The second point to compute the distance to.
  3355. * @returns {Number} The distance between two points.
  3356. *
  3357. * @example
  3358. * // Returns 1.0
  3359. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  3360. */
  3361. Cartesian2.distance = function(left, right) {
  3362. if (!defined(left) || !defined(right)) {
  3363. throw new DeveloperError('left and right are required.');
  3364. }
  3365. Cartesian2.subtract(left, right, distanceScratch);
  3366. return Cartesian2.magnitude(distanceScratch);
  3367. };
  3368. /**
  3369. * Computes the squared distance between two points. Comparing squared distances
  3370. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  3371. *
  3372. * @param {Cartesian2} left The first point to compute the distance from.
  3373. * @param {Cartesian2} right The second point to compute the distance to.
  3374. * @returns {Number} The distance between two points.
  3375. *
  3376. * @example
  3377. * // Returns 4.0, not 2.0
  3378. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  3379. */
  3380. Cartesian2.distanceSquared = function(left, right) {
  3381. if (!defined(left) || !defined(right)) {
  3382. throw new DeveloperError('left and right are required.');
  3383. }
  3384. Cartesian2.subtract(left, right, distanceScratch);
  3385. return Cartesian2.magnitudeSquared(distanceScratch);
  3386. };
  3387. /**
  3388. * Computes the normalized form of the supplied Cartesian.
  3389. *
  3390. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  3391. * @param {Cartesian2} result The object onto which to store the result.
  3392. * @returns {Cartesian2} The modified result parameter.
  3393. */
  3394. Cartesian2.normalize = function(cartesian, result) {
  3395. if (!defined(cartesian)) {
  3396. throw new DeveloperError('cartesian is required');
  3397. }
  3398. if (!defined(result)) {
  3399. throw new DeveloperError('result is required');
  3400. }
  3401. var magnitude = Cartesian2.magnitude(cartesian);
  3402. result.x = cartesian.x / magnitude;
  3403. result.y = cartesian.y / magnitude;
  3404. if (isNaN(result.x) || isNaN(result.y)) {
  3405. throw new DeveloperError('normalized result is not a number');
  3406. }
  3407. return result;
  3408. };
  3409. /**
  3410. * Computes the dot (scalar) product of two Cartesians.
  3411. *
  3412. * @param {Cartesian2} left The first Cartesian.
  3413. * @param {Cartesian2} right The second Cartesian.
  3414. * @returns {Number} The dot product.
  3415. */
  3416. Cartesian2.dot = function(left, right) {
  3417. if (!defined(left)) {
  3418. throw new DeveloperError('left is required');
  3419. }
  3420. if (!defined(right)) {
  3421. throw new DeveloperError('right is required');
  3422. }
  3423. return left.x * right.x + left.y * right.y;
  3424. };
  3425. /**
  3426. * Computes the componentwise product of two Cartesians.
  3427. *
  3428. * @param {Cartesian2} left The first Cartesian.
  3429. * @param {Cartesian2} right The second Cartesian.
  3430. * @param {Cartesian2} result The object onto which to store the result.
  3431. * @returns {Cartesian2} The modified result parameter.
  3432. */
  3433. Cartesian2.multiplyComponents = function(left, right, result) {
  3434. if (!defined(left)) {
  3435. throw new DeveloperError('left is required');
  3436. }
  3437. if (!defined(right)) {
  3438. throw new DeveloperError('right is required');
  3439. }
  3440. if (!defined(result)) {
  3441. throw new DeveloperError('result is required');
  3442. }
  3443. result.x = left.x * right.x;
  3444. result.y = left.y * right.y;
  3445. return result;
  3446. };
  3447. /**
  3448. * Computes the componentwise quotient of two Cartesians.
  3449. *
  3450. * @param {Cartesian2} left The first Cartesian.
  3451. * @param {Cartesian2} right The second Cartesian.
  3452. * @param {Cartesian2} result The object onto which to store the result.
  3453. * @returns {Cartesian2} The modified result parameter.
  3454. */
  3455. Cartesian2.divideComponents = function(left, right, result) {
  3456. if (!defined(left)) {
  3457. throw new DeveloperError('left is required');
  3458. }
  3459. if (!defined(right)) {
  3460. throw new DeveloperError('right is required');
  3461. }
  3462. if (!defined(result)) {
  3463. throw new DeveloperError('result is required');
  3464. }
  3465. result.x = left.x / right.x;
  3466. result.y = left.y / right.y;
  3467. return result;
  3468. };
  3469. /**
  3470. * Computes the componentwise sum of two Cartesians.
  3471. *
  3472. * @param {Cartesian2} left The first Cartesian.
  3473. * @param {Cartesian2} right The second Cartesian.
  3474. * @param {Cartesian2} result The object onto which to store the result.
  3475. * @returns {Cartesian2} The modified result parameter.
  3476. */
  3477. Cartesian2.add = function(left, right, result) {
  3478. if (!defined(left)) {
  3479. throw new DeveloperError('left is required');
  3480. }
  3481. if (!defined(right)) {
  3482. throw new DeveloperError('right is required');
  3483. }
  3484. if (!defined(result)) {
  3485. throw new DeveloperError('result is required');
  3486. }
  3487. result.x = left.x + right.x;
  3488. result.y = left.y + right.y;
  3489. return result;
  3490. };
  3491. /**
  3492. * Computes the componentwise difference of two Cartesians.
  3493. *
  3494. * @param {Cartesian2} left The first Cartesian.
  3495. * @param {Cartesian2} right The second Cartesian.
  3496. * @param {Cartesian2} result The object onto which to store the result.
  3497. * @returns {Cartesian2} The modified result parameter.
  3498. */
  3499. Cartesian2.subtract = function(left, right, result) {
  3500. if (!defined(left)) {
  3501. throw new DeveloperError('left is required');
  3502. }
  3503. if (!defined(right)) {
  3504. throw new DeveloperError('right is required');
  3505. }
  3506. if (!defined(result)) {
  3507. throw new DeveloperError('result is required');
  3508. }
  3509. result.x = left.x - right.x;
  3510. result.y = left.y - right.y;
  3511. return result;
  3512. };
  3513. /**
  3514. * Multiplies the provided Cartesian componentwise by the provided scalar.
  3515. *
  3516. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  3517. * @param {Number} scalar The scalar to multiply with.
  3518. * @param {Cartesian2} result The object onto which to store the result.
  3519. * @returns {Cartesian2} The modified result parameter.
  3520. */
  3521. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  3522. if (!defined(cartesian)) {
  3523. throw new DeveloperError('cartesian is required');
  3524. }
  3525. if (typeof scalar !== 'number') {
  3526. throw new DeveloperError('scalar is required and must be a number.');
  3527. }
  3528. if (!defined(result)) {
  3529. throw new DeveloperError('result is required');
  3530. }
  3531. result.x = cartesian.x * scalar;
  3532. result.y = cartesian.y * scalar;
  3533. return result;
  3534. };
  3535. /**
  3536. * Divides the provided Cartesian componentwise by the provided scalar.
  3537. *
  3538. * @param {Cartesian2} cartesian The Cartesian to be divided.
  3539. * @param {Number} scalar The scalar to divide by.
  3540. * @param {Cartesian2} result The object onto which to store the result.
  3541. * @returns {Cartesian2} The modified result parameter.
  3542. */
  3543. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  3544. if (!defined(cartesian)) {
  3545. throw new DeveloperError('cartesian is required');
  3546. }
  3547. if (typeof scalar !== 'number') {
  3548. throw new DeveloperError('scalar is required and must be a number.');
  3549. }
  3550. if (!defined(result)) {
  3551. throw new DeveloperError('result is required');
  3552. }
  3553. result.x = cartesian.x / scalar;
  3554. result.y = cartesian.y / scalar;
  3555. return result;
  3556. };
  3557. /**
  3558. * Negates the provided Cartesian.
  3559. *
  3560. * @param {Cartesian2} cartesian The Cartesian to be negated.
  3561. * @param {Cartesian2} result The object onto which to store the result.
  3562. * @returns {Cartesian2} The modified result parameter.
  3563. */
  3564. Cartesian2.negate = function(cartesian, result) {
  3565. if (!defined(cartesian)) {
  3566. throw new DeveloperError('cartesian is required');
  3567. }
  3568. if (!defined(result)) {
  3569. throw new DeveloperError('result is required');
  3570. }
  3571. result.x = -cartesian.x;
  3572. result.y = -cartesian.y;
  3573. return result;
  3574. };
  3575. /**
  3576. * Computes the absolute value of the provided Cartesian.
  3577. *
  3578. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  3579. * @param {Cartesian2} result The object onto which to store the result.
  3580. * @returns {Cartesian2} The modified result parameter.
  3581. */
  3582. Cartesian2.abs = function(cartesian, result) {
  3583. if (!defined(cartesian)) {
  3584. throw new DeveloperError('cartesian is required');
  3585. }
  3586. if (!defined(result)) {
  3587. throw new DeveloperError('result is required');
  3588. }
  3589. result.x = Math.abs(cartesian.x);
  3590. result.y = Math.abs(cartesian.y);
  3591. return result;
  3592. };
  3593. var lerpScratch = new Cartesian2();
  3594. /**
  3595. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  3596. *
  3597. * @param {Cartesian2} start The value corresponding to t at 0.0.
  3598. * @param {Cartesian2} end The value corresponding to t at 1.0.
  3599. * @param {Number} t The point along t at which to interpolate.
  3600. * @param {Cartesian2} result The object onto which to store the result.
  3601. * @returns {Cartesian2} The modified result parameter.
  3602. */
  3603. Cartesian2.lerp = function(start, end, t, result) {
  3604. if (!defined(start)) {
  3605. throw new DeveloperError('start is required.');
  3606. }
  3607. if (!defined(end)) {
  3608. throw new DeveloperError('end is required.');
  3609. }
  3610. if (typeof t !== 'number') {
  3611. throw new DeveloperError('t is required and must be a number.');
  3612. }
  3613. if (!defined(result)) {
  3614. throw new DeveloperError('result is required.');
  3615. }
  3616. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  3617. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  3618. return Cartesian2.add(lerpScratch, result, result);
  3619. };
  3620. var angleBetweenScratch = new Cartesian2();
  3621. var angleBetweenScratch2 = new Cartesian2();
  3622. /**
  3623. * Returns the angle, in radians, between the provided Cartesians.
  3624. *
  3625. * @param {Cartesian2} left The first Cartesian.
  3626. * @param {Cartesian2} right The second Cartesian.
  3627. * @returns {Number} The angle between the Cartesians.
  3628. */
  3629. Cartesian2.angleBetween = function(left, right) {
  3630. if (!defined(left)) {
  3631. throw new DeveloperError('left is required');
  3632. }
  3633. if (!defined(right)) {
  3634. throw new DeveloperError('right is required');
  3635. }
  3636. Cartesian2.normalize(left, angleBetweenScratch);
  3637. Cartesian2.normalize(right, angleBetweenScratch2);
  3638. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  3639. };
  3640. var mostOrthogonalAxisScratch = new Cartesian2();
  3641. /**
  3642. * Returns the axis that is most orthogonal to the provided Cartesian.
  3643. *
  3644. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  3645. * @param {Cartesian2} result The object onto which to store the result.
  3646. * @returns {Cartesian2} The most orthogonal axis.
  3647. */
  3648. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  3649. if (!defined(cartesian)) {
  3650. throw new DeveloperError('cartesian is required.');
  3651. }
  3652. if (!defined(result)) {
  3653. throw new DeveloperError('result is required.');
  3654. }
  3655. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  3656. Cartesian2.abs(f, f);
  3657. if (f.x <= f.y) {
  3658. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  3659. } else {
  3660. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  3661. }
  3662. return result;
  3663. };
  3664. /**
  3665. * Compares the provided Cartesians componentwise and returns
  3666. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3667. *
  3668. * @param {Cartesian2} [left] The first Cartesian.
  3669. * @param {Cartesian2} [right] The second Cartesian.
  3670. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3671. */
  3672. Cartesian2.equals = function(left, right) {
  3673. return (left === right) ||
  3674. ((defined(left)) &&
  3675. (defined(right)) &&
  3676. (left.x === right.x) &&
  3677. (left.y === right.y));
  3678. };
  3679. /**
  3680. * @private
  3681. */
  3682. Cartesian2.equalsArray = function(cartesian, array, offset) {
  3683. return cartesian.x === array[offset] &&
  3684. cartesian.y === array[offset + 1];
  3685. };
  3686. /**
  3687. * Compares the provided Cartesians componentwise and returns
  3688. * <code>true</code> if they pass an absolute or relative tolerance test,
  3689. * <code>false</code> otherwise.
  3690. *
  3691. * @param {Cartesian2} [left] The first Cartesian.
  3692. * @param {Cartesian2} [right] The second Cartesian.
  3693. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  3694. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  3695. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3696. */
  3697. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  3698. return (left === right) ||
  3699. (defined(left) &&
  3700. defined(right) &&
  3701. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  3702. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  3703. };
  3704. /**
  3705. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  3706. *
  3707. * @type {Cartesian2}
  3708. * @constant
  3709. */
  3710. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  3711. /**
  3712. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  3713. *
  3714. * @type {Cartesian2}
  3715. * @constant
  3716. */
  3717. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  3718. /**
  3719. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  3720. *
  3721. * @type {Cartesian2}
  3722. * @constant
  3723. */
  3724. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  3725. /**
  3726. * Duplicates this Cartesian2 instance.
  3727. *
  3728. * @param {Cartesian2} [result] The object onto which to store the result.
  3729. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3730. */
  3731. Cartesian2.prototype.clone = function(result) {
  3732. return Cartesian2.clone(this, result);
  3733. };
  3734. /**
  3735. * Compares this Cartesian against the provided Cartesian componentwise and returns
  3736. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3737. *
  3738. * @param {Cartesian2} [right] The right hand side Cartesian.
  3739. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3740. */
  3741. Cartesian2.prototype.equals = function(right) {
  3742. return Cartesian2.equals(this, right);
  3743. };
  3744. /**
  3745. * Compares this Cartesian against the provided Cartesian componentwise and returns
  3746. * <code>true</code> if they pass an absolute or relative tolerance test,
  3747. * <code>false</code> otherwise.
  3748. *
  3749. * @param {Cartesian2} [right] The right hand side Cartesian.
  3750. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  3751. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  3752. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  3753. */
  3754. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  3755. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  3756. };
  3757. /**
  3758. * Creates a string representing this Cartesian in the format '(x, y)'.
  3759. *
  3760. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  3761. */
  3762. Cartesian2.prototype.toString = function() {
  3763. return '(' + this.x + ', ' + this.y + ')';
  3764. };
  3765. return Cartesian2;
  3766. });
  3767. /*global define*/
  3768. define('Core/GeographicProjection',[
  3769. './Cartesian3',
  3770. './Cartographic',
  3771. './defaultValue',
  3772. './defined',
  3773. './defineProperties',
  3774. './DeveloperError',
  3775. './Ellipsoid'
  3776. ], function(
  3777. Cartesian3,
  3778. Cartographic,
  3779. defaultValue,
  3780. defined,
  3781. defineProperties,
  3782. DeveloperError,
  3783. Ellipsoid) {
  3784. 'use strict';
  3785. /**
  3786. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  3787. * them by the {@link Ellipsoid#maximumRadius}. This projection
  3788. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  3789. * is also known as EPSG:4326.
  3790. *
  3791. * @alias GeographicProjection
  3792. * @constructor
  3793. *
  3794. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  3795. *
  3796. * @see WebMercatorProjection
  3797. */
  3798. function GeographicProjection(ellipsoid) {
  3799. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  3800. this._semimajorAxis = this._ellipsoid.maximumRadius;
  3801. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  3802. }
  3803. defineProperties(GeographicProjection.prototype, {
  3804. /**
  3805. * Gets the {@link Ellipsoid}.
  3806. *
  3807. * @memberof GeographicProjection.prototype
  3808. *
  3809. * @type {Ellipsoid}
  3810. * @readonly
  3811. */
  3812. ellipsoid : {
  3813. get : function() {
  3814. return this._ellipsoid;
  3815. }
  3816. }
  3817. });
  3818. /**
  3819. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  3820. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  3821. * ellipsoid. Z is the unmodified height.
  3822. *
  3823. * @param {Cartographic} cartographic The coordinates to project.
  3824. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  3825. * undefined, a new instance is created and returned.
  3826. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  3827. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3828. * created and returned.
  3829. */
  3830. GeographicProjection.prototype.project = function(cartographic, result) {
  3831. // Actually this is the special case of equidistant cylindrical called the plate carree
  3832. var semimajorAxis = this._semimajorAxis;
  3833. var x = cartographic.longitude * semimajorAxis;
  3834. var y = cartographic.latitude * semimajorAxis;
  3835. var z = cartographic.height;
  3836. if (!defined(result)) {
  3837. return new Cartesian3(x, y, z);
  3838. }
  3839. result.x = x;
  3840. result.y = y;
  3841. result.z = z;
  3842. return result;
  3843. };
  3844. /**
  3845. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  3846. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  3847. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  3848. *
  3849. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  3850. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  3851. * undefined, a new instance is created and returned.
  3852. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  3853. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3854. * created and returned.
  3855. */
  3856. GeographicProjection.prototype.unproject = function(cartesian, result) {
  3857. if (!defined(cartesian)) {
  3858. throw new DeveloperError('cartesian is required');
  3859. }
  3860. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  3861. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  3862. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  3863. var height = cartesian.z;
  3864. if (!defined(result)) {
  3865. return new Cartographic(longitude, latitude, height);
  3866. }
  3867. result.longitude = longitude;
  3868. result.latitude = latitude;
  3869. result.height = height;
  3870. return result;
  3871. };
  3872. return GeographicProjection;
  3873. });
  3874. /*global define*/
  3875. define('Core/Intersect',[
  3876. './freezeObject'
  3877. ], function(
  3878. freezeObject) {
  3879. 'use strict';
  3880. /**
  3881. * This enumerated type is used in determining where, relative to the frustum, an
  3882. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3883. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3884. * outside of the frustum's 6 planes (OUTSIDE).
  3885. *
  3886. * @exports Intersect
  3887. */
  3888. var Intersect = {
  3889. /**
  3890. * Represents that an object is not contained within the frustum.
  3891. *
  3892. * @type {Number}
  3893. * @constant
  3894. */
  3895. OUTSIDE : -1,
  3896. /**
  3897. * Represents that an object intersects one of the frustum's planes.
  3898. *
  3899. * @type {Number}
  3900. * @constant
  3901. */
  3902. INTERSECTING : 0,
  3903. /**
  3904. * Represents that an object is fully within the frustum.
  3905. *
  3906. * @type {Number}
  3907. * @constant
  3908. */
  3909. INSIDE : 1
  3910. };
  3911. return freezeObject(Intersect);
  3912. });
  3913. /*global define*/
  3914. define('Core/Rectangle',[
  3915. './Cartographic',
  3916. './defaultValue',
  3917. './defined',
  3918. './defineProperties',
  3919. './DeveloperError',
  3920. './Ellipsoid',
  3921. './freezeObject',
  3922. './Math'
  3923. ], function(
  3924. Cartographic,
  3925. defaultValue,
  3926. defined,
  3927. defineProperties,
  3928. DeveloperError,
  3929. Ellipsoid,
  3930. freezeObject,
  3931. CesiumMath) {
  3932. 'use strict';
  3933. /**
  3934. * A two dimensional region specified as longitude and latitude coordinates.
  3935. *
  3936. * @alias Rectangle
  3937. * @constructor
  3938. *
  3939. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  3940. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  3941. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  3942. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  3943. *
  3944. * @see Packable
  3945. */
  3946. function Rectangle(west, south, east, north) {
  3947. /**
  3948. * The westernmost longitude in radians in the range [-Pi, Pi].
  3949. *
  3950. * @type {Number}
  3951. * @default 0.0
  3952. */
  3953. this.west = defaultValue(west, 0.0);
  3954. /**
  3955. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  3956. *
  3957. * @type {Number}
  3958. * @default 0.0
  3959. */
  3960. this.south = defaultValue(south, 0.0);
  3961. /**
  3962. * The easternmost longitude in radians in the range [-Pi, Pi].
  3963. *
  3964. * @type {Number}
  3965. * @default 0.0
  3966. */
  3967. this.east = defaultValue(east, 0.0);
  3968. /**
  3969. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  3970. *
  3971. * @type {Number}
  3972. * @default 0.0
  3973. */
  3974. this.north = defaultValue(north, 0.0);
  3975. }
  3976. defineProperties(Rectangle.prototype, {
  3977. /**
  3978. * Gets the width of the rectangle in radians.
  3979. * @memberof Rectangle.prototype
  3980. * @type {Number}
  3981. */
  3982. width : {
  3983. get : function() {
  3984. return Rectangle.computeWidth(this);
  3985. }
  3986. },
  3987. /**
  3988. * Gets the height of the rectangle in radians.
  3989. * @memberof Rectangle.prototype
  3990. * @type {Number}
  3991. */
  3992. height : {
  3993. get : function() {
  3994. return Rectangle.computeHeight(this);
  3995. }
  3996. }
  3997. });
  3998. /**
  3999. * The number of elements used to pack the object into an array.
  4000. * @type {Number}
  4001. */
  4002. Rectangle.packedLength = 4;
  4003. /**
  4004. * Stores the provided instance into the provided array.
  4005. *
  4006. * @param {Rectangle} value The value to pack.
  4007. * @param {Number[]} array The array to pack into.
  4008. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4009. *
  4010. * @returns {Number[]} The array that was packed into
  4011. */
  4012. Rectangle.pack = function(value, array, startingIndex) {
  4013. if (!defined(value)) {
  4014. throw new DeveloperError('value is required');
  4015. }
  4016. if (!defined(array)) {
  4017. throw new DeveloperError('array is required');
  4018. }
  4019. startingIndex = defaultValue(startingIndex, 0);
  4020. array[startingIndex++] = value.west;
  4021. array[startingIndex++] = value.south;
  4022. array[startingIndex++] = value.east;
  4023. array[startingIndex] = value.north;
  4024. return array;
  4025. };
  4026. /**
  4027. * Retrieves an instance from a packed array.
  4028. *
  4029. * @param {Number[]} array The packed array.
  4030. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4031. * @param {Rectangle} [result] The object into which to store the result.
  4032. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  4033. */
  4034. Rectangle.unpack = function(array, startingIndex, result) {
  4035. if (!defined(array)) {
  4036. throw new DeveloperError('array is required');
  4037. }
  4038. startingIndex = defaultValue(startingIndex, 0);
  4039. if (!defined(result)) {
  4040. result = new Rectangle();
  4041. }
  4042. result.west = array[startingIndex++];
  4043. result.south = array[startingIndex++];
  4044. result.east = array[startingIndex++];
  4045. result.north = array[startingIndex];
  4046. return result;
  4047. };
  4048. /**
  4049. * Computes the width of a rectangle in radians.
  4050. * @param {Rectangle} rectangle The rectangle to compute the width of.
  4051. * @returns {Number} The width.
  4052. */
  4053. Rectangle.computeWidth = function(rectangle) {
  4054. if (!defined(rectangle)) {
  4055. throw new DeveloperError('rectangle is required.');
  4056. }
  4057. var east = rectangle.east;
  4058. var west = rectangle.west;
  4059. if (east < west) {
  4060. east += CesiumMath.TWO_PI;
  4061. }
  4062. return east - west;
  4063. };
  4064. /**
  4065. * Computes the height of a rectangle in radians.
  4066. * @param {Rectangle} rectangle The rectangle to compute the height of.
  4067. * @returns {Number} The height.
  4068. */
  4069. Rectangle.computeHeight = function(rectangle) {
  4070. if (!defined(rectangle)) {
  4071. throw new DeveloperError('rectangle is required.');
  4072. }
  4073. return rectangle.north - rectangle.south;
  4074. };
  4075. /**
  4076. * Creates an rectangle given the boundary longitude and latitude in degrees.
  4077. *
  4078. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  4079. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  4080. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  4081. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  4082. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4083. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4084. *
  4085. * @example
  4086. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  4087. */
  4088. Rectangle.fromDegrees = function(west, south, east, north, result) {
  4089. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  4090. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  4091. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  4092. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  4093. if (!defined(result)) {
  4094. return new Rectangle(west, south, east, north);
  4095. }
  4096. result.west = west;
  4097. result.south = south;
  4098. result.east = east;
  4099. result.north = north;
  4100. return result;
  4101. };
  4102. /**
  4103. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  4104. *
  4105. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  4106. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4107. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4108. */
  4109. Rectangle.fromCartographicArray = function(cartographics, result) {
  4110. if (!defined(cartographics)) {
  4111. throw new DeveloperError('cartographics is required.');
  4112. }
  4113. var west = Number.MAX_VALUE;
  4114. var east = -Number.MAX_VALUE;
  4115. var westOverIDL = Number.MAX_VALUE;
  4116. var eastOverIDL = -Number.MAX_VALUE;
  4117. var south = Number.MAX_VALUE;
  4118. var north = -Number.MAX_VALUE;
  4119. for ( var i = 0, len = cartographics.length; i < len; i++) {
  4120. var position = cartographics[i];
  4121. west = Math.min(west, position.longitude);
  4122. east = Math.max(east, position.longitude);
  4123. south = Math.min(south, position.latitude);
  4124. north = Math.max(north, position.latitude);
  4125. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  4126. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  4127. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  4128. }
  4129. if(east - west > eastOverIDL - westOverIDL) {
  4130. west = westOverIDL;
  4131. east = eastOverIDL;
  4132. if (east > CesiumMath.PI) {
  4133. east = east - CesiumMath.TWO_PI;
  4134. }
  4135. if (west > CesiumMath.PI) {
  4136. west = west - CesiumMath.TWO_PI;
  4137. }
  4138. }
  4139. if (!defined(result)) {
  4140. return new Rectangle(west, south, east, north);
  4141. }
  4142. result.west = west;
  4143. result.south = south;
  4144. result.east = east;
  4145. result.north = north;
  4146. return result;
  4147. };
  4148. /**
  4149. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  4150. *
  4151. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  4152. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  4153. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4154. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4155. */
  4156. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  4157. if (!defined(cartesians)) {
  4158. throw new DeveloperError('cartesians is required.');
  4159. }
  4160. var west = Number.MAX_VALUE;
  4161. var east = -Number.MAX_VALUE;
  4162. var westOverIDL = Number.MAX_VALUE;
  4163. var eastOverIDL = -Number.MAX_VALUE;
  4164. var south = Number.MAX_VALUE;
  4165. var north = -Number.MAX_VALUE;
  4166. for ( var i = 0, len = cartesians.length; i < len; i++) {
  4167. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  4168. west = Math.min(west, position.longitude);
  4169. east = Math.max(east, position.longitude);
  4170. south = Math.min(south, position.latitude);
  4171. north = Math.max(north, position.latitude);
  4172. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  4173. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  4174. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  4175. }
  4176. if(east - west > eastOverIDL - westOverIDL) {
  4177. west = westOverIDL;
  4178. east = eastOverIDL;
  4179. if (east > CesiumMath.PI) {
  4180. east = east - CesiumMath.TWO_PI;
  4181. }
  4182. if (west > CesiumMath.PI) {
  4183. west = west - CesiumMath.TWO_PI;
  4184. }
  4185. }
  4186. if (!defined(result)) {
  4187. return new Rectangle(west, south, east, north);
  4188. }
  4189. result.west = west;
  4190. result.south = south;
  4191. result.east = east;
  4192. result.north = north;
  4193. return result;
  4194. };
  4195. /**
  4196. * Duplicates an Rectangle.
  4197. *
  4198. * @param {Rectangle} rectangle The rectangle to clone.
  4199. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4200. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  4201. */
  4202. Rectangle.clone = function(rectangle, result) {
  4203. if (!defined(rectangle)) {
  4204. return undefined;
  4205. }
  4206. if (!defined(result)) {
  4207. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  4208. }
  4209. result.west = rectangle.west;
  4210. result.south = rectangle.south;
  4211. result.east = rectangle.east;
  4212. result.north = rectangle.north;
  4213. return result;
  4214. };
  4215. /**
  4216. * Duplicates this Rectangle.
  4217. *
  4218. * @param {Rectangle} [result] The object onto which to store the result.
  4219. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4220. */
  4221. Rectangle.prototype.clone = function(result) {
  4222. return Rectangle.clone(this, result);
  4223. };
  4224. /**
  4225. * Compares the provided Rectangle with this Rectangle componentwise and returns
  4226. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4227. *
  4228. * @param {Rectangle} [other] The Rectangle to compare.
  4229. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  4230. */
  4231. Rectangle.prototype.equals = function(other) {
  4232. return Rectangle.equals(this, other);
  4233. };
  4234. /**
  4235. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  4236. * <code>false</code> otherwise.
  4237. *
  4238. * @param {Rectangle} [left] The first Rectangle.
  4239. * @param {Rectangle} [right] The second Rectangle.
  4240. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  4241. */
  4242. Rectangle.equals = function(left, right) {
  4243. return (left === right) ||
  4244. ((defined(left)) &&
  4245. (defined(right)) &&
  4246. (left.west === right.west) &&
  4247. (left.south === right.south) &&
  4248. (left.east === right.east) &&
  4249. (left.north === right.north));
  4250. };
  4251. /**
  4252. * Compares the provided Rectangle with this Rectangle componentwise and returns
  4253. * <code>true</code> if they are within the provided epsilon,
  4254. * <code>false</code> otherwise.
  4255. *
  4256. * @param {Rectangle} [other] The Rectangle to compare.
  4257. * @param {Number} epsilon The epsilon to use for equality testing.
  4258. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  4259. */
  4260. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  4261. if (typeof epsilon !== 'number') {
  4262. throw new DeveloperError('epsilon is required and must be a number.');
  4263. }
  4264. return defined(other) &&
  4265. (Math.abs(this.west - other.west) <= epsilon) &&
  4266. (Math.abs(this.south - other.south) <= epsilon) &&
  4267. (Math.abs(this.east - other.east) <= epsilon) &&
  4268. (Math.abs(this.north - other.north) <= epsilon);
  4269. };
  4270. /**
  4271. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  4272. *
  4273. * @param {Rectangle} rectangle The rectangle to validate
  4274. *
  4275. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  4276. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  4277. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  4278. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  4279. */
  4280. Rectangle.validate = function(rectangle) {
  4281. if (!defined(rectangle)) {
  4282. throw new DeveloperError('rectangle is required');
  4283. }
  4284. var north = rectangle.north;
  4285. if (typeof north !== 'number') {
  4286. throw new DeveloperError('north is required to be a number.');
  4287. }
  4288. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  4289. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  4290. }
  4291. var south = rectangle.south;
  4292. if (typeof south !== 'number') {
  4293. throw new DeveloperError('south is required to be a number.');
  4294. }
  4295. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  4296. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  4297. }
  4298. var west = rectangle.west;
  4299. if (typeof west !== 'number') {
  4300. throw new DeveloperError('west is required to be a number.');
  4301. }
  4302. if (west < -Math.PI || west > Math.PI) {
  4303. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  4304. }
  4305. var east = rectangle.east;
  4306. if (typeof east !== 'number') {
  4307. throw new DeveloperError('east is required to be a number.');
  4308. }
  4309. if (east < -Math.PI || east > Math.PI) {
  4310. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  4311. }
  4312. };
  4313. /**
  4314. * Computes the southwest corner of an rectangle.
  4315. *
  4316. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4317. * @param {Cartographic} [result] The object onto which to store the result.
  4318. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4319. */
  4320. Rectangle.southwest = function(rectangle, result) {
  4321. if (!defined(rectangle)) {
  4322. throw new DeveloperError('rectangle is required');
  4323. }
  4324. if (!defined(result)) {
  4325. return new Cartographic(rectangle.west, rectangle.south);
  4326. }
  4327. result.longitude = rectangle.west;
  4328. result.latitude = rectangle.south;
  4329. result.height = 0.0;
  4330. return result;
  4331. };
  4332. /**
  4333. * Computes the northwest corner of an rectangle.
  4334. *
  4335. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4336. * @param {Cartographic} [result] The object onto which to store the result.
  4337. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4338. */
  4339. Rectangle.northwest = function(rectangle, result) {
  4340. if (!defined(rectangle)) {
  4341. throw new DeveloperError('rectangle is required');
  4342. }
  4343. if (!defined(result)) {
  4344. return new Cartographic(rectangle.west, rectangle.north);
  4345. }
  4346. result.longitude = rectangle.west;
  4347. result.latitude = rectangle.north;
  4348. result.height = 0.0;
  4349. return result;
  4350. };
  4351. /**
  4352. * Computes the northeast corner of an rectangle.
  4353. *
  4354. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4355. * @param {Cartographic} [result] The object onto which to store the result.
  4356. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4357. */
  4358. Rectangle.northeast = function(rectangle, result) {
  4359. if (!defined(rectangle)) {
  4360. throw new DeveloperError('rectangle is required');
  4361. }
  4362. if (!defined(result)) {
  4363. return new Cartographic(rectangle.east, rectangle.north);
  4364. }
  4365. result.longitude = rectangle.east;
  4366. result.latitude = rectangle.north;
  4367. result.height = 0.0;
  4368. return result;
  4369. };
  4370. /**
  4371. * Computes the southeast corner of an rectangle.
  4372. *
  4373. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4374. * @param {Cartographic} [result] The object onto which to store the result.
  4375. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4376. */
  4377. Rectangle.southeast = function(rectangle, result) {
  4378. if (!defined(rectangle)) {
  4379. throw new DeveloperError('rectangle is required');
  4380. }
  4381. if (!defined(result)) {
  4382. return new Cartographic(rectangle.east, rectangle.south);
  4383. }
  4384. result.longitude = rectangle.east;
  4385. result.latitude = rectangle.south;
  4386. result.height = 0.0;
  4387. return result;
  4388. };
  4389. /**
  4390. * Computes the center of an rectangle.
  4391. *
  4392. * @param {Rectangle} rectangle The rectangle for which to find the center
  4393. * @param {Cartographic} [result] The object onto which to store the result.
  4394. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4395. */
  4396. Rectangle.center = function(rectangle, result) {
  4397. if (!defined(rectangle)) {
  4398. throw new DeveloperError('rectangle is required');
  4399. }
  4400. var east = rectangle.east;
  4401. var west = rectangle.west;
  4402. if (east < west) {
  4403. east += CesiumMath.TWO_PI;
  4404. }
  4405. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  4406. var latitude = (rectangle.south + rectangle.north) * 0.5;
  4407. if (!defined(result)) {
  4408. return new Cartographic(longitude, latitude);
  4409. }
  4410. result.longitude = longitude;
  4411. result.latitude = latitude;
  4412. result.height = 0.0;
  4413. return result;
  4414. };
  4415. /**
  4416. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  4417. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  4418. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  4419. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  4420. * coordinates, see {@link Rectangle.simpleIntersection}.
  4421. *
  4422. * @param {Rectangle} rectangle On rectangle to find an intersection
  4423. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  4424. * @param {Rectangle} [result] The object onto which to store the result.
  4425. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  4426. */
  4427. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  4428. if (!defined(rectangle)) {
  4429. throw new DeveloperError('rectangle is required');
  4430. }
  4431. if (!defined(otherRectangle)) {
  4432. throw new DeveloperError('otherRectangle is required.');
  4433. }
  4434. var rectangleEast = rectangle.east;
  4435. var rectangleWest = rectangle.west;
  4436. var otherRectangleEast = otherRectangle.east;
  4437. var otherRectangleWest = otherRectangle.west;
  4438. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  4439. rectangleEast += CesiumMath.TWO_PI;
  4440. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  4441. otherRectangleEast += CesiumMath.TWO_PI;
  4442. }
  4443. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  4444. otherRectangleWest += CesiumMath.TWO_PI;
  4445. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  4446. rectangleWest += CesiumMath.TWO_PI;
  4447. }
  4448. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  4449. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  4450. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  4451. return undefined;
  4452. }
  4453. var south = Math.max(rectangle.south, otherRectangle.south);
  4454. var north = Math.min(rectangle.north, otherRectangle.north);
  4455. if (south >= north) {
  4456. return undefined;
  4457. }
  4458. if (!defined(result)) {
  4459. return new Rectangle(west, south, east, north);
  4460. }
  4461. result.west = west;
  4462. result.south = south;
  4463. result.east = east;
  4464. result.north = north;
  4465. return result;
  4466. };
  4467. /**
  4468. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  4469. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  4470. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  4471. * and longitude (i.e. projected coordinates).
  4472. *
  4473. * @param {Rectangle} rectangle On rectangle to find an intersection
  4474. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  4475. * @param {Rectangle} [result] The object onto which to store the result.
  4476. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  4477. */
  4478. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  4479. if (!defined(rectangle)) {
  4480. throw new DeveloperError('rectangle is required');
  4481. }
  4482. if (!defined(otherRectangle)) {
  4483. throw new DeveloperError('otherRectangle is required.');
  4484. }
  4485. var west = Math.max(rectangle.west, otherRectangle.west);
  4486. var south = Math.max(rectangle.south, otherRectangle.south);
  4487. var east = Math.min(rectangle.east, otherRectangle.east);
  4488. var north = Math.min(rectangle.north, otherRectangle.north);
  4489. if (south >= north || west >= east) {
  4490. return undefined;
  4491. }
  4492. if (!defined(result)) {
  4493. return new Rectangle(west, south, east, north);
  4494. }
  4495. result.west = west;
  4496. result.south = south;
  4497. result.east = east;
  4498. result.north = north;
  4499. return result;
  4500. };
  4501. /**
  4502. * Computes a rectangle that is the union of two rectangles.
  4503. *
  4504. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  4505. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  4506. * @param {Rectangle} [result] The object onto which to store the result.
  4507. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4508. */
  4509. Rectangle.union = function(rectangle, otherRectangle, result) {
  4510. if (!defined(rectangle)) {
  4511. throw new DeveloperError('rectangle is required');
  4512. }
  4513. if (!defined(otherRectangle)) {
  4514. throw new DeveloperError('otherRectangle is required.');
  4515. }
  4516. if (!defined(result)) {
  4517. result = new Rectangle();
  4518. }
  4519. var rectangleEast = rectangle.east;
  4520. var rectangleWest = rectangle.west;
  4521. var otherRectangleEast = otherRectangle.east;
  4522. var otherRectangleWest = otherRectangle.west;
  4523. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  4524. rectangleEast += CesiumMath.TWO_PI;
  4525. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  4526. otherRectangleEast += CesiumMath.TWO_PI;
  4527. }
  4528. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  4529. otherRectangleWest += CesiumMath.TWO_PI;
  4530. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  4531. rectangleWest += CesiumMath.TWO_PI;
  4532. }
  4533. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  4534. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  4535. result.west = west;
  4536. result.south = Math.min(rectangle.south, otherRectangle.south);
  4537. result.east = east;
  4538. result.north = Math.max(rectangle.north, otherRectangle.north);
  4539. return result;
  4540. };
  4541. /**
  4542. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  4543. *
  4544. * @param {Rectangle} rectangle A rectangle to expand.
  4545. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  4546. * @param {Rectangle} [result] The object onto which to store the result.
  4547. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  4548. */
  4549. Rectangle.expand = function(rectangle, cartographic, result) {
  4550. if (!defined(rectangle)) {
  4551. throw new DeveloperError('rectangle is required.');
  4552. }
  4553. if (!defined(cartographic)) {
  4554. throw new DeveloperError('cartographic is required.');
  4555. }
  4556. if (!defined(result)) {
  4557. result = new Rectangle();
  4558. }
  4559. result.west = Math.min(rectangle.west, cartographic.longitude);
  4560. result.south = Math.min(rectangle.south, cartographic.latitude);
  4561. result.east = Math.max(rectangle.east, cartographic.longitude);
  4562. result.north = Math.max(rectangle.north, cartographic.latitude);
  4563. return result;
  4564. };
  4565. /**
  4566. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  4567. *
  4568. * @param {Rectangle} rectangle The rectangle
  4569. * @param {Cartographic} cartographic The cartographic to test.
  4570. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  4571. */
  4572. Rectangle.contains = function(rectangle, cartographic) {
  4573. if (!defined(rectangle)) {
  4574. throw new DeveloperError('rectangle is required');
  4575. }
  4576. if (!defined(cartographic)) {
  4577. throw new DeveloperError('cartographic is required.');
  4578. }
  4579. var longitude = cartographic.longitude;
  4580. var latitude = cartographic.latitude;
  4581. var west = rectangle.west;
  4582. var east = rectangle.east;
  4583. if (east < west) {
  4584. east += CesiumMath.TWO_PI;
  4585. if (longitude < 0.0) {
  4586. longitude += CesiumMath.TWO_PI;
  4587. }
  4588. }
  4589. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  4590. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  4591. latitude >= rectangle.south &&
  4592. latitude <= rectangle.north;
  4593. };
  4594. var subsampleLlaScratch = new Cartographic();
  4595. /**
  4596. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  4597. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  4598. * for rectangles that cover the poles or cross the equator.
  4599. *
  4600. * @param {Rectangle} rectangle The rectangle to subsample.
  4601. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  4602. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  4603. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  4604. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  4605. */
  4606. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  4607. if (!defined(rectangle)) {
  4608. throw new DeveloperError('rectangle is required');
  4609. }
  4610. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  4611. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  4612. if (!defined(result)) {
  4613. result = [];
  4614. }
  4615. var length = 0;
  4616. var north = rectangle.north;
  4617. var south = rectangle.south;
  4618. var east = rectangle.east;
  4619. var west = rectangle.west;
  4620. var lla = subsampleLlaScratch;
  4621. lla.height = surfaceHeight;
  4622. lla.longitude = west;
  4623. lla.latitude = north;
  4624. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4625. length++;
  4626. lla.longitude = east;
  4627. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4628. length++;
  4629. lla.latitude = south;
  4630. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4631. length++;
  4632. lla.longitude = west;
  4633. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4634. length++;
  4635. if (north < 0.0) {
  4636. lla.latitude = north;
  4637. } else if (south > 0.0) {
  4638. lla.latitude = south;
  4639. } else {
  4640. lla.latitude = 0.0;
  4641. }
  4642. for ( var i = 1; i < 8; ++i) {
  4643. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  4644. if (Rectangle.contains(rectangle, lla)) {
  4645. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4646. length++;
  4647. }
  4648. }
  4649. if (lla.latitude === 0.0) {
  4650. lla.longitude = west;
  4651. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4652. length++;
  4653. lla.longitude = east;
  4654. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4655. length++;
  4656. }
  4657. result.length = length;
  4658. return result;
  4659. };
  4660. /**
  4661. * The largest possible rectangle.
  4662. *
  4663. * @type {Rectangle}
  4664. * @constant
  4665. */
  4666. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  4667. return Rectangle;
  4668. });
  4669. /*global define*/
  4670. define('Core/BoundingRectangle',[
  4671. './Cartesian2',
  4672. './Cartographic',
  4673. './defaultValue',
  4674. './defined',
  4675. './DeveloperError',
  4676. './GeographicProjection',
  4677. './Intersect',
  4678. './Rectangle'
  4679. ], function(
  4680. Cartesian2,
  4681. Cartographic,
  4682. defaultValue,
  4683. defined,
  4684. DeveloperError,
  4685. GeographicProjection,
  4686. Intersect,
  4687. Rectangle) {
  4688. 'use strict';
  4689. /**
  4690. * A bounding rectangle given by a corner, width and height.
  4691. * @alias BoundingRectangle
  4692. * @constructor
  4693. *
  4694. * @param {Number} [x=0.0] The x coordinate of the rectangle.
  4695. * @param {Number} [y=0.0] The y coordinate of the rectangle.
  4696. * @param {Number} [width=0.0] The width of the rectangle.
  4697. * @param {Number} [height=0.0] The height of the rectangle.
  4698. *
  4699. * @see BoundingSphere
  4700. * @see Packable
  4701. */
  4702. function BoundingRectangle(x, y, width, height) {
  4703. /**
  4704. * The x coordinate of the rectangle.
  4705. * @type {Number}
  4706. * @default 0.0
  4707. */
  4708. this.x = defaultValue(x, 0.0);
  4709. /**
  4710. * The y coordinate of the rectangle.
  4711. * @type {Number}
  4712. * @default 0.0
  4713. */
  4714. this.y = defaultValue(y, 0.0);
  4715. /**
  4716. * The width of the rectangle.
  4717. * @type {Number}
  4718. * @default 0.0
  4719. */
  4720. this.width = defaultValue(width, 0.0);
  4721. /**
  4722. * The height of the rectangle.
  4723. * @type {Number}
  4724. * @default 0.0
  4725. */
  4726. this.height = defaultValue(height, 0.0);
  4727. }
  4728. /**
  4729. * The number of elements used to pack the object into an array.
  4730. * @type {Number}
  4731. */
  4732. BoundingRectangle.packedLength = 4;
  4733. /**
  4734. * Stores the provided instance into the provided array.
  4735. *
  4736. * @param {BoundingRectangle} value The value to pack.
  4737. * @param {Number[]} array The array to pack into.
  4738. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4739. *
  4740. * @returns {Number[]} The array that was packed into
  4741. */
  4742. BoundingRectangle.pack = function(value, array, startingIndex) {
  4743. if (!defined(value)) {
  4744. throw new DeveloperError('value is required');
  4745. }
  4746. if (!defined(array)) {
  4747. throw new DeveloperError('array is required');
  4748. }
  4749. startingIndex = defaultValue(startingIndex, 0);
  4750. array[startingIndex++] = value.x;
  4751. array[startingIndex++] = value.y;
  4752. array[startingIndex++] = value.width;
  4753. array[startingIndex] = value.height;
  4754. return array;
  4755. };
  4756. /**
  4757. * Retrieves an instance from a packed array.
  4758. *
  4759. * @param {Number[]} array The packed array.
  4760. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4761. * @param {BoundingRectangle} [result] The object into which to store the result.
  4762. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4763. */
  4764. BoundingRectangle.unpack = function(array, startingIndex, result) {
  4765. if (!defined(array)) {
  4766. throw new DeveloperError('array is required');
  4767. }
  4768. startingIndex = defaultValue(startingIndex, 0);
  4769. if (!defined(result)) {
  4770. result = new BoundingRectangle();
  4771. }
  4772. result.x = array[startingIndex++];
  4773. result.y = array[startingIndex++];
  4774. result.width = array[startingIndex++];
  4775. result.height = array[startingIndex];
  4776. return result;
  4777. };
  4778. /**
  4779. * Computes a bounding rectangle enclosing the list of 2D points.
  4780. * The rectangle is oriented with the corner at the bottom left.
  4781. *
  4782. * @param {Cartesian2[]} positions List of points that the bounding rectangle will enclose. Each point must have <code>x</code> and <code>y</code> properties.
  4783. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4784. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4785. */
  4786. BoundingRectangle.fromPoints = function(positions, result) {
  4787. if (!defined(result)) {
  4788. result = new BoundingRectangle();
  4789. }
  4790. if (!defined(positions) || positions.length === 0) {
  4791. result.x = 0;
  4792. result.y = 0;
  4793. result.width = 0;
  4794. result.height = 0;
  4795. return result;
  4796. }
  4797. var length = positions.length;
  4798. var minimumX = positions[0].x;
  4799. var minimumY = positions[0].y;
  4800. var maximumX = positions[0].x;
  4801. var maximumY = positions[0].y;
  4802. for ( var i = 1; i < length; i++) {
  4803. var p = positions[i];
  4804. var x = p.x;
  4805. var y = p.y;
  4806. minimumX = Math.min(x, minimumX);
  4807. maximumX = Math.max(x, maximumX);
  4808. minimumY = Math.min(y, minimumY);
  4809. maximumY = Math.max(y, maximumY);
  4810. }
  4811. result.x = minimumX;
  4812. result.y = minimumY;
  4813. result.width = maximumX - minimumX;
  4814. result.height = maximumY - minimumY;
  4815. return result;
  4816. };
  4817. var defaultProjection = new GeographicProjection();
  4818. var fromRectangleLowerLeft = new Cartographic();
  4819. var fromRectangleUpperRight = new Cartographic();
  4820. /**
  4821. * Computes a bounding rectangle from an rectangle.
  4822. *
  4823. * @param {Rectangle} rectangle The valid rectangle used to create a bounding rectangle.
  4824. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  4825. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4826. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4827. */
  4828. BoundingRectangle.fromRectangle = function(rectangle, projection, result) {
  4829. if (!defined(result)) {
  4830. result = new BoundingRectangle();
  4831. }
  4832. if (!defined(rectangle)) {
  4833. result.x = 0;
  4834. result.y = 0;
  4835. result.width = 0;
  4836. result.height = 0;
  4837. return result;
  4838. }
  4839. projection = defaultValue(projection, defaultProjection);
  4840. var lowerLeft = projection.project(Rectangle.southwest(rectangle, fromRectangleLowerLeft));
  4841. var upperRight = projection.project(Rectangle.northeast(rectangle, fromRectangleUpperRight));
  4842. Cartesian2.subtract(upperRight, lowerLeft, upperRight);
  4843. result.x = lowerLeft.x;
  4844. result.y = lowerLeft.y;
  4845. result.width = upperRight.x;
  4846. result.height = upperRight.y;
  4847. return result;
  4848. };
  4849. /**
  4850. * Duplicates a BoundingRectangle instance.
  4851. *
  4852. * @param {BoundingRectangle} rectangle The bounding rectangle to duplicate.
  4853. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4854. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. (Returns undefined if rectangle is undefined)
  4855. */
  4856. BoundingRectangle.clone = function(rectangle, result) {
  4857. if (!defined(rectangle)) {
  4858. return undefined;
  4859. }
  4860. if (!defined(result)) {
  4861. return new BoundingRectangle(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
  4862. }
  4863. result.x = rectangle.x;
  4864. result.y = rectangle.y;
  4865. result.width = rectangle.width;
  4866. result.height = rectangle.height;
  4867. return result;
  4868. };
  4869. /**
  4870. * Computes a bounding rectangle that is the union of the left and right bounding rectangles.
  4871. *
  4872. * @param {BoundingRectangle} left A rectangle to enclose in bounding rectangle.
  4873. * @param {BoundingRectangle} right A rectangle to enclose in a bounding rectangle.
  4874. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4875. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4876. */
  4877. BoundingRectangle.union = function(left, right, result) {
  4878. if (!defined(left)) {
  4879. throw new DeveloperError('left is required.');
  4880. }
  4881. if (!defined(right)) {
  4882. throw new DeveloperError('right is required.');
  4883. }
  4884. if (!defined(result)) {
  4885. result = new BoundingRectangle();
  4886. }
  4887. var lowerLeftX = Math.min(left.x, right.x);
  4888. var lowerLeftY = Math.min(left.y, right.y);
  4889. var upperRightX = Math.max(left.x + left.width, right.x + right.width);
  4890. var upperRightY = Math.max(left.y + left.height, right.y + right.height);
  4891. result.x = lowerLeftX;
  4892. result.y = lowerLeftY;
  4893. result.width = upperRightX - lowerLeftX;
  4894. result.height = upperRightY - lowerLeftY;
  4895. return result;
  4896. };
  4897. /**
  4898. * Computes a bounding rectangle by enlarging the provided rectangle until it contains the provided point.
  4899. *
  4900. * @param {BoundingRectangle} rectangle A rectangle to expand.
  4901. * @param {Cartesian2} point A point to enclose in a bounding rectangle.
  4902. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4903. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4904. */
  4905. BoundingRectangle.expand = function(rectangle, point, result) {
  4906. if (!defined(rectangle)) {
  4907. throw new DeveloperError('rectangle is required.');
  4908. }
  4909. if (!defined(point)) {
  4910. throw new DeveloperError('point is required.');
  4911. }
  4912. result = BoundingRectangle.clone(rectangle, result);
  4913. var width = point.x - result.x;
  4914. var height = point.y - result.y;
  4915. if (width > result.width) {
  4916. result.width = width;
  4917. } else if (width < 0) {
  4918. result.width -= width;
  4919. result.x = point.x;
  4920. }
  4921. if (height > result.height) {
  4922. result.height = height;
  4923. } else if (height < 0) {
  4924. result.height -= height;
  4925. result.y = point.y;
  4926. }
  4927. return result;
  4928. };
  4929. /**
  4930. * Determines if two rectangles intersect.
  4931. *
  4932. * @param {BoundingRectangle} left A rectangle to check for intersection.
  4933. * @param {BoundingRectangle} right The other rectangle to check for intersection.
  4934. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
  4935. */
  4936. BoundingRectangle.intersect = function(left, right) {
  4937. if (!defined(left)) {
  4938. throw new DeveloperError('left is required.');
  4939. }
  4940. if (!defined(right)) {
  4941. throw new DeveloperError('right is required.');
  4942. }
  4943. var leftX = left.x;
  4944. var leftY = left.y;
  4945. var rightX = right.x;
  4946. var rightY = right.y;
  4947. if (!(leftX > rightX + right.width ||
  4948. leftX + left.width < rightX ||
  4949. leftY + left.height < rightY ||
  4950. leftY > rightY + right.height)) {
  4951. return Intersect.INTERSECTING;
  4952. }
  4953. return Intersect.OUTSIDE;
  4954. };
  4955. /**
  4956. * Compares the provided BoundingRectangles componentwise and returns
  4957. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4958. *
  4959. * @param {BoundingRectangle} [left] The first BoundingRectangle.
  4960. * @param {BoundingRectangle} [right] The second BoundingRectangle.
  4961. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  4962. */
  4963. BoundingRectangle.equals = function(left, right) {
  4964. return (left === right) ||
  4965. ((defined(left)) &&
  4966. (defined(right)) &&
  4967. (left.x === right.x) &&
  4968. (left.y === right.y) &&
  4969. (left.width === right.width) &&
  4970. (left.height === right.height));
  4971. };
  4972. /**
  4973. * Duplicates this BoundingRectangle instance.
  4974. *
  4975. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4976. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4977. */
  4978. BoundingRectangle.prototype.clone = function(result) {
  4979. return BoundingRectangle.clone(this, result);
  4980. };
  4981. /**
  4982. * Determines if this rectangle intersects with another.
  4983. *
  4984. * @param {BoundingRectangle} right A rectangle to check for intersection.
  4985. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
  4986. */
  4987. BoundingRectangle.prototype.intersect = function(right) {
  4988. return BoundingRectangle.intersect(this, right);
  4989. };
  4990. /**
  4991. * Compares this BoundingRectangle against the provided BoundingRectangle componentwise and returns
  4992. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4993. *
  4994. * @param {BoundingRectangle} [right] The right hand side BoundingRectangle.
  4995. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  4996. */
  4997. BoundingRectangle.prototype.equals = function(right) {
  4998. return BoundingRectangle.equals(this, right);
  4999. };
  5000. return BoundingRectangle;
  5001. });
  5002. /*global define*/
  5003. define('Core/Interval',[
  5004. './defaultValue'
  5005. ], function(
  5006. defaultValue) {
  5007. 'use strict';
  5008. /**
  5009. * Represents the closed interval [start, stop].
  5010. * @alias Interval
  5011. * @constructor
  5012. *
  5013. * @param {Number} [start=0.0] The beginning of the interval.
  5014. * @param {Number} [stop=0.0] The end of the interval.
  5015. */
  5016. function Interval(start, stop) {
  5017. /**
  5018. * The beginning of the interval.
  5019. * @type {Number}
  5020. * @default 0.0
  5021. */
  5022. this.start = defaultValue(start, 0.0);
  5023. /**
  5024. * The end of the interval.
  5025. * @type {Number}
  5026. * @default 0.0
  5027. */
  5028. this.stop = defaultValue(stop, 0.0);
  5029. }
  5030. return Interval;
  5031. });
  5032. /*global define*/
  5033. define('Core/Matrix3',[
  5034. './Cartesian3',
  5035. './defaultValue',
  5036. './defined',
  5037. './defineProperties',
  5038. './DeveloperError',
  5039. './freezeObject',
  5040. './Math'
  5041. ], function(
  5042. Cartesian3,
  5043. defaultValue,
  5044. defined,
  5045. defineProperties,
  5046. DeveloperError,
  5047. freezeObject,
  5048. CesiumMath) {
  5049. 'use strict';
  5050. /**
  5051. * A 3x3 matrix, indexable as a column-major order array.
  5052. * Constructor parameters are in row-major order for code readability.
  5053. * @alias Matrix3
  5054. * @constructor
  5055. *
  5056. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  5057. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  5058. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  5059. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  5060. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  5061. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  5062. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  5063. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  5064. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  5065. *
  5066. * @see Matrix3.fromColumnMajorArray
  5067. * @see Matrix3.fromRowMajorArray
  5068. * @see Matrix3.fromQuaternion
  5069. * @see Matrix3.fromScale
  5070. * @see Matrix3.fromUniformScale
  5071. * @see Matrix2
  5072. * @see Matrix4
  5073. */
  5074. function Matrix3(column0Row0, column1Row0, column2Row0,
  5075. column0Row1, column1Row1, column2Row1,
  5076. column0Row2, column1Row2, column2Row2) {
  5077. this[0] = defaultValue(column0Row0, 0.0);
  5078. this[1] = defaultValue(column0Row1, 0.0);
  5079. this[2] = defaultValue(column0Row2, 0.0);
  5080. this[3] = defaultValue(column1Row0, 0.0);
  5081. this[4] = defaultValue(column1Row1, 0.0);
  5082. this[5] = defaultValue(column1Row2, 0.0);
  5083. this[6] = defaultValue(column2Row0, 0.0);
  5084. this[7] = defaultValue(column2Row1, 0.0);
  5085. this[8] = defaultValue(column2Row2, 0.0);
  5086. }
  5087. /**
  5088. * The number of elements used to pack the object into an array.
  5089. * @type {Number}
  5090. */
  5091. Matrix3.packedLength = 9;
  5092. /**
  5093. * Stores the provided instance into the provided array.
  5094. *
  5095. * @param {Matrix3} value The value to pack.
  5096. * @param {Number[]} array The array to pack into.
  5097. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5098. *
  5099. * @returns {Number[]} The array that was packed into
  5100. */
  5101. Matrix3.pack = function(value, array, startingIndex) {
  5102. if (!defined(value)) {
  5103. throw new DeveloperError('value is required');
  5104. }
  5105. if (!defined(array)) {
  5106. throw new DeveloperError('array is required');
  5107. }
  5108. startingIndex = defaultValue(startingIndex, 0);
  5109. array[startingIndex++] = value[0];
  5110. array[startingIndex++] = value[1];
  5111. array[startingIndex++] = value[2];
  5112. array[startingIndex++] = value[3];
  5113. array[startingIndex++] = value[4];
  5114. array[startingIndex++] = value[5];
  5115. array[startingIndex++] = value[6];
  5116. array[startingIndex++] = value[7];
  5117. array[startingIndex++] = value[8];
  5118. return array;
  5119. };
  5120. /**
  5121. * Retrieves an instance from a packed array.
  5122. *
  5123. * @param {Number[]} array The packed array.
  5124. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5125. * @param {Matrix3} [result] The object into which to store the result.
  5126. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5127. */
  5128. Matrix3.unpack = function(array, startingIndex, result) {
  5129. if (!defined(array)) {
  5130. throw new DeveloperError('array is required');
  5131. }
  5132. startingIndex = defaultValue(startingIndex, 0);
  5133. if (!defined(result)) {
  5134. result = new Matrix3();
  5135. }
  5136. result[0] = array[startingIndex++];
  5137. result[1] = array[startingIndex++];
  5138. result[2] = array[startingIndex++];
  5139. result[3] = array[startingIndex++];
  5140. result[4] = array[startingIndex++];
  5141. result[5] = array[startingIndex++];
  5142. result[6] = array[startingIndex++];
  5143. result[7] = array[startingIndex++];
  5144. result[8] = array[startingIndex++];
  5145. return result;
  5146. };
  5147. /**
  5148. * Duplicates a Matrix3 instance.
  5149. *
  5150. * @param {Matrix3} matrix The matrix to duplicate.
  5151. * @param {Matrix3} [result] The object onto which to store the result.
  5152. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  5153. */
  5154. Matrix3.clone = function(values, result) {
  5155. if (!defined(values)) {
  5156. return undefined;
  5157. }
  5158. if (!defined(result)) {
  5159. return new Matrix3(values[0], values[3], values[6],
  5160. values[1], values[4], values[7],
  5161. values[2], values[5], values[8]);
  5162. }
  5163. result[0] = values[0];
  5164. result[1] = values[1];
  5165. result[2] = values[2];
  5166. result[3] = values[3];
  5167. result[4] = values[4];
  5168. result[5] = values[5];
  5169. result[6] = values[6];
  5170. result[7] = values[7];
  5171. result[8] = values[8];
  5172. return result;
  5173. };
  5174. /**
  5175. * Creates a Matrix3 from 9 consecutive elements in an array.
  5176. *
  5177. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  5178. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  5179. * @param {Matrix3} [result] The object onto which to store the result.
  5180. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5181. *
  5182. * @example
  5183. * // Create the Matrix3:
  5184. * // [1.0, 2.0, 3.0]
  5185. * // [1.0, 2.0, 3.0]
  5186. * // [1.0, 2.0, 3.0]
  5187. *
  5188. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  5189. * var m = Cesium.Matrix3.fromArray(v);
  5190. *
  5191. * // Create same Matrix3 with using an offset into an array
  5192. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  5193. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  5194. */
  5195. Matrix3.fromArray = function(array, startingIndex, result) {
  5196. if (!defined(array)) {
  5197. throw new DeveloperError('array is required');
  5198. }
  5199. startingIndex = defaultValue(startingIndex, 0);
  5200. if (!defined(result)) {
  5201. result = new Matrix3();
  5202. }
  5203. result[0] = array[startingIndex];
  5204. result[1] = array[startingIndex + 1];
  5205. result[2] = array[startingIndex + 2];
  5206. result[3] = array[startingIndex + 3];
  5207. result[4] = array[startingIndex + 4];
  5208. result[5] = array[startingIndex + 5];
  5209. result[6] = array[startingIndex + 6];
  5210. result[7] = array[startingIndex + 7];
  5211. result[8] = array[startingIndex + 8];
  5212. return result;
  5213. };
  5214. /**
  5215. * Creates a Matrix3 instance from a column-major order array.
  5216. *
  5217. * @param {Number[]} values The column-major order array.
  5218. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5219. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5220. */
  5221. Matrix3.fromColumnMajorArray = function(values, result) {
  5222. if (!defined(values)) {
  5223. throw new DeveloperError('values parameter is required');
  5224. }
  5225. return Matrix3.clone(values, result);
  5226. };
  5227. /**
  5228. * Creates a Matrix3 instance from a row-major order array.
  5229. * The resulting matrix will be in column-major order.
  5230. *
  5231. * @param {Number[]} values The row-major order array.
  5232. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5233. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5234. */
  5235. Matrix3.fromRowMajorArray = function(values, result) {
  5236. if (!defined(values)) {
  5237. throw new DeveloperError('values is required.');
  5238. }
  5239. if (!defined(result)) {
  5240. return new Matrix3(values[0], values[1], values[2],
  5241. values[3], values[4], values[5],
  5242. values[6], values[7], values[8]);
  5243. }
  5244. result[0] = values[0];
  5245. result[1] = values[3];
  5246. result[2] = values[6];
  5247. result[3] = values[1];
  5248. result[4] = values[4];
  5249. result[5] = values[7];
  5250. result[6] = values[2];
  5251. result[7] = values[5];
  5252. result[8] = values[8];
  5253. return result;
  5254. };
  5255. /**
  5256. * Computes a 3x3 rotation matrix from the provided quaternion.
  5257. *
  5258. * @param {Quaternion} quaternion the quaternion to use.
  5259. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5260. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  5261. */
  5262. Matrix3.fromQuaternion = function(quaternion, result) {
  5263. if (!defined(quaternion)) {
  5264. throw new DeveloperError('quaternion is required');
  5265. }
  5266. var x2 = quaternion.x * quaternion.x;
  5267. var xy = quaternion.x * quaternion.y;
  5268. var xz = quaternion.x * quaternion.z;
  5269. var xw = quaternion.x * quaternion.w;
  5270. var y2 = quaternion.y * quaternion.y;
  5271. var yz = quaternion.y * quaternion.z;
  5272. var yw = quaternion.y * quaternion.w;
  5273. var z2 = quaternion.z * quaternion.z;
  5274. var zw = quaternion.z * quaternion.w;
  5275. var w2 = quaternion.w * quaternion.w;
  5276. var m00 = x2 - y2 - z2 + w2;
  5277. var m01 = 2.0 * (xy - zw);
  5278. var m02 = 2.0 * (xz + yw);
  5279. var m10 = 2.0 * (xy + zw);
  5280. var m11 = -x2 + y2 - z2 + w2;
  5281. var m12 = 2.0 * (yz - xw);
  5282. var m20 = 2.0 * (xz - yw);
  5283. var m21 = 2.0 * (yz + xw);
  5284. var m22 = -x2 - y2 + z2 + w2;
  5285. if (!defined(result)) {
  5286. return new Matrix3(m00, m01, m02,
  5287. m10, m11, m12,
  5288. m20, m21, m22);
  5289. }
  5290. result[0] = m00;
  5291. result[1] = m10;
  5292. result[2] = m20;
  5293. result[3] = m01;
  5294. result[4] = m11;
  5295. result[5] = m21;
  5296. result[6] = m02;
  5297. result[7] = m12;
  5298. result[8] = m22;
  5299. return result;
  5300. };
  5301. /**
  5302. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  5303. *
  5304. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  5305. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5306. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  5307. */
  5308. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  5309. if (!defined(headingPitchRoll)) {
  5310. throw new DeveloperError('headingPitchRoll is required');
  5311. }
  5312. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  5313. var cosPsi = Math.cos(-headingPitchRoll.heading);
  5314. var cosPhi = Math.cos(headingPitchRoll.roll);
  5315. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  5316. var sinPsi = Math.sin(-headingPitchRoll.heading);
  5317. var sinPhi = Math.sin(headingPitchRoll.roll);
  5318. var m00 = cosTheta * cosPsi;
  5319. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  5320. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  5321. var m10 = cosTheta * sinPsi;
  5322. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  5323. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  5324. var m20 = -sinTheta;
  5325. var m21 = sinPhi * cosTheta;
  5326. var m22 = cosPhi * cosTheta;
  5327. if (!defined(result)) {
  5328. return new Matrix3(m00, m01, m02,
  5329. m10, m11, m12,
  5330. m20, m21, m22);
  5331. }
  5332. result[0] = m00;
  5333. result[1] = m10;
  5334. result[2] = m20;
  5335. result[3] = m01;
  5336. result[4] = m11;
  5337. result[5] = m21;
  5338. result[6] = m02;
  5339. result[7] = m12;
  5340. result[8] = m22;
  5341. return result;
  5342. };
  5343. /**
  5344. * Computes a Matrix3 instance representing a non-uniform scale.
  5345. *
  5346. * @param {Cartesian3} scale The x, y, and z scale factors.
  5347. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5348. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5349. *
  5350. * @example
  5351. * // Creates
  5352. * // [7.0, 0.0, 0.0]
  5353. * // [0.0, 8.0, 0.0]
  5354. * // [0.0, 0.0, 9.0]
  5355. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5356. */
  5357. Matrix3.fromScale = function(scale, result) {
  5358. if (!defined(scale)) {
  5359. throw new DeveloperError('scale is required.');
  5360. }
  5361. if (!defined(result)) {
  5362. return new Matrix3(
  5363. scale.x, 0.0, 0.0,
  5364. 0.0, scale.y, 0.0,
  5365. 0.0, 0.0, scale.z);
  5366. }
  5367. result[0] = scale.x;
  5368. result[1] = 0.0;
  5369. result[2] = 0.0;
  5370. result[3] = 0.0;
  5371. result[4] = scale.y;
  5372. result[5] = 0.0;
  5373. result[6] = 0.0;
  5374. result[7] = 0.0;
  5375. result[8] = scale.z;
  5376. return result;
  5377. };
  5378. /**
  5379. * Computes a Matrix3 instance representing a uniform scale.
  5380. *
  5381. * @param {Number} scale The uniform scale factor.
  5382. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5383. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5384. *
  5385. * @example
  5386. * // Creates
  5387. * // [2.0, 0.0, 0.0]
  5388. * // [0.0, 2.0, 0.0]
  5389. * // [0.0, 0.0, 2.0]
  5390. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  5391. */
  5392. Matrix3.fromUniformScale = function(scale, result) {
  5393. if (typeof scale !== 'number') {
  5394. throw new DeveloperError('scale is required.');
  5395. }
  5396. if (!defined(result)) {
  5397. return new Matrix3(
  5398. scale, 0.0, 0.0,
  5399. 0.0, scale, 0.0,
  5400. 0.0, 0.0, scale);
  5401. }
  5402. result[0] = scale;
  5403. result[1] = 0.0;
  5404. result[2] = 0.0;
  5405. result[3] = 0.0;
  5406. result[4] = scale;
  5407. result[5] = 0.0;
  5408. result[6] = 0.0;
  5409. result[7] = 0.0;
  5410. result[8] = scale;
  5411. return result;
  5412. };
  5413. /**
  5414. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  5415. *
  5416. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  5417. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5418. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5419. *
  5420. * @example
  5421. * // Creates
  5422. * // [0.0, -9.0, 8.0]
  5423. * // [9.0, 0.0, -7.0]
  5424. * // [-8.0, 7.0, 0.0]
  5425. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5426. */
  5427. Matrix3.fromCrossProduct = function(vector, result) {
  5428. if (!defined(vector)) {
  5429. throw new DeveloperError('vector is required.');
  5430. }
  5431. if (!defined(result)) {
  5432. return new Matrix3(
  5433. 0.0, -vector.z, vector.y,
  5434. vector.z, 0.0, -vector.x,
  5435. -vector.y, vector.x, 0.0);
  5436. }
  5437. result[0] = 0.0;
  5438. result[1] = vector.z;
  5439. result[2] = -vector.y;
  5440. result[3] = -vector.z;
  5441. result[4] = 0.0;
  5442. result[5] = vector.x;
  5443. result[6] = vector.y;
  5444. result[7] = -vector.x;
  5445. result[8] = 0.0;
  5446. return result;
  5447. };
  5448. /**
  5449. * Creates a rotation matrix around the x-axis.
  5450. *
  5451. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5452. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5453. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5454. *
  5455. * @example
  5456. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  5457. * var p = new Cesium.Cartesian3(5, 6, 7);
  5458. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  5459. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5460. */
  5461. Matrix3.fromRotationX = function(angle, result) {
  5462. if (!defined(angle)) {
  5463. throw new DeveloperError('angle is required.');
  5464. }
  5465. var cosAngle = Math.cos(angle);
  5466. var sinAngle = Math.sin(angle);
  5467. if (!defined(result)) {
  5468. return new Matrix3(
  5469. 1.0, 0.0, 0.0,
  5470. 0.0, cosAngle, -sinAngle,
  5471. 0.0, sinAngle, cosAngle);
  5472. }
  5473. result[0] = 1.0;
  5474. result[1] = 0.0;
  5475. result[2] = 0.0;
  5476. result[3] = 0.0;
  5477. result[4] = cosAngle;
  5478. result[5] = sinAngle;
  5479. result[6] = 0.0;
  5480. result[7] = -sinAngle;
  5481. result[8] = cosAngle;
  5482. return result;
  5483. };
  5484. /**
  5485. * Creates a rotation matrix around the y-axis.
  5486. *
  5487. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5488. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5489. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5490. *
  5491. * @example
  5492. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  5493. * var p = new Cesium.Cartesian3(5, 6, 7);
  5494. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  5495. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5496. */
  5497. Matrix3.fromRotationY = function(angle, result) {
  5498. if (!defined(angle)) {
  5499. throw new DeveloperError('angle is required.');
  5500. }
  5501. var cosAngle = Math.cos(angle);
  5502. var sinAngle = Math.sin(angle);
  5503. if (!defined(result)) {
  5504. return new Matrix3(
  5505. cosAngle, 0.0, sinAngle,
  5506. 0.0, 1.0, 0.0,
  5507. -sinAngle, 0.0, cosAngle);
  5508. }
  5509. result[0] = cosAngle;
  5510. result[1] = 0.0;
  5511. result[2] = -sinAngle;
  5512. result[3] = 0.0;
  5513. result[4] = 1.0;
  5514. result[5] = 0.0;
  5515. result[6] = sinAngle;
  5516. result[7] = 0.0;
  5517. result[8] = cosAngle;
  5518. return result;
  5519. };
  5520. /**
  5521. * Creates a rotation matrix around the z-axis.
  5522. *
  5523. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5524. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5525. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5526. *
  5527. * @example
  5528. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  5529. * var p = new Cesium.Cartesian3(5, 6, 7);
  5530. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  5531. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5532. */
  5533. Matrix3.fromRotationZ = function(angle, result) {
  5534. if (!defined(angle)) {
  5535. throw new DeveloperError('angle is required.');
  5536. }
  5537. var cosAngle = Math.cos(angle);
  5538. var sinAngle = Math.sin(angle);
  5539. if (!defined(result)) {
  5540. return new Matrix3(
  5541. cosAngle, -sinAngle, 0.0,
  5542. sinAngle, cosAngle, 0.0,
  5543. 0.0, 0.0, 1.0);
  5544. }
  5545. result[0] = cosAngle;
  5546. result[1] = sinAngle;
  5547. result[2] = 0.0;
  5548. result[3] = -sinAngle;
  5549. result[4] = cosAngle;
  5550. result[5] = 0.0;
  5551. result[6] = 0.0;
  5552. result[7] = 0.0;
  5553. result[8] = 1.0;
  5554. return result;
  5555. };
  5556. /**
  5557. * Creates an Array from the provided Matrix3 instance.
  5558. * The array will be in column-major order.
  5559. *
  5560. * @param {Matrix3} matrix The matrix to use..
  5561. * @param {Number[]} [result] The Array onto which to store the result.
  5562. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  5563. */
  5564. Matrix3.toArray = function(matrix, result) {
  5565. if (!defined(matrix)) {
  5566. throw new DeveloperError('matrix is required');
  5567. }
  5568. if (!defined(result)) {
  5569. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  5570. }
  5571. result[0] = matrix[0];
  5572. result[1] = matrix[1];
  5573. result[2] = matrix[2];
  5574. result[3] = matrix[3];
  5575. result[4] = matrix[4];
  5576. result[5] = matrix[5];
  5577. result[6] = matrix[6];
  5578. result[7] = matrix[7];
  5579. result[8] = matrix[8];
  5580. return result;
  5581. };
  5582. /**
  5583. * Computes the array index of the element at the provided row and column.
  5584. *
  5585. * @param {Number} row The zero-based index of the row.
  5586. * @param {Number} column The zero-based index of the column.
  5587. * @returns {Number} The index of the element at the provided row and column.
  5588. *
  5589. * @exception {DeveloperError} row must be 0, 1, or 2.
  5590. * @exception {DeveloperError} column must be 0, 1, or 2.
  5591. *
  5592. * @example
  5593. * var myMatrix = new Cesium.Matrix3();
  5594. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  5595. * var column1Row0 = myMatrix[column1Row0Index]
  5596. * myMatrix[column1Row0Index] = 10.0;
  5597. */
  5598. Matrix3.getElementIndex = function(column, row) {
  5599. if (typeof row !== 'number' || row < 0 || row > 2) {
  5600. throw new DeveloperError('row must be 0, 1, or 2.');
  5601. }
  5602. if (typeof column !== 'number' || column < 0 || column > 2) {
  5603. throw new DeveloperError('column must be 0, 1, or 2.');
  5604. }
  5605. return column * 3 + row;
  5606. };
  5607. /**
  5608. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  5609. *
  5610. * @param {Matrix3} matrix The matrix to use.
  5611. * @param {Number} index The zero-based index of the column to retrieve.
  5612. * @param {Cartesian3} result The object onto which to store the result.
  5613. * @returns {Cartesian3} The modified result parameter.
  5614. *
  5615. * @exception {DeveloperError} index must be 0, 1, or 2.
  5616. */
  5617. Matrix3.getColumn = function(matrix, index, result) {
  5618. if (!defined(matrix)) {
  5619. throw new DeveloperError('matrix is required.');
  5620. }
  5621. if (typeof index !== 'number' || index < 0 || index > 2) {
  5622. throw new DeveloperError('index must be 0, 1, or 2.');
  5623. }
  5624. if (!defined(result)) {
  5625. throw new DeveloperError('result is required');
  5626. }
  5627. var startIndex = index * 3;
  5628. var x = matrix[startIndex];
  5629. var y = matrix[startIndex + 1];
  5630. var z = matrix[startIndex + 2];
  5631. result.x = x;
  5632. result.y = y;
  5633. result.z = z;
  5634. return result;
  5635. };
  5636. /**
  5637. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  5638. *
  5639. * @param {Matrix3} matrix The matrix to use.
  5640. * @param {Number} index The zero-based index of the column to set.
  5641. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  5642. * @param {Matrix3} result The object onto which to store the result.
  5643. * @returns {Matrix3} The modified result parameter.
  5644. *
  5645. * @exception {DeveloperError} index must be 0, 1, or 2.
  5646. */
  5647. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  5648. if (!defined(matrix)) {
  5649. throw new DeveloperError('matrix is required');
  5650. }
  5651. if (!defined(cartesian)) {
  5652. throw new DeveloperError('cartesian is required');
  5653. }
  5654. if (typeof index !== 'number' || index < 0 || index > 2) {
  5655. throw new DeveloperError('index must be 0, 1, or 2.');
  5656. }
  5657. if (!defined(result)) {
  5658. throw new DeveloperError('result is required');
  5659. }
  5660. result = Matrix3.clone(matrix, result);
  5661. var startIndex = index * 3;
  5662. result[startIndex] = cartesian.x;
  5663. result[startIndex + 1] = cartesian.y;
  5664. result[startIndex + 2] = cartesian.z;
  5665. return result;
  5666. };
  5667. /**
  5668. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  5669. *
  5670. * @param {Matrix3} matrix The matrix to use.
  5671. * @param {Number} index The zero-based index of the row to retrieve.
  5672. * @param {Cartesian3} result The object onto which to store the result.
  5673. * @returns {Cartesian3} The modified result parameter.
  5674. *
  5675. * @exception {DeveloperError} index must be 0, 1, or 2.
  5676. */
  5677. Matrix3.getRow = function(matrix, index, result) {
  5678. if (!defined(matrix)) {
  5679. throw new DeveloperError('matrix is required.');
  5680. }
  5681. if (typeof index !== 'number' || index < 0 || index > 2) {
  5682. throw new DeveloperError('index must be 0, 1, or 2.');
  5683. }
  5684. if (!defined(result)) {
  5685. throw new DeveloperError('result is required');
  5686. }
  5687. var x = matrix[index];
  5688. var y = matrix[index + 3];
  5689. var z = matrix[index + 6];
  5690. result.x = x;
  5691. result.y = y;
  5692. result.z = z;
  5693. return result;
  5694. };
  5695. /**
  5696. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  5697. *
  5698. * @param {Matrix3} matrix The matrix to use.
  5699. * @param {Number} index The zero-based index of the row to set.
  5700. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  5701. * @param {Matrix3} result The object onto which to store the result.
  5702. * @returns {Matrix3} The modified result parameter.
  5703. *
  5704. * @exception {DeveloperError} index must be 0, 1, or 2.
  5705. */
  5706. Matrix3.setRow = function(matrix, index, cartesian, result) {
  5707. if (!defined(matrix)) {
  5708. throw new DeveloperError('matrix is required');
  5709. }
  5710. if (!defined(cartesian)) {
  5711. throw new DeveloperError('cartesian is required');
  5712. }
  5713. if (typeof index !== 'number' || index < 0 || index > 2) {
  5714. throw new DeveloperError('index must be 0, 1, or 2.');
  5715. }
  5716. if (!defined(result)) {
  5717. throw new DeveloperError('result is required');
  5718. }
  5719. result = Matrix3.clone(matrix, result);
  5720. result[index] = cartesian.x;
  5721. result[index + 3] = cartesian.y;
  5722. result[index + 6] = cartesian.z;
  5723. return result;
  5724. };
  5725. var scratchColumn = new Cartesian3();
  5726. /**
  5727. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  5728. *
  5729. * @param {Matrix3} matrix The matrix.
  5730. * @param {Cartesian3} result The object onto which to store the result.
  5731. * @returns {Cartesian3} The modified result parameter.
  5732. */
  5733. Matrix3.getScale = function(matrix, result) {
  5734. if (!defined(matrix)) {
  5735. throw new DeveloperError('matrix is required.');
  5736. }
  5737. if (!defined(result)) {
  5738. throw new DeveloperError('result is required');
  5739. }
  5740. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  5741. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  5742. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  5743. return result;
  5744. };
  5745. var scratchScale = new Cartesian3();
  5746. /**
  5747. * Computes the maximum scale assuming the matrix is an affine transformation.
  5748. * The maximum scale is the maximum length of the column vectors.
  5749. *
  5750. * @param {Matrix3} matrix The matrix.
  5751. * @returns {Number} The maximum scale.
  5752. */
  5753. Matrix3.getMaximumScale = function(matrix) {
  5754. Matrix3.getScale(matrix, scratchScale);
  5755. return Cartesian3.maximumComponent(scratchScale);
  5756. };
  5757. /**
  5758. * Computes the product of two matrices.
  5759. *
  5760. * @param {Matrix3} left The first matrix.
  5761. * @param {Matrix3} right The second matrix.
  5762. * @param {Matrix3} result The object onto which to store the result.
  5763. * @returns {Matrix3} The modified result parameter.
  5764. */
  5765. Matrix3.multiply = function(left, right, result) {
  5766. if (!defined(left)) {
  5767. throw new DeveloperError('left is required');
  5768. }
  5769. if (!defined(right)) {
  5770. throw new DeveloperError('right is required');
  5771. }
  5772. if (!defined(result)) {
  5773. throw new DeveloperError('result is required');
  5774. }
  5775. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  5776. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  5777. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  5778. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  5779. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  5780. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  5781. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  5782. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  5783. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  5784. result[0] = column0Row0;
  5785. result[1] = column0Row1;
  5786. result[2] = column0Row2;
  5787. result[3] = column1Row0;
  5788. result[4] = column1Row1;
  5789. result[5] = column1Row2;
  5790. result[6] = column2Row0;
  5791. result[7] = column2Row1;
  5792. result[8] = column2Row2;
  5793. return result;
  5794. };
  5795. /**
  5796. * Computes the sum of two matrices.
  5797. *
  5798. * @param {Matrix3} left The first matrix.
  5799. * @param {Matrix3} right The second matrix.
  5800. * @param {Matrix3} result The object onto which to store the result.
  5801. * @returns {Matrix3} The modified result parameter.
  5802. */
  5803. Matrix3.add = function(left, right, result) {
  5804. if (!defined(left)) {
  5805. throw new DeveloperError('left is required');
  5806. }
  5807. if (!defined(right)) {
  5808. throw new DeveloperError('right is required');
  5809. }
  5810. if (!defined(result)) {
  5811. throw new DeveloperError('result is required');
  5812. }
  5813. result[0] = left[0] + right[0];
  5814. result[1] = left[1] + right[1];
  5815. result[2] = left[2] + right[2];
  5816. result[3] = left[3] + right[3];
  5817. result[4] = left[4] + right[4];
  5818. result[5] = left[5] + right[5];
  5819. result[6] = left[6] + right[6];
  5820. result[7] = left[7] + right[7];
  5821. result[8] = left[8] + right[8];
  5822. return result;
  5823. };
  5824. /**
  5825. * Computes the difference of two matrices.
  5826. *
  5827. * @param {Matrix3} left The first matrix.
  5828. * @param {Matrix3} right The second matrix.
  5829. * @param {Matrix3} result The object onto which to store the result.
  5830. * @returns {Matrix3} The modified result parameter.
  5831. */
  5832. Matrix3.subtract = function(left, right, result) {
  5833. if (!defined(left)) {
  5834. throw new DeveloperError('left is required');
  5835. }
  5836. if (!defined(right)) {
  5837. throw new DeveloperError('right is required');
  5838. }
  5839. if (!defined(result)) {
  5840. throw new DeveloperError('result is required');
  5841. }
  5842. result[0] = left[0] - right[0];
  5843. result[1] = left[1] - right[1];
  5844. result[2] = left[2] - right[2];
  5845. result[3] = left[3] - right[3];
  5846. result[4] = left[4] - right[4];
  5847. result[5] = left[5] - right[5];
  5848. result[6] = left[6] - right[6];
  5849. result[7] = left[7] - right[7];
  5850. result[8] = left[8] - right[8];
  5851. return result;
  5852. };
  5853. /**
  5854. * Computes the product of a matrix and a column vector.
  5855. *
  5856. * @param {Matrix3} matrix The matrix.
  5857. * @param {Cartesian3} cartesian The column.
  5858. * @param {Cartesian3} result The object onto which to store the result.
  5859. * @returns {Cartesian3} The modified result parameter.
  5860. */
  5861. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  5862. if (!defined(matrix)) {
  5863. throw new DeveloperError('matrix is required');
  5864. }
  5865. if (!defined(cartesian)) {
  5866. throw new DeveloperError('cartesian is required');
  5867. }
  5868. if (!defined(result)) {
  5869. throw new DeveloperError('result is required');
  5870. }
  5871. var vX = cartesian.x;
  5872. var vY = cartesian.y;
  5873. var vZ = cartesian.z;
  5874. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  5875. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  5876. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  5877. result.x = x;
  5878. result.y = y;
  5879. result.z = z;
  5880. return result;
  5881. };
  5882. /**
  5883. * Computes the product of a matrix and a scalar.
  5884. *
  5885. * @param {Matrix3} matrix The matrix.
  5886. * @param {Number} scalar The number to multiply by.
  5887. * @param {Matrix3} result The object onto which to store the result.
  5888. * @returns {Matrix3} The modified result parameter.
  5889. */
  5890. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  5891. if (!defined(matrix)) {
  5892. throw new DeveloperError('matrix is required');
  5893. }
  5894. if (typeof scalar !== 'number') {
  5895. throw new DeveloperError('scalar must be a number');
  5896. }
  5897. if (!defined(result)) {
  5898. throw new DeveloperError('result is required');
  5899. }
  5900. result[0] = matrix[0] * scalar;
  5901. result[1] = matrix[1] * scalar;
  5902. result[2] = matrix[2] * scalar;
  5903. result[3] = matrix[3] * scalar;
  5904. result[4] = matrix[4] * scalar;
  5905. result[5] = matrix[5] * scalar;
  5906. result[6] = matrix[6] * scalar;
  5907. result[7] = matrix[7] * scalar;
  5908. result[8] = matrix[8] * scalar;
  5909. return result;
  5910. };
  5911. /**
  5912. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  5913. *
  5914. * @param {Matrix3} matrix The matrix on the left-hand side.
  5915. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  5916. * @param {Matrix3} result The object onto which to store the result.
  5917. * @returns {Matrix3} The modified result parameter.
  5918. *
  5919. *
  5920. * @example
  5921. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  5922. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  5923. *
  5924. * @see Matrix3.fromScale
  5925. * @see Matrix3.multiplyByUniformScale
  5926. */
  5927. Matrix3.multiplyByScale = function(matrix, scale, result) {
  5928. if (!defined(matrix)) {
  5929. throw new DeveloperError('matrix is required');
  5930. }
  5931. if (!defined(scale)) {
  5932. throw new DeveloperError('scale is required');
  5933. }
  5934. if (!defined(result)) {
  5935. throw new DeveloperError('result is required');
  5936. }
  5937. result[0] = matrix[0] * scale.x;
  5938. result[1] = matrix[1] * scale.x;
  5939. result[2] = matrix[2] * scale.x;
  5940. result[3] = matrix[3] * scale.y;
  5941. result[4] = matrix[4] * scale.y;
  5942. result[5] = matrix[5] * scale.y;
  5943. result[6] = matrix[6] * scale.z;
  5944. result[7] = matrix[7] * scale.z;
  5945. result[8] = matrix[8] * scale.z;
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a negated copy of the provided matrix.
  5950. *
  5951. * @param {Matrix3} matrix The matrix to negate.
  5952. * @param {Matrix3} result The object onto which to store the result.
  5953. * @returns {Matrix3} The modified result parameter.
  5954. */
  5955. Matrix3.negate = function(matrix, result) {
  5956. if (!defined(matrix)) {
  5957. throw new DeveloperError('matrix is required');
  5958. }
  5959. if (!defined(result)) {
  5960. throw new DeveloperError('result is required');
  5961. }
  5962. result[0] = -matrix[0];
  5963. result[1] = -matrix[1];
  5964. result[2] = -matrix[2];
  5965. result[3] = -matrix[3];
  5966. result[4] = -matrix[4];
  5967. result[5] = -matrix[5];
  5968. result[6] = -matrix[6];
  5969. result[7] = -matrix[7];
  5970. result[8] = -matrix[8];
  5971. return result;
  5972. };
  5973. /**
  5974. * Computes the transpose of the provided matrix.
  5975. *
  5976. * @param {Matrix3} matrix The matrix to transpose.
  5977. * @param {Matrix3} result The object onto which to store the result.
  5978. * @returns {Matrix3} The modified result parameter.
  5979. */
  5980. Matrix3.transpose = function(matrix, result) {
  5981. if (!defined(matrix)) {
  5982. throw new DeveloperError('matrix is required');
  5983. }
  5984. if (!defined(result)) {
  5985. throw new DeveloperError('result is required');
  5986. }
  5987. var column0Row0 = matrix[0];
  5988. var column0Row1 = matrix[3];
  5989. var column0Row2 = matrix[6];
  5990. var column1Row0 = matrix[1];
  5991. var column1Row1 = matrix[4];
  5992. var column1Row2 = matrix[7];
  5993. var column2Row0 = matrix[2];
  5994. var column2Row1 = matrix[5];
  5995. var column2Row2 = matrix[8];
  5996. result[0] = column0Row0;
  5997. result[1] = column0Row1;
  5998. result[2] = column0Row2;
  5999. result[3] = column1Row0;
  6000. result[4] = column1Row1;
  6001. result[5] = column1Row2;
  6002. result[6] = column2Row0;
  6003. result[7] = column2Row1;
  6004. result[8] = column2Row2;
  6005. return result;
  6006. };
  6007. function computeFrobeniusNorm(matrix) {
  6008. var norm = 0.0;
  6009. for (var i = 0; i < 9; ++i) {
  6010. var temp = matrix[i];
  6011. norm += temp * temp;
  6012. }
  6013. return Math.sqrt(norm);
  6014. }
  6015. var rowVal = [1, 0, 0];
  6016. var colVal = [2, 2, 1];
  6017. function offDiagonalFrobeniusNorm(matrix) {
  6018. // Computes the "off-diagonal" Frobenius norm.
  6019. // Assumes matrix is symmetric.
  6020. var norm = 0.0;
  6021. for (var i = 0; i < 3; ++i) {
  6022. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  6023. norm += 2.0 * temp * temp;
  6024. }
  6025. return Math.sqrt(norm);
  6026. }
  6027. function shurDecomposition(matrix, result) {
  6028. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  6029. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  6030. //
  6031. // The routine takes a matrix, which is assumed to be symmetric, and
  6032. // finds the largest off-diagonal term, and then creates
  6033. // a matrix (result) which can be used to help reduce it
  6034. var tolerance = CesiumMath.EPSILON15;
  6035. var maxDiagonal = 0.0;
  6036. var rotAxis = 1;
  6037. // find pivot (rotAxis) based on max diagonal of matrix
  6038. for (var i = 0; i < 3; ++i) {
  6039. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  6040. if (temp > maxDiagonal) {
  6041. rotAxis = i;
  6042. maxDiagonal = temp;
  6043. }
  6044. }
  6045. var c = 1.0;
  6046. var s = 0.0;
  6047. var p = rowVal[rotAxis];
  6048. var q = colVal[rotAxis];
  6049. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  6050. var qq = matrix[Matrix3.getElementIndex(q, q)];
  6051. var pp = matrix[Matrix3.getElementIndex(p, p)];
  6052. var qp = matrix[Matrix3.getElementIndex(q, p)];
  6053. var tau = (qq - pp) / 2.0 / qp;
  6054. var t;
  6055. if (tau < 0.0) {
  6056. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  6057. } else {
  6058. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  6059. }
  6060. c = 1.0 / Math.sqrt(1.0 + t * t);
  6061. s = t * c;
  6062. }
  6063. result = Matrix3.clone(Matrix3.IDENTITY, result);
  6064. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  6065. result[Matrix3.getElementIndex(q, p)] = s;
  6066. result[Matrix3.getElementIndex(p, q)] = -s;
  6067. return result;
  6068. }
  6069. var jMatrix = new Matrix3();
  6070. var jMatrixTranspose = new Matrix3();
  6071. /**
  6072. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  6073. * <p>
  6074. * Returns a diagonal matrix and unitary matrix such that:
  6075. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  6076. * </p>
  6077. * <p>
  6078. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  6079. * of the unitary matrix are the corresponding eigenvectors.
  6080. * </p>
  6081. *
  6082. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  6083. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  6084. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  6085. *
  6086. * @example
  6087. * var a = //... symetric matrix
  6088. * var result = {
  6089. * unitary : new Cesium.Matrix3(),
  6090. * diagonal : new Cesium.Matrix3()
  6091. * };
  6092. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  6093. *
  6094. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  6095. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  6096. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  6097. *
  6098. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  6099. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  6100. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  6101. */
  6102. Matrix3.computeEigenDecomposition = function(matrix, result) {
  6103. if (!defined(matrix)) {
  6104. throw new DeveloperError('matrix is required.');
  6105. }
  6106. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  6107. // section 8.4.3 The Classical Jacobi Algorithm
  6108. var tolerance = CesiumMath.EPSILON20;
  6109. var maxSweeps = 10;
  6110. var count = 0;
  6111. var sweep = 0;
  6112. if (!defined(result)) {
  6113. result = {};
  6114. }
  6115. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  6116. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  6117. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  6118. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  6119. shurDecomposition(diagMatrix, jMatrix);
  6120. Matrix3.transpose(jMatrix, jMatrixTranspose);
  6121. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  6122. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  6123. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  6124. if (++count > 2) {
  6125. ++sweep;
  6126. count = 0;
  6127. }
  6128. }
  6129. return result;
  6130. };
  6131. /**
  6132. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  6133. *
  6134. * @param {Matrix3} matrix The matrix with signed elements.
  6135. * @param {Matrix3} result The object onto which to store the result.
  6136. * @returns {Matrix3} The modified result parameter.
  6137. */
  6138. Matrix3.abs = function(matrix, result) {
  6139. if (!defined(matrix)) {
  6140. throw new DeveloperError('matrix is required');
  6141. }
  6142. if (!defined(result)) {
  6143. throw new DeveloperError('result is required');
  6144. }
  6145. result[0] = Math.abs(matrix[0]);
  6146. result[1] = Math.abs(matrix[1]);
  6147. result[2] = Math.abs(matrix[2]);
  6148. result[3] = Math.abs(matrix[3]);
  6149. result[4] = Math.abs(matrix[4]);
  6150. result[5] = Math.abs(matrix[5]);
  6151. result[6] = Math.abs(matrix[6]);
  6152. result[7] = Math.abs(matrix[7]);
  6153. result[8] = Math.abs(matrix[8]);
  6154. return result;
  6155. };
  6156. /**
  6157. * Computes the determinant of the provided matrix.
  6158. *
  6159. * @param {Matrix3} matrix The matrix to use.
  6160. * @returns {Number} The value of the determinant of the matrix.
  6161. */
  6162. Matrix3.determinant = function(matrix) {
  6163. if (!defined(matrix)) {
  6164. throw new DeveloperError('matrix is required');
  6165. }
  6166. var m11 = matrix[0];
  6167. var m21 = matrix[3];
  6168. var m31 = matrix[6];
  6169. var m12 = matrix[1];
  6170. var m22 = matrix[4];
  6171. var m32 = matrix[7];
  6172. var m13 = matrix[2];
  6173. var m23 = matrix[5];
  6174. var m33 = matrix[8];
  6175. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  6176. };
  6177. /**
  6178. * Computes the inverse of the provided matrix.
  6179. *
  6180. * @param {Matrix3} matrix The matrix to invert.
  6181. * @param {Matrix3} result The object onto which to store the result.
  6182. * @returns {Matrix3} The modified result parameter.
  6183. *
  6184. * @exception {DeveloperError} matrix is not invertible.
  6185. */
  6186. Matrix3.inverse = function(matrix, result) {
  6187. if (!defined(matrix)) {
  6188. throw new DeveloperError('matrix is required');
  6189. }
  6190. if (!defined(result)) {
  6191. throw new DeveloperError('result is required');
  6192. }
  6193. var m11 = matrix[0];
  6194. var m21 = matrix[1];
  6195. var m31 = matrix[2];
  6196. var m12 = matrix[3];
  6197. var m22 = matrix[4];
  6198. var m32 = matrix[5];
  6199. var m13 = matrix[6];
  6200. var m23 = matrix[7];
  6201. var m33 = matrix[8];
  6202. var determinant = Matrix3.determinant(matrix);
  6203. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  6204. throw new DeveloperError('matrix is not invertible');
  6205. }
  6206. result[0] = m22 * m33 - m23 * m32;
  6207. result[1] = m23 * m31 - m21 * m33;
  6208. result[2] = m21 * m32 - m22 * m31;
  6209. result[3] = m13 * m32 - m12 * m33;
  6210. result[4] = m11 * m33 - m13 * m31;
  6211. result[5] = m12 * m31 - m11 * m32;
  6212. result[6] = m12 * m23 - m13 * m22;
  6213. result[7] = m13 * m21 - m11 * m23;
  6214. result[8] = m11 * m22 - m12 * m21;
  6215. var scale = 1.0 / determinant;
  6216. return Matrix3.multiplyByScalar(result, scale, result);
  6217. };
  6218. /**
  6219. * Compares the provided matrices componentwise and returns
  6220. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6221. *
  6222. * @param {Matrix3} [left] The first matrix.
  6223. * @param {Matrix3} [right] The second matrix.
  6224. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  6225. */
  6226. Matrix3.equals = function(left, right) {
  6227. return (left === right) ||
  6228. (defined(left) &&
  6229. defined(right) &&
  6230. left[0] === right[0] &&
  6231. left[1] === right[1] &&
  6232. left[2] === right[2] &&
  6233. left[3] === right[3] &&
  6234. left[4] === right[4] &&
  6235. left[5] === right[5] &&
  6236. left[6] === right[6] &&
  6237. left[7] === right[7] &&
  6238. left[8] === right[8]);
  6239. };
  6240. /**
  6241. * Compares the provided matrices componentwise and returns
  6242. * <code>true</code> if they are within the provided epsilon,
  6243. * <code>false</code> otherwise.
  6244. *
  6245. * @param {Matrix3} [left] The first matrix.
  6246. * @param {Matrix3} [right] The second matrix.
  6247. * @param {Number} epsilon The epsilon to use for equality testing.
  6248. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  6249. */
  6250. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  6251. if (typeof epsilon !== 'number') {
  6252. throw new DeveloperError('epsilon must be a number');
  6253. }
  6254. return (left === right) ||
  6255. (defined(left) &&
  6256. defined(right) &&
  6257. Math.abs(left[0] - right[0]) <= epsilon &&
  6258. Math.abs(left[1] - right[1]) <= epsilon &&
  6259. Math.abs(left[2] - right[2]) <= epsilon &&
  6260. Math.abs(left[3] - right[3]) <= epsilon &&
  6261. Math.abs(left[4] - right[4]) <= epsilon &&
  6262. Math.abs(left[5] - right[5]) <= epsilon &&
  6263. Math.abs(left[6] - right[6]) <= epsilon &&
  6264. Math.abs(left[7] - right[7]) <= epsilon &&
  6265. Math.abs(left[8] - right[8]) <= epsilon);
  6266. };
  6267. /**
  6268. * An immutable Matrix3 instance initialized to the identity matrix.
  6269. *
  6270. * @type {Matrix3}
  6271. * @constant
  6272. */
  6273. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  6274. 0.0, 1.0, 0.0,
  6275. 0.0, 0.0, 1.0));
  6276. /**
  6277. * An immutable Matrix3 instance initialized to the zero matrix.
  6278. *
  6279. * @type {Matrix3}
  6280. * @constant
  6281. */
  6282. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  6283. 0.0, 0.0, 0.0,
  6284. 0.0, 0.0, 0.0));
  6285. /**
  6286. * The index into Matrix3 for column 0, row 0.
  6287. *
  6288. * @type {Number}
  6289. * @constant
  6290. */
  6291. Matrix3.COLUMN0ROW0 = 0;
  6292. /**
  6293. * The index into Matrix3 for column 0, row 1.
  6294. *
  6295. * @type {Number}
  6296. * @constant
  6297. */
  6298. Matrix3.COLUMN0ROW1 = 1;
  6299. /**
  6300. * The index into Matrix3 for column 0, row 2.
  6301. *
  6302. * @type {Number}
  6303. * @constant
  6304. */
  6305. Matrix3.COLUMN0ROW2 = 2;
  6306. /**
  6307. * The index into Matrix3 for column 1, row 0.
  6308. *
  6309. * @type {Number}
  6310. * @constant
  6311. */
  6312. Matrix3.COLUMN1ROW0 = 3;
  6313. /**
  6314. * The index into Matrix3 for column 1, row 1.
  6315. *
  6316. * @type {Number}
  6317. * @constant
  6318. */
  6319. Matrix3.COLUMN1ROW1 = 4;
  6320. /**
  6321. * The index into Matrix3 for column 1, row 2.
  6322. *
  6323. * @type {Number}
  6324. * @constant
  6325. */
  6326. Matrix3.COLUMN1ROW2 = 5;
  6327. /**
  6328. * The index into Matrix3 for column 2, row 0.
  6329. *
  6330. * @type {Number}
  6331. * @constant
  6332. */
  6333. Matrix3.COLUMN2ROW0 = 6;
  6334. /**
  6335. * The index into Matrix3 for column 2, row 1.
  6336. *
  6337. * @type {Number}
  6338. * @constant
  6339. */
  6340. Matrix3.COLUMN2ROW1 = 7;
  6341. /**
  6342. * The index into Matrix3 for column 2, row 2.
  6343. *
  6344. * @type {Number}
  6345. * @constant
  6346. */
  6347. Matrix3.COLUMN2ROW2 = 8;
  6348. defineProperties(Matrix3.prototype, {
  6349. /**
  6350. * Gets the number of items in the collection.
  6351. * @memberof Matrix3.prototype
  6352. *
  6353. * @type {Number}
  6354. */
  6355. length : {
  6356. get : function() {
  6357. return Matrix3.packedLength;
  6358. }
  6359. }
  6360. });
  6361. /**
  6362. * Duplicates the provided Matrix3 instance.
  6363. *
  6364. * @param {Matrix3} [result] The object onto which to store the result.
  6365. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  6366. */
  6367. Matrix3.prototype.clone = function(result) {
  6368. return Matrix3.clone(this, result);
  6369. };
  6370. /**
  6371. * Compares this matrix to the provided matrix componentwise and returns
  6372. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6373. *
  6374. * @param {Matrix3} [right] The right hand side matrix.
  6375. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  6376. */
  6377. Matrix3.prototype.equals = function(right) {
  6378. return Matrix3.equals(this, right);
  6379. };
  6380. /**
  6381. * @private
  6382. */
  6383. Matrix3.equalsArray = function(matrix, array, offset) {
  6384. return matrix[0] === array[offset] &&
  6385. matrix[1] === array[offset + 1] &&
  6386. matrix[2] === array[offset + 2] &&
  6387. matrix[3] === array[offset + 3] &&
  6388. matrix[4] === array[offset + 4] &&
  6389. matrix[5] === array[offset + 5] &&
  6390. matrix[6] === array[offset + 6] &&
  6391. matrix[7] === array[offset + 7] &&
  6392. matrix[8] === array[offset + 8];
  6393. };
  6394. /**
  6395. * Compares this matrix to the provided matrix componentwise and returns
  6396. * <code>true</code> if they are within the provided epsilon,
  6397. * <code>false</code> otherwise.
  6398. *
  6399. * @param {Matrix3} [right] The right hand side matrix.
  6400. * @param {Number} epsilon The epsilon to use for equality testing.
  6401. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  6402. */
  6403. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  6404. return Matrix3.equalsEpsilon(this, right, epsilon);
  6405. };
  6406. /**
  6407. * Creates a string representing this Matrix with each row being
  6408. * on a separate line and in the format '(column0, column1, column2)'.
  6409. *
  6410. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  6411. */
  6412. Matrix3.prototype.toString = function() {
  6413. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  6414. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  6415. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  6416. };
  6417. return Matrix3;
  6418. });
  6419. /*global define*/
  6420. define('Core/Cartesian4',[
  6421. './defaultValue',
  6422. './defined',
  6423. './DeveloperError',
  6424. './freezeObject',
  6425. './Math'
  6426. ], function(
  6427. defaultValue,
  6428. defined,
  6429. DeveloperError,
  6430. freezeObject,
  6431. CesiumMath) {
  6432. 'use strict';
  6433. /**
  6434. * A 4D Cartesian point.
  6435. * @alias Cartesian4
  6436. * @constructor
  6437. *
  6438. * @param {Number} [x=0.0] The X component.
  6439. * @param {Number} [y=0.0] The Y component.
  6440. * @param {Number} [z=0.0] The Z component.
  6441. * @param {Number} [w=0.0] The W component.
  6442. *
  6443. * @see Cartesian2
  6444. * @see Cartesian3
  6445. * @see Packable
  6446. */
  6447. function Cartesian4(x, y, z, w) {
  6448. /**
  6449. * The X component.
  6450. * @type {Number}
  6451. * @default 0.0
  6452. */
  6453. this.x = defaultValue(x, 0.0);
  6454. /**
  6455. * The Y component.
  6456. * @type {Number}
  6457. * @default 0.0
  6458. */
  6459. this.y = defaultValue(y, 0.0);
  6460. /**
  6461. * The Z component.
  6462. * @type {Number}
  6463. * @default 0.0
  6464. */
  6465. this.z = defaultValue(z, 0.0);
  6466. /**
  6467. * The W component.
  6468. * @type {Number}
  6469. * @default 0.0
  6470. */
  6471. this.w = defaultValue(w, 0.0);
  6472. }
  6473. /**
  6474. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  6475. *
  6476. * @param {Number} x The x coordinate.
  6477. * @param {Number} y The y coordinate.
  6478. * @param {Number} z The z coordinate.
  6479. * @param {Number} w The w coordinate.
  6480. * @param {Cartesian4} [result] The object onto which to store the result.
  6481. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6482. */
  6483. Cartesian4.fromElements = function(x, y, z, w, result) {
  6484. if (!defined(result)) {
  6485. return new Cartesian4(x, y, z, w);
  6486. }
  6487. result.x = x;
  6488. result.y = y;
  6489. result.z = z;
  6490. result.w = w;
  6491. return result;
  6492. };
  6493. /**
  6494. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  6495. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  6496. *
  6497. * @param {Color} color The source color.
  6498. * @param {Cartesian4} [result] The object onto which to store the result.
  6499. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6500. */
  6501. Cartesian4.fromColor = function(color, result) {
  6502. if (!defined(color)) {
  6503. throw new DeveloperError('color is required');
  6504. }
  6505. if (!defined(result)) {
  6506. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  6507. }
  6508. result.x = color.red;
  6509. result.y = color.green;
  6510. result.z = color.blue;
  6511. result.w = color.alpha;
  6512. return result;
  6513. };
  6514. /**
  6515. * Duplicates a Cartesian4 instance.
  6516. *
  6517. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  6518. * @param {Cartesian4} [result] The object onto which to store the result.
  6519. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  6520. */
  6521. Cartesian4.clone = function(cartesian, result) {
  6522. if (!defined(cartesian)) {
  6523. return undefined;
  6524. }
  6525. if (!defined(result)) {
  6526. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6527. }
  6528. result.x = cartesian.x;
  6529. result.y = cartesian.y;
  6530. result.z = cartesian.z;
  6531. result.w = cartesian.w;
  6532. return result;
  6533. };
  6534. /**
  6535. * The number of elements used to pack the object into an array.
  6536. * @type {Number}
  6537. */
  6538. Cartesian4.packedLength = 4;
  6539. /**
  6540. * Stores the provided instance into the provided array.
  6541. *
  6542. * @param {Cartesian4} value The value to pack.
  6543. * @param {Number[]} array The array to pack into.
  6544. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  6545. *
  6546. * @returns {Number[]} The array that was packed into
  6547. */
  6548. Cartesian4.pack = function(value, array, startingIndex) {
  6549. if (!defined(value)) {
  6550. throw new DeveloperError('value is required');
  6551. }
  6552. if (!defined(array)) {
  6553. throw new DeveloperError('array is required');
  6554. }
  6555. startingIndex = defaultValue(startingIndex, 0);
  6556. array[startingIndex++] = value.x;
  6557. array[startingIndex++] = value.y;
  6558. array[startingIndex++] = value.z;
  6559. array[startingIndex] = value.w;
  6560. return array;
  6561. };
  6562. /**
  6563. * Retrieves an instance from a packed array.
  6564. *
  6565. * @param {Number[]} array The packed array.
  6566. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  6567. * @param {Cartesian4} [result] The object into which to store the result.
  6568. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6569. */
  6570. Cartesian4.unpack = function(array, startingIndex, result) {
  6571. if (!defined(array)) {
  6572. throw new DeveloperError('array is required');
  6573. }
  6574. startingIndex = defaultValue(startingIndex, 0);
  6575. if (!defined(result)) {
  6576. result = new Cartesian4();
  6577. }
  6578. result.x = array[startingIndex++];
  6579. result.y = array[startingIndex++];
  6580. result.z = array[startingIndex++];
  6581. result.w = array[startingIndex];
  6582. return result;
  6583. };
  6584. /**
  6585. * Flattens an array of Cartesian4s into and array of components.
  6586. *
  6587. * @param {Cartesian4[]} array The array of cartesians to pack.
  6588. * @param {Number[]} result The array onto which to store the result.
  6589. * @returns {Number[]} The packed array.
  6590. */
  6591. Cartesian4.packArray = function(array, result) {
  6592. if (!defined(array)) {
  6593. throw new DeveloperError('array is required');
  6594. }
  6595. var length = array.length;
  6596. if (!defined(result)) {
  6597. result = new Array(length * 4);
  6598. } else {
  6599. result.length = length * 4;
  6600. }
  6601. for (var i = 0; i < length; ++i) {
  6602. Cartesian4.pack(array[i], result, i * 4);
  6603. }
  6604. return result;
  6605. };
  6606. /**
  6607. * Unpacks an array of cartesian components into and array of Cartesian4s.
  6608. *
  6609. * @param {Number[]} array The array of components to unpack.
  6610. * @param {Cartesian4[]} result The array onto which to store the result.
  6611. * @returns {Cartesian4[]} The unpacked array.
  6612. */
  6613. Cartesian4.unpackArray = function(array, result) {
  6614. if (!defined(array)) {
  6615. throw new DeveloperError('array is required');
  6616. }
  6617. var length = array.length;
  6618. if (!defined(result)) {
  6619. result = new Array(length / 4);
  6620. } else {
  6621. result.length = length / 4;
  6622. }
  6623. for (var i = 0; i < length; i += 4) {
  6624. var index = i / 4;
  6625. result[index] = Cartesian4.unpack(array, i, result[index]);
  6626. }
  6627. return result;
  6628. };
  6629. /**
  6630. * Creates a Cartesian4 from four consecutive elements in an array.
  6631. * @function
  6632. *
  6633. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  6634. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  6635. * @param {Cartesian4} [result] The object onto which to store the result.
  6636. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6637. *
  6638. * @example
  6639. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  6640. * var v = [1.0, 2.0, 3.0, 4.0];
  6641. * var p = Cesium.Cartesian4.fromArray(v);
  6642. *
  6643. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  6644. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  6645. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  6646. */
  6647. Cartesian4.fromArray = Cartesian4.unpack;
  6648. /**
  6649. * Computes the value of the maximum component for the supplied Cartesian.
  6650. *
  6651. * @param {Cartesian4} cartesian The cartesian to use.
  6652. * @returns {Number} The value of the maximum component.
  6653. */
  6654. Cartesian4.maximumComponent = function(cartesian) {
  6655. if (!defined(cartesian)) {
  6656. throw new DeveloperError('cartesian is required');
  6657. }
  6658. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6659. };
  6660. /**
  6661. * Computes the value of the minimum component for the supplied Cartesian.
  6662. *
  6663. * @param {Cartesian4} cartesian The cartesian to use.
  6664. * @returns {Number} The value of the minimum component.
  6665. */
  6666. Cartesian4.minimumComponent = function(cartesian) {
  6667. if (!defined(cartesian)) {
  6668. throw new DeveloperError('cartesian is required');
  6669. }
  6670. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6671. };
  6672. /**
  6673. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  6674. *
  6675. * @param {Cartesian4} first A cartesian to compare.
  6676. * @param {Cartesian4} second A cartesian to compare.
  6677. * @param {Cartesian4} result The object into which to store the result.
  6678. * @returns {Cartesian4} A cartesian with the minimum components.
  6679. */
  6680. Cartesian4.minimumByComponent = function(first, second, result) {
  6681. if (!defined(first)) {
  6682. throw new DeveloperError('first is required.');
  6683. }
  6684. if (!defined(second)) {
  6685. throw new DeveloperError('second is required.');
  6686. }
  6687. if (!defined(result)) {
  6688. throw new DeveloperError('result is required.');
  6689. }
  6690. result.x = Math.min(first.x, second.x);
  6691. result.y = Math.min(first.y, second.y);
  6692. result.z = Math.min(first.z, second.z);
  6693. result.w = Math.min(first.w, second.w);
  6694. return result;
  6695. };
  6696. /**
  6697. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  6698. *
  6699. * @param {Cartesian4} first A cartesian to compare.
  6700. * @param {Cartesian4} second A cartesian to compare.
  6701. * @param {Cartesian4} result The object into which to store the result.
  6702. * @returns {Cartesian4} A cartesian with the maximum components.
  6703. */
  6704. Cartesian4.maximumByComponent = function(first, second, result) {
  6705. if (!defined(first)) {
  6706. throw new DeveloperError('first is required.');
  6707. }
  6708. if (!defined(second)) {
  6709. throw new DeveloperError('second is required.');
  6710. }
  6711. if (!defined(result)) {
  6712. throw new DeveloperError('result is required.');
  6713. }
  6714. result.x = Math.max(first.x, second.x);
  6715. result.y = Math.max(first.y, second.y);
  6716. result.z = Math.max(first.z, second.z);
  6717. result.w = Math.max(first.w, second.w);
  6718. return result;
  6719. };
  6720. /**
  6721. * Computes the provided Cartesian's squared magnitude.
  6722. *
  6723. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  6724. * @returns {Number} The squared magnitude.
  6725. */
  6726. Cartesian4.magnitudeSquared = function(cartesian) {
  6727. if (!defined(cartesian)) {
  6728. throw new DeveloperError('cartesian is required');
  6729. }
  6730. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  6731. };
  6732. /**
  6733. * Computes the Cartesian's magnitude (length).
  6734. *
  6735. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  6736. * @returns {Number} The magnitude.
  6737. */
  6738. Cartesian4.magnitude = function(cartesian) {
  6739. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  6740. };
  6741. var distanceScratch = new Cartesian4();
  6742. /**
  6743. * Computes the 4-space distance between two points.
  6744. *
  6745. * @param {Cartesian4} left The first point to compute the distance from.
  6746. * @param {Cartesian4} right The second point to compute the distance to.
  6747. * @returns {Number} The distance between two points.
  6748. *
  6749. * @example
  6750. * // Returns 1.0
  6751. * var d = Cesium.Cartesian4.distance(
  6752. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6753. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  6754. */
  6755. Cartesian4.distance = function(left, right) {
  6756. if (!defined(left) || !defined(right)) {
  6757. throw new DeveloperError('left and right are required.');
  6758. }
  6759. Cartesian4.subtract(left, right, distanceScratch);
  6760. return Cartesian4.magnitude(distanceScratch);
  6761. };
  6762. /**
  6763. * Computes the squared distance between two points. Comparing squared distances
  6764. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  6765. *
  6766. * @param {Cartesian4} left The first point to compute the distance from.
  6767. * @param {Cartesian4} right The second point to compute the distance to.
  6768. * @returns {Number} The distance between two points.
  6769. *
  6770. * @example
  6771. * // Returns 4.0, not 2.0
  6772. * var d = Cesium.Cartesian4.distance(
  6773. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6774. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  6775. */
  6776. Cartesian4.distanceSquared = function(left, right) {
  6777. if (!defined(left) || !defined(right)) {
  6778. throw new DeveloperError('left and right are required.');
  6779. }
  6780. Cartesian4.subtract(left, right, distanceScratch);
  6781. return Cartesian4.magnitudeSquared(distanceScratch);
  6782. };
  6783. /**
  6784. * Computes the normalized form of the supplied Cartesian.
  6785. *
  6786. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  6787. * @param {Cartesian4} result The object onto which to store the result.
  6788. * @returns {Cartesian4} The modified result parameter.
  6789. */
  6790. Cartesian4.normalize = function(cartesian, result) {
  6791. if (!defined(cartesian)) {
  6792. throw new DeveloperError('cartesian is required');
  6793. }
  6794. if (!defined(result)) {
  6795. throw new DeveloperError('result is required');
  6796. }
  6797. var magnitude = Cartesian4.magnitude(cartesian);
  6798. result.x = cartesian.x / magnitude;
  6799. result.y = cartesian.y / magnitude;
  6800. result.z = cartesian.z / magnitude;
  6801. result.w = cartesian.w / magnitude;
  6802. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  6803. throw new DeveloperError('normalized result is not a number');
  6804. }
  6805. return result;
  6806. };
  6807. /**
  6808. * Computes the dot (scalar) product of two Cartesians.
  6809. *
  6810. * @param {Cartesian4} left The first Cartesian.
  6811. * @param {Cartesian4} right The second Cartesian.
  6812. * @returns {Number} The dot product.
  6813. */
  6814. Cartesian4.dot = function(left, right) {
  6815. if (!defined(left)) {
  6816. throw new DeveloperError('left is required');
  6817. }
  6818. if (!defined(right)) {
  6819. throw new DeveloperError('right is required');
  6820. }
  6821. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  6822. };
  6823. /**
  6824. * Computes the componentwise product of two Cartesians.
  6825. *
  6826. * @param {Cartesian4} left The first Cartesian.
  6827. * @param {Cartesian4} right The second Cartesian.
  6828. * @param {Cartesian4} result The object onto which to store the result.
  6829. * @returns {Cartesian4} The modified result parameter.
  6830. */
  6831. Cartesian4.multiplyComponents = function(left, right, result) {
  6832. if (!defined(left)) {
  6833. throw new DeveloperError('left is required');
  6834. }
  6835. if (!defined(right)) {
  6836. throw new DeveloperError('right is required');
  6837. }
  6838. if (!defined(result)) {
  6839. throw new DeveloperError('result is required');
  6840. }
  6841. result.x = left.x * right.x;
  6842. result.y = left.y * right.y;
  6843. result.z = left.z * right.z;
  6844. result.w = left.w * right.w;
  6845. return result;
  6846. };
  6847. /**
  6848. * Computes the componentwise quotient of two Cartesians.
  6849. *
  6850. * @param {Cartesian4} left The first Cartesian.
  6851. * @param {Cartesian4} right The second Cartesian.
  6852. * @param {Cartesian4} result The object onto which to store the result.
  6853. * @returns {Cartesian4} The modified result parameter.
  6854. */
  6855. Cartesian4.divideComponents = function(left, right, result) {
  6856. if (!defined(left)) {
  6857. throw new DeveloperError('left is required');
  6858. }
  6859. if (!defined(right)) {
  6860. throw new DeveloperError('right is required');
  6861. }
  6862. if (!defined(result)) {
  6863. throw new DeveloperError('result is required');
  6864. }
  6865. result.x = left.x / right.x;
  6866. result.y = left.y / right.y;
  6867. result.z = left.z / right.z;
  6868. result.w = left.w / right.w;
  6869. return result;
  6870. };
  6871. /**
  6872. * Computes the componentwise sum of two Cartesians.
  6873. *
  6874. * @param {Cartesian4} left The first Cartesian.
  6875. * @param {Cartesian4} right The second Cartesian.
  6876. * @param {Cartesian4} result The object onto which to store the result.
  6877. * @returns {Cartesian4} The modified result parameter.
  6878. */
  6879. Cartesian4.add = function(left, right, result) {
  6880. if (!defined(left)) {
  6881. throw new DeveloperError('left is required');
  6882. }
  6883. if (!defined(right)) {
  6884. throw new DeveloperError('right is required');
  6885. }
  6886. if (!defined(result)) {
  6887. throw new DeveloperError('result is required');
  6888. }
  6889. result.x = left.x + right.x;
  6890. result.y = left.y + right.y;
  6891. result.z = left.z + right.z;
  6892. result.w = left.w + right.w;
  6893. return result;
  6894. };
  6895. /**
  6896. * Computes the componentwise difference of two Cartesians.
  6897. *
  6898. * @param {Cartesian4} left The first Cartesian.
  6899. * @param {Cartesian4} right The second Cartesian.
  6900. * @param {Cartesian4} result The object onto which to store the result.
  6901. * @returns {Cartesian4} The modified result parameter.
  6902. */
  6903. Cartesian4.subtract = function(left, right, result) {
  6904. if (!defined(left)) {
  6905. throw new DeveloperError('left is required');
  6906. }
  6907. if (!defined(right)) {
  6908. throw new DeveloperError('right is required');
  6909. }
  6910. if (!defined(result)) {
  6911. throw new DeveloperError('result is required');
  6912. }
  6913. result.x = left.x - right.x;
  6914. result.y = left.y - right.y;
  6915. result.z = left.z - right.z;
  6916. result.w = left.w - right.w;
  6917. return result;
  6918. };
  6919. /**
  6920. * Multiplies the provided Cartesian componentwise by the provided scalar.
  6921. *
  6922. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  6923. * @param {Number} scalar The scalar to multiply with.
  6924. * @param {Cartesian4} result The object onto which to store the result.
  6925. * @returns {Cartesian4} The modified result parameter.
  6926. */
  6927. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  6928. if (!defined(cartesian)) {
  6929. throw new DeveloperError('cartesian is required');
  6930. }
  6931. if (typeof scalar !== 'number') {
  6932. throw new DeveloperError('scalar is required and must be a number.');
  6933. }
  6934. if (!defined(result)) {
  6935. throw new DeveloperError('result is required');
  6936. }
  6937. result.x = cartesian.x * scalar;
  6938. result.y = cartesian.y * scalar;
  6939. result.z = cartesian.z * scalar;
  6940. result.w = cartesian.w * scalar;
  6941. return result;
  6942. };
  6943. /**
  6944. * Divides the provided Cartesian componentwise by the provided scalar.
  6945. *
  6946. * @param {Cartesian4} cartesian The Cartesian to be divided.
  6947. * @param {Number} scalar The scalar to divide by.
  6948. * @param {Cartesian4} result The object onto which to store the result.
  6949. * @returns {Cartesian4} The modified result parameter.
  6950. */
  6951. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  6952. if (!defined(cartesian)) {
  6953. throw new DeveloperError('cartesian is required');
  6954. }
  6955. if (typeof scalar !== 'number') {
  6956. throw new DeveloperError('scalar is required and must be a number.');
  6957. }
  6958. if (!defined(result)) {
  6959. throw new DeveloperError('result is required');
  6960. }
  6961. result.x = cartesian.x / scalar;
  6962. result.y = cartesian.y / scalar;
  6963. result.z = cartesian.z / scalar;
  6964. result.w = cartesian.w / scalar;
  6965. return result;
  6966. };
  6967. /**
  6968. * Negates the provided Cartesian.
  6969. *
  6970. * @param {Cartesian4} cartesian The Cartesian to be negated.
  6971. * @param {Cartesian4} result The object onto which to store the result.
  6972. * @returns {Cartesian4} The modified result parameter.
  6973. */
  6974. Cartesian4.negate = function(cartesian, result) {
  6975. if (!defined(cartesian)) {
  6976. throw new DeveloperError('cartesian is required');
  6977. }
  6978. if (!defined(result)) {
  6979. throw new DeveloperError('result is required');
  6980. }
  6981. result.x = -cartesian.x;
  6982. result.y = -cartesian.y;
  6983. result.z = -cartesian.z;
  6984. result.w = -cartesian.w;
  6985. return result;
  6986. };
  6987. /**
  6988. * Computes the absolute value of the provided Cartesian.
  6989. *
  6990. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  6991. * @param {Cartesian4} result The object onto which to store the result.
  6992. * @returns {Cartesian4} The modified result parameter.
  6993. */
  6994. Cartesian4.abs = function(cartesian, result) {
  6995. if (!defined(cartesian)) {
  6996. throw new DeveloperError('cartesian is required');
  6997. }
  6998. if (!defined(result)) {
  6999. throw new DeveloperError('result is required');
  7000. }
  7001. result.x = Math.abs(cartesian.x);
  7002. result.y = Math.abs(cartesian.y);
  7003. result.z = Math.abs(cartesian.z);
  7004. result.w = Math.abs(cartesian.w);
  7005. return result;
  7006. };
  7007. var lerpScratch = new Cartesian4();
  7008. /**
  7009. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  7010. *
  7011. * @param {Cartesian4} start The value corresponding to t at 0.0.
  7012. * @param {Cartesian4}end The value corresponding to t at 1.0.
  7013. * @param {Number} t The point along t at which to interpolate.
  7014. * @param {Cartesian4} result The object onto which to store the result.
  7015. * @returns {Cartesian4} The modified result parameter.
  7016. */
  7017. Cartesian4.lerp = function(start, end, t, result) {
  7018. if (!defined(start)) {
  7019. throw new DeveloperError('start is required.');
  7020. }
  7021. if (!defined(end)) {
  7022. throw new DeveloperError('end is required.');
  7023. }
  7024. if (typeof t !== 'number') {
  7025. throw new DeveloperError('t is required and must be a number.');
  7026. }
  7027. if (!defined(result)) {
  7028. throw new DeveloperError('result is required.');
  7029. }
  7030. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  7031. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  7032. return Cartesian4.add(lerpScratch, result, result);
  7033. };
  7034. var mostOrthogonalAxisScratch = new Cartesian4();
  7035. /**
  7036. * Returns the axis that is most orthogonal to the provided Cartesian.
  7037. *
  7038. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  7039. * @param {Cartesian4} result The object onto which to store the result.
  7040. * @returns {Cartesian4} The most orthogonal axis.
  7041. */
  7042. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  7043. if (!defined(cartesian)) {
  7044. throw new DeveloperError('cartesian is required.');
  7045. }
  7046. if (!defined(result)) {
  7047. throw new DeveloperError('result is required.');
  7048. }
  7049. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  7050. Cartesian4.abs(f, f);
  7051. if (f.x <= f.y) {
  7052. if (f.x <= f.z) {
  7053. if (f.x <= f.w) {
  7054. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  7055. } else {
  7056. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7057. }
  7058. } else if (f.z <= f.w) {
  7059. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  7060. } else {
  7061. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7062. }
  7063. } else if (f.y <= f.z) {
  7064. if (f.y <= f.w) {
  7065. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  7066. } else {
  7067. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7068. }
  7069. } else if (f.z <= f.w) {
  7070. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  7071. } else {
  7072. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7073. }
  7074. return result;
  7075. };
  7076. /**
  7077. * Compares the provided Cartesians componentwise and returns
  7078. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7079. *
  7080. * @param {Cartesian4} [left] The first Cartesian.
  7081. * @param {Cartesian4} [right] The second Cartesian.
  7082. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7083. */
  7084. Cartesian4.equals = function(left, right) {
  7085. return (left === right) ||
  7086. ((defined(left)) &&
  7087. (defined(right)) &&
  7088. (left.x === right.x) &&
  7089. (left.y === right.y) &&
  7090. (left.z === right.z) &&
  7091. (left.w === right.w));
  7092. };
  7093. /**
  7094. * @private
  7095. */
  7096. Cartesian4.equalsArray = function(cartesian, array, offset) {
  7097. return cartesian.x === array[offset] &&
  7098. cartesian.y === array[offset + 1] &&
  7099. cartesian.z === array[offset + 2] &&
  7100. cartesian.w === array[offset + 3];
  7101. };
  7102. /**
  7103. * Compares the provided Cartesians componentwise and returns
  7104. * <code>true</code> if they pass an absolute or relative tolerance test,
  7105. * <code>false</code> otherwise.
  7106. *
  7107. * @param {Cartesian4} [left] The first Cartesian.
  7108. * @param {Cartesian4} [right] The second Cartesian.
  7109. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  7110. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  7111. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7112. */
  7113. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  7114. return (left === right) ||
  7115. (defined(left) &&
  7116. defined(right) &&
  7117. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  7118. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  7119. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  7120. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  7121. };
  7122. /**
  7123. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  7124. *
  7125. * @type {Cartesian4}
  7126. * @constant
  7127. */
  7128. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  7129. /**
  7130. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  7131. *
  7132. * @type {Cartesian4}
  7133. * @constant
  7134. */
  7135. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  7136. /**
  7137. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  7138. *
  7139. * @type {Cartesian4}
  7140. * @constant
  7141. */
  7142. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  7143. /**
  7144. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  7145. *
  7146. * @type {Cartesian4}
  7147. * @constant
  7148. */
  7149. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  7150. /**
  7151. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  7152. *
  7153. * @type {Cartesian4}
  7154. * @constant
  7155. */
  7156. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  7157. /**
  7158. * Duplicates this Cartesian4 instance.
  7159. *
  7160. * @param {Cartesian4} [result] The object onto which to store the result.
  7161. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  7162. */
  7163. Cartesian4.prototype.clone = function(result) {
  7164. return Cartesian4.clone(this, result);
  7165. };
  7166. /**
  7167. * Compares this Cartesian against the provided Cartesian componentwise and returns
  7168. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7169. *
  7170. * @param {Cartesian4} [right] The right hand side Cartesian.
  7171. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  7172. */
  7173. Cartesian4.prototype.equals = function(right) {
  7174. return Cartesian4.equals(this, right);
  7175. };
  7176. /**
  7177. * Compares this Cartesian against the provided Cartesian componentwise and returns
  7178. * <code>true</code> if they pass an absolute or relative tolerance test,
  7179. * <code>false</code> otherwise.
  7180. *
  7181. * @param {Cartesian4} [right] The right hand side Cartesian.
  7182. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  7183. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  7184. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  7185. */
  7186. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  7187. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  7188. };
  7189. /**
  7190. * Creates a string representing this Cartesian in the format '(x, y)'.
  7191. *
  7192. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  7193. */
  7194. Cartesian4.prototype.toString = function() {
  7195. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  7196. };
  7197. return Cartesian4;
  7198. });
  7199. /*global define*/
  7200. define('Core/RuntimeError',[
  7201. './defined'
  7202. ], function(
  7203. defined) {
  7204. 'use strict';
  7205. /**
  7206. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  7207. * out of memory, could not compile shader, etc. If a function may throw this
  7208. * exception, the calling code should be prepared to catch it.
  7209. * <br /><br />
  7210. * On the other hand, a {@link DeveloperError} indicates an exception due
  7211. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  7212. * calling code.
  7213. *
  7214. * @alias RuntimeError
  7215. * @constructor
  7216. * @extends Error
  7217. *
  7218. * @param {String} [message] The error message for this exception.
  7219. *
  7220. * @see DeveloperError
  7221. */
  7222. function RuntimeError(message) {
  7223. /**
  7224. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  7225. * @type {String}
  7226. * @readonly
  7227. */
  7228. this.name = 'RuntimeError';
  7229. /**
  7230. * The explanation for why this exception was thrown.
  7231. * @type {String}
  7232. * @readonly
  7233. */
  7234. this.message = message;
  7235. //Browsers such as IE don't have a stack property until you actually throw the error.
  7236. var stack;
  7237. try {
  7238. throw new Error();
  7239. } catch (e) {
  7240. stack = e.stack;
  7241. }
  7242. /**
  7243. * The stack trace of this exception, if available.
  7244. * @type {String}
  7245. * @readonly
  7246. */
  7247. this.stack = stack;
  7248. }
  7249. if (defined(Object.create)) {
  7250. RuntimeError.prototype = Object.create(Error.prototype);
  7251. RuntimeError.prototype.constructor = RuntimeError;
  7252. }
  7253. RuntimeError.prototype.toString = function() {
  7254. var str = this.name + ': ' + this.message;
  7255. if (defined(this.stack)) {
  7256. str += '\n' + this.stack.toString();
  7257. }
  7258. return str;
  7259. };
  7260. return RuntimeError;
  7261. });
  7262. /*global define*/
  7263. define('Core/Matrix4',[
  7264. './Cartesian3',
  7265. './Cartesian4',
  7266. './defaultValue',
  7267. './defined',
  7268. './defineProperties',
  7269. './DeveloperError',
  7270. './freezeObject',
  7271. './Math',
  7272. './Matrix3',
  7273. './RuntimeError'
  7274. ], function(
  7275. Cartesian3,
  7276. Cartesian4,
  7277. defaultValue,
  7278. defined,
  7279. defineProperties,
  7280. DeveloperError,
  7281. freezeObject,
  7282. CesiumMath,
  7283. Matrix3,
  7284. RuntimeError) {
  7285. 'use strict';
  7286. /**
  7287. * A 4x4 matrix, indexable as a column-major order array.
  7288. * Constructor parameters are in row-major order for code readability.
  7289. * @alias Matrix4
  7290. * @constructor
  7291. *
  7292. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  7293. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  7294. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  7295. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  7296. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  7297. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  7298. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  7299. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  7300. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  7301. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  7302. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  7303. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  7304. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  7305. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  7306. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  7307. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  7308. *
  7309. * @see Matrix4.fromColumnMajorArray
  7310. * @see Matrix4.fromRowMajorArray
  7311. * @see Matrix4.fromRotationTranslation
  7312. * @see Matrix4.fromTranslationRotationScale
  7313. * @see Matrix4.fromTranslationQuaternionRotationScale
  7314. * @see Matrix4.fromTranslation
  7315. * @see Matrix4.fromScale
  7316. * @see Matrix4.fromUniformScale
  7317. * @see Matrix4.fromCamera
  7318. * @see Matrix4.computePerspectiveFieldOfView
  7319. * @see Matrix4.computeOrthographicOffCenter
  7320. * @see Matrix4.computePerspectiveOffCenter
  7321. * @see Matrix4.computeInfinitePerspectiveOffCenter
  7322. * @see Matrix4.computeViewportTransformation
  7323. * @see Matrix4.computeView
  7324. * @see Matrix2
  7325. * @see Matrix3
  7326. * @see Packable
  7327. */
  7328. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  7329. column0Row1, column1Row1, column2Row1, column3Row1,
  7330. column0Row2, column1Row2, column2Row2, column3Row2,
  7331. column0Row3, column1Row3, column2Row3, column3Row3) {
  7332. this[0] = defaultValue(column0Row0, 0.0);
  7333. this[1] = defaultValue(column0Row1, 0.0);
  7334. this[2] = defaultValue(column0Row2, 0.0);
  7335. this[3] = defaultValue(column0Row3, 0.0);
  7336. this[4] = defaultValue(column1Row0, 0.0);
  7337. this[5] = defaultValue(column1Row1, 0.0);
  7338. this[6] = defaultValue(column1Row2, 0.0);
  7339. this[7] = defaultValue(column1Row3, 0.0);
  7340. this[8] = defaultValue(column2Row0, 0.0);
  7341. this[9] = defaultValue(column2Row1, 0.0);
  7342. this[10] = defaultValue(column2Row2, 0.0);
  7343. this[11] = defaultValue(column2Row3, 0.0);
  7344. this[12] = defaultValue(column3Row0, 0.0);
  7345. this[13] = defaultValue(column3Row1, 0.0);
  7346. this[14] = defaultValue(column3Row2, 0.0);
  7347. this[15] = defaultValue(column3Row3, 0.0);
  7348. }
  7349. /**
  7350. * The number of elements used to pack the object into an array.
  7351. * @type {Number}
  7352. */
  7353. Matrix4.packedLength = 16;
  7354. /**
  7355. * Stores the provided instance into the provided array.
  7356. *
  7357. * @param {Matrix4} value The value to pack.
  7358. * @param {Number[]} array The array to pack into.
  7359. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  7360. *
  7361. * @returns {Number[]} The array that was packed into
  7362. */
  7363. Matrix4.pack = function(value, array, startingIndex) {
  7364. if (!defined(value)) {
  7365. throw new DeveloperError('value is required');
  7366. }
  7367. if (!defined(array)) {
  7368. throw new DeveloperError('array is required');
  7369. }
  7370. startingIndex = defaultValue(startingIndex, 0);
  7371. array[startingIndex++] = value[0];
  7372. array[startingIndex++] = value[1];
  7373. array[startingIndex++] = value[2];
  7374. array[startingIndex++] = value[3];
  7375. array[startingIndex++] = value[4];
  7376. array[startingIndex++] = value[5];
  7377. array[startingIndex++] = value[6];
  7378. array[startingIndex++] = value[7];
  7379. array[startingIndex++] = value[8];
  7380. array[startingIndex++] = value[9];
  7381. array[startingIndex++] = value[10];
  7382. array[startingIndex++] = value[11];
  7383. array[startingIndex++] = value[12];
  7384. array[startingIndex++] = value[13];
  7385. array[startingIndex++] = value[14];
  7386. array[startingIndex] = value[15];
  7387. return array;
  7388. };
  7389. /**
  7390. * Retrieves an instance from a packed array.
  7391. *
  7392. * @param {Number[]} array The packed array.
  7393. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  7394. * @param {Matrix4} [result] The object into which to store the result.
  7395. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7396. */
  7397. Matrix4.unpack = function(array, startingIndex, result) {
  7398. if (!defined(array)) {
  7399. throw new DeveloperError('array is required');
  7400. }
  7401. startingIndex = defaultValue(startingIndex, 0);
  7402. if (!defined(result)) {
  7403. result = new Matrix4();
  7404. }
  7405. result[0] = array[startingIndex++];
  7406. result[1] = array[startingIndex++];
  7407. result[2] = array[startingIndex++];
  7408. result[3] = array[startingIndex++];
  7409. result[4] = array[startingIndex++];
  7410. result[5] = array[startingIndex++];
  7411. result[6] = array[startingIndex++];
  7412. result[7] = array[startingIndex++];
  7413. result[8] = array[startingIndex++];
  7414. result[9] = array[startingIndex++];
  7415. result[10] = array[startingIndex++];
  7416. result[11] = array[startingIndex++];
  7417. result[12] = array[startingIndex++];
  7418. result[13] = array[startingIndex++];
  7419. result[14] = array[startingIndex++];
  7420. result[15] = array[startingIndex];
  7421. return result;
  7422. };
  7423. /**
  7424. * Duplicates a Matrix4 instance.
  7425. *
  7426. * @param {Matrix4} matrix The matrix to duplicate.
  7427. * @param {Matrix4} [result] The object onto which to store the result.
  7428. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  7429. */
  7430. Matrix4.clone = function(matrix, result) {
  7431. if (!defined(matrix)) {
  7432. return undefined;
  7433. }
  7434. if (!defined(result)) {
  7435. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  7436. matrix[1], matrix[5], matrix[9], matrix[13],
  7437. matrix[2], matrix[6], matrix[10], matrix[14],
  7438. matrix[3], matrix[7], matrix[11], matrix[15]);
  7439. }
  7440. result[0] = matrix[0];
  7441. result[1] = matrix[1];
  7442. result[2] = matrix[2];
  7443. result[3] = matrix[3];
  7444. result[4] = matrix[4];
  7445. result[5] = matrix[5];
  7446. result[6] = matrix[6];
  7447. result[7] = matrix[7];
  7448. result[8] = matrix[8];
  7449. result[9] = matrix[9];
  7450. result[10] = matrix[10];
  7451. result[11] = matrix[11];
  7452. result[12] = matrix[12];
  7453. result[13] = matrix[13];
  7454. result[14] = matrix[14];
  7455. result[15] = matrix[15];
  7456. return result;
  7457. };
  7458. /**
  7459. * Creates a Matrix4 from 16 consecutive elements in an array.
  7460. * @function
  7461. *
  7462. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  7463. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  7464. * @param {Matrix4} [result] The object onto which to store the result.
  7465. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7466. *
  7467. * @example
  7468. * // Create the Matrix4:
  7469. * // [1.0, 2.0, 3.0, 4.0]
  7470. * // [1.0, 2.0, 3.0, 4.0]
  7471. * // [1.0, 2.0, 3.0, 4.0]
  7472. * // [1.0, 2.0, 3.0, 4.0]
  7473. *
  7474. * 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];
  7475. * var m = Cesium.Matrix4.fromArray(v);
  7476. *
  7477. * // Create same Matrix4 with using an offset into an array
  7478. * 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];
  7479. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  7480. */
  7481. Matrix4.fromArray = Matrix4.unpack;
  7482. /**
  7483. * Computes a Matrix4 instance from a column-major order array.
  7484. *
  7485. * @param {Number[]} values The column-major order array.
  7486. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7487. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7488. */
  7489. Matrix4.fromColumnMajorArray = function(values, result) {
  7490. if (!defined(values)) {
  7491. throw new DeveloperError('values is required');
  7492. }
  7493. return Matrix4.clone(values, result);
  7494. };
  7495. /**
  7496. * Computes a Matrix4 instance from a row-major order array.
  7497. * The resulting matrix will be in column-major order.
  7498. *
  7499. * @param {Number[]} values The row-major order array.
  7500. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7501. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7502. */
  7503. Matrix4.fromRowMajorArray = function(values, result) {
  7504. if (!defined(values)) {
  7505. throw new DeveloperError('values is required.');
  7506. }
  7507. if (!defined(result)) {
  7508. return new Matrix4(values[0], values[1], values[2], values[3],
  7509. values[4], values[5], values[6], values[7],
  7510. values[8], values[9], values[10], values[11],
  7511. values[12], values[13], values[14], values[15]);
  7512. }
  7513. result[0] = values[0];
  7514. result[1] = values[4];
  7515. result[2] = values[8];
  7516. result[3] = values[12];
  7517. result[4] = values[1];
  7518. result[5] = values[5];
  7519. result[6] = values[9];
  7520. result[7] = values[13];
  7521. result[8] = values[2];
  7522. result[9] = values[6];
  7523. result[10] = values[10];
  7524. result[11] = values[14];
  7525. result[12] = values[3];
  7526. result[13] = values[7];
  7527. result[14] = values[11];
  7528. result[15] = values[15];
  7529. return result;
  7530. };
  7531. /**
  7532. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  7533. * and a Cartesian3 representing the translation.
  7534. *
  7535. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  7536. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  7537. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7538. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7539. */
  7540. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  7541. if (!defined(rotation)) {
  7542. throw new DeveloperError('rotation is required.');
  7543. }
  7544. translation = defaultValue(translation, Cartesian3.ZERO);
  7545. if (!defined(result)) {
  7546. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  7547. rotation[1], rotation[4], rotation[7], translation.y,
  7548. rotation[2], rotation[5], rotation[8], translation.z,
  7549. 0.0, 0.0, 0.0, 1.0);
  7550. }
  7551. result[0] = rotation[0];
  7552. result[1] = rotation[1];
  7553. result[2] = rotation[2];
  7554. result[3] = 0.0;
  7555. result[4] = rotation[3];
  7556. result[5] = rotation[4];
  7557. result[6] = rotation[5];
  7558. result[7] = 0.0;
  7559. result[8] = rotation[6];
  7560. result[9] = rotation[7];
  7561. result[10] = rotation[8];
  7562. result[11] = 0.0;
  7563. result[12] = translation.x;
  7564. result[13] = translation.y;
  7565. result[14] = translation.z;
  7566. result[15] = 1.0;
  7567. return result;
  7568. };
  7569. /**
  7570. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  7571. * representation with the rotation represented as a quaternion.
  7572. *
  7573. * @param {Cartesian3} translation The translation transformation.
  7574. * @param {Quaternion} rotation The rotation transformation.
  7575. * @param {Cartesian3} scale The non-uniform scale transformation.
  7576. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7577. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7578. *
  7579. * @example
  7580. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  7581. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  7582. * Cesium.Quaternion.IDENTITY, // rotation
  7583. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  7584. * result);
  7585. */
  7586. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  7587. if (!defined(translation)) {
  7588. throw new DeveloperError('translation is required.');
  7589. }
  7590. if (!defined(rotation)) {
  7591. throw new DeveloperError('rotation is required.');
  7592. }
  7593. if (!defined(scale)) {
  7594. throw new DeveloperError('scale is required.');
  7595. }
  7596. if (!defined(result)) {
  7597. result = new Matrix4();
  7598. }
  7599. var scaleX = scale.x;
  7600. var scaleY = scale.y;
  7601. var scaleZ = scale.z;
  7602. var x2 = rotation.x * rotation.x;
  7603. var xy = rotation.x * rotation.y;
  7604. var xz = rotation.x * rotation.z;
  7605. var xw = rotation.x * rotation.w;
  7606. var y2 = rotation.y * rotation.y;
  7607. var yz = rotation.y * rotation.z;
  7608. var yw = rotation.y * rotation.w;
  7609. var z2 = rotation.z * rotation.z;
  7610. var zw = rotation.z * rotation.w;
  7611. var w2 = rotation.w * rotation.w;
  7612. var m00 = x2 - y2 - z2 + w2;
  7613. var m01 = 2.0 * (xy - zw);
  7614. var m02 = 2.0 * (xz + yw);
  7615. var m10 = 2.0 * (xy + zw);
  7616. var m11 = -x2 + y2 - z2 + w2;
  7617. var m12 = 2.0 * (yz - xw);
  7618. var m20 = 2.0 * (xz - yw);
  7619. var m21 = 2.0 * (yz + xw);
  7620. var m22 = -x2 - y2 + z2 + w2;
  7621. result[0] = m00 * scaleX;
  7622. result[1] = m10 * scaleX;
  7623. result[2] = m20 * scaleX;
  7624. result[3] = 0.0;
  7625. result[4] = m01 * scaleY;
  7626. result[5] = m11 * scaleY;
  7627. result[6] = m21 * scaleY;
  7628. result[7] = 0.0;
  7629. result[8] = m02 * scaleZ;
  7630. result[9] = m12 * scaleZ;
  7631. result[10] = m22 * scaleZ;
  7632. result[11] = 0.0;
  7633. result[12] = translation.x;
  7634. result[13] = translation.y;
  7635. result[14] = translation.z;
  7636. result[15] = 1.0;
  7637. return result;
  7638. };
  7639. /**
  7640. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  7641. *
  7642. * @param {TranslationRotationScale} translationRotationScale The instance.
  7643. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7644. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7645. */
  7646. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  7647. if (!defined(translationRotationScale)) {
  7648. throw new DeveloperError('translationRotationScale is required.');
  7649. }
  7650. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  7651. };
  7652. /**
  7653. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  7654. *
  7655. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  7656. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7657. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7658. *
  7659. * @see Matrix4.multiplyByTranslation
  7660. */
  7661. Matrix4.fromTranslation = function(translation, result) {
  7662. if (!defined(translation)) {
  7663. throw new DeveloperError('translation is required.');
  7664. }
  7665. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  7666. };
  7667. /**
  7668. * Computes a Matrix4 instance representing a non-uniform scale.
  7669. *
  7670. * @param {Cartesian3} scale The x, y, and z scale factors.
  7671. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7672. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7673. *
  7674. * @example
  7675. * // Creates
  7676. * // [7.0, 0.0, 0.0, 0.0]
  7677. * // [0.0, 8.0, 0.0, 0.0]
  7678. * // [0.0, 0.0, 9.0, 0.0]
  7679. * // [0.0, 0.0, 0.0, 1.0]
  7680. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  7681. */
  7682. Matrix4.fromScale = function(scale, result) {
  7683. if (!defined(scale)) {
  7684. throw new DeveloperError('scale is required.');
  7685. }
  7686. if (!defined(result)) {
  7687. return new Matrix4(
  7688. scale.x, 0.0, 0.0, 0.0,
  7689. 0.0, scale.y, 0.0, 0.0,
  7690. 0.0, 0.0, scale.z, 0.0,
  7691. 0.0, 0.0, 0.0, 1.0);
  7692. }
  7693. result[0] = scale.x;
  7694. result[1] = 0.0;
  7695. result[2] = 0.0;
  7696. result[3] = 0.0;
  7697. result[4] = 0.0;
  7698. result[5] = scale.y;
  7699. result[6] = 0.0;
  7700. result[7] = 0.0;
  7701. result[8] = 0.0;
  7702. result[9] = 0.0;
  7703. result[10] = scale.z;
  7704. result[11] = 0.0;
  7705. result[12] = 0.0;
  7706. result[13] = 0.0;
  7707. result[14] = 0.0;
  7708. result[15] = 1.0;
  7709. return result;
  7710. };
  7711. /**
  7712. * Computes a Matrix4 instance representing a uniform scale.
  7713. *
  7714. * @param {Number} scale The uniform scale factor.
  7715. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7716. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7717. *
  7718. * @example
  7719. * // Creates
  7720. * // [2.0, 0.0, 0.0, 0.0]
  7721. * // [0.0, 2.0, 0.0, 0.0]
  7722. * // [0.0, 0.0, 2.0, 0.0]
  7723. * // [0.0, 0.0, 0.0, 1.0]
  7724. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  7725. */
  7726. Matrix4.fromUniformScale = function(scale, result) {
  7727. if (typeof scale !== 'number') {
  7728. throw new DeveloperError('scale is required.');
  7729. }
  7730. if (!defined(result)) {
  7731. return new Matrix4(scale, 0.0, 0.0, 0.0,
  7732. 0.0, scale, 0.0, 0.0,
  7733. 0.0, 0.0, scale, 0.0,
  7734. 0.0, 0.0, 0.0, 1.0);
  7735. }
  7736. result[0] = scale;
  7737. result[1] = 0.0;
  7738. result[2] = 0.0;
  7739. result[3] = 0.0;
  7740. result[4] = 0.0;
  7741. result[5] = scale;
  7742. result[6] = 0.0;
  7743. result[7] = 0.0;
  7744. result[8] = 0.0;
  7745. result[9] = 0.0;
  7746. result[10] = scale;
  7747. result[11] = 0.0;
  7748. result[12] = 0.0;
  7749. result[13] = 0.0;
  7750. result[14] = 0.0;
  7751. result[15] = 1.0;
  7752. return result;
  7753. };
  7754. var fromCameraF = new Cartesian3();
  7755. var fromCameraR = new Cartesian3();
  7756. var fromCameraU = new Cartesian3();
  7757. /**
  7758. * Computes a Matrix4 instance from a Camera.
  7759. *
  7760. * @param {Camera} camera The camera to use.
  7761. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7762. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7763. */
  7764. Matrix4.fromCamera = function(camera, result) {
  7765. if (!defined(camera)) {
  7766. throw new DeveloperError('camera is required.');
  7767. }
  7768. var position = camera.position;
  7769. var direction = camera.direction;
  7770. var up = camera.up;
  7771. if (!defined(position)) {
  7772. throw new DeveloperError('camera.position is required.');
  7773. }
  7774. if (!defined(direction)) {
  7775. throw new DeveloperError('camera.direction is required.');
  7776. }
  7777. if (!defined(up)) {
  7778. throw new DeveloperError('camera.up is required.');
  7779. }
  7780. Cartesian3.normalize(direction, fromCameraF);
  7781. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  7782. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  7783. var sX = fromCameraR.x;
  7784. var sY = fromCameraR.y;
  7785. var sZ = fromCameraR.z;
  7786. var fX = fromCameraF.x;
  7787. var fY = fromCameraF.y;
  7788. var fZ = fromCameraF.z;
  7789. var uX = fromCameraU.x;
  7790. var uY = fromCameraU.y;
  7791. var uZ = fromCameraU.z;
  7792. var positionX = position.x;
  7793. var positionY = position.y;
  7794. var positionZ = position.z;
  7795. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  7796. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  7797. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  7798. // The code below this comment is an optimized
  7799. // version of the commented lines.
  7800. // Rather that create two matrices and then multiply,
  7801. // we just bake in the multiplcation as part of creation.
  7802. // var rotation = new Matrix4(
  7803. // sX, sY, sZ, 0.0,
  7804. // uX, uY, uZ, 0.0,
  7805. // -fX, -fY, -fZ, 0.0,
  7806. // 0.0, 0.0, 0.0, 1.0);
  7807. // var translation = new Matrix4(
  7808. // 1.0, 0.0, 0.0, -position.x,
  7809. // 0.0, 1.0, 0.0, -position.y,
  7810. // 0.0, 0.0, 1.0, -position.z,
  7811. // 0.0, 0.0, 0.0, 1.0);
  7812. // return rotation.multiply(translation);
  7813. if (!defined(result)) {
  7814. return new Matrix4(
  7815. sX, sY, sZ, t0,
  7816. uX, uY, uZ, t1,
  7817. -fX, -fY, -fZ, t2,
  7818. 0.0, 0.0, 0.0, 1.0);
  7819. }
  7820. result[0] = sX;
  7821. result[1] = uX;
  7822. result[2] = -fX;
  7823. result[3] = 0.0;
  7824. result[4] = sY;
  7825. result[5] = uY;
  7826. result[6] = -fY;
  7827. result[7] = 0.0;
  7828. result[8] = sZ;
  7829. result[9] = uZ;
  7830. result[10] = -fZ;
  7831. result[11] = 0.0;
  7832. result[12] = t0;
  7833. result[13] = t1;
  7834. result[14] = t2;
  7835. result[15] = 1.0;
  7836. return result;
  7837. };
  7838. /**
  7839. * Computes a Matrix4 instance representing a perspective transformation matrix.
  7840. *
  7841. * @param {Number} fovY The field of view along the Y axis in radians.
  7842. * @param {Number} aspectRatio The aspect ratio.
  7843. * @param {Number} near The distance to the near plane in meters.
  7844. * @param {Number} far The distance to the far plane in meters.
  7845. * @param {Matrix4} result The object in which the result will be stored.
  7846. * @returns {Matrix4} The modified result parameter.
  7847. *
  7848. * @exception {DeveloperError} fovY must be in (0, PI].
  7849. * @exception {DeveloperError} aspectRatio must be greater than zero.
  7850. * @exception {DeveloperError} near must be greater than zero.
  7851. * @exception {DeveloperError} far must be greater than zero.
  7852. */
  7853. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  7854. if (fovY <= 0.0 || fovY > Math.PI) {
  7855. throw new DeveloperError('fovY must be in (0, PI].');
  7856. }
  7857. if (aspectRatio <= 0.0) {
  7858. throw new DeveloperError('aspectRatio must be greater than zero.');
  7859. }
  7860. if (near <= 0.0) {
  7861. throw new DeveloperError('near must be greater than zero.');
  7862. }
  7863. if (far <= 0.0) {
  7864. throw new DeveloperError('far must be greater than zero.');
  7865. }
  7866. if (!defined(result)) {
  7867. throw new DeveloperError('result is required');
  7868. }
  7869. var bottom = Math.tan(fovY * 0.5);
  7870. var column1Row1 = 1.0 / bottom;
  7871. var column0Row0 = column1Row1 / aspectRatio;
  7872. var column2Row2 = (far + near) / (near - far);
  7873. var column3Row2 = (2.0 * far * near) / (near - far);
  7874. result[0] = column0Row0;
  7875. result[1] = 0.0;
  7876. result[2] = 0.0;
  7877. result[3] = 0.0;
  7878. result[4] = 0.0;
  7879. result[5] = column1Row1;
  7880. result[6] = 0.0;
  7881. result[7] = 0.0;
  7882. result[8] = 0.0;
  7883. result[9] = 0.0;
  7884. result[10] = column2Row2;
  7885. result[11] = -1.0;
  7886. result[12] = 0.0;
  7887. result[13] = 0.0;
  7888. result[14] = column3Row2;
  7889. result[15] = 0.0;
  7890. return result;
  7891. };
  7892. /**
  7893. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  7894. *
  7895. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7896. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7897. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7898. * @param {Number} top The number of meters above of the camera that will be in view.
  7899. * @param {Number} near The distance to the near plane in meters.
  7900. * @param {Number} far The distance to the far plane in meters.
  7901. * @param {Matrix4} result The object in which the result will be stored.
  7902. * @returns {Matrix4} The modified result parameter.
  7903. */
  7904. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  7905. if (!defined(left)) {
  7906. throw new DeveloperError('left is required.');
  7907. }
  7908. if (!defined(right)) {
  7909. throw new DeveloperError('right is required.');
  7910. }
  7911. if (!defined(bottom)) {
  7912. throw new DeveloperError('bottom is required.');
  7913. }
  7914. if (!defined(top)) {
  7915. throw new DeveloperError('top is required.');
  7916. }
  7917. if (!defined(near)) {
  7918. throw new DeveloperError('near is required.');
  7919. }
  7920. if (!defined(far)) {
  7921. throw new DeveloperError('far is required.');
  7922. }
  7923. if (!defined(result)) {
  7924. throw new DeveloperError('result is required');
  7925. }
  7926. var a = 1.0 / (right - left);
  7927. var b = 1.0 / (top - bottom);
  7928. var c = 1.0 / (far - near);
  7929. var tx = -(right + left) * a;
  7930. var ty = -(top + bottom) * b;
  7931. var tz = -(far + near) * c;
  7932. a *= 2.0;
  7933. b *= 2.0;
  7934. c *= -2.0;
  7935. result[0] = a;
  7936. result[1] = 0.0;
  7937. result[2] = 0.0;
  7938. result[3] = 0.0;
  7939. result[4] = 0.0;
  7940. result[5] = b;
  7941. result[6] = 0.0;
  7942. result[7] = 0.0;
  7943. result[8] = 0.0;
  7944. result[9] = 0.0;
  7945. result[10] = c;
  7946. result[11] = 0.0;
  7947. result[12] = tx;
  7948. result[13] = ty;
  7949. result[14] = tz;
  7950. result[15] = 1.0;
  7951. return result;
  7952. };
  7953. /**
  7954. * Computes a Matrix4 instance representing an off center perspective transformation.
  7955. *
  7956. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7957. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7958. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7959. * @param {Number} top The number of meters above of the camera that will be in view.
  7960. * @param {Number} near The distance to the near plane in meters.
  7961. * @param {Number} far The distance to the far plane in meters.
  7962. * @param {Matrix4} result The object in which the result will be stored.
  7963. * @returns {Matrix4} The modified result parameter.
  7964. */
  7965. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  7966. if (!defined(left)) {
  7967. throw new DeveloperError('left is required.');
  7968. }
  7969. if (!defined(right)) {
  7970. throw new DeveloperError('right is required.');
  7971. }
  7972. if (!defined(bottom)) {
  7973. throw new DeveloperError('bottom is required.');
  7974. }
  7975. if (!defined(top)) {
  7976. throw new DeveloperError('top is required.');
  7977. }
  7978. if (!defined(near)) {
  7979. throw new DeveloperError('near is required.');
  7980. }
  7981. if (!defined(far)) {
  7982. throw new DeveloperError('far is required.');
  7983. }
  7984. if (!defined(result)) {
  7985. throw new DeveloperError('result is required');
  7986. }
  7987. var column0Row0 = 2.0 * near / (right - left);
  7988. var column1Row1 = 2.0 * near / (top - bottom);
  7989. var column2Row0 = (right + left) / (right - left);
  7990. var column2Row1 = (top + bottom) / (top - bottom);
  7991. var column2Row2 = -(far + near) / (far - near);
  7992. var column2Row3 = -1.0;
  7993. var column3Row2 = -2.0 * far * near / (far - near);
  7994. result[0] = column0Row0;
  7995. result[1] = 0.0;
  7996. result[2] = 0.0;
  7997. result[3] = 0.0;
  7998. result[4] = 0.0;
  7999. result[5] = column1Row1;
  8000. result[6] = 0.0;
  8001. result[7] = 0.0;
  8002. result[8] = column2Row0;
  8003. result[9] = column2Row1;
  8004. result[10] = column2Row2;
  8005. result[11] = column2Row3;
  8006. result[12] = 0.0;
  8007. result[13] = 0.0;
  8008. result[14] = column3Row2;
  8009. result[15] = 0.0;
  8010. return result;
  8011. };
  8012. /**
  8013. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  8014. *
  8015. * @param {Number} left The number of meters to the left of the camera that will be in view.
  8016. * @param {Number} right The number of meters to the right of the camera that will be in view.
  8017. * @param {Number} bottom The number of meters below of the camera that will be in view.
  8018. * @param {Number} top The number of meters above of the camera that will be in view.
  8019. * @param {Number} near The distance to the near plane in meters.
  8020. * @param {Matrix4} result The object in which the result will be stored.
  8021. * @returns {Matrix4} The modified result parameter.
  8022. */
  8023. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  8024. if (!defined(left)) {
  8025. throw new DeveloperError('left is required.');
  8026. }
  8027. if (!defined(right)) {
  8028. throw new DeveloperError('right is required.');
  8029. }
  8030. if (!defined(bottom)) {
  8031. throw new DeveloperError('bottom is required.');
  8032. }
  8033. if (!defined(top)) {
  8034. throw new DeveloperError('top is required.');
  8035. }
  8036. if (!defined(near)) {
  8037. throw new DeveloperError('near is required.');
  8038. }
  8039. if (!defined(result)) {
  8040. throw new DeveloperError('result is required');
  8041. }
  8042. var column0Row0 = 2.0 * near / (right - left);
  8043. var column1Row1 = 2.0 * near / (top - bottom);
  8044. var column2Row0 = (right + left) / (right - left);
  8045. var column2Row1 = (top + bottom) / (top - bottom);
  8046. var column2Row2 = -1.0;
  8047. var column2Row3 = -1.0;
  8048. var column3Row2 = -2.0 * near;
  8049. result[0] = column0Row0;
  8050. result[1] = 0.0;
  8051. result[2] = 0.0;
  8052. result[3] = 0.0;
  8053. result[4] = 0.0;
  8054. result[5] = column1Row1;
  8055. result[6] = 0.0;
  8056. result[7] = 0.0;
  8057. result[8] = column2Row0;
  8058. result[9] = column2Row1;
  8059. result[10] = column2Row2;
  8060. result[11] = column2Row3;
  8061. result[12] = 0.0;
  8062. result[13] = 0.0;
  8063. result[14] = column3Row2;
  8064. result[15] = 0.0;
  8065. return result;
  8066. };
  8067. /**
  8068. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  8069. *
  8070. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  8071. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  8072. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  8073. * @param {Matrix4} result The object in which the result will be stored.
  8074. * @returns {Matrix4} The modified result parameter.
  8075. *
  8076. * @example
  8077. * // Create viewport transformation using an explicit viewport and depth range.
  8078. * var m = Cesium.Matrix4.computeViewportTransformation({
  8079. * x : 0.0,
  8080. * y : 0.0,
  8081. * width : 1024.0,
  8082. * height : 768.0
  8083. * }, 0.0, 1.0, new Cesium.Matrix4());
  8084. */
  8085. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  8086. if (!defined(result)) {
  8087. throw new DeveloperError('result is required');
  8088. }
  8089. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  8090. var x = defaultValue(viewport.x, 0.0);
  8091. var y = defaultValue(viewport.y, 0.0);
  8092. var width = defaultValue(viewport.width, 0.0);
  8093. var height = defaultValue(viewport.height, 0.0);
  8094. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  8095. farDepthRange = defaultValue(farDepthRange, 1.0);
  8096. var halfWidth = width * 0.5;
  8097. var halfHeight = height * 0.5;
  8098. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  8099. var column0Row0 = halfWidth;
  8100. var column1Row1 = halfHeight;
  8101. var column2Row2 = halfDepth;
  8102. var column3Row0 = x + halfWidth;
  8103. var column3Row1 = y + halfHeight;
  8104. var column3Row2 = nearDepthRange + halfDepth;
  8105. var column3Row3 = 1.0;
  8106. result[0] = column0Row0;
  8107. result[1] = 0.0;
  8108. result[2] = 0.0;
  8109. result[3] = 0.0;
  8110. result[4] = 0.0;
  8111. result[5] = column1Row1;
  8112. result[6] = 0.0;
  8113. result[7] = 0.0;
  8114. result[8] = 0.0;
  8115. result[9] = 0.0;
  8116. result[10] = column2Row2;
  8117. result[11] = 0.0;
  8118. result[12] = column3Row0;
  8119. result[13] = column3Row1;
  8120. result[14] = column3Row2;
  8121. result[15] = column3Row3;
  8122. return result;
  8123. };
  8124. /**
  8125. * Computes a Matrix4 instance that transforms from world space to view space.
  8126. *
  8127. * @param {Cartesian3} position The position of the camera.
  8128. * @param {Cartesian3} direction The forward direction.
  8129. * @param {Cartesian3} up The up direction.
  8130. * @param {Cartesian3} right The right direction.
  8131. * @param {Matrix4} result The object in which the result will be stored.
  8132. * @returns {Matrix4} The modified result parameter.
  8133. */
  8134. Matrix4.computeView = function(position, direction, up, right, result) {
  8135. if (!defined(position)) {
  8136. throw new DeveloperError('position is required');
  8137. }
  8138. if (!defined(direction)) {
  8139. throw new DeveloperError('direction is required');
  8140. }
  8141. if (!defined(up)) {
  8142. throw new DeveloperError('up is required');
  8143. }
  8144. if (!defined(right)) {
  8145. throw new DeveloperError('right is required');
  8146. }
  8147. if (!defined(result)) {
  8148. throw new DeveloperError('result is required');
  8149. }
  8150. result[0] = right.x;
  8151. result[1] = up.x;
  8152. result[2] = -direction.x;
  8153. result[3] = 0.0;
  8154. result[4] = right.y;
  8155. result[5] = up.y;
  8156. result[6] = -direction.y;
  8157. result[7] = 0.0;
  8158. result[8] = right.z;
  8159. result[9] = up.z;
  8160. result[10] = -direction.z;
  8161. result[11] = 0.0;
  8162. result[12] = -Cartesian3.dot(right, position);
  8163. result[13] = -Cartesian3.dot(up, position);
  8164. result[14] = Cartesian3.dot(direction, position);
  8165. result[15] = 1.0;
  8166. return result;
  8167. };
  8168. /**
  8169. * Computes an Array from the provided Matrix4 instance.
  8170. * The array will be in column-major order.
  8171. *
  8172. * @param {Matrix4} matrix The matrix to use..
  8173. * @param {Number[]} [result] The Array onto which to store the result.
  8174. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  8175. *
  8176. * @example
  8177. * //create an array from an instance of Matrix4
  8178. * // m = [10.0, 14.0, 18.0, 22.0]
  8179. * // [11.0, 15.0, 19.0, 23.0]
  8180. * // [12.0, 16.0, 20.0, 24.0]
  8181. * // [13.0, 17.0, 21.0, 25.0]
  8182. * var a = Cesium.Matrix4.toArray(m);
  8183. *
  8184. * // m remains the same
  8185. * //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]
  8186. */
  8187. Matrix4.toArray = function(matrix, result) {
  8188. if (!defined(matrix)) {
  8189. throw new DeveloperError('matrix is required');
  8190. }
  8191. if (!defined(result)) {
  8192. return [matrix[0], matrix[1], matrix[2], matrix[3],
  8193. matrix[4], matrix[5], matrix[6], matrix[7],
  8194. matrix[8], matrix[9], matrix[10], matrix[11],
  8195. matrix[12], matrix[13], matrix[14], matrix[15]];
  8196. }
  8197. result[0] = matrix[0];
  8198. result[1] = matrix[1];
  8199. result[2] = matrix[2];
  8200. result[3] = matrix[3];
  8201. result[4] = matrix[4];
  8202. result[5] = matrix[5];
  8203. result[6] = matrix[6];
  8204. result[7] = matrix[7];
  8205. result[8] = matrix[8];
  8206. result[9] = matrix[9];
  8207. result[10] = matrix[10];
  8208. result[11] = matrix[11];
  8209. result[12] = matrix[12];
  8210. result[13] = matrix[13];
  8211. result[14] = matrix[14];
  8212. result[15] = matrix[15];
  8213. return result;
  8214. };
  8215. /**
  8216. * Computes the array index of the element at the provided row and column.
  8217. *
  8218. * @param {Number} row The zero-based index of the row.
  8219. * @param {Number} column The zero-based index of the column.
  8220. * @returns {Number} The index of the element at the provided row and column.
  8221. *
  8222. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  8223. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  8224. *
  8225. * @example
  8226. * var myMatrix = new Cesium.Matrix4();
  8227. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  8228. * var column1Row0 = myMatrix[column1Row0Index];
  8229. * myMatrix[column1Row0Index] = 10.0;
  8230. */
  8231. Matrix4.getElementIndex = function(column, row) {
  8232. if (typeof row !== 'number' || row < 0 || row > 3) {
  8233. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  8234. }
  8235. if (typeof column !== 'number' || column < 0 || column > 3) {
  8236. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  8237. }
  8238. return column * 4 + row;
  8239. };
  8240. /**
  8241. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  8242. *
  8243. * @param {Matrix4} matrix The matrix to use.
  8244. * @param {Number} index The zero-based index of the column to retrieve.
  8245. * @param {Cartesian4} result The object onto which to store the result.
  8246. * @returns {Cartesian4} The modified result parameter.
  8247. *
  8248. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8249. *
  8250. * @example
  8251. * //returns a Cartesian4 instance with values from the specified column
  8252. * // m = [10.0, 11.0, 12.0, 13.0]
  8253. * // [14.0, 15.0, 16.0, 17.0]
  8254. * // [18.0, 19.0, 20.0, 21.0]
  8255. * // [22.0, 23.0, 24.0, 25.0]
  8256. *
  8257. * //Example 1: Creates an instance of Cartesian
  8258. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  8259. *
  8260. * @example
  8261. * //Example 2: Sets values for Cartesian instance
  8262. * var a = new Cesium.Cartesian4();
  8263. * Cesium.Matrix4.getColumn(m, 2, a);
  8264. *
  8265. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  8266. */
  8267. Matrix4.getColumn = function(matrix, index, result) {
  8268. if (!defined(matrix)) {
  8269. throw new DeveloperError('matrix is required.');
  8270. }
  8271. if (typeof index !== 'number' || index < 0 || index > 3) {
  8272. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8273. }
  8274. if (!defined(result)) {
  8275. throw new DeveloperError('result is required');
  8276. }
  8277. var startIndex = index * 4;
  8278. var x = matrix[startIndex];
  8279. var y = matrix[startIndex + 1];
  8280. var z = matrix[startIndex + 2];
  8281. var w = matrix[startIndex + 3];
  8282. result.x = x;
  8283. result.y = y;
  8284. result.z = z;
  8285. result.w = w;
  8286. return result;
  8287. };
  8288. /**
  8289. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  8290. *
  8291. * @param {Matrix4} matrix The matrix to use.
  8292. * @param {Number} index The zero-based index of the column to set.
  8293. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  8294. * @param {Matrix4} result The object onto which to store the result.
  8295. * @returns {Matrix4} The modified result parameter.
  8296. *
  8297. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8298. *
  8299. * @example
  8300. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  8301. * // m = [10.0, 11.0, 12.0, 13.0]
  8302. * // [14.0, 15.0, 16.0, 17.0]
  8303. * // [18.0, 19.0, 20.0, 21.0]
  8304. * // [22.0, 23.0, 24.0, 25.0]
  8305. *
  8306. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  8307. *
  8308. * // m remains the same
  8309. * // a = [10.0, 11.0, 99.0, 13.0]
  8310. * // [14.0, 15.0, 98.0, 17.0]
  8311. * // [18.0, 19.0, 97.0, 21.0]
  8312. * // [22.0, 23.0, 96.0, 25.0]
  8313. */
  8314. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  8315. if (!defined(matrix)) {
  8316. throw new DeveloperError('matrix is required');
  8317. }
  8318. if (!defined(cartesian)) {
  8319. throw new DeveloperError('cartesian is required');
  8320. }
  8321. if (typeof index !== 'number' || index < 0 || index > 3) {
  8322. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8323. }
  8324. if (!defined(result)) {
  8325. throw new DeveloperError('result is required');
  8326. }
  8327. result = Matrix4.clone(matrix, result);
  8328. var startIndex = index * 4;
  8329. result[startIndex] = cartesian.x;
  8330. result[startIndex + 1] = cartesian.y;
  8331. result[startIndex + 2] = cartesian.z;
  8332. result[startIndex + 3] = cartesian.w;
  8333. return result;
  8334. };
  8335. /**
  8336. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  8337. * matrix with the provided translation. This assumes the matrix is an affine transformation
  8338. *
  8339. * @param {Matrix4} matrix The matrix to use.
  8340. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  8341. * @param {Cartesian4} result The object onto which to store the result.
  8342. * @returns {Matrix4} The modified result parameter.
  8343. */
  8344. Matrix4.setTranslation = function(matrix, translation, result) {
  8345. if (!defined(matrix)) {
  8346. throw new DeveloperError('matrix is required');
  8347. }
  8348. if (!defined(translation)) {
  8349. throw new DeveloperError('translation is required');
  8350. }
  8351. if (!defined(result)) {
  8352. throw new DeveloperError('result is required');
  8353. }
  8354. result[0] = matrix[0];
  8355. result[1] = matrix[1];
  8356. result[2] = matrix[2];
  8357. result[3] = matrix[3];
  8358. result[4] = matrix[4];
  8359. result[5] = matrix[5];
  8360. result[6] = matrix[6];
  8361. result[7] = matrix[7];
  8362. result[8] = matrix[8];
  8363. result[9] = matrix[9];
  8364. result[10] = matrix[10];
  8365. result[11] = matrix[11];
  8366. result[12] = translation.x;
  8367. result[13] = translation.y;
  8368. result[14] = translation.z;
  8369. result[15] = matrix[15];
  8370. return result;
  8371. };
  8372. /**
  8373. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  8374. *
  8375. * @param {Matrix4} matrix The matrix to use.
  8376. * @param {Number} index The zero-based index of the row to retrieve.
  8377. * @param {Cartesian4} result The object onto which to store the result.
  8378. * @returns {Cartesian4} The modified result parameter.
  8379. *
  8380. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8381. *
  8382. * @example
  8383. * //returns a Cartesian4 instance with values from the specified column
  8384. * // m = [10.0, 11.0, 12.0, 13.0]
  8385. * // [14.0, 15.0, 16.0, 17.0]
  8386. * // [18.0, 19.0, 20.0, 21.0]
  8387. * // [22.0, 23.0, 24.0, 25.0]
  8388. *
  8389. * //Example 1: Returns an instance of Cartesian
  8390. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  8391. *
  8392. * @example
  8393. * //Example 2: Sets values for a Cartesian instance
  8394. * var a = new Cesium.Cartesian4();
  8395. * Cesium.Matrix4.getRow(m, 2, a);
  8396. *
  8397. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  8398. */
  8399. Matrix4.getRow = function(matrix, index, result) {
  8400. if (!defined(matrix)) {
  8401. throw new DeveloperError('matrix is required.');
  8402. }
  8403. if (typeof index !== 'number' || index < 0 || index > 3) {
  8404. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8405. }
  8406. if (!defined(result)) {
  8407. throw new DeveloperError('result is required');
  8408. }
  8409. var x = matrix[index];
  8410. var y = matrix[index + 4];
  8411. var z = matrix[index + 8];
  8412. var w = matrix[index + 12];
  8413. result.x = x;
  8414. result.y = y;
  8415. result.z = z;
  8416. result.w = w;
  8417. return result;
  8418. };
  8419. /**
  8420. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  8421. *
  8422. * @param {Matrix4} matrix The matrix to use.
  8423. * @param {Number} index The zero-based index of the row to set.
  8424. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  8425. * @param {Matrix4} result The object onto which to store the result.
  8426. * @returns {Matrix4} The modified result parameter.
  8427. *
  8428. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8429. *
  8430. * @example
  8431. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  8432. * // m = [10.0, 11.0, 12.0, 13.0]
  8433. * // [14.0, 15.0, 16.0, 17.0]
  8434. * // [18.0, 19.0, 20.0, 21.0]
  8435. * // [22.0, 23.0, 24.0, 25.0]
  8436. *
  8437. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  8438. *
  8439. * // m remains the same
  8440. * // a = [10.0, 11.0, 12.0, 13.0]
  8441. * // [14.0, 15.0, 16.0, 17.0]
  8442. * // [99.0, 98.0, 97.0, 96.0]
  8443. * // [22.0, 23.0, 24.0, 25.0]
  8444. */
  8445. Matrix4.setRow = function(matrix, index, cartesian, result) {
  8446. if (!defined(matrix)) {
  8447. throw new DeveloperError('matrix is required');
  8448. }
  8449. if (!defined(cartesian)) {
  8450. throw new DeveloperError('cartesian is required');
  8451. }
  8452. if (typeof index !== 'number' || index < 0 || index > 3) {
  8453. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8454. }
  8455. if (!defined(result)) {
  8456. throw new DeveloperError('result is required');
  8457. }
  8458. result = Matrix4.clone(matrix, result);
  8459. result[index] = cartesian.x;
  8460. result[index + 4] = cartesian.y;
  8461. result[index + 8] = cartesian.z;
  8462. result[index + 12] = cartesian.w;
  8463. return result;
  8464. };
  8465. var scratchColumn = new Cartesian3();
  8466. /**
  8467. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  8468. *
  8469. * @param {Matrix4} matrix The matrix.
  8470. * @param {Cartesian3} result The object onto which to store the result.
  8471. * @returns {Cartesian3} The modified result parameter
  8472. */
  8473. Matrix4.getScale = function(matrix, result) {
  8474. if (!defined(matrix)) {
  8475. throw new DeveloperError('matrix is required.');
  8476. }
  8477. if (!defined(result)) {
  8478. throw new DeveloperError('result is required');
  8479. }
  8480. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  8481. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  8482. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  8483. return result;
  8484. };
  8485. var scratchScale = new Cartesian3();
  8486. /**
  8487. * Computes the maximum scale assuming the matrix is an affine transformation.
  8488. * The maximum scale is the maximum length of the column vectors in the upper-left
  8489. * 3x3 matrix.
  8490. *
  8491. * @param {Matrix4} matrix The matrix.
  8492. * @returns {Number} The maximum scale.
  8493. */
  8494. Matrix4.getMaximumScale = function(matrix) {
  8495. Matrix4.getScale(matrix, scratchScale);
  8496. return Cartesian3.maximumComponent(scratchScale);
  8497. };
  8498. /**
  8499. * Computes the product of two matrices.
  8500. *
  8501. * @param {Matrix4} left The first matrix.
  8502. * @param {Matrix4} right The second matrix.
  8503. * @param {Matrix4} result The object onto which to store the result.
  8504. * @returns {Matrix4} The modified result parameter.
  8505. */
  8506. Matrix4.multiply = function(left, right, result) {
  8507. if (!defined(left)) {
  8508. throw new DeveloperError('left is required');
  8509. }
  8510. if (!defined(right)) {
  8511. throw new DeveloperError('right is required');
  8512. }
  8513. if (!defined(result)) {
  8514. throw new DeveloperError('result is required');
  8515. }
  8516. var left0 = left[0];
  8517. var left1 = left[1];
  8518. var left2 = left[2];
  8519. var left3 = left[3];
  8520. var left4 = left[4];
  8521. var left5 = left[5];
  8522. var left6 = left[6];
  8523. var left7 = left[7];
  8524. var left8 = left[8];
  8525. var left9 = left[9];
  8526. var left10 = left[10];
  8527. var left11 = left[11];
  8528. var left12 = left[12];
  8529. var left13 = left[13];
  8530. var left14 = left[14];
  8531. var left15 = left[15];
  8532. var right0 = right[0];
  8533. var right1 = right[1];
  8534. var right2 = right[2];
  8535. var right3 = right[3];
  8536. var right4 = right[4];
  8537. var right5 = right[5];
  8538. var right6 = right[6];
  8539. var right7 = right[7];
  8540. var right8 = right[8];
  8541. var right9 = right[9];
  8542. var right10 = right[10];
  8543. var right11 = right[11];
  8544. var right12 = right[12];
  8545. var right13 = right[13];
  8546. var right14 = right[14];
  8547. var right15 = right[15];
  8548. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  8549. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  8550. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  8551. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  8552. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  8553. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  8554. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  8555. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  8556. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  8557. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  8558. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  8559. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  8560. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  8561. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  8562. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  8563. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  8564. result[0] = column0Row0;
  8565. result[1] = column0Row1;
  8566. result[2] = column0Row2;
  8567. result[3] = column0Row3;
  8568. result[4] = column1Row0;
  8569. result[5] = column1Row1;
  8570. result[6] = column1Row2;
  8571. result[7] = column1Row3;
  8572. result[8] = column2Row0;
  8573. result[9] = column2Row1;
  8574. result[10] = column2Row2;
  8575. result[11] = column2Row3;
  8576. result[12] = column3Row0;
  8577. result[13] = column3Row1;
  8578. result[14] = column3Row2;
  8579. result[15] = column3Row3;
  8580. return result;
  8581. };
  8582. /**
  8583. * Computes the sum of two matrices.
  8584. *
  8585. * @param {Matrix4} left The first matrix.
  8586. * @param {Matrix4} right The second matrix.
  8587. * @param {Matrix4} result The object onto which to store the result.
  8588. * @returns {Matrix4} The modified result parameter.
  8589. */
  8590. Matrix4.add = function(left, right, result) {
  8591. if (!defined(left)) {
  8592. throw new DeveloperError('left is required');
  8593. }
  8594. if (!defined(right)) {
  8595. throw new DeveloperError('right is required');
  8596. }
  8597. if (!defined(result)) {
  8598. throw new DeveloperError('result is required');
  8599. }
  8600. result[0] = left[0] + right[0];
  8601. result[1] = left[1] + right[1];
  8602. result[2] = left[2] + right[2];
  8603. result[3] = left[3] + right[3];
  8604. result[4] = left[4] + right[4];
  8605. result[5] = left[5] + right[5];
  8606. result[6] = left[6] + right[6];
  8607. result[7] = left[7] + right[7];
  8608. result[8] = left[8] + right[8];
  8609. result[9] = left[9] + right[9];
  8610. result[10] = left[10] + right[10];
  8611. result[11] = left[11] + right[11];
  8612. result[12] = left[12] + right[12];
  8613. result[13] = left[13] + right[13];
  8614. result[14] = left[14] + right[14];
  8615. result[15] = left[15] + right[15];
  8616. return result;
  8617. };
  8618. /**
  8619. * Computes the difference of two matrices.
  8620. *
  8621. * @param {Matrix4} left The first matrix.
  8622. * @param {Matrix4} right The second matrix.
  8623. * @param {Matrix4} result The object onto which to store the result.
  8624. * @returns {Matrix4} The modified result parameter.
  8625. */
  8626. Matrix4.subtract = function(left, right, result) {
  8627. if (!defined(left)) {
  8628. throw new DeveloperError('left is required');
  8629. }
  8630. if (!defined(right)) {
  8631. throw new DeveloperError('right is required');
  8632. }
  8633. if (!defined(result)) {
  8634. throw new DeveloperError('result is required');
  8635. }
  8636. result[0] = left[0] - right[0];
  8637. result[1] = left[1] - right[1];
  8638. result[2] = left[2] - right[2];
  8639. result[3] = left[3] - right[3];
  8640. result[4] = left[4] - right[4];
  8641. result[5] = left[5] - right[5];
  8642. result[6] = left[6] - right[6];
  8643. result[7] = left[7] - right[7];
  8644. result[8] = left[8] - right[8];
  8645. result[9] = left[9] - right[9];
  8646. result[10] = left[10] - right[10];
  8647. result[11] = left[11] - right[11];
  8648. result[12] = left[12] - right[12];
  8649. result[13] = left[13] - right[13];
  8650. result[14] = left[14] - right[14];
  8651. result[15] = left[15] - right[15];
  8652. return result;
  8653. };
  8654. /**
  8655. * Computes the product of two matrices assuming the matrices are
  8656. * affine transformation matrices, where the upper left 3x3 elements
  8657. * are a rotation matrix, and the upper three elements in the fourth
  8658. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  8659. * The matrix is not verified to be in the proper form.
  8660. * This method is faster than computing the product for general 4x4
  8661. * matrices using {@link Matrix4.multiply}.
  8662. *
  8663. * @param {Matrix4} left The first matrix.
  8664. * @param {Matrix4} right The second matrix.
  8665. * @param {Matrix4} result The object onto which to store the result.
  8666. * @returns {Matrix4} The modified result parameter.
  8667. *
  8668. * @example
  8669. * 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);
  8670. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  8671. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  8672. */
  8673. Matrix4.multiplyTransformation = function(left, right, result) {
  8674. if (!defined(left)) {
  8675. throw new DeveloperError('left is required');
  8676. }
  8677. if (!defined(right)) {
  8678. throw new DeveloperError('right is required');
  8679. }
  8680. if (!defined(result)) {
  8681. throw new DeveloperError('result is required');
  8682. }
  8683. var left0 = left[0];
  8684. var left1 = left[1];
  8685. var left2 = left[2];
  8686. var left4 = left[4];
  8687. var left5 = left[5];
  8688. var left6 = left[6];
  8689. var left8 = left[8];
  8690. var left9 = left[9];
  8691. var left10 = left[10];
  8692. var left12 = left[12];
  8693. var left13 = left[13];
  8694. var left14 = left[14];
  8695. var right0 = right[0];
  8696. var right1 = right[1];
  8697. var right2 = right[2];
  8698. var right4 = right[4];
  8699. var right5 = right[5];
  8700. var right6 = right[6];
  8701. var right8 = right[8];
  8702. var right9 = right[9];
  8703. var right10 = right[10];
  8704. var right12 = right[12];
  8705. var right13 = right[13];
  8706. var right14 = right[14];
  8707. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8708. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8709. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8710. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8711. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8712. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8713. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8714. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8715. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8716. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  8717. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  8718. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  8719. result[0] = column0Row0;
  8720. result[1] = column0Row1;
  8721. result[2] = column0Row2;
  8722. result[3] = 0.0;
  8723. result[4] = column1Row0;
  8724. result[5] = column1Row1;
  8725. result[6] = column1Row2;
  8726. result[7] = 0.0;
  8727. result[8] = column2Row0;
  8728. result[9] = column2Row1;
  8729. result[10] = column2Row2;
  8730. result[11] = 0.0;
  8731. result[12] = column3Row0;
  8732. result[13] = column3Row1;
  8733. result[14] = column3Row2;
  8734. result[15] = 1.0;
  8735. return result;
  8736. };
  8737. /**
  8738. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8739. * by a 3x3 rotation matrix. This is an optimization
  8740. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  8741. *
  8742. * @param {Matrix4} matrix The matrix on the left-hand side.
  8743. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  8744. * @param {Matrix4} result The object onto which to store the result.
  8745. * @returns {Matrix4} The modified result parameter.
  8746. *
  8747. * @example
  8748. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  8749. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  8750. */
  8751. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  8752. if (!defined(matrix)) {
  8753. throw new DeveloperError('matrix is required');
  8754. }
  8755. if (!defined(rotation)) {
  8756. throw new DeveloperError('rotation is required');
  8757. }
  8758. if (!defined(result)) {
  8759. throw new DeveloperError('result is required');
  8760. }
  8761. var left0 = matrix[0];
  8762. var left1 = matrix[1];
  8763. var left2 = matrix[2];
  8764. var left4 = matrix[4];
  8765. var left5 = matrix[5];
  8766. var left6 = matrix[6];
  8767. var left8 = matrix[8];
  8768. var left9 = matrix[9];
  8769. var left10 = matrix[10];
  8770. var right0 = rotation[0];
  8771. var right1 = rotation[1];
  8772. var right2 = rotation[2];
  8773. var right4 = rotation[3];
  8774. var right5 = rotation[4];
  8775. var right6 = rotation[5];
  8776. var right8 = rotation[6];
  8777. var right9 = rotation[7];
  8778. var right10 = rotation[8];
  8779. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8780. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8781. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8782. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8783. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8784. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8785. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8786. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8787. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8788. result[0] = column0Row0;
  8789. result[1] = column0Row1;
  8790. result[2] = column0Row2;
  8791. result[3] = 0.0;
  8792. result[4] = column1Row0;
  8793. result[5] = column1Row1;
  8794. result[6] = column1Row2;
  8795. result[7] = 0.0;
  8796. result[8] = column2Row0;
  8797. result[9] = column2Row1;
  8798. result[10] = column2Row2;
  8799. result[11] = 0.0;
  8800. result[12] = matrix[12];
  8801. result[13] = matrix[13];
  8802. result[14] = matrix[14];
  8803. result[15] = matrix[15];
  8804. return result;
  8805. };
  8806. /**
  8807. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8808. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  8809. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  8810. *
  8811. * @param {Matrix4} matrix The matrix on the left-hand side.
  8812. * @param {Cartesian3} translation The translation on the right-hand side.
  8813. * @param {Matrix4} result The object onto which to store the result.
  8814. * @returns {Matrix4} The modified result parameter.
  8815. *
  8816. * @example
  8817. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  8818. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  8819. */
  8820. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  8821. if (!defined(matrix)) {
  8822. throw new DeveloperError('matrix is required');
  8823. }
  8824. if (!defined(translation)) {
  8825. throw new DeveloperError('translation is required');
  8826. }
  8827. if (!defined(result)) {
  8828. throw new DeveloperError('result is required');
  8829. }
  8830. var x = translation.x;
  8831. var y = translation.y;
  8832. var z = translation.z;
  8833. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  8834. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  8835. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  8836. result[0] = matrix[0];
  8837. result[1] = matrix[1];
  8838. result[2] = matrix[2];
  8839. result[3] = matrix[3];
  8840. result[4] = matrix[4];
  8841. result[5] = matrix[5];
  8842. result[6] = matrix[6];
  8843. result[7] = matrix[7];
  8844. result[8] = matrix[8];
  8845. result[9] = matrix[9];
  8846. result[10] = matrix[10];
  8847. result[11] = matrix[11];
  8848. result[12] = tx;
  8849. result[13] = ty;
  8850. result[14] = tz;
  8851. result[15] = matrix[15];
  8852. return result;
  8853. };
  8854. var uniformScaleScratch = new Cartesian3();
  8855. /**
  8856. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8857. * by an implicit uniform scale matrix. This is an optimization
  8858. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8859. * <code>m</code> must be an affine matrix.
  8860. * This function performs fewer allocations and arithmetic operations.
  8861. *
  8862. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8863. * @param {Number} scale The uniform scale on the right-hand side.
  8864. * @param {Matrix4} result The object onto which to store the result.
  8865. * @returns {Matrix4} The modified result parameter.
  8866. *
  8867. *
  8868. * @example
  8869. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  8870. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  8871. *
  8872. * @see Matrix4.fromUniformScale
  8873. * @see Matrix4.multiplyByScale
  8874. */
  8875. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  8876. if (!defined(matrix)) {
  8877. throw new DeveloperError('matrix is required');
  8878. }
  8879. if (typeof scale !== 'number') {
  8880. throw new DeveloperError('scale is required');
  8881. }
  8882. if (!defined(result)) {
  8883. throw new DeveloperError('result is required');
  8884. }
  8885. uniformScaleScratch.x = scale;
  8886. uniformScaleScratch.y = scale;
  8887. uniformScaleScratch.z = scale;
  8888. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  8889. };
  8890. /**
  8891. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8892. * by an implicit non-uniform scale matrix. This is an optimization
  8893. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8894. * <code>m</code> must be an affine matrix.
  8895. * This function performs fewer allocations and arithmetic operations.
  8896. *
  8897. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8898. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  8899. * @param {Matrix4} result The object onto which to store the result.
  8900. * @returns {Matrix4} The modified result parameter.
  8901. *
  8902. *
  8903. * @example
  8904. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  8905. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  8906. *
  8907. * @see Matrix4.fromScale
  8908. * @see Matrix4.multiplyByUniformScale
  8909. */
  8910. Matrix4.multiplyByScale = function(matrix, scale, result) {
  8911. if (!defined(matrix)) {
  8912. throw new DeveloperError('matrix is required');
  8913. }
  8914. if (!defined(scale)) {
  8915. throw new DeveloperError('scale is required');
  8916. }
  8917. if (!defined(result)) {
  8918. throw new DeveloperError('result is required');
  8919. }
  8920. var scaleX = scale.x;
  8921. var scaleY = scale.y;
  8922. var scaleZ = scale.z;
  8923. // Faster than Cartesian3.equals
  8924. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  8925. return Matrix4.clone(matrix, result);
  8926. }
  8927. result[0] = scaleX * matrix[0];
  8928. result[1] = scaleX * matrix[1];
  8929. result[2] = scaleX * matrix[2];
  8930. result[3] = 0.0;
  8931. result[4] = scaleY * matrix[4];
  8932. result[5] = scaleY * matrix[5];
  8933. result[6] = scaleY * matrix[6];
  8934. result[7] = 0.0;
  8935. result[8] = scaleZ * matrix[8];
  8936. result[9] = scaleZ * matrix[9];
  8937. result[10] = scaleZ * matrix[10];
  8938. result[11] = 0.0;
  8939. result[12] = matrix[12];
  8940. result[13] = matrix[13];
  8941. result[14] = matrix[14];
  8942. result[15] = 1.0;
  8943. return result;
  8944. };
  8945. /**
  8946. * Computes the product of a matrix and a column vector.
  8947. *
  8948. * @param {Matrix4} matrix The matrix.
  8949. * @param {Cartesian4} cartesian The vector.
  8950. * @param {Cartesian4} result The object onto which to store the result.
  8951. * @returns {Cartesian4} The modified result parameter.
  8952. */
  8953. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  8954. if (!defined(matrix)) {
  8955. throw new DeveloperError('matrix is required');
  8956. }
  8957. if (!defined(cartesian)) {
  8958. throw new DeveloperError('cartesian is required');
  8959. }
  8960. if (!defined(result)) {
  8961. throw new DeveloperError('result is required');
  8962. }
  8963. var vX = cartesian.x;
  8964. var vY = cartesian.y;
  8965. var vZ = cartesian.z;
  8966. var vW = cartesian.w;
  8967. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  8968. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  8969. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  8970. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  8971. result.x = x;
  8972. result.y = y;
  8973. result.z = z;
  8974. result.w = w;
  8975. return result;
  8976. };
  8977. /**
  8978. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  8979. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  8980. *
  8981. * @param {Matrix4} matrix The matrix.
  8982. * @param {Cartesian3} cartesian The point.
  8983. * @param {Cartesian3} result The object onto which to store the result.
  8984. * @returns {Cartesian3} The modified result parameter.
  8985. *
  8986. * @example
  8987. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  8988. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  8989. * // A shortcut for
  8990. * // Cartesian3 p = ...
  8991. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  8992. */
  8993. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  8994. if (!defined(matrix)) {
  8995. throw new DeveloperError('matrix is required');
  8996. }
  8997. if (!defined(cartesian)) {
  8998. throw new DeveloperError('cartesian is required');
  8999. }
  9000. if (!defined(result)) {
  9001. throw new DeveloperError('result is required');
  9002. }
  9003. var vX = cartesian.x;
  9004. var vY = cartesian.y;
  9005. var vZ = cartesian.z;
  9006. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  9007. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  9008. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  9009. result.x = x;
  9010. result.y = y;
  9011. result.z = z;
  9012. return result;
  9013. };
  9014. /**
  9015. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  9016. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  9017. *
  9018. * @param {Matrix4} matrix The matrix.
  9019. * @param {Cartesian3} cartesian The point.
  9020. * @param {Cartesian3} result The object onto which to store the result.
  9021. * @returns {Cartesian3} The modified result parameter.
  9022. *
  9023. * @example
  9024. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9025. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  9026. */
  9027. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  9028. if (!defined(matrix)) {
  9029. throw new DeveloperError('matrix is required');
  9030. }
  9031. if (!defined(cartesian)) {
  9032. throw new DeveloperError('cartesian is required');
  9033. }
  9034. if (!defined(result)) {
  9035. throw new DeveloperError('result is required');
  9036. }
  9037. var vX = cartesian.x;
  9038. var vY = cartesian.y;
  9039. var vZ = cartesian.z;
  9040. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  9041. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  9042. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  9043. result.x = x;
  9044. result.y = y;
  9045. result.z = z;
  9046. return result;
  9047. };
  9048. /**
  9049. * Computes the product of a matrix and a scalar.
  9050. *
  9051. * @param {Matrix4} matrix The matrix.
  9052. * @param {Number} scalar The number to multiply by.
  9053. * @param {Matrix4} result The object onto which to store the result.
  9054. * @returns {Matrix4} The modified result parameter.
  9055. *
  9056. * @example
  9057. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  9058. * // m = [10.0, 11.0, 12.0, 13.0]
  9059. * // [14.0, 15.0, 16.0, 17.0]
  9060. * // [18.0, 19.0, 20.0, 21.0]
  9061. * // [22.0, 23.0, 24.0, 25.0]
  9062. *
  9063. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  9064. *
  9065. * // m remains the same
  9066. * // a = [-20.0, -22.0, -24.0, -26.0]
  9067. * // [-28.0, -30.0, -32.0, -34.0]
  9068. * // [-36.0, -38.0, -40.0, -42.0]
  9069. * // [-44.0, -46.0, -48.0, -50.0]
  9070. */
  9071. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  9072. if (!defined(matrix)) {
  9073. throw new DeveloperError('matrix is required');
  9074. }
  9075. if (typeof scalar !== 'number') {
  9076. throw new DeveloperError('scalar must be a number');
  9077. }
  9078. if (!defined(result)) {
  9079. throw new DeveloperError('result is required');
  9080. }
  9081. result[0] = matrix[0] * scalar;
  9082. result[1] = matrix[1] * scalar;
  9083. result[2] = matrix[2] * scalar;
  9084. result[3] = matrix[3] * scalar;
  9085. result[4] = matrix[4] * scalar;
  9086. result[5] = matrix[5] * scalar;
  9087. result[6] = matrix[6] * scalar;
  9088. result[7] = matrix[7] * scalar;
  9089. result[8] = matrix[8] * scalar;
  9090. result[9] = matrix[9] * scalar;
  9091. result[10] = matrix[10] * scalar;
  9092. result[11] = matrix[11] * scalar;
  9093. result[12] = matrix[12] * scalar;
  9094. result[13] = matrix[13] * scalar;
  9095. result[14] = matrix[14] * scalar;
  9096. result[15] = matrix[15] * scalar;
  9097. return result;
  9098. };
  9099. /**
  9100. * Computes a negated copy of the provided matrix.
  9101. *
  9102. * @param {Matrix4} matrix The matrix to negate.
  9103. * @param {Matrix4} result The object onto which to store the result.
  9104. * @returns {Matrix4} The modified result parameter.
  9105. *
  9106. * @example
  9107. * //create a new Matrix4 instance which is a negation of a Matrix4
  9108. * // m = [10.0, 11.0, 12.0, 13.0]
  9109. * // [14.0, 15.0, 16.0, 17.0]
  9110. * // [18.0, 19.0, 20.0, 21.0]
  9111. * // [22.0, 23.0, 24.0, 25.0]
  9112. *
  9113. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  9114. *
  9115. * // m remains the same
  9116. * // a = [-10.0, -11.0, -12.0, -13.0]
  9117. * // [-14.0, -15.0, -16.0, -17.0]
  9118. * // [-18.0, -19.0, -20.0, -21.0]
  9119. * // [-22.0, -23.0, -24.0, -25.0]
  9120. */
  9121. Matrix4.negate = function(matrix, result) {
  9122. if (!defined(matrix)) {
  9123. throw new DeveloperError('matrix is required');
  9124. }
  9125. if (!defined(result)) {
  9126. throw new DeveloperError('result is required');
  9127. }
  9128. result[0] = -matrix[0];
  9129. result[1] = -matrix[1];
  9130. result[2] = -matrix[2];
  9131. result[3] = -matrix[3];
  9132. result[4] = -matrix[4];
  9133. result[5] = -matrix[5];
  9134. result[6] = -matrix[6];
  9135. result[7] = -matrix[7];
  9136. result[8] = -matrix[8];
  9137. result[9] = -matrix[9];
  9138. result[10] = -matrix[10];
  9139. result[11] = -matrix[11];
  9140. result[12] = -matrix[12];
  9141. result[13] = -matrix[13];
  9142. result[14] = -matrix[14];
  9143. result[15] = -matrix[15];
  9144. return result;
  9145. };
  9146. /**
  9147. * Computes the transpose of the provided matrix.
  9148. *
  9149. * @param {Matrix4} matrix The matrix to transpose.
  9150. * @param {Matrix4} result The object onto which to store the result.
  9151. * @returns {Matrix4} The modified result parameter.
  9152. *
  9153. * @example
  9154. * //returns transpose of a Matrix4
  9155. * // m = [10.0, 11.0, 12.0, 13.0]
  9156. * // [14.0, 15.0, 16.0, 17.0]
  9157. * // [18.0, 19.0, 20.0, 21.0]
  9158. * // [22.0, 23.0, 24.0, 25.0]
  9159. *
  9160. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  9161. *
  9162. * // m remains the same
  9163. * // a = [10.0, 14.0, 18.0, 22.0]
  9164. * // [11.0, 15.0, 19.0, 23.0]
  9165. * // [12.0, 16.0, 20.0, 24.0]
  9166. * // [13.0, 17.0, 21.0, 25.0]
  9167. */
  9168. Matrix4.transpose = function(matrix, result) {
  9169. if (!defined(matrix)) {
  9170. throw new DeveloperError('matrix is required');
  9171. }
  9172. if (!defined(result)) {
  9173. throw new DeveloperError('result is required');
  9174. }
  9175. var matrix1 = matrix[1];
  9176. var matrix2 = matrix[2];
  9177. var matrix3 = matrix[3];
  9178. var matrix6 = matrix[6];
  9179. var matrix7 = matrix[7];
  9180. var matrix11 = matrix[11];
  9181. result[0] = matrix[0];
  9182. result[1] = matrix[4];
  9183. result[2] = matrix[8];
  9184. result[3] = matrix[12];
  9185. result[4] = matrix1;
  9186. result[5] = matrix[5];
  9187. result[6] = matrix[9];
  9188. result[7] = matrix[13];
  9189. result[8] = matrix2;
  9190. result[9] = matrix6;
  9191. result[10] = matrix[10];
  9192. result[11] = matrix[14];
  9193. result[12] = matrix3;
  9194. result[13] = matrix7;
  9195. result[14] = matrix11;
  9196. result[15] = matrix[15];
  9197. return result;
  9198. };
  9199. /**
  9200. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  9201. *
  9202. * @param {Matrix4} matrix The matrix with signed elements.
  9203. * @param {Matrix4} result The object onto which to store the result.
  9204. * @returns {Matrix4} The modified result parameter.
  9205. */
  9206. Matrix4.abs = function(matrix, result) {
  9207. if (!defined(matrix)) {
  9208. throw new DeveloperError('matrix is required');
  9209. }
  9210. if (!defined(result)) {
  9211. throw new DeveloperError('result is required');
  9212. }
  9213. result[0] = Math.abs(matrix[0]);
  9214. result[1] = Math.abs(matrix[1]);
  9215. result[2] = Math.abs(matrix[2]);
  9216. result[3] = Math.abs(matrix[3]);
  9217. result[4] = Math.abs(matrix[4]);
  9218. result[5] = Math.abs(matrix[5]);
  9219. result[6] = Math.abs(matrix[6]);
  9220. result[7] = Math.abs(matrix[7]);
  9221. result[8] = Math.abs(matrix[8]);
  9222. result[9] = Math.abs(matrix[9]);
  9223. result[10] = Math.abs(matrix[10]);
  9224. result[11] = Math.abs(matrix[11]);
  9225. result[12] = Math.abs(matrix[12]);
  9226. result[13] = Math.abs(matrix[13]);
  9227. result[14] = Math.abs(matrix[14]);
  9228. result[15] = Math.abs(matrix[15]);
  9229. return result;
  9230. };
  9231. /**
  9232. * Compares the provided matrices componentwise and returns
  9233. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9234. *
  9235. * @param {Matrix4} [left] The first matrix.
  9236. * @param {Matrix4} [right] The second matrix.
  9237. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  9238. *
  9239. * @example
  9240. * //compares two Matrix4 instances
  9241. *
  9242. * // a = [10.0, 14.0, 18.0, 22.0]
  9243. * // [11.0, 15.0, 19.0, 23.0]
  9244. * // [12.0, 16.0, 20.0, 24.0]
  9245. * // [13.0, 17.0, 21.0, 25.0]
  9246. *
  9247. * // b = [10.0, 14.0, 18.0, 22.0]
  9248. * // [11.0, 15.0, 19.0, 23.0]
  9249. * // [12.0, 16.0, 20.0, 24.0]
  9250. * // [13.0, 17.0, 21.0, 25.0]
  9251. *
  9252. * if(Cesium.Matrix4.equals(a,b)) {
  9253. * console.log("Both matrices are equal");
  9254. * } else {
  9255. * console.log("They are not equal");
  9256. * }
  9257. *
  9258. * //Prints "Both matrices are equal" on the console
  9259. */
  9260. Matrix4.equals = function(left, right) {
  9261. // Given that most matrices will be transformation matrices, the elements
  9262. // are tested in order such that the test is likely to fail as early
  9263. // as possible. I _think_ this is just as friendly to the L1 cache
  9264. // as testing in index order. It is certainty faster in practice.
  9265. return (left === right) ||
  9266. (defined(left) &&
  9267. defined(right) &&
  9268. // Translation
  9269. left[12] === right[12] &&
  9270. left[13] === right[13] &&
  9271. left[14] === right[14] &&
  9272. // Rotation/scale
  9273. left[0] === right[0] &&
  9274. left[1] === right[1] &&
  9275. left[2] === right[2] &&
  9276. left[4] === right[4] &&
  9277. left[5] === right[5] &&
  9278. left[6] === right[6] &&
  9279. left[8] === right[8] &&
  9280. left[9] === right[9] &&
  9281. left[10] === right[10] &&
  9282. // Bottom row
  9283. left[3] === right[3] &&
  9284. left[7] === right[7] &&
  9285. left[11] === right[11] &&
  9286. left[15] === right[15]);
  9287. };
  9288. /**
  9289. * Compares the provided matrices componentwise and returns
  9290. * <code>true</code> if they are within the provided epsilon,
  9291. * <code>false</code> otherwise.
  9292. *
  9293. * @param {Matrix4} [left] The first matrix.
  9294. * @param {Matrix4} [right] The second matrix.
  9295. * @param {Number} epsilon The epsilon to use for equality testing.
  9296. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  9297. *
  9298. * @example
  9299. * //compares two Matrix4 instances
  9300. *
  9301. * // a = [10.5, 14.5, 18.5, 22.5]
  9302. * // [11.5, 15.5, 19.5, 23.5]
  9303. * // [12.5, 16.5, 20.5, 24.5]
  9304. * // [13.5, 17.5, 21.5, 25.5]
  9305. *
  9306. * // b = [10.0, 14.0, 18.0, 22.0]
  9307. * // [11.0, 15.0, 19.0, 23.0]
  9308. * // [12.0, 16.0, 20.0, 24.0]
  9309. * // [13.0, 17.0, 21.0, 25.0]
  9310. *
  9311. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  9312. * console.log("Difference between both the matrices is less than 0.1");
  9313. * } else {
  9314. * console.log("Difference between both the matrices is not less than 0.1");
  9315. * }
  9316. *
  9317. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  9318. */
  9319. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  9320. if (typeof epsilon !== 'number') {
  9321. throw new DeveloperError('epsilon must be a number');
  9322. }
  9323. return (left === right) ||
  9324. (defined(left) &&
  9325. defined(right) &&
  9326. Math.abs(left[0] - right[0]) <= epsilon &&
  9327. Math.abs(left[1] - right[1]) <= epsilon &&
  9328. Math.abs(left[2] - right[2]) <= epsilon &&
  9329. Math.abs(left[3] - right[3]) <= epsilon &&
  9330. Math.abs(left[4] - right[4]) <= epsilon &&
  9331. Math.abs(left[5] - right[5]) <= epsilon &&
  9332. Math.abs(left[6] - right[6]) <= epsilon &&
  9333. Math.abs(left[7] - right[7]) <= epsilon &&
  9334. Math.abs(left[8] - right[8]) <= epsilon &&
  9335. Math.abs(left[9] - right[9]) <= epsilon &&
  9336. Math.abs(left[10] - right[10]) <= epsilon &&
  9337. Math.abs(left[11] - right[11]) <= epsilon &&
  9338. Math.abs(left[12] - right[12]) <= epsilon &&
  9339. Math.abs(left[13] - right[13]) <= epsilon &&
  9340. Math.abs(left[14] - right[14]) <= epsilon &&
  9341. Math.abs(left[15] - right[15]) <= epsilon);
  9342. };
  9343. /**
  9344. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  9345. *
  9346. * @param {Matrix4} matrix The matrix to use.
  9347. * @param {Cartesian3} result The object onto which to store the result.
  9348. * @returns {Cartesian3} The modified result parameter.
  9349. */
  9350. Matrix4.getTranslation = function(matrix, result) {
  9351. if (!defined(matrix)) {
  9352. throw new DeveloperError('matrix is required');
  9353. }
  9354. if (!defined(result)) {
  9355. throw new DeveloperError('result is required');
  9356. }
  9357. result.x = matrix[12];
  9358. result.y = matrix[13];
  9359. result.z = matrix[14];
  9360. return result;
  9361. };
  9362. /**
  9363. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  9364. *
  9365. * @param {Matrix4} matrix The matrix to use.
  9366. * @param {Matrix3} result The object onto which to store the result.
  9367. * @returns {Matrix3} The modified result parameter.
  9368. *
  9369. * @example
  9370. * // returns a Matrix3 instance from a Matrix4 instance
  9371. *
  9372. * // m = [10.0, 14.0, 18.0, 22.0]
  9373. * // [11.0, 15.0, 19.0, 23.0]
  9374. * // [12.0, 16.0, 20.0, 24.0]
  9375. * // [13.0, 17.0, 21.0, 25.0]
  9376. *
  9377. * var b = new Cesium.Matrix3();
  9378. * Cesium.Matrix4.getRotation(m,b);
  9379. *
  9380. * // b = [10.0, 14.0, 18.0]
  9381. * // [11.0, 15.0, 19.0]
  9382. * // [12.0, 16.0, 20.0]
  9383. */
  9384. Matrix4.getRotation = function(matrix, result) {
  9385. if (!defined(matrix)) {
  9386. throw new DeveloperError('matrix is required');
  9387. }
  9388. if (!defined(result)) {
  9389. throw new DeveloperError('result is required');
  9390. }
  9391. result[0] = matrix[0];
  9392. result[1] = matrix[1];
  9393. result[2] = matrix[2];
  9394. result[3] = matrix[4];
  9395. result[4] = matrix[5];
  9396. result[5] = matrix[6];
  9397. result[6] = matrix[8];
  9398. result[7] = matrix[9];
  9399. result[8] = matrix[10];
  9400. return result;
  9401. };
  9402. var scratchInverseRotation = new Matrix3();
  9403. var scratchMatrix3Zero = new Matrix3();
  9404. var scratchBottomRow = new Cartesian4();
  9405. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  9406. /**
  9407. * Computes the inverse of the provided matrix using Cramers Rule.
  9408. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  9409. * If the matrix is an affine transformation matrix, it is more efficient
  9410. * to invert it with {@link Matrix4.inverseTransformation}.
  9411. *
  9412. * @param {Matrix4} matrix The matrix to invert.
  9413. * @param {Matrix4} result The object onto which to store the result.
  9414. * @returns {Matrix4} The modified result parameter.
  9415. *
  9416. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  9417. */
  9418. Matrix4.inverse = function(matrix, result) {
  9419. if (!defined(matrix)) {
  9420. throw new DeveloperError('matrix is required');
  9421. }
  9422. if (!defined(result)) {
  9423. throw new DeveloperError('result is required');
  9424. }
  9425. // Special case for a zero scale matrix that can occur, for example,
  9426. // when a model's node has a [0, 0, 0] scale.
  9427. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  9428. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  9429. result[0] = 0.0;
  9430. result[1] = 0.0;
  9431. result[2] = 0.0;
  9432. result[3] = 0.0;
  9433. result[4] = 0.0;
  9434. result[5] = 0.0;
  9435. result[6] = 0.0;
  9436. result[7] = 0.0;
  9437. result[8] = 0.0;
  9438. result[9] = 0.0;
  9439. result[10] = 0.0;
  9440. result[11] = 0.0;
  9441. result[12] = -matrix[12];
  9442. result[13] = -matrix[13];
  9443. result[14] = -matrix[14];
  9444. result[15] = 1.0;
  9445. return result;
  9446. }
  9447. //
  9448. // Ported from:
  9449. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  9450. //
  9451. var src0 = matrix[0];
  9452. var src1 = matrix[4];
  9453. var src2 = matrix[8];
  9454. var src3 = matrix[12];
  9455. var src4 = matrix[1];
  9456. var src5 = matrix[5];
  9457. var src6 = matrix[9];
  9458. var src7 = matrix[13];
  9459. var src8 = matrix[2];
  9460. var src9 = matrix[6];
  9461. var src10 = matrix[10];
  9462. var src11 = matrix[14];
  9463. var src12 = matrix[3];
  9464. var src13 = matrix[7];
  9465. var src14 = matrix[11];
  9466. var src15 = matrix[15];
  9467. // calculate pairs for first 8 elements (cofactors)
  9468. var tmp0 = src10 * src15;
  9469. var tmp1 = src11 * src14;
  9470. var tmp2 = src9 * src15;
  9471. var tmp3 = src11 * src13;
  9472. var tmp4 = src9 * src14;
  9473. var tmp5 = src10 * src13;
  9474. var tmp6 = src8 * src15;
  9475. var tmp7 = src11 * src12;
  9476. var tmp8 = src8 * src14;
  9477. var tmp9 = src10 * src12;
  9478. var tmp10 = src8 * src13;
  9479. var tmp11 = src9 * src12;
  9480. // calculate first 8 elements (cofactors)
  9481. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  9482. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  9483. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  9484. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  9485. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  9486. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  9487. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  9488. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  9489. // calculate pairs for second 8 elements (cofactors)
  9490. tmp0 = src2 * src7;
  9491. tmp1 = src3 * src6;
  9492. tmp2 = src1 * src7;
  9493. tmp3 = src3 * src5;
  9494. tmp4 = src1 * src6;
  9495. tmp5 = src2 * src5;
  9496. tmp6 = src0 * src7;
  9497. tmp7 = src3 * src4;
  9498. tmp8 = src0 * src6;
  9499. tmp9 = src2 * src4;
  9500. tmp10 = src0 * src5;
  9501. tmp11 = src1 * src4;
  9502. // calculate second 8 elements (cofactors)
  9503. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  9504. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  9505. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  9506. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  9507. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  9508. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  9509. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  9510. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  9511. // calculate determinant
  9512. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  9513. if (Math.abs(det) < CesiumMath.EPSILON20) {
  9514. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  9515. }
  9516. // calculate matrix inverse
  9517. det = 1.0 / det;
  9518. result[0] = dst0 * det;
  9519. result[1] = dst1 * det;
  9520. result[2] = dst2 * det;
  9521. result[3] = dst3 * det;
  9522. result[4] = dst4 * det;
  9523. result[5] = dst5 * det;
  9524. result[6] = dst6 * det;
  9525. result[7] = dst7 * det;
  9526. result[8] = dst8 * det;
  9527. result[9] = dst9 * det;
  9528. result[10] = dst10 * det;
  9529. result[11] = dst11 * det;
  9530. result[12] = dst12 * det;
  9531. result[13] = dst13 * det;
  9532. result[14] = dst14 * det;
  9533. result[15] = dst15 * det;
  9534. return result;
  9535. };
  9536. /**
  9537. * Computes the inverse of the provided matrix assuming it is
  9538. * an affine transformation matrix, where the upper left 3x3 elements
  9539. * are a rotation matrix, and the upper three elements in the fourth
  9540. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  9541. * The matrix is not verified to be in the proper form.
  9542. * This method is faster than computing the inverse for a general 4x4
  9543. * matrix using {@link Matrix4.inverse}.
  9544. *
  9545. * @param {Matrix4} matrix The matrix to invert.
  9546. * @param {Matrix4} result The object onto which to store the result.
  9547. * @returns {Matrix4} The modified result parameter.
  9548. */
  9549. Matrix4.inverseTransformation = function(matrix, result) {
  9550. if (!defined(matrix)) {
  9551. throw new DeveloperError('matrix is required');
  9552. }
  9553. if (!defined(result)) {
  9554. throw new DeveloperError('result is required');
  9555. }
  9556. //This function is an optimized version of the below 4 lines.
  9557. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  9558. //var rTN = Matrix3.negate(rT);
  9559. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  9560. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  9561. var matrix0 = matrix[0];
  9562. var matrix1 = matrix[1];
  9563. var matrix2 = matrix[2];
  9564. var matrix4 = matrix[4];
  9565. var matrix5 = matrix[5];
  9566. var matrix6 = matrix[6];
  9567. var matrix8 = matrix[8];
  9568. var matrix9 = matrix[9];
  9569. var matrix10 = matrix[10];
  9570. var vX = matrix[12];
  9571. var vY = matrix[13];
  9572. var vZ = matrix[14];
  9573. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  9574. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  9575. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  9576. result[0] = matrix0;
  9577. result[1] = matrix4;
  9578. result[2] = matrix8;
  9579. result[3] = 0.0;
  9580. result[4] = matrix1;
  9581. result[5] = matrix5;
  9582. result[6] = matrix9;
  9583. result[7] = 0.0;
  9584. result[8] = matrix2;
  9585. result[9] = matrix6;
  9586. result[10] = matrix10;
  9587. result[11] = 0.0;
  9588. result[12] = x;
  9589. result[13] = y;
  9590. result[14] = z;
  9591. result[15] = 1.0;
  9592. return result;
  9593. };
  9594. /**
  9595. * An immutable Matrix4 instance initialized to the identity matrix.
  9596. *
  9597. * @type {Matrix4}
  9598. * @constant
  9599. */
  9600. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  9601. 0.0, 1.0, 0.0, 0.0,
  9602. 0.0, 0.0, 1.0, 0.0,
  9603. 0.0, 0.0, 0.0, 1.0));
  9604. /**
  9605. * An immutable Matrix4 instance initialized to the zero matrix.
  9606. *
  9607. * @type {Matrix4}
  9608. * @constant
  9609. */
  9610. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  9611. 0.0, 0.0, 0.0, 0.0,
  9612. 0.0, 0.0, 0.0, 0.0,
  9613. 0.0, 0.0, 0.0, 0.0));
  9614. /**
  9615. * The index into Matrix4 for column 0, row 0.
  9616. *
  9617. * @type {Number}
  9618. * @constant
  9619. */
  9620. Matrix4.COLUMN0ROW0 = 0;
  9621. /**
  9622. * The index into Matrix4 for column 0, row 1.
  9623. *
  9624. * @type {Number}
  9625. * @constant
  9626. */
  9627. Matrix4.COLUMN0ROW1 = 1;
  9628. /**
  9629. * The index into Matrix4 for column 0, row 2.
  9630. *
  9631. * @type {Number}
  9632. * @constant
  9633. */
  9634. Matrix4.COLUMN0ROW2 = 2;
  9635. /**
  9636. * The index into Matrix4 for column 0, row 3.
  9637. *
  9638. * @type {Number}
  9639. * @constant
  9640. */
  9641. Matrix4.COLUMN0ROW3 = 3;
  9642. /**
  9643. * The index into Matrix4 for column 1, row 0.
  9644. *
  9645. * @type {Number}
  9646. * @constant
  9647. */
  9648. Matrix4.COLUMN1ROW0 = 4;
  9649. /**
  9650. * The index into Matrix4 for column 1, row 1.
  9651. *
  9652. * @type {Number}
  9653. * @constant
  9654. */
  9655. Matrix4.COLUMN1ROW1 = 5;
  9656. /**
  9657. * The index into Matrix4 for column 1, row 2.
  9658. *
  9659. * @type {Number}
  9660. * @constant
  9661. */
  9662. Matrix4.COLUMN1ROW2 = 6;
  9663. /**
  9664. * The index into Matrix4 for column 1, row 3.
  9665. *
  9666. * @type {Number}
  9667. * @constant
  9668. */
  9669. Matrix4.COLUMN1ROW3 = 7;
  9670. /**
  9671. * The index into Matrix4 for column 2, row 0.
  9672. *
  9673. * @type {Number}
  9674. * @constant
  9675. */
  9676. Matrix4.COLUMN2ROW0 = 8;
  9677. /**
  9678. * The index into Matrix4 for column 2, row 1.
  9679. *
  9680. * @type {Number}
  9681. * @constant
  9682. */
  9683. Matrix4.COLUMN2ROW1 = 9;
  9684. /**
  9685. * The index into Matrix4 for column 2, row 2.
  9686. *
  9687. * @type {Number}
  9688. * @constant
  9689. */
  9690. Matrix4.COLUMN2ROW2 = 10;
  9691. /**
  9692. * The index into Matrix4 for column 2, row 3.
  9693. *
  9694. * @type {Number}
  9695. * @constant
  9696. */
  9697. Matrix4.COLUMN2ROW3 = 11;
  9698. /**
  9699. * The index into Matrix4 for column 3, row 0.
  9700. *
  9701. * @type {Number}
  9702. * @constant
  9703. */
  9704. Matrix4.COLUMN3ROW0 = 12;
  9705. /**
  9706. * The index into Matrix4 for column 3, row 1.
  9707. *
  9708. * @type {Number}
  9709. * @constant
  9710. */
  9711. Matrix4.COLUMN3ROW1 = 13;
  9712. /**
  9713. * The index into Matrix4 for column 3, row 2.
  9714. *
  9715. * @type {Number}
  9716. * @constant
  9717. */
  9718. Matrix4.COLUMN3ROW2 = 14;
  9719. /**
  9720. * The index into Matrix4 for column 3, row 3.
  9721. *
  9722. * @type {Number}
  9723. * @constant
  9724. */
  9725. Matrix4.COLUMN3ROW3 = 15;
  9726. defineProperties(Matrix4.prototype, {
  9727. /**
  9728. * Gets the number of items in the collection.
  9729. * @memberof Matrix4.prototype
  9730. *
  9731. * @type {Number}
  9732. */
  9733. length : {
  9734. get : function() {
  9735. return Matrix4.packedLength;
  9736. }
  9737. }
  9738. });
  9739. /**
  9740. * Duplicates the provided Matrix4 instance.
  9741. *
  9742. * @param {Matrix4} [result] The object onto which to store the result.
  9743. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  9744. */
  9745. Matrix4.prototype.clone = function(result) {
  9746. return Matrix4.clone(this, result);
  9747. };
  9748. /**
  9749. * Compares this matrix to the provided matrix componentwise and returns
  9750. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9751. *
  9752. * @param {Matrix4} [right] The right hand side matrix.
  9753. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  9754. */
  9755. Matrix4.prototype.equals = function(right) {
  9756. return Matrix4.equals(this, right);
  9757. };
  9758. /**
  9759. * @private
  9760. */
  9761. Matrix4.equalsArray = function(matrix, array, offset) {
  9762. return matrix[0] === array[offset] &&
  9763. matrix[1] === array[offset + 1] &&
  9764. matrix[2] === array[offset + 2] &&
  9765. matrix[3] === array[offset + 3] &&
  9766. matrix[4] === array[offset + 4] &&
  9767. matrix[5] === array[offset + 5] &&
  9768. matrix[6] === array[offset + 6] &&
  9769. matrix[7] === array[offset + 7] &&
  9770. matrix[8] === array[offset + 8] &&
  9771. matrix[9] === array[offset + 9] &&
  9772. matrix[10] === array[offset + 10] &&
  9773. matrix[11] === array[offset + 11] &&
  9774. matrix[12] === array[offset + 12] &&
  9775. matrix[13] === array[offset + 13] &&
  9776. matrix[14] === array[offset + 14] &&
  9777. matrix[15] === array[offset + 15];
  9778. };
  9779. /**
  9780. * Compares this matrix to the provided matrix componentwise and returns
  9781. * <code>true</code> if they are within the provided epsilon,
  9782. * <code>false</code> otherwise.
  9783. *
  9784. * @param {Matrix4} [right] The right hand side matrix.
  9785. * @param {Number} epsilon The epsilon to use for equality testing.
  9786. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  9787. */
  9788. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  9789. return Matrix4.equalsEpsilon(this, right, epsilon);
  9790. };
  9791. /**
  9792. * Computes a string representing this Matrix with each row being
  9793. * on a separate line and in the format '(column0, column1, column2, column3)'.
  9794. *
  9795. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  9796. */
  9797. Matrix4.prototype.toString = function() {
  9798. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  9799. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  9800. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  9801. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  9802. };
  9803. return Matrix4;
  9804. });
  9805. /*global define*/
  9806. define('Core/BoundingSphere',[
  9807. './Cartesian3',
  9808. './Cartographic',
  9809. './defaultValue',
  9810. './defined',
  9811. './DeveloperError',
  9812. './Ellipsoid',
  9813. './GeographicProjection',
  9814. './Intersect',
  9815. './Interval',
  9816. './Matrix3',
  9817. './Matrix4',
  9818. './Rectangle'
  9819. ], function(
  9820. Cartesian3,
  9821. Cartographic,
  9822. defaultValue,
  9823. defined,
  9824. DeveloperError,
  9825. Ellipsoid,
  9826. GeographicProjection,
  9827. Intersect,
  9828. Interval,
  9829. Matrix3,
  9830. Matrix4,
  9831. Rectangle) {
  9832. 'use strict';
  9833. /**
  9834. * A bounding sphere with a center and a radius.
  9835. * @alias BoundingSphere
  9836. * @constructor
  9837. *
  9838. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  9839. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  9840. *
  9841. * @see AxisAlignedBoundingBox
  9842. * @see BoundingRectangle
  9843. * @see Packable
  9844. */
  9845. function BoundingSphere(center, radius) {
  9846. /**
  9847. * The center point of the sphere.
  9848. * @type {Cartesian3}
  9849. * @default {@link Cartesian3.ZERO}
  9850. */
  9851. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  9852. /**
  9853. * The radius of the sphere.
  9854. * @type {Number}
  9855. * @default 0.0
  9856. */
  9857. this.radius = defaultValue(radius, 0.0);
  9858. }
  9859. var fromPointsXMin = new Cartesian3();
  9860. var fromPointsYMin = new Cartesian3();
  9861. var fromPointsZMin = new Cartesian3();
  9862. var fromPointsXMax = new Cartesian3();
  9863. var fromPointsYMax = new Cartesian3();
  9864. var fromPointsZMax = new Cartesian3();
  9865. var fromPointsCurrentPos = new Cartesian3();
  9866. var fromPointsScratch = new Cartesian3();
  9867. var fromPointsRitterCenter = new Cartesian3();
  9868. var fromPointsMinBoxPt = new Cartesian3();
  9869. var fromPointsMaxBoxPt = new Cartesian3();
  9870. var fromPointsNaiveCenterScratch = new Cartesian3();
  9871. /**
  9872. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  9873. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  9874. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  9875. *
  9876. * @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.
  9877. * @param {BoundingSphere} [result] The object onto which to store the result.
  9878. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9879. *
  9880. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9881. */
  9882. BoundingSphere.fromPoints = function(positions, result) {
  9883. if (!defined(result)) {
  9884. result = new BoundingSphere();
  9885. }
  9886. if (!defined(positions) || positions.length === 0) {
  9887. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9888. result.radius = 0.0;
  9889. return result;
  9890. }
  9891. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  9892. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9893. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9894. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9895. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9896. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9897. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9898. var numPositions = positions.length;
  9899. for (var i = 1; i < numPositions; i++) {
  9900. Cartesian3.clone(positions[i], currentPos);
  9901. var x = currentPos.x;
  9902. var y = currentPos.y;
  9903. var z = currentPos.z;
  9904. // Store points containing the the smallest and largest components
  9905. if (x < xMin.x) {
  9906. Cartesian3.clone(currentPos, xMin);
  9907. }
  9908. if (x > xMax.x) {
  9909. Cartesian3.clone(currentPos, xMax);
  9910. }
  9911. if (y < yMin.y) {
  9912. Cartesian3.clone(currentPos, yMin);
  9913. }
  9914. if (y > yMax.y) {
  9915. Cartesian3.clone(currentPos, yMax);
  9916. }
  9917. if (z < zMin.z) {
  9918. Cartesian3.clone(currentPos, zMin);
  9919. }
  9920. if (z > zMax.z) {
  9921. Cartesian3.clone(currentPos, zMax);
  9922. }
  9923. }
  9924. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9925. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9926. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9927. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9928. // Set the diameter endpoints to the largest span.
  9929. var diameter1 = xMin;
  9930. var diameter2 = xMax;
  9931. var maxSpan = xSpan;
  9932. if (ySpan > maxSpan) {
  9933. maxSpan = ySpan;
  9934. diameter1 = yMin;
  9935. diameter2 = yMax;
  9936. }
  9937. if (zSpan > maxSpan) {
  9938. maxSpan = zSpan;
  9939. diameter1 = zMin;
  9940. diameter2 = zMax;
  9941. }
  9942. // Calculate the center of the initial sphere found by Ritter's algorithm
  9943. var ritterCenter = fromPointsRitterCenter;
  9944. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9945. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9946. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9947. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9948. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9949. var ritterRadius = Math.sqrt(radiusSquared);
  9950. // Find the center of the sphere found using the Naive method.
  9951. var minBoxPt = fromPointsMinBoxPt;
  9952. minBoxPt.x = xMin.x;
  9953. minBoxPt.y = yMin.y;
  9954. minBoxPt.z = zMin.z;
  9955. var maxBoxPt = fromPointsMaxBoxPt;
  9956. maxBoxPt.x = xMax.x;
  9957. maxBoxPt.y = yMax.y;
  9958. maxBoxPt.z = zMax.z;
  9959. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9960. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9961. var naiveRadius = 0;
  9962. for (i = 0; i < numPositions; i++) {
  9963. Cartesian3.clone(positions[i], currentPos);
  9964. // Find the furthest point from the naive center to calculate the naive radius.
  9965. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9966. if (r > naiveRadius) {
  9967. naiveRadius = r;
  9968. }
  9969. // Make adjustments to the Ritter Sphere to include all points.
  9970. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9971. if (oldCenterToPointSquared > radiusSquared) {
  9972. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9973. // Calculate new radius to include the point that lies outside
  9974. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9975. radiusSquared = ritterRadius * ritterRadius;
  9976. // Calculate center of new Ritter sphere
  9977. var oldToNew = oldCenterToPoint - ritterRadius;
  9978. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9979. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9980. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9981. }
  9982. }
  9983. if (ritterRadius < naiveRadius) {
  9984. Cartesian3.clone(ritterCenter, result.center);
  9985. result.radius = ritterRadius;
  9986. } else {
  9987. Cartesian3.clone(naiveCenter, result.center);
  9988. result.radius = naiveRadius;
  9989. }
  9990. return result;
  9991. };
  9992. var defaultProjection = new GeographicProjection();
  9993. var fromRectangle2DLowerLeft = new Cartesian3();
  9994. var fromRectangle2DUpperRight = new Cartesian3();
  9995. var fromRectangle2DSouthwest = new Cartographic();
  9996. var fromRectangle2DNortheast = new Cartographic();
  9997. /**
  9998. * Computes a bounding sphere from an rectangle projected in 2D.
  9999. *
  10000. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10001. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10002. * @param {BoundingSphere} [result] The object onto which to store the result.
  10003. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10004. */
  10005. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  10006. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  10007. };
  10008. /**
  10009. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  10010. * object's minimum and maximum heights over the rectangle.
  10011. *
  10012. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10013. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10014. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  10015. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  10016. * @param {BoundingSphere} [result] The object onto which to store the result.
  10017. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10018. */
  10019. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  10020. if (!defined(result)) {
  10021. result = new BoundingSphere();
  10022. }
  10023. if (!defined(rectangle)) {
  10024. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10025. result.radius = 0.0;
  10026. return result;
  10027. }
  10028. projection = defaultValue(projection, defaultProjection);
  10029. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  10030. fromRectangle2DSouthwest.height = minimumHeight;
  10031. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  10032. fromRectangle2DNortheast.height = maximumHeight;
  10033. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  10034. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  10035. var width = upperRight.x - lowerLeft.x;
  10036. var height = upperRight.y - lowerLeft.y;
  10037. var elevation = upperRight.z - lowerLeft.z;
  10038. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  10039. var center = result.center;
  10040. center.x = lowerLeft.x + width * 0.5;
  10041. center.y = lowerLeft.y + height * 0.5;
  10042. center.z = lowerLeft.z + elevation * 0.5;
  10043. return result;
  10044. };
  10045. var fromRectangle3DScratch = [];
  10046. /**
  10047. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  10048. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  10049. *
  10050. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  10051. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  10052. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  10053. * @param {BoundingSphere} [result] The object onto which to store the result.
  10054. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10055. */
  10056. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  10057. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  10058. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  10059. var positions;
  10060. if (defined(rectangle)) {
  10061. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  10062. }
  10063. return BoundingSphere.fromPoints(positions, result);
  10064. };
  10065. /**
  10066. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  10067. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  10068. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10069. * ensure a tight fit.
  10070. *
  10071. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  10072. * is formed from three elements in the array in the order X, Y, Z.
  10073. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  10074. * origin of the coordinate system. This is useful when the positions are to be used for
  10075. * relative-to-center (RTC) rendering.
  10076. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  10077. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  10078. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  10079. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  10080. * the stride is 5, however, two array elements are skipped and the next position begins at array
  10081. * index 5.
  10082. * @param {BoundingSphere} [result] The object onto which to store the result.
  10083. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10084. *
  10085. * @example
  10086. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  10087. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  10088. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  10089. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  10090. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  10091. * 4.0, 5.0, 6.0, 0.1, 0.2,
  10092. * 7.0, 8.0, 9.0, 0.1, 0.2];
  10093. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  10094. *
  10095. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10096. */
  10097. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  10098. if (!defined(result)) {
  10099. result = new BoundingSphere();
  10100. }
  10101. if (!defined(positions) || positions.length === 0) {
  10102. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10103. result.radius = 0.0;
  10104. return result;
  10105. }
  10106. center = defaultValue(center, Cartesian3.ZERO);
  10107. stride = defaultValue(stride, 3);
  10108. if (stride < 3) {
  10109. throw new DeveloperError('stride must be 3 or greater.');
  10110. }
  10111. var currentPos = fromPointsCurrentPos;
  10112. currentPos.x = positions[0] + center.x;
  10113. currentPos.y = positions[1] + center.y;
  10114. currentPos.z = positions[2] + center.z;
  10115. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10116. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10117. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10118. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10119. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10120. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10121. var numElements = positions.length;
  10122. for (var i = 0; i < numElements; i += stride) {
  10123. var x = positions[i] + center.x;
  10124. var y = positions[i + 1] + center.y;
  10125. var z = positions[i + 2] + center.z;
  10126. currentPos.x = x;
  10127. currentPos.y = y;
  10128. currentPos.z = z;
  10129. // Store points containing the the smallest and largest components
  10130. if (x < xMin.x) {
  10131. Cartesian3.clone(currentPos, xMin);
  10132. }
  10133. if (x > xMax.x) {
  10134. Cartesian3.clone(currentPos, xMax);
  10135. }
  10136. if (y < yMin.y) {
  10137. Cartesian3.clone(currentPos, yMin);
  10138. }
  10139. if (y > yMax.y) {
  10140. Cartesian3.clone(currentPos, yMax);
  10141. }
  10142. if (z < zMin.z) {
  10143. Cartesian3.clone(currentPos, zMin);
  10144. }
  10145. if (z > zMax.z) {
  10146. Cartesian3.clone(currentPos, zMax);
  10147. }
  10148. }
  10149. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10150. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10151. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10152. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10153. // Set the diameter endpoints to the largest span.
  10154. var diameter1 = xMin;
  10155. var diameter2 = xMax;
  10156. var maxSpan = xSpan;
  10157. if (ySpan > maxSpan) {
  10158. maxSpan = ySpan;
  10159. diameter1 = yMin;
  10160. diameter2 = yMax;
  10161. }
  10162. if (zSpan > maxSpan) {
  10163. maxSpan = zSpan;
  10164. diameter1 = zMin;
  10165. diameter2 = zMax;
  10166. }
  10167. // Calculate the center of the initial sphere found by Ritter's algorithm
  10168. var ritterCenter = fromPointsRitterCenter;
  10169. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10170. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10171. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10172. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10173. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10174. var ritterRadius = Math.sqrt(radiusSquared);
  10175. // Find the center of the sphere found using the Naive method.
  10176. var minBoxPt = fromPointsMinBoxPt;
  10177. minBoxPt.x = xMin.x;
  10178. minBoxPt.y = yMin.y;
  10179. minBoxPt.z = zMin.z;
  10180. var maxBoxPt = fromPointsMaxBoxPt;
  10181. maxBoxPt.x = xMax.x;
  10182. maxBoxPt.y = yMax.y;
  10183. maxBoxPt.z = zMax.z;
  10184. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10185. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10186. var naiveRadius = 0;
  10187. for (i = 0; i < numElements; i += stride) {
  10188. currentPos.x = positions[i] + center.x;
  10189. currentPos.y = positions[i + 1] + center.y;
  10190. currentPos.z = positions[i + 2] + center.z;
  10191. // Find the furthest point from the naive center to calculate the naive radius.
  10192. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10193. if (r > naiveRadius) {
  10194. naiveRadius = r;
  10195. }
  10196. // Make adjustments to the Ritter Sphere to include all points.
  10197. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10198. if (oldCenterToPointSquared > radiusSquared) {
  10199. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10200. // Calculate new radius to include the point that lies outside
  10201. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10202. radiusSquared = ritterRadius * ritterRadius;
  10203. // Calculate center of new Ritter sphere
  10204. var oldToNew = oldCenterToPoint - ritterRadius;
  10205. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10206. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10207. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10208. }
  10209. }
  10210. if (ritterRadius < naiveRadius) {
  10211. Cartesian3.clone(ritterCenter, result.center);
  10212. result.radius = ritterRadius;
  10213. } else {
  10214. Cartesian3.clone(naiveCenter, result.center);
  10215. result.radius = naiveRadius;
  10216. }
  10217. return result;
  10218. };
  10219. /**
  10220. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  10221. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  10222. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10223. * ensure a tight fit.
  10224. *
  10225. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10226. * is formed from three elements in the array in the order X, Y, Z.
  10227. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10228. * is formed from three elements in the array in the order X, Y, Z.
  10229. * @param {BoundingSphere} [result] The object onto which to store the result.
  10230. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10231. *
  10232. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10233. */
  10234. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  10235. if (!defined(result)) {
  10236. result = new BoundingSphere();
  10237. }
  10238. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  10239. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10240. result.radius = 0.0;
  10241. return result;
  10242. }
  10243. var currentPos = fromPointsCurrentPos;
  10244. currentPos.x = positionsHigh[0] + positionsLow[0];
  10245. currentPos.y = positionsHigh[1] + positionsLow[1];
  10246. currentPos.z = positionsHigh[2] + positionsLow[2];
  10247. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10248. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10249. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10250. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10251. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10252. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10253. var numElements = positionsHigh.length;
  10254. for (var i = 0; i < numElements; i += 3) {
  10255. var x = positionsHigh[i] + positionsLow[i];
  10256. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  10257. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  10258. currentPos.x = x;
  10259. currentPos.y = y;
  10260. currentPos.z = z;
  10261. // Store points containing the the smallest and largest components
  10262. if (x < xMin.x) {
  10263. Cartesian3.clone(currentPos, xMin);
  10264. }
  10265. if (x > xMax.x) {
  10266. Cartesian3.clone(currentPos, xMax);
  10267. }
  10268. if (y < yMin.y) {
  10269. Cartesian3.clone(currentPos, yMin);
  10270. }
  10271. if (y > yMax.y) {
  10272. Cartesian3.clone(currentPos, yMax);
  10273. }
  10274. if (z < zMin.z) {
  10275. Cartesian3.clone(currentPos, zMin);
  10276. }
  10277. if (z > zMax.z) {
  10278. Cartesian3.clone(currentPos, zMax);
  10279. }
  10280. }
  10281. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10282. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10283. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10284. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10285. // Set the diameter endpoints to the largest span.
  10286. var diameter1 = xMin;
  10287. var diameter2 = xMax;
  10288. var maxSpan = xSpan;
  10289. if (ySpan > maxSpan) {
  10290. maxSpan = ySpan;
  10291. diameter1 = yMin;
  10292. diameter2 = yMax;
  10293. }
  10294. if (zSpan > maxSpan) {
  10295. maxSpan = zSpan;
  10296. diameter1 = zMin;
  10297. diameter2 = zMax;
  10298. }
  10299. // Calculate the center of the initial sphere found by Ritter's algorithm
  10300. var ritterCenter = fromPointsRitterCenter;
  10301. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10302. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10303. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10304. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10305. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10306. var ritterRadius = Math.sqrt(radiusSquared);
  10307. // Find the center of the sphere found using the Naive method.
  10308. var minBoxPt = fromPointsMinBoxPt;
  10309. minBoxPt.x = xMin.x;
  10310. minBoxPt.y = yMin.y;
  10311. minBoxPt.z = zMin.z;
  10312. var maxBoxPt = fromPointsMaxBoxPt;
  10313. maxBoxPt.x = xMax.x;
  10314. maxBoxPt.y = yMax.y;
  10315. maxBoxPt.z = zMax.z;
  10316. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10317. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10318. var naiveRadius = 0;
  10319. for (i = 0; i < numElements; i += 3) {
  10320. currentPos.x = positionsHigh[i] + positionsLow[i];
  10321. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  10322. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  10323. // Find the furthest point from the naive center to calculate the naive radius.
  10324. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10325. if (r > naiveRadius) {
  10326. naiveRadius = r;
  10327. }
  10328. // Make adjustments to the Ritter Sphere to include all points.
  10329. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10330. if (oldCenterToPointSquared > radiusSquared) {
  10331. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10332. // Calculate new radius to include the point that lies outside
  10333. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10334. radiusSquared = ritterRadius * ritterRadius;
  10335. // Calculate center of new Ritter sphere
  10336. var oldToNew = oldCenterToPoint - ritterRadius;
  10337. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10338. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10339. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10340. }
  10341. }
  10342. if (ritterRadius < naiveRadius) {
  10343. Cartesian3.clone(ritterCenter, result.center);
  10344. result.radius = ritterRadius;
  10345. } else {
  10346. Cartesian3.clone(naiveCenter, result.center);
  10347. result.radius = naiveRadius;
  10348. }
  10349. return result;
  10350. };
  10351. /**
  10352. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  10353. * tighly and fully encompases the box.
  10354. *
  10355. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  10356. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  10357. * @param {BoundingSphere} [result] The object onto which to store the result.
  10358. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10359. *
  10360. * @example
  10361. * // Create a bounding sphere around the unit cube
  10362. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  10363. */
  10364. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  10365. if (!defined(corner) || !defined(oppositeCorner)) {
  10366. throw new DeveloperError('corner and oppositeCorner are required.');
  10367. }
  10368. if (!defined(result)) {
  10369. result = new BoundingSphere();
  10370. }
  10371. var center = result.center;
  10372. Cartesian3.add(corner, oppositeCorner, center);
  10373. Cartesian3.multiplyByScalar(center, 0.5, center);
  10374. result.radius = Cartesian3.distance(center, oppositeCorner);
  10375. return result;
  10376. };
  10377. /**
  10378. * Creates a bounding sphere encompassing an ellipsoid.
  10379. *
  10380. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  10381. * @param {BoundingSphere} [result] The object onto which to store the result.
  10382. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10383. *
  10384. * @example
  10385. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  10386. */
  10387. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  10388. if (!defined(ellipsoid)) {
  10389. throw new DeveloperError('ellipsoid is required.');
  10390. }
  10391. if (!defined(result)) {
  10392. result = new BoundingSphere();
  10393. }
  10394. Cartesian3.clone(Cartesian3.ZERO, result.center);
  10395. result.radius = ellipsoid.maximumRadius;
  10396. return result;
  10397. };
  10398. var fromBoundingSpheresScratch = new Cartesian3();
  10399. /**
  10400. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  10401. *
  10402. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  10403. * @param {BoundingSphere} [result] The object onto which to store the result.
  10404. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10405. */
  10406. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  10407. if (!defined(result)) {
  10408. result = new BoundingSphere();
  10409. }
  10410. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  10411. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10412. result.radius = 0.0;
  10413. return result;
  10414. }
  10415. var length = boundingSpheres.length;
  10416. if (length === 1) {
  10417. return BoundingSphere.clone(boundingSpheres[0], result);
  10418. }
  10419. if (length === 2) {
  10420. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  10421. }
  10422. var positions = [];
  10423. for (var i = 0; i < length; i++) {
  10424. positions.push(boundingSpheres[i].center);
  10425. }
  10426. result = BoundingSphere.fromPoints(positions, result);
  10427. var center = result.center;
  10428. var radius = result.radius;
  10429. for (i = 0; i < length; i++) {
  10430. var tmp = boundingSpheres[i];
  10431. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  10432. }
  10433. result.radius = radius;
  10434. return result;
  10435. };
  10436. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  10437. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  10438. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  10439. /**
  10440. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  10441. *
  10442. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  10443. * @param {BoundingSphere} [result] The object onto which to store the result.
  10444. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10445. */
  10446. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  10447. if (!defined(result)) {
  10448. result = new BoundingSphere();
  10449. }
  10450. var halfAxes = orientedBoundingBox.halfAxes;
  10451. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  10452. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  10453. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  10454. var uHalf = Cartesian3.magnitude(u);
  10455. var vHalf = Cartesian3.magnitude(v);
  10456. var wHalf = Cartesian3.magnitude(w);
  10457. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  10458. result.radius = Math.max(uHalf, vHalf, wHalf);
  10459. return result;
  10460. };
  10461. /**
  10462. * Duplicates a BoundingSphere instance.
  10463. *
  10464. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  10465. * @param {BoundingSphere} [result] The object onto which to store the result.
  10466. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  10467. */
  10468. BoundingSphere.clone = function(sphere, result) {
  10469. if (!defined(sphere)) {
  10470. return undefined;
  10471. }
  10472. if (!defined(result)) {
  10473. return new BoundingSphere(sphere.center, sphere.radius);
  10474. }
  10475. result.center = Cartesian3.clone(sphere.center, result.center);
  10476. result.radius = sphere.radius;
  10477. return result;
  10478. };
  10479. /**
  10480. * The number of elements used to pack the object into an array.
  10481. * @type {Number}
  10482. */
  10483. BoundingSphere.packedLength = 4;
  10484. /**
  10485. * Stores the provided instance into the provided array.
  10486. *
  10487. * @param {BoundingSphere} value The value to pack.
  10488. * @param {Number[]} array The array to pack into.
  10489. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  10490. *
  10491. * @returns {Number[]} The array that was packed into
  10492. */
  10493. BoundingSphere.pack = function(value, array, startingIndex) {
  10494. if (!defined(value)) {
  10495. throw new DeveloperError('value is required');
  10496. }
  10497. if (!defined(array)) {
  10498. throw new DeveloperError('array is required');
  10499. }
  10500. startingIndex = defaultValue(startingIndex, 0);
  10501. var center = value.center;
  10502. array[startingIndex++] = center.x;
  10503. array[startingIndex++] = center.y;
  10504. array[startingIndex++] = center.z;
  10505. array[startingIndex] = value.radius;
  10506. return array;
  10507. };
  10508. /**
  10509. * Retrieves an instance from a packed array.
  10510. *
  10511. * @param {Number[]} array The packed array.
  10512. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  10513. * @param {BoundingSphere} [result] The object into which to store the result.
  10514. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10515. */
  10516. BoundingSphere.unpack = function(array, startingIndex, result) {
  10517. if (!defined(array)) {
  10518. throw new DeveloperError('array is required');
  10519. }
  10520. startingIndex = defaultValue(startingIndex, 0);
  10521. if (!defined(result)) {
  10522. result = new BoundingSphere();
  10523. }
  10524. var center = result.center;
  10525. center.x = array[startingIndex++];
  10526. center.y = array[startingIndex++];
  10527. center.z = array[startingIndex++];
  10528. result.radius = array[startingIndex];
  10529. return result;
  10530. };
  10531. var unionScratch = new Cartesian3();
  10532. var unionScratchCenter = new Cartesian3();
  10533. /**
  10534. * Computes a bounding sphere that contains both the left and right bounding spheres.
  10535. *
  10536. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  10537. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  10538. * @param {BoundingSphere} [result] The object onto which to store the result.
  10539. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10540. */
  10541. BoundingSphere.union = function(left, right, result) {
  10542. if (!defined(left)) {
  10543. throw new DeveloperError('left is required.');
  10544. }
  10545. if (!defined(right)) {
  10546. throw new DeveloperError('right is required.');
  10547. }
  10548. if (!defined(result)) {
  10549. result = new BoundingSphere();
  10550. }
  10551. var leftCenter = left.center;
  10552. var leftRadius = left.radius;
  10553. var rightCenter = right.center;
  10554. var rightRadius = right.radius;
  10555. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  10556. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  10557. if (leftRadius >= (centerSeparation + rightRadius)) {
  10558. // Left sphere wins.
  10559. left.clone(result);
  10560. return result;
  10561. }
  10562. if (rightRadius >= (centerSeparation + leftRadius)) {
  10563. // Right sphere wins.
  10564. right.clone(result);
  10565. return result;
  10566. }
  10567. // There are two tangent points, one on far side of each sphere.
  10568. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  10569. // Compute the center point halfway between the two tangent points.
  10570. var center = Cartesian3.multiplyByScalar(toRightCenter,
  10571. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  10572. Cartesian3.add(center, leftCenter, center);
  10573. Cartesian3.clone(center, result.center);
  10574. result.radius = halfDistanceBetweenTangentPoints;
  10575. return result;
  10576. };
  10577. var expandScratch = new Cartesian3();
  10578. /**
  10579. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  10580. *
  10581. * @param {BoundingSphere} sphere A sphere to expand.
  10582. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  10583. * @param {BoundingSphere} [result] The object onto which to store the result.
  10584. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10585. */
  10586. BoundingSphere.expand = function(sphere, point, result) {
  10587. if (!defined(sphere)) {
  10588. throw new DeveloperError('sphere is required.');
  10589. }
  10590. if (!defined(point)) {
  10591. throw new DeveloperError('point is required.');
  10592. }
  10593. result = BoundingSphere.clone(sphere, result);
  10594. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  10595. if (radius > result.radius) {
  10596. result.radius = radius;
  10597. }
  10598. return result;
  10599. };
  10600. /**
  10601. * Determines which side of a plane a sphere is located.
  10602. *
  10603. * @param {BoundingSphere} sphere The bounding sphere to test.
  10604. * @param {Plane} plane The plane to test against.
  10605. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10606. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10607. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10608. * intersects the plane.
  10609. */
  10610. BoundingSphere.intersectPlane = function(sphere, plane) {
  10611. if (!defined(sphere)) {
  10612. throw new DeveloperError('sphere is required.');
  10613. }
  10614. if (!defined(plane)) {
  10615. throw new DeveloperError('plane is required.');
  10616. }
  10617. var center = sphere.center;
  10618. var radius = sphere.radius;
  10619. var normal = plane.normal;
  10620. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  10621. if (distanceToPlane < -radius) {
  10622. // The center point is negative side of the plane normal
  10623. return Intersect.OUTSIDE;
  10624. } else if (distanceToPlane < radius) {
  10625. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  10626. return Intersect.INTERSECTING;
  10627. }
  10628. return Intersect.INSIDE;
  10629. };
  10630. /**
  10631. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  10632. *
  10633. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10634. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10635. * @param {BoundingSphere} [result] The object onto which to store the result.
  10636. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10637. */
  10638. BoundingSphere.transform = function(sphere, transform, result) {
  10639. if (!defined(sphere)) {
  10640. throw new DeveloperError('sphere is required.');
  10641. }
  10642. if (!defined(transform)) {
  10643. throw new DeveloperError('transform is required.');
  10644. }
  10645. if (!defined(result)) {
  10646. result = new BoundingSphere();
  10647. }
  10648. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10649. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  10650. return result;
  10651. };
  10652. var distanceSquaredToScratch = new Cartesian3();
  10653. /**
  10654. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10655. *
  10656. * @param {BoundingSphere} sphere The sphere.
  10657. * @param {Cartesian3} cartesian The point
  10658. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10659. *
  10660. * @example
  10661. * // Sort bounding spheres from back to front
  10662. * spheres.sort(function(a, b) {
  10663. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  10664. * });
  10665. */
  10666. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  10667. if (!defined(sphere)) {
  10668. throw new DeveloperError('sphere is required.');
  10669. }
  10670. if (!defined(cartesian)) {
  10671. throw new DeveloperError('cartesian is required.');
  10672. }
  10673. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  10674. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  10675. };
  10676. /**
  10677. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  10678. * The transformation matrix is not verified to have a uniform scale of 1.
  10679. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  10680. *
  10681. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10682. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10683. * @param {BoundingSphere} [result] The object onto which to store the result.
  10684. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10685. *
  10686. * @example
  10687. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  10688. * var boundingSphere = new Cesium.BoundingSphere();
  10689. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  10690. */
  10691. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  10692. if (!defined(sphere)) {
  10693. throw new DeveloperError('sphere is required.');
  10694. }
  10695. if (!defined(transform)) {
  10696. throw new DeveloperError('transform is required.');
  10697. }
  10698. if (!defined(result)) {
  10699. result = new BoundingSphere();
  10700. }
  10701. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10702. result.radius = sphere.radius;
  10703. return result;
  10704. };
  10705. var scratchCartesian3 = new Cartesian3();
  10706. /**
  10707. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10708. * plus/minus the radius of the bounding sphere.
  10709. * <br>
  10710. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10711. * closest and farthest planes from position that intersect the bounding sphere.
  10712. *
  10713. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  10714. * @param {Cartesian3} position The position to calculate the distance from.
  10715. * @param {Cartesian3} direction The direction from position.
  10716. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10717. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10718. */
  10719. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  10720. if (!defined(sphere)) {
  10721. throw new DeveloperError('sphere is required.');
  10722. }
  10723. if (!defined(position)) {
  10724. throw new DeveloperError('position is required.');
  10725. }
  10726. if (!defined(direction)) {
  10727. throw new DeveloperError('direction is required.');
  10728. }
  10729. if (!defined(result)) {
  10730. result = new Interval();
  10731. }
  10732. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  10733. var mag = Cartesian3.dot(direction, toCenter);
  10734. result.start = mag - sphere.radius;
  10735. result.stop = mag + sphere.radius;
  10736. return result;
  10737. };
  10738. var projectTo2DNormalScratch = new Cartesian3();
  10739. var projectTo2DEastScratch = new Cartesian3();
  10740. var projectTo2DNorthScratch = new Cartesian3();
  10741. var projectTo2DWestScratch = new Cartesian3();
  10742. var projectTo2DSouthScratch = new Cartesian3();
  10743. var projectTo2DCartographicScratch = new Cartographic();
  10744. var projectTo2DPositionsScratch = new Array(8);
  10745. for (var n = 0; n < 8; ++n) {
  10746. projectTo2DPositionsScratch[n] = new Cartesian3();
  10747. }
  10748. var projectTo2DProjection = new GeographicProjection();
  10749. /**
  10750. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  10751. *
  10752. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  10753. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  10754. * @param {BoundingSphere} [result] The object onto which to store the result.
  10755. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10756. */
  10757. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  10758. if (!defined(sphere)) {
  10759. throw new DeveloperError('sphere is required.');
  10760. }
  10761. projection = defaultValue(projection, projectTo2DProjection);
  10762. var ellipsoid = projection.ellipsoid;
  10763. var center = sphere.center;
  10764. var radius = sphere.radius;
  10765. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  10766. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  10767. Cartesian3.normalize(east, east);
  10768. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  10769. Cartesian3.normalize(north, north);
  10770. Cartesian3.multiplyByScalar(normal, radius, normal);
  10771. Cartesian3.multiplyByScalar(north, radius, north);
  10772. Cartesian3.multiplyByScalar(east, radius, east);
  10773. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  10774. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  10775. var positions = projectTo2DPositionsScratch;
  10776. // top NE corner
  10777. var corner = positions[0];
  10778. Cartesian3.add(normal, north, corner);
  10779. Cartesian3.add(corner, east, corner);
  10780. // top NW corner
  10781. corner = positions[1];
  10782. Cartesian3.add(normal, north, corner);
  10783. Cartesian3.add(corner, west, corner);
  10784. // top SW corner
  10785. corner = positions[2];
  10786. Cartesian3.add(normal, south, corner);
  10787. Cartesian3.add(corner, west, corner);
  10788. // top SE corner
  10789. corner = positions[3];
  10790. Cartesian3.add(normal, south, corner);
  10791. Cartesian3.add(corner, east, corner);
  10792. Cartesian3.negate(normal, normal);
  10793. // bottom NE corner
  10794. corner = positions[4];
  10795. Cartesian3.add(normal, north, corner);
  10796. Cartesian3.add(corner, east, corner);
  10797. // bottom NW corner
  10798. corner = positions[5];
  10799. Cartesian3.add(normal, north, corner);
  10800. Cartesian3.add(corner, west, corner);
  10801. // bottom SW corner
  10802. corner = positions[6];
  10803. Cartesian3.add(normal, south, corner);
  10804. Cartesian3.add(corner, west, corner);
  10805. // bottom SE corner
  10806. corner = positions[7];
  10807. Cartesian3.add(normal, south, corner);
  10808. Cartesian3.add(corner, east, corner);
  10809. var length = positions.length;
  10810. for (var i = 0; i < length; ++i) {
  10811. var position = positions[i];
  10812. Cartesian3.add(center, position, position);
  10813. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  10814. projection.project(cartographic, position);
  10815. }
  10816. result = BoundingSphere.fromPoints(positions, result);
  10817. // swizzle center components
  10818. center = result.center;
  10819. var x = center.x;
  10820. var y = center.y;
  10821. var z = center.z;
  10822. center.x = z;
  10823. center.y = x;
  10824. center.z = y;
  10825. return result;
  10826. };
  10827. /**
  10828. * Determines whether or not a sphere is hidden from view by the occluder.
  10829. *
  10830. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  10831. * @param {Occluder} occluder The occluder.
  10832. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10833. */
  10834. BoundingSphere.isOccluded = function(sphere, occluder) {
  10835. if (!defined(sphere)) {
  10836. throw new DeveloperError('sphere is required.');
  10837. }
  10838. if (!defined(occluder)) {
  10839. throw new DeveloperError('occluder is required.');
  10840. }
  10841. return !occluder.isBoundingSphereVisible(sphere);
  10842. };
  10843. /**
  10844. * Compares the provided BoundingSphere componentwise and returns
  10845. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10846. *
  10847. * @param {BoundingSphere} [left] The first BoundingSphere.
  10848. * @param {BoundingSphere} [right] The second BoundingSphere.
  10849. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10850. */
  10851. BoundingSphere.equals = function(left, right) {
  10852. return (left === right) ||
  10853. ((defined(left)) &&
  10854. (defined(right)) &&
  10855. Cartesian3.equals(left.center, right.center) &&
  10856. left.radius === right.radius);
  10857. };
  10858. /**
  10859. * Determines which side of a plane the sphere is located.
  10860. *
  10861. * @param {Plane} plane The plane to test against.
  10862. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10863. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10864. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10865. * intersects the plane.
  10866. */
  10867. BoundingSphere.prototype.intersectPlane = function(plane) {
  10868. return BoundingSphere.intersectPlane(this, plane);
  10869. };
  10870. /**
  10871. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10872. *
  10873. * @param {Cartesian3} cartesian The point
  10874. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10875. *
  10876. * @example
  10877. * // Sort bounding spheres from back to front
  10878. * spheres.sort(function(a, b) {
  10879. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  10880. * });
  10881. */
  10882. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  10883. return BoundingSphere.distanceSquaredTo(this, cartesian);
  10884. };
  10885. /**
  10886. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10887. * plus/minus the radius of the bounding sphere.
  10888. * <br>
  10889. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10890. * closest and farthest planes from position that intersect the bounding sphere.
  10891. *
  10892. * @param {Cartesian3} position The position to calculate the distance from.
  10893. * @param {Cartesian3} direction The direction from position.
  10894. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10895. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10896. */
  10897. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  10898. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  10899. };
  10900. /**
  10901. * Determines whether or not a sphere is hidden from view by the occluder.
  10902. *
  10903. * @param {Occluder} occluder The occluder.
  10904. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10905. */
  10906. BoundingSphere.prototype.isOccluded = function(occluder) {
  10907. return BoundingSphere.isOccluded(this, occluder);
  10908. };
  10909. /**
  10910. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  10911. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10912. *
  10913. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  10914. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  10915. */
  10916. BoundingSphere.prototype.equals = function(right) {
  10917. return BoundingSphere.equals(this, right);
  10918. };
  10919. /**
  10920. * Duplicates this BoundingSphere instance.
  10921. *
  10922. * @param {BoundingSphere} [result] The object onto which to store the result.
  10923. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10924. */
  10925. BoundingSphere.prototype.clone = function(result) {
  10926. return BoundingSphere.clone(this, result);
  10927. };
  10928. return BoundingSphere;
  10929. });
  10930. /*global define*/
  10931. define('Core/Fullscreen',[
  10932. './defined',
  10933. './defineProperties'
  10934. ], function(
  10935. defined,
  10936. defineProperties) {
  10937. 'use strict';
  10938. var _supportsFullscreen;
  10939. var _names = {
  10940. requestFullscreen : undefined,
  10941. exitFullscreen : undefined,
  10942. fullscreenEnabled : undefined,
  10943. fullscreenElement : undefined,
  10944. fullscreenchange : undefined,
  10945. fullscreenerror : undefined
  10946. };
  10947. /**
  10948. * Browser-independent functions for working with the standard fullscreen API.
  10949. *
  10950. * @exports Fullscreen
  10951. *
  10952. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  10953. */
  10954. var Fullscreen = {};
  10955. defineProperties(Fullscreen, {
  10956. /**
  10957. * The element that is currently fullscreen, if any. To simply check if the
  10958. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  10959. * @memberof Fullscreen
  10960. * @type {Object}
  10961. * @readonly
  10962. */
  10963. element : {
  10964. get : function() {
  10965. if (!Fullscreen.supportsFullscreen()) {
  10966. return undefined;
  10967. }
  10968. return document[_names.fullscreenElement];
  10969. }
  10970. },
  10971. /**
  10972. * The name of the event on the document that is fired when fullscreen is
  10973. * entered or exited. This event name is intended for use with addEventListener.
  10974. * In your event handler, to determine if the browser is in fullscreen mode or not,
  10975. * use {@link Fullscreen#fullscreen}.
  10976. * @memberof Fullscreen
  10977. * @type {String}
  10978. * @readonly
  10979. */
  10980. changeEventName : {
  10981. get : function() {
  10982. if (!Fullscreen.supportsFullscreen()) {
  10983. return undefined;
  10984. }
  10985. return _names.fullscreenchange;
  10986. }
  10987. },
  10988. /**
  10989. * The name of the event that is fired when a fullscreen error
  10990. * occurs. This event name is intended for use with addEventListener.
  10991. * @memberof Fullscreen
  10992. * @type {String}
  10993. * @readonly
  10994. */
  10995. errorEventName : {
  10996. get : function() {
  10997. if (!Fullscreen.supportsFullscreen()) {
  10998. return undefined;
  10999. }
  11000. return _names.fullscreenerror;
  11001. }
  11002. },
  11003. /**
  11004. * Determine whether the browser will allow an element to be made fullscreen, or not.
  11005. * For example, by default, iframes cannot go fullscreen unless the containing page
  11006. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  11007. * @memberof Fullscreen
  11008. * @type {Boolean}
  11009. * @readonly
  11010. */
  11011. enabled : {
  11012. get : function() {
  11013. if (!Fullscreen.supportsFullscreen()) {
  11014. return undefined;
  11015. }
  11016. return document[_names.fullscreenEnabled];
  11017. }
  11018. },
  11019. /**
  11020. * Determines if the browser is currently in fullscreen mode.
  11021. * @memberof Fullscreen
  11022. * @type {Boolean}
  11023. * @readonly
  11024. */
  11025. fullscreen : {
  11026. get : function() {
  11027. if (!Fullscreen.supportsFullscreen()) {
  11028. return undefined;
  11029. }
  11030. return Fullscreen.element !== null;
  11031. }
  11032. }
  11033. });
  11034. /**
  11035. * Detects whether the browser supports the standard fullscreen API.
  11036. *
  11037. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  11038. * <code>false</code> otherwise.
  11039. */
  11040. Fullscreen.supportsFullscreen = function() {
  11041. if (defined(_supportsFullscreen)) {
  11042. return _supportsFullscreen;
  11043. }
  11044. _supportsFullscreen = false;
  11045. var body = document.body;
  11046. if (typeof body.requestFullscreen === 'function') {
  11047. // go with the unprefixed, standard set of names
  11048. _names.requestFullscreen = 'requestFullscreen';
  11049. _names.exitFullscreen = 'exitFullscreen';
  11050. _names.fullscreenEnabled = 'fullscreenEnabled';
  11051. _names.fullscreenElement = 'fullscreenElement';
  11052. _names.fullscreenchange = 'fullscreenchange';
  11053. _names.fullscreenerror = 'fullscreenerror';
  11054. _supportsFullscreen = true;
  11055. return _supportsFullscreen;
  11056. }
  11057. //check for the correct combination of prefix plus the various names that browsers use
  11058. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  11059. var name;
  11060. for (var i = 0, len = prefixes.length; i < len; ++i) {
  11061. var prefix = prefixes[i];
  11062. // casing of Fullscreen differs across browsers
  11063. name = prefix + 'RequestFullscreen';
  11064. if (typeof body[name] === 'function') {
  11065. _names.requestFullscreen = name;
  11066. _supportsFullscreen = true;
  11067. } else {
  11068. name = prefix + 'RequestFullScreen';
  11069. if (typeof body[name] === 'function') {
  11070. _names.requestFullscreen = name;
  11071. _supportsFullscreen = true;
  11072. }
  11073. }
  11074. // disagreement about whether it's "exit" as per spec, or "cancel"
  11075. name = prefix + 'ExitFullscreen';
  11076. if (typeof document[name] === 'function') {
  11077. _names.exitFullscreen = name;
  11078. } else {
  11079. name = prefix + 'CancelFullScreen';
  11080. if (typeof document[name] === 'function') {
  11081. _names.exitFullscreen = name;
  11082. }
  11083. }
  11084. // casing of Fullscreen differs across browsers
  11085. name = prefix + 'FullscreenEnabled';
  11086. if (document[name] !== undefined) {
  11087. _names.fullscreenEnabled = name;
  11088. } else {
  11089. name = prefix + 'FullScreenEnabled';
  11090. if (document[name] !== undefined) {
  11091. _names.fullscreenEnabled = name;
  11092. }
  11093. }
  11094. // casing of Fullscreen differs across browsers
  11095. name = prefix + 'FullscreenElement';
  11096. if (document[name] !== undefined) {
  11097. _names.fullscreenElement = name;
  11098. } else {
  11099. name = prefix + 'FullScreenElement';
  11100. if (document[name] !== undefined) {
  11101. _names.fullscreenElement = name;
  11102. }
  11103. }
  11104. // thankfully, event names are all lowercase per spec
  11105. name = prefix + 'fullscreenchange';
  11106. // event names do not have 'on' in the front, but the property on the document does
  11107. if (document['on' + name] !== undefined) {
  11108. //except on IE
  11109. if (prefix === 'ms') {
  11110. name = 'MSFullscreenChange';
  11111. }
  11112. _names.fullscreenchange = name;
  11113. }
  11114. name = prefix + 'fullscreenerror';
  11115. if (document['on' + name] !== undefined) {
  11116. //except on IE
  11117. if (prefix === 'ms') {
  11118. name = 'MSFullscreenError';
  11119. }
  11120. _names.fullscreenerror = name;
  11121. }
  11122. }
  11123. return _supportsFullscreen;
  11124. };
  11125. /**
  11126. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  11127. * If fullscreen mode is not supported by the browser, does nothing.
  11128. *
  11129. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  11130. * @param {HMDVRDevice} [vrDevice] The VR device.
  11131. *
  11132. * @example
  11133. * // Put the entire page into fullscreen.
  11134. * Cesium.Fullscreen.requestFullscreen(document.body)
  11135. *
  11136. * // Place only the Cesium canvas into fullscreen.
  11137. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  11138. */
  11139. Fullscreen.requestFullscreen = function(element, vrDevice) {
  11140. if (!Fullscreen.supportsFullscreen()) {
  11141. return;
  11142. }
  11143. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  11144. };
  11145. /**
  11146. * Asynchronously exits fullscreen mode. If the browser is not currently
  11147. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  11148. */
  11149. Fullscreen.exitFullscreen = function() {
  11150. if (!Fullscreen.supportsFullscreen()) {
  11151. return;
  11152. }
  11153. document[_names.exitFullscreen]();
  11154. };
  11155. return Fullscreen;
  11156. });
  11157. /*global define*/
  11158. define('Core/FeatureDetection',[
  11159. './defaultValue',
  11160. './defined',
  11161. './Fullscreen'
  11162. ], function(
  11163. defaultValue,
  11164. defined,
  11165. Fullscreen) {
  11166. 'use strict';
  11167. var theNavigator;
  11168. if (typeof navigator !== 'undefined') {
  11169. theNavigator = navigator;
  11170. } else {
  11171. theNavigator = {};
  11172. }
  11173. function extractVersion(versionString) {
  11174. var parts = versionString.split('.');
  11175. for (var i = 0, len = parts.length; i < len; ++i) {
  11176. parts[i] = parseInt(parts[i], 10);
  11177. }
  11178. return parts;
  11179. }
  11180. var isChromeResult;
  11181. var chromeVersionResult;
  11182. function isChrome() {
  11183. if (!defined(isChromeResult)) {
  11184. isChromeResult = false;
  11185. // Edge contains Chrome in the user agent too
  11186. if (!isEdge()) {
  11187. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11188. if (fields !== null) {
  11189. isChromeResult = true;
  11190. chromeVersionResult = extractVersion(fields[1]);
  11191. }
  11192. }
  11193. }
  11194. return isChromeResult;
  11195. }
  11196. function chromeVersion() {
  11197. return isChrome() && chromeVersionResult;
  11198. }
  11199. var isSafariResult;
  11200. var safariVersionResult;
  11201. function isSafari() {
  11202. if (!defined(isSafariResult)) {
  11203. isSafariResult = false;
  11204. // Chrome and Edge contain Safari in the user agent too
  11205. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  11206. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11207. if (fields !== null) {
  11208. isSafariResult = true;
  11209. safariVersionResult = extractVersion(fields[1]);
  11210. }
  11211. }
  11212. }
  11213. return isSafariResult;
  11214. }
  11215. function safariVersion() {
  11216. return isSafari() && safariVersionResult;
  11217. }
  11218. var isWebkitResult;
  11219. var webkitVersionResult;
  11220. function isWebkit() {
  11221. if (!defined(isWebkitResult)) {
  11222. isWebkitResult = false;
  11223. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  11224. if (fields !== null) {
  11225. isWebkitResult = true;
  11226. webkitVersionResult = extractVersion(fields[1]);
  11227. webkitVersionResult.isNightly = !!fields[2];
  11228. }
  11229. }
  11230. return isWebkitResult;
  11231. }
  11232. function webkitVersion() {
  11233. return isWebkit() && webkitVersionResult;
  11234. }
  11235. var isInternetExplorerResult;
  11236. var internetExplorerVersionResult;
  11237. function isInternetExplorer() {
  11238. if (!defined(isInternetExplorerResult)) {
  11239. isInternetExplorerResult = false;
  11240. var fields;
  11241. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  11242. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  11243. if (fields !== null) {
  11244. isInternetExplorerResult = true;
  11245. internetExplorerVersionResult = extractVersion(fields[1]);
  11246. }
  11247. } else if (theNavigator.appName === 'Netscape') {
  11248. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  11249. if (fields !== null) {
  11250. isInternetExplorerResult = true;
  11251. internetExplorerVersionResult = extractVersion(fields[1]);
  11252. }
  11253. }
  11254. }
  11255. return isInternetExplorerResult;
  11256. }
  11257. function internetExplorerVersion() {
  11258. return isInternetExplorer() && internetExplorerVersionResult;
  11259. }
  11260. var isEdgeResult;
  11261. var edgeVersionResult;
  11262. function isEdge() {
  11263. if (!defined(isEdgeResult)) {
  11264. isEdgeResult = false;
  11265. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11266. if (fields !== null) {
  11267. isEdgeResult = true;
  11268. edgeVersionResult = extractVersion(fields[1]);
  11269. }
  11270. }
  11271. return isEdgeResult;
  11272. }
  11273. function edgeVersion() {
  11274. return isEdge() && edgeVersionResult;
  11275. }
  11276. var isFirefoxResult;
  11277. var firefoxVersionResult;
  11278. function isFirefox() {
  11279. if (!defined(isFirefoxResult)) {
  11280. isFirefoxResult = false;
  11281. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  11282. if (fields !== null) {
  11283. isFirefoxResult = true;
  11284. firefoxVersionResult = extractVersion(fields[1]);
  11285. }
  11286. }
  11287. return isFirefoxResult;
  11288. }
  11289. var isWindowsResult;
  11290. function isWindows() {
  11291. if (!defined(isWindowsResult)) {
  11292. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  11293. }
  11294. return isWindowsResult;
  11295. }
  11296. function firefoxVersion() {
  11297. return isFirefox() && firefoxVersionResult;
  11298. }
  11299. var hasPointerEvents;
  11300. function supportsPointerEvents() {
  11301. if (!defined(hasPointerEvents)) {
  11302. //While navigator.pointerEnabled is deprecated in the W3C specification
  11303. //we still need to use it if it exists in order to support browsers
  11304. //that rely on it, such as the Windows WebBrowser control which defines
  11305. //PointerEvent but sets navigator.pointerEnabled to false.
  11306. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  11307. }
  11308. return hasPointerEvents;
  11309. }
  11310. var imageRenderingValueResult;
  11311. var supportsImageRenderingPixelatedResult;
  11312. function supportsImageRenderingPixelated() {
  11313. if (!defined(supportsImageRenderingPixelatedResult)) {
  11314. var canvas = document.createElement('canvas');
  11315. canvas.setAttribute('style',
  11316. 'image-rendering: -moz-crisp-edges;' +
  11317. 'image-rendering: pixelated;');
  11318. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  11319. var tmp = canvas.style.imageRendering;
  11320. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  11321. if (supportsImageRenderingPixelatedResult) {
  11322. imageRenderingValueResult = tmp;
  11323. }
  11324. }
  11325. return supportsImageRenderingPixelatedResult;
  11326. }
  11327. function imageRenderingValue() {
  11328. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  11329. }
  11330. /**
  11331. * A set of functions to detect whether the current browser supports
  11332. * various features.
  11333. *
  11334. * @exports FeatureDetection
  11335. */
  11336. var FeatureDetection = {
  11337. isChrome : isChrome,
  11338. chromeVersion : chromeVersion,
  11339. isSafari : isSafari,
  11340. safariVersion : safariVersion,
  11341. isWebkit : isWebkit,
  11342. webkitVersion : webkitVersion,
  11343. isInternetExplorer : isInternetExplorer,
  11344. internetExplorerVersion : internetExplorerVersion,
  11345. isEdge : isEdge,
  11346. edgeVersion : edgeVersion,
  11347. isFirefox : isFirefox,
  11348. firefoxVersion : firefoxVersion,
  11349. isWindows : isWindows,
  11350. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  11351. supportsPointerEvents : supportsPointerEvents,
  11352. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  11353. imageRenderingValue: imageRenderingValue
  11354. };
  11355. /**
  11356. * Detects whether the current browser supports the full screen standard.
  11357. *
  11358. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  11359. *
  11360. * @see Fullscreen
  11361. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  11362. */
  11363. FeatureDetection.supportsFullscreen = function() {
  11364. return Fullscreen.supportsFullscreen();
  11365. };
  11366. /**
  11367. * Detects whether the current browser supports typed arrays.
  11368. *
  11369. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  11370. *
  11371. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  11372. */
  11373. FeatureDetection.supportsTypedArrays = function() {
  11374. return typeof ArrayBuffer !== 'undefined';
  11375. };
  11376. /**
  11377. * Detects whether the current browser supports Web Workers.
  11378. *
  11379. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  11380. *
  11381. * @see {@link http://www.w3.org/TR/workers/}
  11382. */
  11383. FeatureDetection.supportsWebWorkers = function() {
  11384. return typeof Worker !== 'undefined';
  11385. };
  11386. return FeatureDetection;
  11387. });
  11388. /*global define*/
  11389. define('Core/WebGLConstants',[
  11390. './freezeObject'
  11391. ], function(
  11392. freezeObject) {
  11393. 'use strict';
  11394. /**
  11395. * Enum containing WebGL Constant values by name.
  11396. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  11397. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  11398. *
  11399. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  11400. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  11401. * specifications.
  11402. *
  11403. * @exports WebGLConstants
  11404. */
  11405. var WebGLConstants = {
  11406. DEPTH_BUFFER_BIT : 0x00000100,
  11407. STENCIL_BUFFER_BIT : 0x00000400,
  11408. COLOR_BUFFER_BIT : 0x00004000,
  11409. POINTS : 0x0000,
  11410. LINES : 0x0001,
  11411. LINE_LOOP : 0x0002,
  11412. LINE_STRIP : 0x0003,
  11413. TRIANGLES : 0x0004,
  11414. TRIANGLE_STRIP : 0x0005,
  11415. TRIANGLE_FAN : 0x0006,
  11416. ZERO : 0,
  11417. ONE : 1,
  11418. SRC_COLOR : 0x0300,
  11419. ONE_MINUS_SRC_COLOR : 0x0301,
  11420. SRC_ALPHA : 0x0302,
  11421. ONE_MINUS_SRC_ALPHA : 0x0303,
  11422. DST_ALPHA : 0x0304,
  11423. ONE_MINUS_DST_ALPHA : 0x0305,
  11424. DST_COLOR : 0x0306,
  11425. ONE_MINUS_DST_COLOR : 0x0307,
  11426. SRC_ALPHA_SATURATE : 0x0308,
  11427. FUNC_ADD : 0x8006,
  11428. BLEND_EQUATION : 0x8009,
  11429. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  11430. BLEND_EQUATION_ALPHA : 0x883D,
  11431. FUNC_SUBTRACT : 0x800A,
  11432. FUNC_REVERSE_SUBTRACT : 0x800B,
  11433. BLEND_DST_RGB : 0x80C8,
  11434. BLEND_SRC_RGB : 0x80C9,
  11435. BLEND_DST_ALPHA : 0x80CA,
  11436. BLEND_SRC_ALPHA : 0x80CB,
  11437. CONSTANT_COLOR : 0x8001,
  11438. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  11439. CONSTANT_ALPHA : 0x8003,
  11440. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  11441. BLEND_COLOR : 0x8005,
  11442. ARRAY_BUFFER : 0x8892,
  11443. ELEMENT_ARRAY_BUFFER : 0x8893,
  11444. ARRAY_BUFFER_BINDING : 0x8894,
  11445. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  11446. STREAM_DRAW : 0x88E0,
  11447. STATIC_DRAW : 0x88E4,
  11448. DYNAMIC_DRAW : 0x88E8,
  11449. BUFFER_SIZE : 0x8764,
  11450. BUFFER_USAGE : 0x8765,
  11451. CURRENT_VERTEX_ATTRIB : 0x8626,
  11452. FRONT : 0x0404,
  11453. BACK : 0x0405,
  11454. FRONT_AND_BACK : 0x0408,
  11455. CULL_FACE : 0x0B44,
  11456. BLEND : 0x0BE2,
  11457. DITHER : 0x0BD0,
  11458. STENCIL_TEST : 0x0B90,
  11459. DEPTH_TEST : 0x0B71,
  11460. SCISSOR_TEST : 0x0C11,
  11461. POLYGON_OFFSET_FILL : 0x8037,
  11462. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  11463. SAMPLE_COVERAGE : 0x80A0,
  11464. NO_ERROR : 0,
  11465. INVALID_ENUM : 0x0500,
  11466. INVALID_VALUE : 0x0501,
  11467. INVALID_OPERATION : 0x0502,
  11468. OUT_OF_MEMORY : 0x0505,
  11469. CW : 0x0900,
  11470. CCW : 0x0901,
  11471. LINE_WIDTH : 0x0B21,
  11472. ALIASED_POINT_SIZE_RANGE : 0x846D,
  11473. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  11474. CULL_FACE_MODE : 0x0B45,
  11475. FRONT_FACE : 0x0B46,
  11476. DEPTH_RANGE : 0x0B70,
  11477. DEPTH_WRITEMASK : 0x0B72,
  11478. DEPTH_CLEAR_VALUE : 0x0B73,
  11479. DEPTH_FUNC : 0x0B74,
  11480. STENCIL_CLEAR_VALUE : 0x0B91,
  11481. STENCIL_FUNC : 0x0B92,
  11482. STENCIL_FAIL : 0x0B94,
  11483. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  11484. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  11485. STENCIL_REF : 0x0B97,
  11486. STENCIL_VALUE_MASK : 0x0B93,
  11487. STENCIL_WRITEMASK : 0x0B98,
  11488. STENCIL_BACK_FUNC : 0x8800,
  11489. STENCIL_BACK_FAIL : 0x8801,
  11490. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  11491. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  11492. STENCIL_BACK_REF : 0x8CA3,
  11493. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  11494. STENCIL_BACK_WRITEMASK : 0x8CA5,
  11495. VIEWPORT : 0x0BA2,
  11496. SCISSOR_BOX : 0x0C10,
  11497. COLOR_CLEAR_VALUE : 0x0C22,
  11498. COLOR_WRITEMASK : 0x0C23,
  11499. UNPACK_ALIGNMENT : 0x0CF5,
  11500. PACK_ALIGNMENT : 0x0D05,
  11501. MAX_TEXTURE_SIZE : 0x0D33,
  11502. MAX_VIEWPORT_DIMS : 0x0D3A,
  11503. SUBPIXEL_BITS : 0x0D50,
  11504. RED_BITS : 0x0D52,
  11505. GREEN_BITS : 0x0D53,
  11506. BLUE_BITS : 0x0D54,
  11507. ALPHA_BITS : 0x0D55,
  11508. DEPTH_BITS : 0x0D56,
  11509. STENCIL_BITS : 0x0D57,
  11510. POLYGON_OFFSET_UNITS : 0x2A00,
  11511. POLYGON_OFFSET_FACTOR : 0x8038,
  11512. TEXTURE_BINDING_2D : 0x8069,
  11513. SAMPLE_BUFFERS : 0x80A8,
  11514. SAMPLES : 0x80A9,
  11515. SAMPLE_COVERAGE_VALUE : 0x80AA,
  11516. SAMPLE_COVERAGE_INVERT : 0x80AB,
  11517. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  11518. DONT_CARE : 0x1100,
  11519. FASTEST : 0x1101,
  11520. NICEST : 0x1102,
  11521. GENERATE_MIPMAP_HINT : 0x8192,
  11522. BYTE : 0x1400,
  11523. UNSIGNED_BYTE : 0x1401,
  11524. SHORT : 0x1402,
  11525. UNSIGNED_SHORT : 0x1403,
  11526. INT : 0x1404,
  11527. UNSIGNED_INT : 0x1405,
  11528. FLOAT : 0x1406,
  11529. DEPTH_COMPONENT : 0x1902,
  11530. ALPHA : 0x1906,
  11531. RGB : 0x1907,
  11532. RGBA : 0x1908,
  11533. LUMINANCE : 0x1909,
  11534. LUMINANCE_ALPHA : 0x190A,
  11535. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  11536. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  11537. UNSIGNED_SHORT_5_6_5 : 0x8363,
  11538. FRAGMENT_SHADER : 0x8B30,
  11539. VERTEX_SHADER : 0x8B31,
  11540. MAX_VERTEX_ATTRIBS : 0x8869,
  11541. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  11542. MAX_VARYING_VECTORS : 0x8DFC,
  11543. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  11544. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  11545. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  11546. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  11547. SHADER_TYPE : 0x8B4F,
  11548. DELETE_STATUS : 0x8B80,
  11549. LINK_STATUS : 0x8B82,
  11550. VALIDATE_STATUS : 0x8B83,
  11551. ATTACHED_SHADERS : 0x8B85,
  11552. ACTIVE_UNIFORMS : 0x8B86,
  11553. ACTIVE_ATTRIBUTES : 0x8B89,
  11554. SHADING_LANGUAGE_VERSION : 0x8B8C,
  11555. CURRENT_PROGRAM : 0x8B8D,
  11556. NEVER : 0x0200,
  11557. LESS : 0x0201,
  11558. EQUAL : 0x0202,
  11559. LEQUAL : 0x0203,
  11560. GREATER : 0x0204,
  11561. NOTEQUAL : 0x0205,
  11562. GEQUAL : 0x0206,
  11563. ALWAYS : 0x0207,
  11564. KEEP : 0x1E00,
  11565. REPLACE : 0x1E01,
  11566. INCR : 0x1E02,
  11567. DECR : 0x1E03,
  11568. INVERT : 0x150A,
  11569. INCR_WRAP : 0x8507,
  11570. DECR_WRAP : 0x8508,
  11571. VENDOR : 0x1F00,
  11572. RENDERER : 0x1F01,
  11573. VERSION : 0x1F02,
  11574. NEAREST : 0x2600,
  11575. LINEAR : 0x2601,
  11576. NEAREST_MIPMAP_NEAREST : 0x2700,
  11577. LINEAR_MIPMAP_NEAREST : 0x2701,
  11578. NEAREST_MIPMAP_LINEAR : 0x2702,
  11579. LINEAR_MIPMAP_LINEAR : 0x2703,
  11580. TEXTURE_MAG_FILTER : 0x2800,
  11581. TEXTURE_MIN_FILTER : 0x2801,
  11582. TEXTURE_WRAP_S : 0x2802,
  11583. TEXTURE_WRAP_T : 0x2803,
  11584. TEXTURE_2D : 0x0DE1,
  11585. TEXTURE : 0x1702,
  11586. TEXTURE_CUBE_MAP : 0x8513,
  11587. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  11588. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  11589. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  11590. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  11591. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  11592. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  11593. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  11594. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  11595. TEXTURE0 : 0x84C0,
  11596. TEXTURE1 : 0x84C1,
  11597. TEXTURE2 : 0x84C2,
  11598. TEXTURE3 : 0x84C3,
  11599. TEXTURE4 : 0x84C4,
  11600. TEXTURE5 : 0x84C5,
  11601. TEXTURE6 : 0x84C6,
  11602. TEXTURE7 : 0x84C7,
  11603. TEXTURE8 : 0x84C8,
  11604. TEXTURE9 : 0x84C9,
  11605. TEXTURE10 : 0x84CA,
  11606. TEXTURE11 : 0x84CB,
  11607. TEXTURE12 : 0x84CC,
  11608. TEXTURE13 : 0x84CD,
  11609. TEXTURE14 : 0x84CE,
  11610. TEXTURE15 : 0x84CF,
  11611. TEXTURE16 : 0x84D0,
  11612. TEXTURE17 : 0x84D1,
  11613. TEXTURE18 : 0x84D2,
  11614. TEXTURE19 : 0x84D3,
  11615. TEXTURE20 : 0x84D4,
  11616. TEXTURE21 : 0x84D5,
  11617. TEXTURE22 : 0x84D6,
  11618. TEXTURE23 : 0x84D7,
  11619. TEXTURE24 : 0x84D8,
  11620. TEXTURE25 : 0x84D9,
  11621. TEXTURE26 : 0x84DA,
  11622. TEXTURE27 : 0x84DB,
  11623. TEXTURE28 : 0x84DC,
  11624. TEXTURE29 : 0x84DD,
  11625. TEXTURE30 : 0x84DE,
  11626. TEXTURE31 : 0x84DF,
  11627. ACTIVE_TEXTURE : 0x84E0,
  11628. REPEAT : 0x2901,
  11629. CLAMP_TO_EDGE : 0x812F,
  11630. MIRRORED_REPEAT : 0x8370,
  11631. FLOAT_VEC2 : 0x8B50,
  11632. FLOAT_VEC3 : 0x8B51,
  11633. FLOAT_VEC4 : 0x8B52,
  11634. INT_VEC2 : 0x8B53,
  11635. INT_VEC3 : 0x8B54,
  11636. INT_VEC4 : 0x8B55,
  11637. BOOL : 0x8B56,
  11638. BOOL_VEC2 : 0x8B57,
  11639. BOOL_VEC3 : 0x8B58,
  11640. BOOL_VEC4 : 0x8B59,
  11641. FLOAT_MAT2 : 0x8B5A,
  11642. FLOAT_MAT3 : 0x8B5B,
  11643. FLOAT_MAT4 : 0x8B5C,
  11644. SAMPLER_2D : 0x8B5E,
  11645. SAMPLER_CUBE : 0x8B60,
  11646. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  11647. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  11648. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  11649. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  11650. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  11651. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  11652. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  11653. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  11654. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  11655. COMPILE_STATUS : 0x8B81,
  11656. LOW_FLOAT : 0x8DF0,
  11657. MEDIUM_FLOAT : 0x8DF1,
  11658. HIGH_FLOAT : 0x8DF2,
  11659. LOW_INT : 0x8DF3,
  11660. MEDIUM_INT : 0x8DF4,
  11661. HIGH_INT : 0x8DF5,
  11662. FRAMEBUFFER : 0x8D40,
  11663. RENDERBUFFER : 0x8D41,
  11664. RGBA4 : 0x8056,
  11665. RGB5_A1 : 0x8057,
  11666. RGB565 : 0x8D62,
  11667. DEPTH_COMPONENT16 : 0x81A5,
  11668. STENCIL_INDEX : 0x1901,
  11669. STENCIL_INDEX8 : 0x8D48,
  11670. DEPTH_STENCIL : 0x84F9,
  11671. RENDERBUFFER_WIDTH : 0x8D42,
  11672. RENDERBUFFER_HEIGHT : 0x8D43,
  11673. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  11674. RENDERBUFFER_RED_SIZE : 0x8D50,
  11675. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  11676. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  11677. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  11678. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  11679. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  11680. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  11681. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  11682. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  11683. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  11684. COLOR_ATTACHMENT0 : 0x8CE0,
  11685. DEPTH_ATTACHMENT : 0x8D00,
  11686. STENCIL_ATTACHMENT : 0x8D20,
  11687. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  11688. NONE : 0,
  11689. FRAMEBUFFER_COMPLETE : 0x8CD5,
  11690. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  11691. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  11692. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  11693. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  11694. FRAMEBUFFER_BINDING : 0x8CA6,
  11695. RENDERBUFFER_BINDING : 0x8CA7,
  11696. MAX_RENDERBUFFER_SIZE : 0x84E8,
  11697. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  11698. UNPACK_FLIP_Y_WEBGL : 0x9240,
  11699. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  11700. CONTEXT_LOST_WEBGL : 0x9242,
  11701. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  11702. BROWSER_DEFAULT_WEBGL : 0x9244,
  11703. // Desktop OpenGL
  11704. DOUBLE : 0x140A,
  11705. // WebGL 2
  11706. READ_BUFFER : 0x0C02,
  11707. UNPACK_ROW_LENGTH : 0x0CF2,
  11708. UNPACK_SKIP_ROWS : 0x0CF3,
  11709. UNPACK_SKIP_PIXELS : 0x0CF4,
  11710. PACK_ROW_LENGTH : 0x0D02,
  11711. PACK_SKIP_ROWS : 0x0D03,
  11712. PACK_SKIP_PIXELS : 0x0D04,
  11713. COLOR : 0x1800,
  11714. DEPTH : 0x1801,
  11715. STENCIL : 0x1802,
  11716. RED : 0x1903,
  11717. RGB8 : 0x8051,
  11718. RGBA8 : 0x8058,
  11719. RGB10_A2 : 0x8059,
  11720. TEXTURE_BINDING_3D : 0x806A,
  11721. UNPACK_SKIP_IMAGES : 0x806D,
  11722. UNPACK_IMAGE_HEIGHT : 0x806E,
  11723. TEXTURE_3D : 0x806F,
  11724. TEXTURE_WRAP_R : 0x8072,
  11725. MAX_3D_TEXTURE_SIZE : 0x8073,
  11726. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  11727. MAX_ELEMENTS_VERTICES : 0x80E8,
  11728. MAX_ELEMENTS_INDICES : 0x80E9,
  11729. TEXTURE_MIN_LOD : 0x813A,
  11730. TEXTURE_MAX_LOD : 0x813B,
  11731. TEXTURE_BASE_LEVEL : 0x813C,
  11732. TEXTURE_MAX_LEVEL : 0x813D,
  11733. MIN : 0x8007,
  11734. MAX : 0x8008,
  11735. DEPTH_COMPONENT24 : 0x81A6,
  11736. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  11737. TEXTURE_COMPARE_MODE : 0x884C,
  11738. TEXTURE_COMPARE_FUNC : 0x884D,
  11739. CURRENT_QUERY : 0x8865,
  11740. QUERY_RESULT : 0x8866,
  11741. QUERY_RESULT_AVAILABLE : 0x8867,
  11742. STREAM_READ : 0x88E1,
  11743. STREAM_COPY : 0x88E2,
  11744. STATIC_READ : 0x88E5,
  11745. STATIC_COPY : 0x88E6,
  11746. DYNAMIC_READ : 0x88E9,
  11747. DYNAMIC_COPY : 0x88EA,
  11748. MAX_DRAW_BUFFERS : 0x8824,
  11749. DRAW_BUFFER0 : 0x8825,
  11750. DRAW_BUFFER1 : 0x8826,
  11751. DRAW_BUFFER2 : 0x8827,
  11752. DRAW_BUFFER3 : 0x8828,
  11753. DRAW_BUFFER4 : 0x8829,
  11754. DRAW_BUFFER5 : 0x882A,
  11755. DRAW_BUFFER6 : 0x882B,
  11756. DRAW_BUFFER7 : 0x882C,
  11757. DRAW_BUFFER8 : 0x882D,
  11758. DRAW_BUFFER9 : 0x882E,
  11759. DRAW_BUFFER10 : 0x882F,
  11760. DRAW_BUFFER11 : 0x8830,
  11761. DRAW_BUFFER12 : 0x8831,
  11762. DRAW_BUFFER13 : 0x8832,
  11763. DRAW_BUFFER14 : 0x8833,
  11764. DRAW_BUFFER15 : 0x8834,
  11765. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  11766. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  11767. SAMPLER_3D : 0x8B5F,
  11768. SAMPLER_2D_SHADOW : 0x8B62,
  11769. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  11770. PIXEL_PACK_BUFFER : 0x88EB,
  11771. PIXEL_UNPACK_BUFFER : 0x88EC,
  11772. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  11773. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  11774. FLOAT_MAT2x3 : 0x8B65,
  11775. FLOAT_MAT2x4 : 0x8B66,
  11776. FLOAT_MAT3x2 : 0x8B67,
  11777. FLOAT_MAT3x4 : 0x8B68,
  11778. FLOAT_MAT4x2 : 0x8B69,
  11779. FLOAT_MAT4x3 : 0x8B6A,
  11780. SRGB : 0x8C40,
  11781. SRGB8 : 0x8C41,
  11782. SRGB8_ALPHA8 : 0x8C43,
  11783. COMPARE_REF_TO_TEXTURE : 0x884E,
  11784. RGBA32F : 0x8814,
  11785. RGB32F : 0x8815,
  11786. RGBA16F : 0x881A,
  11787. RGB16F : 0x881B,
  11788. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  11789. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  11790. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  11791. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  11792. MAX_VARYING_COMPONENTS : 0x8B4B,
  11793. TEXTURE_2D_ARRAY : 0x8C1A,
  11794. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  11795. R11F_G11F_B10F : 0x8C3A,
  11796. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  11797. RGB9_E5 : 0x8C3D,
  11798. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  11799. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  11800. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  11801. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  11802. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  11803. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  11804. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  11805. RASTERIZER_DISCARD : 0x8C89,
  11806. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  11807. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  11808. INTERLEAVED_ATTRIBS : 0x8C8C,
  11809. SEPARATE_ATTRIBS : 0x8C8D,
  11810. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  11811. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  11812. RGBA32UI : 0x8D70,
  11813. RGB32UI : 0x8D71,
  11814. RGBA16UI : 0x8D76,
  11815. RGB16UI : 0x8D77,
  11816. RGBA8UI : 0x8D7C,
  11817. RGB8UI : 0x8D7D,
  11818. RGBA32I : 0x8D82,
  11819. RGB32I : 0x8D83,
  11820. RGBA16I : 0x8D88,
  11821. RGB16I : 0x8D89,
  11822. RGBA8I : 0x8D8E,
  11823. RGB8I : 0x8D8F,
  11824. RED_INTEGER : 0x8D94,
  11825. RGB_INTEGER : 0x8D98,
  11826. RGBA_INTEGER : 0x8D99,
  11827. SAMPLER_2D_ARRAY : 0x8DC1,
  11828. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  11829. SAMPLER_CUBE_SHADOW : 0x8DC5,
  11830. UNSIGNED_INT_VEC2 : 0x8DC6,
  11831. UNSIGNED_INT_VEC3 : 0x8DC7,
  11832. UNSIGNED_INT_VEC4 : 0x8DC8,
  11833. INT_SAMPLER_2D : 0x8DCA,
  11834. INT_SAMPLER_3D : 0x8DCB,
  11835. INT_SAMPLER_CUBE : 0x8DCC,
  11836. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  11837. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  11838. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  11839. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  11840. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  11841. DEPTH_COMPONENT32F : 0x8CAC,
  11842. DEPTH32F_STENCIL8 : 0x8CAD,
  11843. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  11844. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  11845. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  11846. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  11847. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  11848. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  11849. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  11850. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  11851. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  11852. FRAMEBUFFER_DEFAULT : 0x8218,
  11853. UNSIGNED_INT_24_8 : 0x84FA,
  11854. DEPTH24_STENCIL8 : 0x88F0,
  11855. UNSIGNED_NORMALIZED : 0x8C17,
  11856. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  11857. READ_FRAMEBUFFER : 0x8CA8,
  11858. DRAW_FRAMEBUFFER : 0x8CA9,
  11859. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  11860. RENDERBUFFER_SAMPLES : 0x8CAB,
  11861. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  11862. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  11863. COLOR_ATTACHMENT1 : 0x8CE1,
  11864. COLOR_ATTACHMENT2 : 0x8CE2,
  11865. COLOR_ATTACHMENT3 : 0x8CE3,
  11866. COLOR_ATTACHMENT4 : 0x8CE4,
  11867. COLOR_ATTACHMENT5 : 0x8CE5,
  11868. COLOR_ATTACHMENT6 : 0x8CE6,
  11869. COLOR_ATTACHMENT7 : 0x8CE7,
  11870. COLOR_ATTACHMENT8 : 0x8CE8,
  11871. COLOR_ATTACHMENT9 : 0x8CE9,
  11872. COLOR_ATTACHMENT10 : 0x8CEA,
  11873. COLOR_ATTACHMENT11 : 0x8CEB,
  11874. COLOR_ATTACHMENT12 : 0x8CEC,
  11875. COLOR_ATTACHMENT13 : 0x8CED,
  11876. COLOR_ATTACHMENT14 : 0x8CEE,
  11877. COLOR_ATTACHMENT15 : 0x8CEF,
  11878. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  11879. MAX_SAMPLES : 0x8D57,
  11880. HALF_FLOAT : 0x140B,
  11881. RG : 0x8227,
  11882. RG_INTEGER : 0x8228,
  11883. R8 : 0x8229,
  11884. RG8 : 0x822B,
  11885. R16F : 0x822D,
  11886. R32F : 0x822E,
  11887. RG16F : 0x822F,
  11888. RG32F : 0x8230,
  11889. R8I : 0x8231,
  11890. R8UI : 0x8232,
  11891. R16I : 0x8233,
  11892. R16UI : 0x8234,
  11893. R32I : 0x8235,
  11894. R32UI : 0x8236,
  11895. RG8I : 0x8237,
  11896. RG8UI : 0x8238,
  11897. RG16I : 0x8239,
  11898. RG16UI : 0x823A,
  11899. RG32I : 0x823B,
  11900. RG32UI : 0x823C,
  11901. VERTEX_ARRAY_BINDING : 0x85B5,
  11902. R8_SNORM : 0x8F94,
  11903. RG8_SNORM : 0x8F95,
  11904. RGB8_SNORM : 0x8F96,
  11905. RGBA8_SNORM : 0x8F97,
  11906. SIGNED_NORMALIZED : 0x8F9C,
  11907. COPY_READ_BUFFER : 0x8F36,
  11908. COPY_WRITE_BUFFER : 0x8F37,
  11909. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  11910. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  11911. UNIFORM_BUFFER : 0x8A11,
  11912. UNIFORM_BUFFER_BINDING : 0x8A28,
  11913. UNIFORM_BUFFER_START : 0x8A29,
  11914. UNIFORM_BUFFER_SIZE : 0x8A2A,
  11915. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  11916. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  11917. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  11918. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  11919. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  11920. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  11921. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  11922. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  11923. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  11924. UNIFORM_TYPE : 0x8A37,
  11925. UNIFORM_SIZE : 0x8A38,
  11926. UNIFORM_BLOCK_INDEX : 0x8A3A,
  11927. UNIFORM_OFFSET : 0x8A3B,
  11928. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  11929. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  11930. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  11931. UNIFORM_BLOCK_BINDING : 0x8A3F,
  11932. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  11933. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  11934. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  11935. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  11936. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  11937. INVALID_INDEX : 0xFFFFFFFF,
  11938. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  11939. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  11940. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  11941. OBJECT_TYPE : 0x9112,
  11942. SYNC_CONDITION : 0x9113,
  11943. SYNC_STATUS : 0x9114,
  11944. SYNC_FLAGS : 0x9115,
  11945. SYNC_FENCE : 0x9116,
  11946. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  11947. UNSIGNALED : 0x9118,
  11948. SIGNALED : 0x9119,
  11949. ALREADY_SIGNALED : 0x911A,
  11950. TIMEOUT_EXPIRED : 0x911B,
  11951. CONDITION_SATISFIED : 0x911C,
  11952. WAIT_FAILED : 0x911D,
  11953. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  11954. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  11955. ANY_SAMPLES_PASSED : 0x8C2F,
  11956. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  11957. SAMPLER_BINDING : 0x8919,
  11958. RGB10_A2UI : 0x906F,
  11959. INT_2_10_10_10_REV : 0x8D9F,
  11960. TRANSFORM_FEEDBACK : 0x8E22,
  11961. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  11962. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  11963. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  11964. COMPRESSED_R11_EAC : 0x9270,
  11965. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  11966. COMPRESSED_RG11_EAC : 0x9272,
  11967. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  11968. COMPRESSED_RGB8_ETC2 : 0x9274,
  11969. COMPRESSED_SRGB8_ETC2 : 0x9275,
  11970. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  11971. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  11972. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  11973. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  11974. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  11975. MAX_ELEMENT_INDEX : 0x8D6B,
  11976. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  11977. };
  11978. return freezeObject(WebGLConstants);
  11979. });
  11980. /*global define*/
  11981. define('Core/ComponentDatatype',[
  11982. './defaultValue',
  11983. './defined',
  11984. './DeveloperError',
  11985. './FeatureDetection',
  11986. './freezeObject',
  11987. './WebGLConstants'
  11988. ], function(
  11989. defaultValue,
  11990. defined,
  11991. DeveloperError,
  11992. FeatureDetection,
  11993. freezeObject,
  11994. WebGLConstants) {
  11995. 'use strict';
  11996. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  11997. // from failing, since we won't be able to create a WebGL context anyway.
  11998. if (!FeatureDetection.supportsTypedArrays()) {
  11999. return {};
  12000. }
  12001. /**
  12002. * WebGL component datatypes. Components are intrinsics,
  12003. * which form attributes, which form vertices.
  12004. *
  12005. * @exports ComponentDatatype
  12006. */
  12007. var ComponentDatatype = {
  12008. /**
  12009. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  12010. * of an element in <code>Int8Array</code>.
  12011. *
  12012. * @type {Number}
  12013. * @constant
  12014. */
  12015. BYTE : WebGLConstants.BYTE,
  12016. /**
  12017. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  12018. * of an element in <code>Uint8Array</code>.
  12019. *
  12020. * @type {Number}
  12021. * @constant
  12022. */
  12023. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  12024. /**
  12025. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  12026. * of an element in <code>Int16Array</code>.
  12027. *
  12028. * @type {Number}
  12029. * @constant
  12030. */
  12031. SHORT : WebGLConstants.SHORT,
  12032. /**
  12033. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  12034. * of an element in <code>Uint16Array</code>.
  12035. *
  12036. * @type {Number}
  12037. * @constant
  12038. */
  12039. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  12040. /**
  12041. * 32-bit signed int corresponding to <code>INT</code> and the type
  12042. * of an element in <code>Int32Array</code>.
  12043. *
  12044. * @memberOf ComponentDatatype
  12045. *
  12046. * @type {Number}
  12047. * @constant
  12048. */
  12049. INT : WebGLConstants.INT,
  12050. /**
  12051. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  12052. * of an element in <code>Uint32Array</code>.
  12053. *
  12054. * @memberOf ComponentDatatype
  12055. *
  12056. * @type {Number}
  12057. * @constant
  12058. */
  12059. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  12060. /**
  12061. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  12062. * of an element in <code>Float32Array</code>.
  12063. *
  12064. * @type {Number}
  12065. * @constant
  12066. */
  12067. FLOAT : WebGLConstants.FLOAT,
  12068. /**
  12069. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  12070. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  12071. * and the type of an element in <code>Float64Array</code>.
  12072. *
  12073. * @memberOf ComponentDatatype
  12074. *
  12075. * @type {Number}
  12076. * @constant
  12077. * @default 0x140A
  12078. */
  12079. DOUBLE : WebGLConstants.DOUBLE
  12080. };
  12081. /**
  12082. * Returns the size, in bytes, of the corresponding datatype.
  12083. *
  12084. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  12085. * @returns {Number} The size in bytes.
  12086. *
  12087. * @exception {DeveloperError} componentDatatype is not a valid value.
  12088. *
  12089. * @example
  12090. * // Returns Int8Array.BYTES_PER_ELEMENT
  12091. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  12092. */
  12093. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  12094. if (!defined(componentDatatype)) {
  12095. throw new DeveloperError('value is required.');
  12096. }
  12097. switch (componentDatatype) {
  12098. case ComponentDatatype.BYTE:
  12099. return Int8Array.BYTES_PER_ELEMENT;
  12100. case ComponentDatatype.UNSIGNED_BYTE:
  12101. return Uint8Array.BYTES_PER_ELEMENT;
  12102. case ComponentDatatype.SHORT:
  12103. return Int16Array.BYTES_PER_ELEMENT;
  12104. case ComponentDatatype.UNSIGNED_SHORT:
  12105. return Uint16Array.BYTES_PER_ELEMENT;
  12106. case ComponentDatatype.INT:
  12107. return Int32Array.BYTES_PER_ELEMENT;
  12108. case ComponentDatatype.UNSIGNED_INT:
  12109. return Uint32Array.BYTES_PER_ELEMENT;
  12110. case ComponentDatatype.FLOAT:
  12111. return Float32Array.BYTES_PER_ELEMENT;
  12112. case ComponentDatatype.DOUBLE:
  12113. return Float64Array.BYTES_PER_ELEMENT;
  12114. default:
  12115. throw new DeveloperError('componentDatatype is not a valid value.');
  12116. }
  12117. };
  12118. /**
  12119. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  12120. *
  12121. * @param {TypedArray} array The typed array.
  12122. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  12123. */
  12124. ComponentDatatype.fromTypedArray = function(array) {
  12125. if (array instanceof Int8Array) {
  12126. return ComponentDatatype.BYTE;
  12127. }
  12128. if (array instanceof Uint8Array) {
  12129. return ComponentDatatype.UNSIGNED_BYTE;
  12130. }
  12131. if (array instanceof Int16Array) {
  12132. return ComponentDatatype.SHORT;
  12133. }
  12134. if (array instanceof Uint16Array) {
  12135. return ComponentDatatype.UNSIGNED_SHORT;
  12136. }
  12137. if (array instanceof Int32Array) {
  12138. return ComponentDatatype.INT;
  12139. }
  12140. if (array instanceof Uint32Array) {
  12141. return ComponentDatatype.UNSIGNED_INT;
  12142. }
  12143. if (array instanceof Float32Array) {
  12144. return ComponentDatatype.FLOAT;
  12145. }
  12146. if (array instanceof Float64Array) {
  12147. return ComponentDatatype.DOUBLE;
  12148. }
  12149. };
  12150. /**
  12151. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  12152. *
  12153. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  12154. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  12155. *
  12156. * @example
  12157. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  12158. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  12159. * }
  12160. */
  12161. ComponentDatatype.validate = function(componentDatatype) {
  12162. return defined(componentDatatype) &&
  12163. (componentDatatype === ComponentDatatype.BYTE ||
  12164. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  12165. componentDatatype === ComponentDatatype.SHORT ||
  12166. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  12167. componentDatatype === ComponentDatatype.INT ||
  12168. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  12169. componentDatatype === ComponentDatatype.FLOAT ||
  12170. componentDatatype === ComponentDatatype.DOUBLE);
  12171. };
  12172. /**
  12173. * Creates a typed array corresponding to component data type.
  12174. *
  12175. * @param {ComponentDatatype} componentDatatype The component data type.
  12176. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  12177. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  12178. *
  12179. * @exception {DeveloperError} componentDatatype is not a valid value.
  12180. *
  12181. * @example
  12182. * // creates a Float32Array with length of 100
  12183. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  12184. */
  12185. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  12186. if (!defined(componentDatatype)) {
  12187. throw new DeveloperError('componentDatatype is required.');
  12188. }
  12189. if (!defined(valuesOrLength)) {
  12190. throw new DeveloperError('valuesOrLength is required.');
  12191. }
  12192. switch (componentDatatype) {
  12193. case ComponentDatatype.BYTE:
  12194. return new Int8Array(valuesOrLength);
  12195. case ComponentDatatype.UNSIGNED_BYTE:
  12196. return new Uint8Array(valuesOrLength);
  12197. case ComponentDatatype.SHORT:
  12198. return new Int16Array(valuesOrLength);
  12199. case ComponentDatatype.UNSIGNED_SHORT:
  12200. return new Uint16Array(valuesOrLength);
  12201. case ComponentDatatype.INT:
  12202. return new Int32Array(valuesOrLength);
  12203. case ComponentDatatype.UNSIGNED_INT:
  12204. return new Uint32Array(valuesOrLength);
  12205. case ComponentDatatype.FLOAT:
  12206. return new Float32Array(valuesOrLength);
  12207. case ComponentDatatype.DOUBLE:
  12208. return new Float64Array(valuesOrLength);
  12209. default:
  12210. throw new DeveloperError('componentDatatype is not a valid value.');
  12211. }
  12212. };
  12213. /**
  12214. * Creates a typed view of an array of bytes.
  12215. *
  12216. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  12217. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  12218. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  12219. * @param {Number} [length] The number of elements in the view.
  12220. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  12221. *
  12222. * @exception {DeveloperError} componentDatatype is not a valid value.
  12223. */
  12224. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  12225. if (!defined(componentDatatype)) {
  12226. throw new DeveloperError('componentDatatype is required.');
  12227. }
  12228. if (!defined(buffer)) {
  12229. throw new DeveloperError('buffer is required.');
  12230. }
  12231. byteOffset = defaultValue(byteOffset, 0);
  12232. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  12233. switch (componentDatatype) {
  12234. case ComponentDatatype.BYTE:
  12235. return new Int8Array(buffer, byteOffset, length);
  12236. case ComponentDatatype.UNSIGNED_BYTE:
  12237. return new Uint8Array(buffer, byteOffset, length);
  12238. case ComponentDatatype.SHORT:
  12239. return new Int16Array(buffer, byteOffset, length);
  12240. case ComponentDatatype.UNSIGNED_SHORT:
  12241. return new Uint16Array(buffer, byteOffset, length);
  12242. case ComponentDatatype.INT:
  12243. return new Int32Array(buffer, byteOffset, length);
  12244. case ComponentDatatype.UNSIGNED_INT:
  12245. return new Uint32Array(buffer, byteOffset, length);
  12246. case ComponentDatatype.FLOAT:
  12247. return new Float32Array(buffer, byteOffset, length);
  12248. case ComponentDatatype.DOUBLE:
  12249. return new Float64Array(buffer, byteOffset, length);
  12250. default:
  12251. throw new DeveloperError('componentDatatype is not a valid value.');
  12252. }
  12253. };
  12254. /**
  12255. * Get the ComponentDatatype from its name.
  12256. *
  12257. * @param {String} name The name of the ComponentDatatype.
  12258. * @returns {ComponentDatatype} The ComponentDatatype.
  12259. *
  12260. * @exception {DeveloperError} name is not a valid value.
  12261. */
  12262. ComponentDatatype.fromName = function(name) {
  12263. switch (name) {
  12264. case 'BYTE':
  12265. return ComponentDatatype.BYTE;
  12266. case 'UNSIGNED_BYTE':
  12267. return ComponentDatatype.UNSIGNED_BYTE;
  12268. case 'SHORT':
  12269. return ComponentDatatype.SHORT;
  12270. case 'UNSIGNED_SHORT':
  12271. return ComponentDatatype.UNSIGNED_SHORT;
  12272. case 'INT':
  12273. return ComponentDatatype.INT;
  12274. case 'UNSIGNED_INT':
  12275. return ComponentDatatype.UNSIGNED_INT;
  12276. case 'FLOAT':
  12277. return ComponentDatatype.FLOAT;
  12278. case 'DOUBLE':
  12279. return ComponentDatatype.DOUBLE;
  12280. default:
  12281. throw new DeveloperError('name is not a valid value.');
  12282. }
  12283. };
  12284. return freezeObject(ComponentDatatype);
  12285. });
  12286. /*global define*/
  12287. define('Core/AxisAlignedBoundingBox',[
  12288. './Cartesian3',
  12289. './defaultValue',
  12290. './defined',
  12291. './DeveloperError',
  12292. './Intersect'
  12293. ], function(
  12294. Cartesian3,
  12295. defaultValue,
  12296. defined,
  12297. DeveloperError,
  12298. Intersect) {
  12299. 'use strict';
  12300. /**
  12301. * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
  12302. * @alias AxisAlignedBoundingBox
  12303. * @constructor
  12304. *
  12305. * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
  12306. * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
  12307. * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
  12308. *
  12309. * @see BoundingSphere
  12310. * @see BoundingRectangle
  12311. */
  12312. function AxisAlignedBoundingBox(minimum, maximum, center) {
  12313. /**
  12314. * The minimum point defining the bounding box.
  12315. * @type {Cartesian3}
  12316. * @default {@link Cartesian3.ZERO}
  12317. */
  12318. this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));
  12319. /**
  12320. * The maximum point defining the bounding box.
  12321. * @type {Cartesian3}
  12322. * @default {@link Cartesian3.ZERO}
  12323. */
  12324. this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));
  12325. //If center was not defined, compute it.
  12326. if (!defined(center)) {
  12327. center = Cartesian3.add(this.minimum, this.maximum, new Cartesian3());
  12328. Cartesian3.multiplyByScalar(center, 0.5, center);
  12329. } else {
  12330. center = Cartesian3.clone(center);
  12331. }
  12332. /**
  12333. * The center point of the bounding box.
  12334. * @type {Cartesian3}
  12335. */
  12336. this.center = center;
  12337. }
  12338. /**
  12339. * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
  12340. * finding the points spaced the farthest apart on the x, y, and z axes.
  12341. *
  12342. * @param {Cartesian3[]} positions List of points that the bounding box will enclose. Each point must have a <code>x</code>, <code>y</code>, and <code>z</code> properties.
  12343. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  12344. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  12345. *
  12346. * @example
  12347. * // Compute an axis aligned bounding box enclosing two points.
  12348. * var box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  12349. */
  12350. AxisAlignedBoundingBox.fromPoints = function(positions, result) {
  12351. if (!defined(result)) {
  12352. result = new AxisAlignedBoundingBox();
  12353. }
  12354. if (!defined(positions) || positions.length === 0) {
  12355. result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
  12356. result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
  12357. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  12358. return result;
  12359. }
  12360. var minimumX = positions[0].x;
  12361. var minimumY = positions[0].y;
  12362. var minimumZ = positions[0].z;
  12363. var maximumX = positions[0].x;
  12364. var maximumY = positions[0].y;
  12365. var maximumZ = positions[0].z;
  12366. var length = positions.length;
  12367. for ( var i = 1; i < length; i++) {
  12368. var p = positions[i];
  12369. var x = p.x;
  12370. var y = p.y;
  12371. var z = p.z;
  12372. minimumX = Math.min(x, minimumX);
  12373. maximumX = Math.max(x, maximumX);
  12374. minimumY = Math.min(y, minimumY);
  12375. maximumY = Math.max(y, maximumY);
  12376. minimumZ = Math.min(z, minimumZ);
  12377. maximumZ = Math.max(z, maximumZ);
  12378. }
  12379. var minimum = result.minimum;
  12380. minimum.x = minimumX;
  12381. minimum.y = minimumY;
  12382. minimum.z = minimumZ;
  12383. var maximum = result.maximum;
  12384. maximum.x = maximumX;
  12385. maximum.y = maximumY;
  12386. maximum.z = maximumZ;
  12387. var center = Cartesian3.add(minimum, maximum, result.center);
  12388. Cartesian3.multiplyByScalar(center, 0.5, center);
  12389. return result;
  12390. };
  12391. /**
  12392. * Duplicates a AxisAlignedBoundingBox instance.
  12393. *
  12394. * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
  12395. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  12396. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  12397. */
  12398. AxisAlignedBoundingBox.clone = function(box, result) {
  12399. if (!defined(box)) {
  12400. return undefined;
  12401. }
  12402. if (!defined(result)) {
  12403. return new AxisAlignedBoundingBox(box.minimum, box.maximum);
  12404. }
  12405. result.minimum = Cartesian3.clone(box.minimum, result.minimum);
  12406. result.maximum = Cartesian3.clone(box.maximum, result.maximum);
  12407. result.center = Cartesian3.clone(box.center, result.center);
  12408. return result;
  12409. };
  12410. /**
  12411. * Compares the provided AxisAlignedBoundingBox componentwise and returns
  12412. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12413. *
  12414. * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
  12415. * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
  12416. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  12417. */
  12418. AxisAlignedBoundingBox.equals = function(left, right) {
  12419. return (left === right) ||
  12420. ((defined(left)) &&
  12421. (defined(right)) &&
  12422. Cartesian3.equals(left.center, right.center) &&
  12423. Cartesian3.equals(left.minimum, right.minimum) &&
  12424. Cartesian3.equals(left.maximum, right.maximum));
  12425. };
  12426. var intersectScratch = new Cartesian3();
  12427. /**
  12428. * Determines which side of a plane a box is located.
  12429. *
  12430. * @param {AxisAlignedBoundingBox} box The bounding box to test.
  12431. * @param {Plane} plane The plane to test against.
  12432. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  12433. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  12434. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  12435. * intersects the plane.
  12436. */
  12437. AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
  12438. if (!defined(box)) {
  12439. throw new DeveloperError('box is required.');
  12440. }
  12441. if (!defined(plane)) {
  12442. throw new DeveloperError('plane is required.');
  12443. }
  12444. intersectScratch = Cartesian3.subtract(box.maximum, box.minimum, intersectScratch);
  12445. var h = Cartesian3.multiplyByScalar(intersectScratch, 0.5, intersectScratch); //The positive half diagonal
  12446. var normal = plane.normal;
  12447. var e = h.x * Math.abs(normal.x) + h.y * Math.abs(normal.y) + h.z * Math.abs(normal.z);
  12448. var s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center
  12449. if (s - e > 0) {
  12450. return Intersect.INSIDE;
  12451. }
  12452. if (s + e < 0) {
  12453. //Not in front because normals point inward
  12454. return Intersect.OUTSIDE;
  12455. }
  12456. return Intersect.INTERSECTING;
  12457. };
  12458. /**
  12459. * Duplicates this AxisAlignedBoundingBox instance.
  12460. *
  12461. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  12462. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  12463. */
  12464. AxisAlignedBoundingBox.prototype.clone = function(result) {
  12465. return AxisAlignedBoundingBox.clone(this, result);
  12466. };
  12467. /**
  12468. * Determines which side of a plane this box is located.
  12469. *
  12470. * @param {Plane} plane The plane to test against.
  12471. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  12472. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  12473. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  12474. * intersects the plane.
  12475. */
  12476. AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
  12477. return AxisAlignedBoundingBox.intersectPlane(this, plane);
  12478. };
  12479. /**
  12480. * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
  12481. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12482. *
  12483. * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
  12484. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  12485. */
  12486. AxisAlignedBoundingBox.prototype.equals = function(right) {
  12487. return AxisAlignedBoundingBox.equals(this, right);
  12488. };
  12489. return AxisAlignedBoundingBox;
  12490. });
  12491. /*global define*/
  12492. define('Core/QuadraticRealPolynomial',[
  12493. './DeveloperError',
  12494. './Math'
  12495. ], function(
  12496. DeveloperError,
  12497. CesiumMath) {
  12498. 'use strict';
  12499. /**
  12500. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  12501. *
  12502. * @exports QuadraticRealPolynomial
  12503. */
  12504. var QuadraticRealPolynomial = {};
  12505. /**
  12506. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  12507. *
  12508. * @param {Number} a The coefficient of the 2nd order monomial.
  12509. * @param {Number} b The coefficient of the 1st order monomial.
  12510. * @param {Number} c The coefficient of the 0th order monomial.
  12511. * @returns {Number} The value of the discriminant.
  12512. */
  12513. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  12514. if (typeof a !== 'number') {
  12515. throw new DeveloperError('a is a required number.');
  12516. }
  12517. if (typeof b !== 'number') {
  12518. throw new DeveloperError('b is a required number.');
  12519. }
  12520. if (typeof c !== 'number') {
  12521. throw new DeveloperError('c is a required number.');
  12522. }
  12523. var discriminant = b * b - 4.0 * a * c;
  12524. return discriminant;
  12525. };
  12526. function addWithCancellationCheck(left, right, tolerance) {
  12527. var difference = left + right;
  12528. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  12529. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  12530. return 0.0;
  12531. }
  12532. return difference;
  12533. }
  12534. /**
  12535. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  12536. *
  12537. * @param {Number} a The coefficient of the 2nd order monomial.
  12538. * @param {Number} b The coefficient of the 1st order monomial.
  12539. * @param {Number} c The coefficient of the 0th order monomial.
  12540. * @returns {Number[]} The real valued roots.
  12541. */
  12542. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  12543. if (typeof a !== 'number') {
  12544. throw new DeveloperError('a is a required number.');
  12545. }
  12546. if (typeof b !== 'number') {
  12547. throw new DeveloperError('b is a required number.');
  12548. }
  12549. if (typeof c !== 'number') {
  12550. throw new DeveloperError('c is a required number.');
  12551. }
  12552. var ratio;
  12553. if (a === 0.0) {
  12554. if (b === 0.0) {
  12555. // Constant function: c = 0.
  12556. return [];
  12557. }
  12558. // Linear function: b * x + c = 0.
  12559. return [-c / b];
  12560. } else if (b === 0.0) {
  12561. if (c === 0.0) {
  12562. // 2nd order monomial: a * x^2 = 0.
  12563. return [0.0, 0.0];
  12564. }
  12565. var cMagnitude = Math.abs(c);
  12566. var aMagnitude = Math.abs(a);
  12567. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  12568. // 2nd order monomial: a * x^2 = 0.
  12569. return [0.0, 0.0];
  12570. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  12571. // Constant function: c = 0.
  12572. return [];
  12573. }
  12574. // a * x^2 + c = 0
  12575. ratio = -c / a;
  12576. if (ratio < 0.0) {
  12577. // Both roots are complex.
  12578. return [];
  12579. }
  12580. // Both roots are real.
  12581. var root = Math.sqrt(ratio);
  12582. return [-root, root];
  12583. } else if (c === 0.0) {
  12584. // a * x^2 + b * x = 0
  12585. ratio = -b / a;
  12586. if (ratio < 0.0) {
  12587. return [ratio, 0.0];
  12588. }
  12589. return [0.0, ratio];
  12590. }
  12591. // a * x^2 + b * x + c = 0
  12592. var b2 = b * b;
  12593. var four_ac = 4.0 * a * c;
  12594. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  12595. if (radicand < 0.0) {
  12596. // Both roots are complex.
  12597. return [];
  12598. }
  12599. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  12600. if (b > 0.0) {
  12601. return [q / a, c / q];
  12602. }
  12603. return [c / q, q / a];
  12604. };
  12605. return QuadraticRealPolynomial;
  12606. });
  12607. /*global define*/
  12608. define('Core/CubicRealPolynomial',[
  12609. './DeveloperError',
  12610. './QuadraticRealPolynomial'
  12611. ], function(
  12612. DeveloperError,
  12613. QuadraticRealPolynomial) {
  12614. 'use strict';
  12615. /**
  12616. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  12617. *
  12618. * @exports CubicRealPolynomial
  12619. */
  12620. var CubicRealPolynomial = {};
  12621. /**
  12622. * Provides the discriminant of the cubic equation from the supplied coefficients.
  12623. *
  12624. * @param {Number} a The coefficient of the 3rd order monomial.
  12625. * @param {Number} b The coefficient of the 2nd order monomial.
  12626. * @param {Number} c The coefficient of the 1st order monomial.
  12627. * @param {Number} d The coefficient of the 0th order monomial.
  12628. * @returns {Number} The value of the discriminant.
  12629. */
  12630. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  12631. if (typeof a !== 'number') {
  12632. throw new DeveloperError('a is a required number.');
  12633. }
  12634. if (typeof b !== 'number') {
  12635. throw new DeveloperError('b is a required number.');
  12636. }
  12637. if (typeof c !== 'number') {
  12638. throw new DeveloperError('c is a required number.');
  12639. }
  12640. if (typeof d !== 'number') {
  12641. throw new DeveloperError('d is a required number.');
  12642. }
  12643. var a2 = a * a;
  12644. var b2 = b * b;
  12645. var c2 = c * c;
  12646. var d2 = d * d;
  12647. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  12648. return discriminant;
  12649. };
  12650. function computeRealRoots(a, b, c, d) {
  12651. var A = a;
  12652. var B = b / 3.0;
  12653. var C = c / 3.0;
  12654. var D = d;
  12655. var AC = A * C;
  12656. var BD = B * D;
  12657. var B2 = B * B;
  12658. var C2 = C * C;
  12659. var delta1 = A * C - B2;
  12660. var delta2 = A * D - B * C;
  12661. var delta3 = B * D - C2;
  12662. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  12663. var temp;
  12664. var temp1;
  12665. if (discriminant < 0.0) {
  12666. var ABar;
  12667. var CBar;
  12668. var DBar;
  12669. if (B2 * BD >= AC * C2) {
  12670. ABar = A;
  12671. CBar = delta1;
  12672. DBar = -2.0 * B * delta1 + A * delta2;
  12673. } else {
  12674. ABar = D;
  12675. CBar = delta3;
  12676. DBar = -D * delta2 + 2.0 * C * delta3;
  12677. }
  12678. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  12679. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  12680. temp1 = -DBar + temp0;
  12681. var x = temp1 / 2.0;
  12682. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  12683. var q = (temp1 === temp0) ? -p : -CBar / p;
  12684. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  12685. if (B2 * BD >= AC * C2) {
  12686. return [(temp - B) / A];
  12687. }
  12688. return [-D / (temp + C)];
  12689. }
  12690. var CBarA = delta1;
  12691. var DBarA = -2.0 * B * delta1 + A * delta2;
  12692. var CBarD = delta3;
  12693. var DBarD = -D * delta2 + 2.0 * C * delta3;
  12694. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  12695. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  12696. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  12697. temp = 2.0 * Math.sqrt(-CBarA);
  12698. var cosine = Math.cos(theta);
  12699. temp1 = temp * cosine;
  12700. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  12701. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  12702. var denominatorLarge = A;
  12703. var root1 = numeratorLarge / denominatorLarge;
  12704. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  12705. temp = 2.0 * Math.sqrt(-CBarD);
  12706. cosine = Math.cos(theta);
  12707. temp1 = temp * cosine;
  12708. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  12709. var numeratorSmall = -D;
  12710. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  12711. var root3 = numeratorSmall / denominatorSmall;
  12712. var E = denominatorLarge * denominatorSmall;
  12713. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  12714. var G = numeratorLarge * numeratorSmall;
  12715. var root2 = (C * F - B * G) / (-B * F + C * E);
  12716. if (root1 <= root2) {
  12717. if (root1 <= root3) {
  12718. if (root2 <= root3) {
  12719. return [root1, root2, root3];
  12720. }
  12721. return [root1, root3, root2];
  12722. }
  12723. return [root3, root1, root2];
  12724. }
  12725. if (root1 <= root3) {
  12726. return [root2, root1, root3];
  12727. }
  12728. if (root2 <= root3) {
  12729. return [root2, root3, root1];
  12730. }
  12731. return [root3, root2, root1];
  12732. }
  12733. /**
  12734. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  12735. *
  12736. * @param {Number} a The coefficient of the 3rd order monomial.
  12737. * @param {Number} b The coefficient of the 2nd order monomial.
  12738. * @param {Number} c The coefficient of the 1st order monomial.
  12739. * @param {Number} d The coefficient of the 0th order monomial.
  12740. * @returns {Number[]} The real valued roots.
  12741. */
  12742. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  12743. if (typeof a !== 'number') {
  12744. throw new DeveloperError('a is a required number.');
  12745. }
  12746. if (typeof b !== 'number') {
  12747. throw new DeveloperError('b is a required number.');
  12748. }
  12749. if (typeof c !== 'number') {
  12750. throw new DeveloperError('c is a required number.');
  12751. }
  12752. if (typeof d !== 'number') {
  12753. throw new DeveloperError('d is a required number.');
  12754. }
  12755. var roots;
  12756. var ratio;
  12757. if (a === 0.0) {
  12758. // Quadratic function: b * x^2 + c * x + d = 0.
  12759. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  12760. } else if (b === 0.0) {
  12761. if (c === 0.0) {
  12762. if (d === 0.0) {
  12763. // 3rd order monomial: a * x^3 = 0.
  12764. return [0.0, 0.0, 0.0];
  12765. }
  12766. // a * x^3 + d = 0
  12767. ratio = -d / a;
  12768. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  12769. return [root, root, root];
  12770. } else if (d === 0.0) {
  12771. // x * (a * x^2 + c) = 0.
  12772. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  12773. // Return the roots in ascending order.
  12774. if (roots.Length === 0) {
  12775. return [0.0];
  12776. }
  12777. return [roots[0], 0.0, roots[1]];
  12778. }
  12779. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  12780. return computeRealRoots(a, 0, c, d);
  12781. } else if (c === 0.0) {
  12782. if (d === 0.0) {
  12783. // x^2 * (a * x + b) = 0.
  12784. ratio = -b / a;
  12785. if (ratio < 0.0) {
  12786. return [ratio, 0.0, 0.0];
  12787. }
  12788. return [0.0, 0.0, ratio];
  12789. }
  12790. // a * x^3 + b * x^2 + d = 0.
  12791. return computeRealRoots(a, b, 0, d);
  12792. } else if (d === 0.0) {
  12793. // x * (a * x^2 + b * x + c) = 0
  12794. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  12795. // Return the roots in ascending order.
  12796. if (roots.length === 0) {
  12797. return [0.0];
  12798. } else if (roots[1] <= 0.0) {
  12799. return [roots[0], roots[1], 0.0];
  12800. } else if (roots[0] >= 0.0) {
  12801. return [0.0, roots[0], roots[1]];
  12802. }
  12803. return [roots[0], 0.0, roots[1]];
  12804. }
  12805. return computeRealRoots(a, b, c, d);
  12806. };
  12807. return CubicRealPolynomial;
  12808. });
  12809. /*global define*/
  12810. define('Core/QuarticRealPolynomial',[
  12811. './CubicRealPolynomial',
  12812. './DeveloperError',
  12813. './Math',
  12814. './QuadraticRealPolynomial'
  12815. ], function(
  12816. CubicRealPolynomial,
  12817. DeveloperError,
  12818. CesiumMath,
  12819. QuadraticRealPolynomial) {
  12820. 'use strict';
  12821. /**
  12822. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  12823. *
  12824. * @exports QuarticRealPolynomial
  12825. */
  12826. var QuarticRealPolynomial = {};
  12827. /**
  12828. * Provides the discriminant of the quartic equation from the supplied coefficients.
  12829. *
  12830. * @param {Number} a The coefficient of the 4th order monomial.
  12831. * @param {Number} b The coefficient of the 3rd order monomial.
  12832. * @param {Number} c The coefficient of the 2nd order monomial.
  12833. * @param {Number} d The coefficient of the 1st order monomial.
  12834. * @param {Number} e The coefficient of the 0th order monomial.
  12835. * @returns {Number} The value of the discriminant.
  12836. */
  12837. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  12838. if (typeof a !== 'number') {
  12839. throw new DeveloperError('a is a required number.');
  12840. }
  12841. if (typeof b !== 'number') {
  12842. throw new DeveloperError('b is a required number.');
  12843. }
  12844. if (typeof c !== 'number') {
  12845. throw new DeveloperError('c is a required number.');
  12846. }
  12847. if (typeof d !== 'number') {
  12848. throw new DeveloperError('d is a required number.');
  12849. }
  12850. if (typeof e !== 'number') {
  12851. throw new DeveloperError('e is a required number.');
  12852. }
  12853. var a2 = a * a;
  12854. var a3 = a2 * a;
  12855. var b2 = b * b;
  12856. var b3 = b2 * b;
  12857. var c2 = c * c;
  12858. var c3 = c2 * c;
  12859. var d2 = d * d;
  12860. var d3 = d2 * d;
  12861. var e2 = e * e;
  12862. var e3 = e2 * e;
  12863. 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) +
  12864. 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) +
  12865. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  12866. return discriminant;
  12867. };
  12868. function original(a3, a2, a1, a0) {
  12869. var a3Squared = a3 * a3;
  12870. var p = a2 - 3.0 * a3Squared / 8.0;
  12871. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  12872. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  12873. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  12874. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  12875. if (cubicRoots.length > 0) {
  12876. var temp = -a3 / 4.0;
  12877. // Use the largest positive root.
  12878. var hSquared = cubicRoots[cubicRoots.length - 1];
  12879. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  12880. // y^4 + p y^2 + r = 0.
  12881. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  12882. if (roots.length === 2) {
  12883. var root0 = roots[0];
  12884. var root1 = roots[1];
  12885. var y;
  12886. if (root0 >= 0.0 && root1 >= 0.0) {
  12887. var y0 = Math.sqrt(root0);
  12888. var y1 = Math.sqrt(root1);
  12889. return [temp - y1, temp - y0, temp + y0, temp + y1];
  12890. } else if (root0 >= 0.0 && root1 < 0.0) {
  12891. y = Math.sqrt(root0);
  12892. return [temp - y, temp + y];
  12893. } else if (root0 < 0.0 && root1 >= 0.0) {
  12894. y = Math.sqrt(root1);
  12895. return [temp - y, temp + y];
  12896. }
  12897. }
  12898. return [];
  12899. } else if (hSquared > 0.0) {
  12900. var h = Math.sqrt(hSquared);
  12901. var m = (p + hSquared - q / h) / 2.0;
  12902. var n = (p + hSquared + q / h) / 2.0;
  12903. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  12904. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  12905. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  12906. if (roots1.length !== 0) {
  12907. roots1[0] += temp;
  12908. roots1[1] += temp;
  12909. if (roots2.length !== 0) {
  12910. roots2[0] += temp;
  12911. roots2[1] += temp;
  12912. if (roots1[1] <= roots2[0]) {
  12913. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  12914. } else if (roots2[1] <= roots1[0]) {
  12915. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  12916. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  12917. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  12918. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  12919. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  12920. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  12921. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  12922. }
  12923. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  12924. }
  12925. return roots1;
  12926. }
  12927. if (roots2.length !== 0) {
  12928. roots2[0] += temp;
  12929. roots2[1] += temp;
  12930. return roots2;
  12931. }
  12932. return [];
  12933. }
  12934. }
  12935. return [];
  12936. }
  12937. function neumark(a3, a2, a1, a0) {
  12938. var a1Squared = a1 * a1;
  12939. var a2Squared = a2 * a2;
  12940. var a3Squared = a3 * a3;
  12941. var p = -2.0 * a2;
  12942. var q = a1 * a3 + a2Squared - 4.0 * a0;
  12943. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  12944. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  12945. if (cubicRoots.length > 0) {
  12946. // Use the most positive root
  12947. var y = cubicRoots[0];
  12948. var temp = (a2 - y);
  12949. var tempSquared = temp * temp;
  12950. var g1 = a3 / 2.0;
  12951. var h1 = temp / 2.0;
  12952. var m = tempSquared - 4.0 * a0;
  12953. var mError = tempSquared + 4.0 * Math.abs(a0);
  12954. var n = a3Squared - 4.0 * y;
  12955. var nError = a3Squared + 4.0 * Math.abs(y);
  12956. var g2;
  12957. var h2;
  12958. if (y < 0.0 || (m * nError < n * mError)) {
  12959. var squareRootOfN = Math.sqrt(n);
  12960. g2 = squareRootOfN / 2.0;
  12961. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  12962. } else {
  12963. var squareRootOfM = Math.sqrt(m);
  12964. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  12965. h2 = squareRootOfM / 2.0;
  12966. }
  12967. var G;
  12968. var g;
  12969. if (g1 === 0.0 && g2 === 0.0) {
  12970. G = 0.0;
  12971. g = 0.0;
  12972. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  12973. G = g1 + g2;
  12974. g = y / G;
  12975. } else {
  12976. g = g1 - g2;
  12977. G = y / g;
  12978. }
  12979. var H;
  12980. var h;
  12981. if (h1 === 0.0 && h2 === 0.0) {
  12982. H = 0.0;
  12983. h = 0.0;
  12984. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  12985. H = h1 + h2;
  12986. h = a0 / H;
  12987. } else {
  12988. h = h1 - h2;
  12989. H = a0 / h;
  12990. }
  12991. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  12992. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  12993. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  12994. if (roots1.length !== 0) {
  12995. if (roots2.length !== 0) {
  12996. if (roots1[1] <= roots2[0]) {
  12997. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  12998. } else if (roots2[1] <= roots1[0]) {
  12999. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  13000. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  13001. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  13002. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  13003. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  13004. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  13005. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  13006. } else {
  13007. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  13008. }
  13009. }
  13010. return roots1;
  13011. }
  13012. if (roots2.length !== 0) {
  13013. return roots2;
  13014. }
  13015. }
  13016. return [];
  13017. }
  13018. /**
  13019. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  13020. *
  13021. * @param {Number} a The coefficient of the 4th order monomial.
  13022. * @param {Number} b The coefficient of the 3rd order monomial.
  13023. * @param {Number} c The coefficient of the 2nd order monomial.
  13024. * @param {Number} d The coefficient of the 1st order monomial.
  13025. * @param {Number} e The coefficient of the 0th order monomial.
  13026. * @returns {Number[]} The real valued roots.
  13027. */
  13028. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  13029. if (typeof a !== 'number') {
  13030. throw new DeveloperError('a is a required number.');
  13031. }
  13032. if (typeof b !== 'number') {
  13033. throw new DeveloperError('b is a required number.');
  13034. }
  13035. if (typeof c !== 'number') {
  13036. throw new DeveloperError('c is a required number.');
  13037. }
  13038. if (typeof d !== 'number') {
  13039. throw new DeveloperError('d is a required number.');
  13040. }
  13041. if (typeof e !== 'number') {
  13042. throw new DeveloperError('e is a required number.');
  13043. }
  13044. if (Math.abs(a) < CesiumMath.EPSILON15) {
  13045. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  13046. }
  13047. var a3 = b / a;
  13048. var a2 = c / a;
  13049. var a1 = d / a;
  13050. var a0 = e / a;
  13051. var k = (a3 < 0.0) ? 1 : 0;
  13052. k += (a2 < 0.0) ? k + 1 : k;
  13053. k += (a1 < 0.0) ? k + 1 : k;
  13054. k += (a0 < 0.0) ? k + 1 : k;
  13055. switch (k) {
  13056. case 0:
  13057. return original(a3, a2, a1, a0);
  13058. case 1:
  13059. return neumark(a3, a2, a1, a0);
  13060. case 2:
  13061. return neumark(a3, a2, a1, a0);
  13062. case 3:
  13063. return original(a3, a2, a1, a0);
  13064. case 4:
  13065. return original(a3, a2, a1, a0);
  13066. case 5:
  13067. return neumark(a3, a2, a1, a0);
  13068. case 6:
  13069. return original(a3, a2, a1, a0);
  13070. case 7:
  13071. return original(a3, a2, a1, a0);
  13072. case 8:
  13073. return neumark(a3, a2, a1, a0);
  13074. case 9:
  13075. return original(a3, a2, a1, a0);
  13076. case 10:
  13077. return original(a3, a2, a1, a0);
  13078. case 11:
  13079. return neumark(a3, a2, a1, a0);
  13080. case 12:
  13081. return original(a3, a2, a1, a0);
  13082. case 13:
  13083. return original(a3, a2, a1, a0);
  13084. case 14:
  13085. return original(a3, a2, a1, a0);
  13086. case 15:
  13087. return original(a3, a2, a1, a0);
  13088. default:
  13089. return undefined;
  13090. }
  13091. };
  13092. return QuarticRealPolynomial;
  13093. });
  13094. /*global define*/
  13095. define('Core/Ray',[
  13096. './Cartesian3',
  13097. './defaultValue',
  13098. './defined',
  13099. './DeveloperError'
  13100. ], function(
  13101. Cartesian3,
  13102. defaultValue,
  13103. defined,
  13104. DeveloperError) {
  13105. 'use strict';
  13106. /**
  13107. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  13108. * @alias Ray
  13109. * @constructor
  13110. *
  13111. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  13112. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  13113. */
  13114. function Ray(origin, direction) {
  13115. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  13116. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  13117. Cartesian3.normalize(direction, direction);
  13118. }
  13119. /**
  13120. * The origin of the ray.
  13121. * @type {Cartesian3}
  13122. * @default {@link Cartesian3.ZERO}
  13123. */
  13124. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  13125. /**
  13126. * The direction of the ray.
  13127. * @type {Cartesian3}
  13128. */
  13129. this.direction = direction;
  13130. }
  13131. /**
  13132. * Computes the point along the ray given by r(t) = o + t*d,
  13133. * where o is the origin of the ray and d is the direction.
  13134. *
  13135. * @param {Ray} ray The ray.
  13136. * @param {Number} t A scalar value.
  13137. * @param {Cartesian3} [result] The object in which the result will be stored.
  13138. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  13139. *
  13140. * @example
  13141. * //Get the first intersection point of a ray and an ellipsoid.
  13142. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  13143. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  13144. */
  13145. Ray.getPoint = function(ray, t, result) {
  13146. if (!defined(ray)){
  13147. throw new DeveloperError('ray is requred');
  13148. }
  13149. if (typeof t !== 'number') {
  13150. throw new DeveloperError('t is a required number');
  13151. }
  13152. if (!defined(result)) {
  13153. result = new Cartesian3();
  13154. }
  13155. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  13156. return Cartesian3.add(ray.origin, result, result);
  13157. };
  13158. return Ray;
  13159. });
  13160. /*global define*/
  13161. define('Core/IntersectionTests',[
  13162. './Cartesian3',
  13163. './Cartographic',
  13164. './defaultValue',
  13165. './defined',
  13166. './DeveloperError',
  13167. './Math',
  13168. './Matrix3',
  13169. './QuadraticRealPolynomial',
  13170. './QuarticRealPolynomial',
  13171. './Ray'
  13172. ], function(
  13173. Cartesian3,
  13174. Cartographic,
  13175. defaultValue,
  13176. defined,
  13177. DeveloperError,
  13178. CesiumMath,
  13179. Matrix3,
  13180. QuadraticRealPolynomial,
  13181. QuarticRealPolynomial,
  13182. Ray) {
  13183. 'use strict';
  13184. /**
  13185. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  13186. *
  13187. * @exports IntersectionTests
  13188. */
  13189. var IntersectionTests = {};
  13190. /**
  13191. * Computes the intersection of a ray and a plane.
  13192. *
  13193. * @param {Ray} ray The ray.
  13194. * @param {Plane} plane The plane.
  13195. * @param {Cartesian3} [result] The object onto which to store the result.
  13196. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  13197. */
  13198. IntersectionTests.rayPlane = function(ray, plane, result) {
  13199. if (!defined(ray)) {
  13200. throw new DeveloperError('ray is required.');
  13201. }
  13202. if (!defined(plane)) {
  13203. throw new DeveloperError('plane is required.');
  13204. }
  13205. if (!defined(result)) {
  13206. result = new Cartesian3();
  13207. }
  13208. var origin = ray.origin;
  13209. var direction = ray.direction;
  13210. var normal = plane.normal;
  13211. var denominator = Cartesian3.dot(normal, direction);
  13212. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  13213. // Ray is parallel to plane. The ray may be in the polygon's plane.
  13214. return undefined;
  13215. }
  13216. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  13217. if (t < 0) {
  13218. return undefined;
  13219. }
  13220. result = Cartesian3.multiplyByScalar(direction, t, result);
  13221. return Cartesian3.add(origin, result, result);
  13222. };
  13223. var scratchEdge0 = new Cartesian3();
  13224. var scratchEdge1 = new Cartesian3();
  13225. var scratchPVec = new Cartesian3();
  13226. var scratchTVec = new Cartesian3();
  13227. var scratchQVec = new Cartesian3();
  13228. /**
  13229. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  13230. *
  13231. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  13232. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  13233. *
  13234. * @memberof IntersectionTests
  13235. *
  13236. * @param {Ray} ray The ray.
  13237. * @param {Cartesian3} p0 The first vertex of the triangle.
  13238. * @param {Cartesian3} p1 The second vertex of the triangle.
  13239. * @param {Cartesian3} p2 The third vertex of the triangle.
  13240. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  13241. * and return undefined for intersections with the back face.
  13242. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  13243. */
  13244. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  13245. if (!defined(ray)) {
  13246. throw new DeveloperError('ray is required.');
  13247. }
  13248. if (!defined(p0)) {
  13249. throw new DeveloperError('p0 is required.');
  13250. }
  13251. if (!defined(p1)) {
  13252. throw new DeveloperError('p1 is required.');
  13253. }
  13254. if (!defined(p2)) {
  13255. throw new DeveloperError('p2 is required.');
  13256. }
  13257. cullBackFaces = defaultValue(cullBackFaces, false);
  13258. var origin = ray.origin;
  13259. var direction = ray.direction;
  13260. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  13261. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  13262. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  13263. var det = Cartesian3.dot(edge0, p);
  13264. var tvec;
  13265. var q;
  13266. var u;
  13267. var v;
  13268. var t;
  13269. if (cullBackFaces) {
  13270. if (det < CesiumMath.EPSILON6) {
  13271. return undefined;
  13272. }
  13273. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  13274. u = Cartesian3.dot(tvec, p);
  13275. if (u < 0.0 || u > det) {
  13276. return undefined;
  13277. }
  13278. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  13279. v = Cartesian3.dot(direction, q);
  13280. if (v < 0.0 || u + v > det) {
  13281. return undefined;
  13282. }
  13283. t = Cartesian3.dot(edge1, q) / det;
  13284. } else {
  13285. if (Math.abs(det) < CesiumMath.EPSILON6) {
  13286. return undefined;
  13287. }
  13288. var invDet = 1.0 / det;
  13289. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  13290. u = Cartesian3.dot(tvec, p) * invDet;
  13291. if (u < 0.0 || u > 1.0) {
  13292. return undefined;
  13293. }
  13294. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  13295. v = Cartesian3.dot(direction, q) * invDet;
  13296. if (v < 0.0 || u + v > 1.0) {
  13297. return undefined;
  13298. }
  13299. t = Cartesian3.dot(edge1, q) * invDet;
  13300. }
  13301. return t;
  13302. };
  13303. /**
  13304. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  13305. *
  13306. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  13307. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  13308. *
  13309. * @memberof IntersectionTests
  13310. *
  13311. * @param {Ray} ray The ray.
  13312. * @param {Cartesian3} p0 The first vertex of the triangle.
  13313. * @param {Cartesian3} p1 The second vertex of the triangle.
  13314. * @param {Cartesian3} p2 The third vertex of the triangle.
  13315. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  13316. * and return undefined for intersections with the back face.
  13317. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  13318. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  13319. */
  13320. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  13321. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  13322. if (!defined(t) || t < 0.0) {
  13323. return undefined;
  13324. }
  13325. if (!defined(result)) {
  13326. result = new Cartesian3();
  13327. }
  13328. Cartesian3.multiplyByScalar(ray.direction, t, result);
  13329. return Cartesian3.add(ray.origin, result, result);
  13330. };
  13331. var scratchLineSegmentTriangleRay = new Ray();
  13332. /**
  13333. * Computes the intersection of a line segment and a triangle.
  13334. * @memberof IntersectionTests
  13335. *
  13336. * @param {Cartesian3} v0 The an end point of the line segment.
  13337. * @param {Cartesian3} v1 The other end point of the line segment.
  13338. * @param {Cartesian3} p0 The first vertex of the triangle.
  13339. * @param {Cartesian3} p1 The second vertex of the triangle.
  13340. * @param {Cartesian3} p2 The third vertex of the triangle.
  13341. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  13342. * and return undefined for intersections with the back face.
  13343. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  13344. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  13345. */
  13346. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  13347. if (!defined(v0)) {
  13348. throw new DeveloperError('v0 is required.');
  13349. }
  13350. if (!defined(v1)) {
  13351. throw new DeveloperError('v1 is required.');
  13352. }
  13353. if (!defined(p0)) {
  13354. throw new DeveloperError('p0 is required.');
  13355. }
  13356. if (!defined(p1)) {
  13357. throw new DeveloperError('p1 is required.');
  13358. }
  13359. if (!defined(p2)) {
  13360. throw new DeveloperError('p2 is required.');
  13361. }
  13362. var ray = scratchLineSegmentTriangleRay;
  13363. Cartesian3.clone(v0, ray.origin);
  13364. Cartesian3.subtract(v1, v0, ray.direction);
  13365. Cartesian3.normalize(ray.direction, ray.direction);
  13366. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  13367. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  13368. return undefined;
  13369. }
  13370. if (!defined(result)) {
  13371. result = new Cartesian3();
  13372. }
  13373. Cartesian3.multiplyByScalar(ray.direction, t, result);
  13374. return Cartesian3.add(ray.origin, result, result);
  13375. };
  13376. function solveQuadratic(a, b, c, result) {
  13377. var det = b * b - 4.0 * a * c;
  13378. if (det < 0.0) {
  13379. return undefined;
  13380. } else if (det > 0.0) {
  13381. var denom = 1.0 / (2.0 * a);
  13382. var disc = Math.sqrt(det);
  13383. var root0 = (-b + disc) * denom;
  13384. var root1 = (-b - disc) * denom;
  13385. if (root0 < root1) {
  13386. result.root0 = root0;
  13387. result.root1 = root1;
  13388. } else {
  13389. result.root0 = root1;
  13390. result.root1 = root0;
  13391. }
  13392. return result;
  13393. }
  13394. var root = -b / (2.0 * a);
  13395. if (root === 0.0) {
  13396. return undefined;
  13397. }
  13398. result.root0 = result.root1 = root;
  13399. return result;
  13400. }
  13401. var raySphereRoots = {
  13402. root0 : 0.0,
  13403. root1 : 0.0
  13404. };
  13405. function raySphere(ray, sphere, result) {
  13406. if (!defined(result)) {
  13407. result = {};
  13408. }
  13409. var origin = ray.origin;
  13410. var direction = ray.direction;
  13411. var center = sphere.center;
  13412. var radiusSquared = sphere.radius * sphere.radius;
  13413. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  13414. var a = Cartesian3.dot(direction, direction);
  13415. var b = 2.0 * Cartesian3.dot(direction, diff);
  13416. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  13417. var roots = solveQuadratic(a, b, c, raySphereRoots);
  13418. if (!defined(roots)) {
  13419. return undefined;
  13420. }
  13421. result.start = roots.root0;
  13422. result.stop = roots.root1;
  13423. return result;
  13424. }
  13425. /**
  13426. * Computes the intersection points of a ray with a sphere.
  13427. * @memberof IntersectionTests
  13428. *
  13429. * @param {Ray} ray The ray.
  13430. * @param {BoundingSphere} sphere The sphere.
  13431. * @param {Object} [result] The result onto which to store the result.
  13432. * @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.
  13433. */
  13434. IntersectionTests.raySphere = function(ray, sphere, result) {
  13435. if (!defined(ray)) {
  13436. throw new DeveloperError('ray is required.');
  13437. }
  13438. if (!defined(sphere)) {
  13439. throw new DeveloperError('sphere is required.');
  13440. }
  13441. result = raySphere(ray, sphere, result);
  13442. if (!defined(result) || result.stop < 0.0) {
  13443. return undefined;
  13444. }
  13445. result.start = Math.max(result.start, 0.0);
  13446. return result;
  13447. };
  13448. var scratchLineSegmentRay = new Ray();
  13449. /**
  13450. * Computes the intersection points of a line segment with a sphere.
  13451. * @memberof IntersectionTests
  13452. *
  13453. * @param {Cartesian3} p0 An end point of the line segment.
  13454. * @param {Cartesian3} p1 The other end point of the line segment.
  13455. * @param {BoundingSphere} sphere The sphere.
  13456. * @param {Object} [result] The result onto which to store the result.
  13457. * @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.
  13458. */
  13459. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  13460. if (!defined(p0)) {
  13461. throw new DeveloperError('p0 is required.');
  13462. }
  13463. if (!defined(p1)) {
  13464. throw new DeveloperError('p1 is required.');
  13465. }
  13466. if (!defined(sphere)) {
  13467. throw new DeveloperError('sphere is required.');
  13468. }
  13469. var ray = scratchLineSegmentRay;
  13470. Cartesian3.clone(p0, ray.origin);
  13471. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  13472. var maxT = Cartesian3.magnitude(direction);
  13473. Cartesian3.normalize(direction, direction);
  13474. result = raySphere(ray, sphere, result);
  13475. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  13476. return undefined;
  13477. }
  13478. result.start = Math.max(result.start, 0.0);
  13479. result.stop = Math.min(result.stop, maxT);
  13480. return result;
  13481. };
  13482. var scratchQ = new Cartesian3();
  13483. var scratchW = new Cartesian3();
  13484. /**
  13485. * Computes the intersection points of a ray with an ellipsoid.
  13486. *
  13487. * @param {Ray} ray The ray.
  13488. * @param {Ellipsoid} ellipsoid The ellipsoid.
  13489. * @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.
  13490. */
  13491. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  13492. if (!defined(ray)) {
  13493. throw new DeveloperError('ray is required.');
  13494. }
  13495. if (!defined(ellipsoid)) {
  13496. throw new DeveloperError('ellipsoid is required.');
  13497. }
  13498. var inverseRadii = ellipsoid.oneOverRadii;
  13499. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  13500. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  13501. var q2 = Cartesian3.magnitudeSquared(q);
  13502. var qw = Cartesian3.dot(q, w);
  13503. var difference, w2, product, discriminant, temp;
  13504. if (q2 > 1.0) {
  13505. // Outside ellipsoid.
  13506. if (qw >= 0.0) {
  13507. // Looking outward or tangent (0 intersections).
  13508. return undefined;
  13509. }
  13510. // qw < 0.0.
  13511. var qw2 = qw * qw;
  13512. difference = q2 - 1.0; // Positively valued.
  13513. w2 = Cartesian3.magnitudeSquared(w);
  13514. product = w2 * difference;
  13515. if (qw2 < product) {
  13516. // Imaginary roots (0 intersections).
  13517. return undefined;
  13518. } else if (qw2 > product) {
  13519. // Distinct roots (2 intersections).
  13520. discriminant = qw * qw - product;
  13521. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  13522. var root0 = temp / w2;
  13523. var root1 = difference / temp;
  13524. if (root0 < root1) {
  13525. return {
  13526. start : root0,
  13527. stop : root1
  13528. };
  13529. }
  13530. return {
  13531. start : root1,
  13532. stop : root0
  13533. };
  13534. } else {
  13535. // qw2 == product. Repeated roots (2 intersections).
  13536. var root = Math.sqrt(difference / w2);
  13537. return {
  13538. start : root,
  13539. stop : root
  13540. };
  13541. }
  13542. } else if (q2 < 1.0) {
  13543. // Inside ellipsoid (2 intersections).
  13544. difference = q2 - 1.0; // Negatively valued.
  13545. w2 = Cartesian3.magnitudeSquared(w);
  13546. product = w2 * difference; // Negatively valued.
  13547. discriminant = qw * qw - product;
  13548. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  13549. return {
  13550. start : 0.0,
  13551. stop : temp / w2
  13552. };
  13553. } else {
  13554. // q2 == 1.0. On ellipsoid.
  13555. if (qw < 0.0) {
  13556. // Looking inward.
  13557. w2 = Cartesian3.magnitudeSquared(w);
  13558. return {
  13559. start : 0.0,
  13560. stop : -qw / w2
  13561. };
  13562. }
  13563. // qw >= 0.0. Looking outward or tangent.
  13564. return undefined;
  13565. }
  13566. };
  13567. function addWithCancellationCheck(left, right, tolerance) {
  13568. var difference = left + right;
  13569. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  13570. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  13571. return 0.0;
  13572. }
  13573. return difference;
  13574. }
  13575. function quadraticVectorExpression(A, b, c, x, w) {
  13576. var xSquared = x * x;
  13577. var wSquared = w * w;
  13578. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  13579. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  13580. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  13581. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  13582. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  13583. var cosines;
  13584. var solutions = [];
  13585. if (r0 === 0.0 && r1 === 0.0) {
  13586. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  13587. if (cosines.length === 0) {
  13588. return solutions;
  13589. }
  13590. var cosine0 = cosines[0];
  13591. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  13592. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  13593. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  13594. if (cosines.length === 2) {
  13595. var cosine1 = cosines[1];
  13596. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  13597. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  13598. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  13599. }
  13600. return solutions;
  13601. }
  13602. var r0Squared = r0 * r0;
  13603. var r1Squared = r1 * r1;
  13604. var l2Squared = l2 * l2;
  13605. var r0r1 = r0 * r1;
  13606. var c4 = l2Squared + r1Squared;
  13607. var c3 = 2.0 * (l1 * l2 + r0r1);
  13608. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  13609. var c1 = 2.0 * (l0 * l1 - r0r1);
  13610. var c0 = l0 * l0 - r0Squared;
  13611. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  13612. return solutions;
  13613. }
  13614. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  13615. var length = cosines.length;
  13616. if (length === 0) {
  13617. return solutions;
  13618. }
  13619. for ( var i = 0; i < length; ++i) {
  13620. var cosine = cosines[i];
  13621. var cosineSquared = cosine * cosine;
  13622. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  13623. var sine = Math.sqrt(sineSquared);
  13624. //var left = l2 * cosineSquared + l1 * cosine + l0;
  13625. var left;
  13626. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  13627. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  13628. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  13629. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  13630. } else {
  13631. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  13632. }
  13633. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  13634. var product = left * right;
  13635. if (product < 0.0) {
  13636. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  13637. } else if (product > 0.0) {
  13638. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  13639. } else if (sine !== 0.0) {
  13640. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  13641. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  13642. ++i;
  13643. } else {
  13644. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  13645. }
  13646. }
  13647. return solutions;
  13648. }
  13649. var firstAxisScratch = new Cartesian3();
  13650. var secondAxisScratch = new Cartesian3();
  13651. var thirdAxisScratch = new Cartesian3();
  13652. var referenceScratch = new Cartesian3();
  13653. var bCart = new Cartesian3();
  13654. var bScratch = new Matrix3();
  13655. var btScratch = new Matrix3();
  13656. var diScratch = new Matrix3();
  13657. var dScratch = new Matrix3();
  13658. var cScratch = new Matrix3();
  13659. var tempMatrix = new Matrix3();
  13660. var aScratch = new Matrix3();
  13661. var sScratch = new Cartesian3();
  13662. var closestScratch = new Cartesian3();
  13663. var surfPointScratch = new Cartographic();
  13664. /**
  13665. * Provides the point along the ray which is nearest to the ellipsoid.
  13666. *
  13667. * @param {Ray} ray The ray.
  13668. * @param {Ellipsoid} ellipsoid The ellipsoid.
  13669. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  13670. */
  13671. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  13672. if (!defined(ray)) {
  13673. throw new DeveloperError('ray is required.');
  13674. }
  13675. if (!defined(ellipsoid)) {
  13676. throw new DeveloperError('ellipsoid is required.');
  13677. }
  13678. var position = ray.origin;
  13679. var direction = ray.direction;
  13680. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  13681. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  13682. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  13683. return position;
  13684. }
  13685. }
  13686. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  13687. // Compute the scaled direction vector.
  13688. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  13689. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  13690. var firstAxis = Cartesian3.normalize(f, f);
  13691. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  13692. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  13693. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  13694. var B = bScratch;
  13695. B[0] = firstAxis.x;
  13696. B[1] = firstAxis.y;
  13697. B[2] = firstAxis.z;
  13698. B[3] = secondAxis.x;
  13699. B[4] = secondAxis.y;
  13700. B[5] = secondAxis.z;
  13701. B[6] = thirdAxis.x;
  13702. B[7] = thirdAxis.y;
  13703. B[8] = thirdAxis.z;
  13704. var B_T = Matrix3.transpose(B, btScratch);
  13705. // Get the scaling matrix and its inverse.
  13706. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  13707. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  13708. var C = cScratch;
  13709. C[0] = 0.0;
  13710. C[1] = -direction.z;
  13711. C[2] = direction.y;
  13712. C[3] = direction.z;
  13713. C[4] = 0.0;
  13714. C[5] = -direction.x;
  13715. C[6] = -direction.y;
  13716. C[7] = direction.x;
  13717. C[8] = 0.0;
  13718. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  13719. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  13720. var b = Matrix3.multiplyByVector(temp, position, bCart);
  13721. // Solve for the solutions to the expression in standard form:
  13722. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  13723. var s;
  13724. var altitude;
  13725. var length = solutions.length;
  13726. if (length > 0) {
  13727. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  13728. var maximumValue = Number.NEGATIVE_INFINITY;
  13729. for ( var i = 0; i < length; ++i) {
  13730. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  13731. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  13732. var dotProduct = Cartesian3.dot(v, direction);
  13733. if (dotProduct > maximumValue) {
  13734. maximumValue = dotProduct;
  13735. closest = Cartesian3.clone(s, closest);
  13736. }
  13737. }
  13738. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  13739. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  13740. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  13741. altitude = intersects ? -altitude : altitude;
  13742. surfacePoint.height = altitude;
  13743. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  13744. }
  13745. return undefined;
  13746. };
  13747. var lineSegmentPlaneDifference = new Cartesian3();
  13748. /**
  13749. * Computes the intersection of a line segment and a plane.
  13750. *
  13751. * @param {Cartesian3} endPoint0 An end point of the line segment.
  13752. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  13753. * @param {Plane} plane The plane.
  13754. * @param {Cartesian3} [result] The object onto which to store the result.
  13755. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  13756. *
  13757. * @example
  13758. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  13759. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  13760. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  13761. *
  13762. * var p0 = new Cesium.Cartesian3(...);
  13763. * var p1 = new Cesium.Cartesian3(...);
  13764. *
  13765. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  13766. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  13767. */
  13768. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  13769. if (!defined(endPoint0)) {
  13770. throw new DeveloperError('endPoint0 is required.');
  13771. }
  13772. if (!defined(endPoint1)) {
  13773. throw new DeveloperError('endPoint1 is required.');
  13774. }
  13775. if (!defined(plane)) {
  13776. throw new DeveloperError('plane is required.');
  13777. }
  13778. if (!defined(result)) {
  13779. result = new Cartesian3();
  13780. }
  13781. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  13782. var normal = plane.normal;
  13783. var nDotDiff = Cartesian3.dot(normal, difference);
  13784. // check if the segment and plane are parallel
  13785. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  13786. return undefined;
  13787. }
  13788. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  13789. var t = -(plane.distance + nDotP0) / nDotDiff;
  13790. // intersection only if t is in [0, 1]
  13791. if (t < 0.0 || t > 1.0) {
  13792. return undefined;
  13793. }
  13794. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  13795. Cartesian3.multiplyByScalar(difference, t, result);
  13796. Cartesian3.add(endPoint0, result, result);
  13797. return result;
  13798. };
  13799. /**
  13800. * Computes the intersection of a triangle and a plane
  13801. *
  13802. * @param {Cartesian3} p0 First point of the triangle
  13803. * @param {Cartesian3} p1 Second point of the triangle
  13804. * @param {Cartesian3} p2 Third point of the triangle
  13805. * @param {Plane} plane Intersection plane
  13806. * @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)
  13807. *
  13808. * @example
  13809. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  13810. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  13811. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  13812. *
  13813. * var p0 = new Cesium.Cartesian3(...);
  13814. * var p1 = new Cesium.Cartesian3(...);
  13815. * var p2 = new Cesium.Cartesian3(...);
  13816. *
  13817. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  13818. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  13819. */
  13820. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  13821. if ((!defined(p0)) ||
  13822. (!defined(p1)) ||
  13823. (!defined(p2)) ||
  13824. (!defined(plane))) {
  13825. throw new DeveloperError('p0, p1, p2, and plane are required.');
  13826. }
  13827. var planeNormal = plane.normal;
  13828. var planeD = plane.distance;
  13829. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  13830. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  13831. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  13832. // Given these dots products, the calls to lineSegmentPlaneIntersection
  13833. // always have defined results.
  13834. var numBehind = 0;
  13835. numBehind += p0Behind ? 1 : 0;
  13836. numBehind += p1Behind ? 1 : 0;
  13837. numBehind += p2Behind ? 1 : 0;
  13838. var u1, u2;
  13839. if (numBehind === 1 || numBehind === 2) {
  13840. u1 = new Cartesian3();
  13841. u2 = new Cartesian3();
  13842. }
  13843. if (numBehind === 1) {
  13844. if (p0Behind) {
  13845. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  13846. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  13847. return {
  13848. positions : [p0, p1, p2, u1, u2 ],
  13849. indices : [
  13850. // Behind
  13851. 0, 3, 4,
  13852. // In front
  13853. 1, 2, 4,
  13854. 1, 4, 3
  13855. ]
  13856. };
  13857. } else if (p1Behind) {
  13858. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  13859. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  13860. return {
  13861. positions : [p0, p1, p2, u1, u2 ],
  13862. indices : [
  13863. // Behind
  13864. 1, 3, 4,
  13865. // In front
  13866. 2, 0, 4,
  13867. 2, 4, 3
  13868. ]
  13869. };
  13870. } else if (p2Behind) {
  13871. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  13872. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  13873. return {
  13874. positions : [p0, p1, p2, u1, u2 ],
  13875. indices : [
  13876. // Behind
  13877. 2, 3, 4,
  13878. // In front
  13879. 0, 1, 4,
  13880. 0, 4, 3
  13881. ]
  13882. };
  13883. }
  13884. } else if (numBehind === 2) {
  13885. if (!p0Behind) {
  13886. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  13887. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  13888. return {
  13889. positions : [p0, p1, p2, u1, u2 ],
  13890. indices : [
  13891. // Behind
  13892. 1, 2, 4,
  13893. 1, 4, 3,
  13894. // In front
  13895. 0, 3, 4
  13896. ]
  13897. };
  13898. } else if (!p1Behind) {
  13899. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  13900. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  13901. return {
  13902. positions : [p0, p1, p2, u1, u2 ],
  13903. indices : [
  13904. // Behind
  13905. 2, 0, 4,
  13906. 2, 4, 3,
  13907. // In front
  13908. 1, 3, 4
  13909. ]
  13910. };
  13911. } else if (!p2Behind) {
  13912. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  13913. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  13914. return {
  13915. positions : [p0, p1, p2, u1, u2 ],
  13916. indices : [
  13917. // Behind
  13918. 0, 1, 4,
  13919. 0, 4, 3,
  13920. // In front
  13921. 2, 3, 4
  13922. ]
  13923. };
  13924. }
  13925. }
  13926. // if numBehind is 3, the triangle is completely behind the plane;
  13927. // otherwise, it is completely in front (numBehind is 0).
  13928. return undefined;
  13929. };
  13930. return IntersectionTests;
  13931. });
  13932. /*global define*/
  13933. define('Core/Plane',[
  13934. './Cartesian3',
  13935. './defined',
  13936. './DeveloperError',
  13937. './freezeObject'
  13938. ], function(
  13939. Cartesian3,
  13940. defined,
  13941. DeveloperError,
  13942. freezeObject) {
  13943. 'use strict';
  13944. /**
  13945. * A plane in Hessian Normal Form defined by
  13946. * <pre>
  13947. * ax + by + cz + d = 0
  13948. * </pre>
  13949. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  13950. * <code>distance</code> to the plane, and (x, y, z) is any point on
  13951. * the plane.
  13952. *
  13953. * @alias Plane
  13954. * @constructor
  13955. *
  13956. * @param {Cartesian3} normal The plane's normal (normalized).
  13957. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  13958. * <code>distance</code> determines which side of the plane the origin
  13959. * is on. If <code>distance</code> is positive, the origin is in the half-space
  13960. * in the direction of the normal; if negative, the origin is in the half-space
  13961. * opposite to the normal; if zero, the plane passes through the origin.
  13962. *
  13963. * @example
  13964. * // The plane x=0
  13965. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  13966. */
  13967. function Plane(normal, distance) {
  13968. if (!defined(normal)) {
  13969. throw new DeveloperError('normal is required.');
  13970. }
  13971. if (!defined(distance)) {
  13972. throw new DeveloperError('distance is required.');
  13973. }
  13974. /**
  13975. * The plane's normal.
  13976. *
  13977. * @type {Cartesian3}
  13978. */
  13979. this.normal = Cartesian3.clone(normal);
  13980. /**
  13981. * The shortest distance from the origin to the plane. The sign of
  13982. * <code>distance</code> determines which side of the plane the origin
  13983. * is on. If <code>distance</code> is positive, the origin is in the half-space
  13984. * in the direction of the normal; if negative, the origin is in the half-space
  13985. * opposite to the normal; if zero, the plane passes through the origin.
  13986. *
  13987. * @type {Number}
  13988. */
  13989. this.distance = distance;
  13990. }
  13991. /**
  13992. * Creates a plane from a normal and a point on the plane.
  13993. *
  13994. * @param {Cartesian3} point The point on the plane.
  13995. * @param {Cartesian3} normal The plane's normal (normalized).
  13996. * @param {Plane} [result] The object onto which to store the result.
  13997. * @returns {Plane} A new plane instance or the modified result parameter.
  13998. *
  13999. * @example
  14000. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  14001. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  14002. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  14003. */
  14004. Plane.fromPointNormal = function(point, normal, result) {
  14005. if (!defined(point)) {
  14006. throw new DeveloperError('point is required.');
  14007. }
  14008. if (!defined(normal)) {
  14009. throw new DeveloperError('normal is required.');
  14010. }
  14011. var distance = -Cartesian3.dot(normal, point);
  14012. if (!defined(result)) {
  14013. return new Plane(normal, distance);
  14014. }
  14015. Cartesian3.clone(normal, result.normal);
  14016. result.distance = distance;
  14017. return result;
  14018. };
  14019. var scratchNormal = new Cartesian3();
  14020. /**
  14021. * Creates a plane from the general equation
  14022. *
  14023. * @param {Cartesian4} coefficients The plane's normal (normalized).
  14024. * @param {Plane} [result] The object onto which to store the result.
  14025. * @returns {Plane} A new plane instance or the modified result parameter.
  14026. */
  14027. Plane.fromCartesian4 = function(coefficients, result) {
  14028. if (!defined(coefficients)) {
  14029. throw new DeveloperError('coefficients is required.');
  14030. }
  14031. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  14032. var distance = coefficients.w;
  14033. if (!defined(result)) {
  14034. return new Plane(normal, distance);
  14035. } else {
  14036. Cartesian3.clone(normal, result.normal);
  14037. result.distance = distance;
  14038. return result;
  14039. }
  14040. };
  14041. /**
  14042. * Computes the signed shortest distance of a point to a plane.
  14043. * The sign of the distance determines which side of the plane the point
  14044. * is on. If the distance is positive, the point is in the half-space
  14045. * in the direction of the normal; if negative, the point is in the half-space
  14046. * opposite to the normal; if zero, the plane passes through the point.
  14047. *
  14048. * @param {Plane} plane The plane.
  14049. * @param {Cartesian3} point The point.
  14050. * @returns {Number} The signed shortest distance of the point to the plane.
  14051. */
  14052. Plane.getPointDistance = function(plane, point) {
  14053. if (!defined(plane)) {
  14054. throw new DeveloperError('plane is required.');
  14055. }
  14056. if (!defined(point)) {
  14057. throw new DeveloperError('point is required.');
  14058. }
  14059. return Cartesian3.dot(plane.normal, point) + plane.distance;
  14060. };
  14061. /**
  14062. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  14063. *
  14064. * @type {Plane}
  14065. * @constant
  14066. */
  14067. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  14068. /**
  14069. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  14070. *
  14071. * @type {Plane}
  14072. * @constant
  14073. */
  14074. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  14075. /**
  14076. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  14077. *
  14078. * @type {Plane}
  14079. * @constant
  14080. */
  14081. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  14082. return Plane;
  14083. });
  14084. /**
  14085. @license
  14086. when.js - https://github.com/cujojs/when
  14087. MIT License (c) copyright B Cavalier & J Hann
  14088. * A lightweight CommonJS Promises/A and when() implementation
  14089. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  14090. *
  14091. * Licensed under the MIT License at:
  14092. * http://www.opensource.org/licenses/mit-license.php
  14093. *
  14094. * @version 1.7.1
  14095. */
  14096. (function(define) { 'use strict';
  14097. define('ThirdParty/when',[],function () {
  14098. var reduceArray, slice, undef;
  14099. //
  14100. // Public API
  14101. //
  14102. when.defer = defer; // Create a deferred
  14103. when.resolve = resolve; // Create a resolved promise
  14104. when.reject = reject; // Create a rejected promise
  14105. when.join = join; // Join 2 or more promises
  14106. when.all = all; // Resolve a list of promises
  14107. when.map = map; // Array.map() for promises
  14108. when.reduce = reduce; // Array.reduce() for promises
  14109. when.any = any; // One-winner race
  14110. when.some = some; // Multi-winner race
  14111. when.chain = chain; // Make a promise trigger another resolver
  14112. when.isPromise = isPromise; // Determine if a thing is a promise
  14113. /**
  14114. * Register an observer for a promise or immediate value.
  14115. *
  14116. * @param {*} promiseOrValue
  14117. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  14118. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  14119. * will be invoked immediately.
  14120. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  14121. * rejected.
  14122. * @param {function?} [onProgress] callback to be called when progress updates
  14123. * are issued for promiseOrValue.
  14124. * @returns {Promise} a new {@link Promise} that will complete with the return
  14125. * value of callback or errback or the completion value of promiseOrValue if
  14126. * callback and/or errback is not supplied.
  14127. */
  14128. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  14129. // Get a trusted promise for the input promiseOrValue, and then
  14130. // register promise handlers
  14131. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  14132. }
  14133. /**
  14134. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  14135. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  14136. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  14137. *
  14138. * @param {*} promiseOrValue
  14139. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  14140. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  14141. * whose resolution value is:
  14142. * * the resolution value of promiseOrValue if it's a foreign promise, or
  14143. * * promiseOrValue if it's a value
  14144. */
  14145. function resolve(promiseOrValue) {
  14146. var promise, deferred;
  14147. if(promiseOrValue instanceof Promise) {
  14148. // It's a when.js promise, so we trust it
  14149. promise = promiseOrValue;
  14150. } else {
  14151. // It's not a when.js promise. See if it's a foreign promise or a value.
  14152. if(isPromise(promiseOrValue)) {
  14153. // It's a thenable, but we don't know where it came from, so don't trust
  14154. // its implementation entirely. Introduce a trusted middleman when.js promise
  14155. deferred = defer();
  14156. // IMPORTANT: This is the only place when.js should ever call .then() on an
  14157. // untrusted promise. Don't expose the return value to the untrusted promise
  14158. promiseOrValue.then(
  14159. function(value) { deferred.resolve(value); },
  14160. function(reason) { deferred.reject(reason); },
  14161. function(update) { deferred.progress(update); }
  14162. );
  14163. promise = deferred.promise;
  14164. } else {
  14165. // It's a value, not a promise. Create a resolved promise for it.
  14166. promise = fulfilled(promiseOrValue);
  14167. }
  14168. }
  14169. return promise;
  14170. }
  14171. /**
  14172. * Returns a rejected promise for the supplied promiseOrValue. The returned
  14173. * promise will be rejected with:
  14174. * - promiseOrValue, if it is a value, or
  14175. * - if promiseOrValue is a promise
  14176. * - promiseOrValue's value after it is fulfilled
  14177. * - promiseOrValue's reason after it is rejected
  14178. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  14179. * @returns {Promise} rejected {@link Promise}
  14180. */
  14181. function reject(promiseOrValue) {
  14182. return when(promiseOrValue, rejected);
  14183. }
  14184. /**
  14185. * Trusted Promise constructor. A Promise created from this constructor is
  14186. * a trusted when.js promise. Any other duck-typed promise is considered
  14187. * untrusted.
  14188. * @constructor
  14189. * @name Promise
  14190. */
  14191. function Promise(then) {
  14192. this.then = then;
  14193. }
  14194. Promise.prototype = {
  14195. /**
  14196. * Register a callback that will be called when a promise is
  14197. * fulfilled or rejected. Optionally also register a progress handler.
  14198. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  14199. * @param {function?} [onFulfilledOrRejected]
  14200. * @param {function?} [onProgress]
  14201. * @returns {Promise}
  14202. */
  14203. always: function(onFulfilledOrRejected, onProgress) {
  14204. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  14205. },
  14206. /**
  14207. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  14208. * @param {function?} onRejected
  14209. * @returns {Promise}
  14210. */
  14211. otherwise: function(onRejected) {
  14212. return this.then(undef, onRejected);
  14213. },
  14214. /**
  14215. * Shortcut for .then(function() { return value; })
  14216. * @param {*} value
  14217. * @returns {Promise} a promise that:
  14218. * - is fulfilled if value is not a promise, or
  14219. * - if value is a promise, will fulfill with its value, or reject
  14220. * with its reason.
  14221. */
  14222. yield: function(value) {
  14223. return this.then(function() {
  14224. return value;
  14225. });
  14226. },
  14227. /**
  14228. * Assumes that this promise will fulfill with an array, and arranges
  14229. * for the onFulfilled to be called with the array as its argument list
  14230. * i.e. onFulfilled.spread(undefined, array).
  14231. * @param {function} onFulfilled function to receive spread arguments
  14232. * @returns {Promise}
  14233. */
  14234. spread: function(onFulfilled) {
  14235. return this.then(function(array) {
  14236. // array may contain promises, so resolve its contents.
  14237. return all(array, function(array) {
  14238. return onFulfilled.apply(undef, array);
  14239. });
  14240. });
  14241. }
  14242. };
  14243. /**
  14244. * Create an already-resolved promise for the supplied value
  14245. * @private
  14246. *
  14247. * @param {*} value
  14248. * @returns {Promise} fulfilled promise
  14249. */
  14250. function fulfilled(value) {
  14251. var p = new Promise(function(onFulfilled) {
  14252. // TODO: Promises/A+ check typeof onFulfilled
  14253. try {
  14254. return resolve(onFulfilled ? onFulfilled(value) : value);
  14255. } catch(e) {
  14256. return rejected(e);
  14257. }
  14258. });
  14259. return p;
  14260. }
  14261. /**
  14262. * Create an already-rejected {@link Promise} with the supplied
  14263. * rejection reason.
  14264. * @private
  14265. *
  14266. * @param {*} reason
  14267. * @returns {Promise} rejected promise
  14268. */
  14269. function rejected(reason) {
  14270. var p = new Promise(function(_, onRejected) {
  14271. // TODO: Promises/A+ check typeof onRejected
  14272. try {
  14273. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  14274. } catch(e) {
  14275. return rejected(e);
  14276. }
  14277. });
  14278. return p;
  14279. }
  14280. /**
  14281. * Creates a new, Deferred with fully isolated resolver and promise parts,
  14282. * either or both of which may be given out safely to consumers.
  14283. * The Deferred itself has the full API: resolve, reject, progress, and
  14284. * then. The resolver has resolve, reject, and progress. The promise
  14285. * only has then.
  14286. *
  14287. * @returns {Deferred}
  14288. */
  14289. function defer() {
  14290. var deferred, promise, handlers, progressHandlers,
  14291. _then, _progress, _resolve;
  14292. /**
  14293. * The promise for the new deferred
  14294. * @type {Promise}
  14295. */
  14296. promise = new Promise(then);
  14297. /**
  14298. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  14299. * @class Deferred
  14300. * @name Deferred
  14301. */
  14302. deferred = {
  14303. then: then, // DEPRECATED: use deferred.promise.then
  14304. resolve: promiseResolve,
  14305. reject: promiseReject,
  14306. // TODO: Consider renaming progress() to notify()
  14307. progress: promiseProgress,
  14308. promise: promise,
  14309. resolver: {
  14310. resolve: promiseResolve,
  14311. reject: promiseReject,
  14312. progress: promiseProgress
  14313. }
  14314. };
  14315. handlers = [];
  14316. progressHandlers = [];
  14317. /**
  14318. * Pre-resolution then() that adds the supplied callback, errback, and progback
  14319. * functions to the registered listeners
  14320. * @private
  14321. *
  14322. * @param {function?} [onFulfilled] resolution handler
  14323. * @param {function?} [onRejected] rejection handler
  14324. * @param {function?} [onProgress] progress handler
  14325. */
  14326. _then = function(onFulfilled, onRejected, onProgress) {
  14327. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  14328. var deferred, progressHandler;
  14329. deferred = defer();
  14330. progressHandler = typeof onProgress === 'function'
  14331. ? function(update) {
  14332. try {
  14333. // Allow progress handler to transform progress event
  14334. deferred.progress(onProgress(update));
  14335. } catch(e) {
  14336. // Use caught value as progress
  14337. deferred.progress(e);
  14338. }
  14339. }
  14340. : function(update) { deferred.progress(update); };
  14341. handlers.push(function(promise) {
  14342. promise.then(onFulfilled, onRejected)
  14343. .then(deferred.resolve, deferred.reject, progressHandler);
  14344. });
  14345. progressHandlers.push(progressHandler);
  14346. return deferred.promise;
  14347. };
  14348. /**
  14349. * Issue a progress event, notifying all progress listeners
  14350. * @private
  14351. * @param {*} update progress event payload to pass to all listeners
  14352. */
  14353. _progress = function(update) {
  14354. processQueue(progressHandlers, update);
  14355. return update;
  14356. };
  14357. /**
  14358. * Transition from pre-resolution state to post-resolution state, notifying
  14359. * all listeners of the resolution or rejection
  14360. * @private
  14361. * @param {*} value the value of this deferred
  14362. */
  14363. _resolve = function(value) {
  14364. value = resolve(value);
  14365. // Replace _then with one that directly notifies with the result.
  14366. _then = value.then;
  14367. // Replace _resolve so that this Deferred can only be resolved once
  14368. _resolve = resolve;
  14369. // Make _progress a noop, to disallow progress for the resolved promise.
  14370. _progress = noop;
  14371. // Notify handlers
  14372. processQueue(handlers, value);
  14373. // Free progressHandlers array since we'll never issue progress events
  14374. progressHandlers = handlers = undef;
  14375. return value;
  14376. };
  14377. return deferred;
  14378. /**
  14379. * Wrapper to allow _then to be replaced safely
  14380. * @param {function?} [onFulfilled] resolution handler
  14381. * @param {function?} [onRejected] rejection handler
  14382. * @param {function?} [onProgress] progress handler
  14383. * @returns {Promise} new promise
  14384. */
  14385. function then(onFulfilled, onRejected, onProgress) {
  14386. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  14387. return _then(onFulfilled, onRejected, onProgress);
  14388. }
  14389. /**
  14390. * Wrapper to allow _resolve to be replaced
  14391. */
  14392. function promiseResolve(val) {
  14393. return _resolve(val);
  14394. }
  14395. /**
  14396. * Wrapper to allow _reject to be replaced
  14397. */
  14398. function promiseReject(err) {
  14399. return _resolve(rejected(err));
  14400. }
  14401. /**
  14402. * Wrapper to allow _progress to be replaced
  14403. */
  14404. function promiseProgress(update) {
  14405. return _progress(update);
  14406. }
  14407. }
  14408. /**
  14409. * Determines if promiseOrValue is a promise or not. Uses the feature
  14410. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  14411. * promiseOrValue is a promise.
  14412. *
  14413. * @param {*} promiseOrValue anything
  14414. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  14415. */
  14416. function isPromise(promiseOrValue) {
  14417. return promiseOrValue && typeof promiseOrValue.then === 'function';
  14418. }
  14419. /**
  14420. * Initiates a competitive race, returning a promise that will resolve when
  14421. * howMany of the supplied promisesOrValues have resolved, or will reject when
  14422. * it becomes impossible for howMany to resolve, for example, when
  14423. * (promisesOrValues.length - howMany) + 1 input promises reject.
  14424. *
  14425. * @param {Array} promisesOrValues array of anything, may contain a mix
  14426. * of promises and values
  14427. * @param howMany {number} number of promisesOrValues to resolve
  14428. * @param {function?} [onFulfilled] resolution handler
  14429. * @param {function?} [onRejected] rejection handler
  14430. * @param {function?} [onProgress] progress handler
  14431. * @returns {Promise} promise that will resolve to an array of howMany values that
  14432. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  14433. * rejection reasons.
  14434. */
  14435. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  14436. checkCallbacks(2, arguments);
  14437. return when(promisesOrValues, function(promisesOrValues) {
  14438. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  14439. len = promisesOrValues.length >>> 0;
  14440. toResolve = Math.max(0, Math.min(howMany, len));
  14441. values = [];
  14442. toReject = (len - toResolve) + 1;
  14443. reasons = [];
  14444. deferred = defer();
  14445. // No items in the input, resolve immediately
  14446. if (!toResolve) {
  14447. deferred.resolve(values);
  14448. } else {
  14449. progress = deferred.progress;
  14450. rejectOne = function(reason) {
  14451. reasons.push(reason);
  14452. if(!--toReject) {
  14453. fulfillOne = rejectOne = noop;
  14454. deferred.reject(reasons);
  14455. }
  14456. };
  14457. fulfillOne = function(val) {
  14458. // This orders the values based on promise resolution order
  14459. // Another strategy would be to use the original position of
  14460. // the corresponding promise.
  14461. values.push(val);
  14462. if (!--toResolve) {
  14463. fulfillOne = rejectOne = noop;
  14464. deferred.resolve(values);
  14465. }
  14466. };
  14467. for(i = 0; i < len; ++i) {
  14468. if(i in promisesOrValues) {
  14469. when(promisesOrValues[i], fulfiller, rejecter, progress);
  14470. }
  14471. }
  14472. }
  14473. return deferred.then(onFulfilled, onRejected, onProgress);
  14474. function rejecter(reason) {
  14475. rejectOne(reason);
  14476. }
  14477. function fulfiller(val) {
  14478. fulfillOne(val);
  14479. }
  14480. });
  14481. }
  14482. /**
  14483. * Initiates a competitive race, returning a promise that will resolve when
  14484. * any one of the supplied promisesOrValues has resolved or will reject when
  14485. * *all* promisesOrValues have rejected.
  14486. *
  14487. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  14488. * of {@link Promise}s and values
  14489. * @param {function?} [onFulfilled] resolution handler
  14490. * @param {function?} [onRejected] rejection handler
  14491. * @param {function?} [onProgress] progress handler
  14492. * @returns {Promise} promise that will resolve to the value that resolved first, or
  14493. * will reject with an array of all rejected inputs.
  14494. */
  14495. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  14496. function unwrapSingleResult(val) {
  14497. return onFulfilled ? onFulfilled(val[0]) : val[0];
  14498. }
  14499. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  14500. }
  14501. /**
  14502. * Return a promise that will resolve only once all the supplied promisesOrValues
  14503. * have resolved. The resolution value of the returned promise will be an array
  14504. * containing the resolution values of each of the promisesOrValues.
  14505. * @memberOf when
  14506. *
  14507. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  14508. * of {@link Promise}s and values
  14509. * @param {function?} [onFulfilled] resolution handler
  14510. * @param {function?} [onRejected] rejection handler
  14511. * @param {function?} [onProgress] progress handler
  14512. * @returns {Promise}
  14513. */
  14514. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  14515. checkCallbacks(1, arguments);
  14516. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  14517. }
  14518. /**
  14519. * Joins multiple promises into a single returned promise.
  14520. * @returns {Promise} a promise that will fulfill when *all* the input promises
  14521. * have fulfilled, or will reject when *any one* of the input promises rejects.
  14522. */
  14523. function join(/* ...promises */) {
  14524. return map(arguments, identity);
  14525. }
  14526. /**
  14527. * Traditional map function, similar to `Array.prototype.map()`, but allows
  14528. * input to contain {@link Promise}s and/or values, and mapFunc may return
  14529. * either a value or a {@link Promise}
  14530. *
  14531. * @param {Array|Promise} promise array of anything, may contain a mix
  14532. * of {@link Promise}s and values
  14533. * @param {function} mapFunc mapping function mapFunc(value) which may return
  14534. * either a {@link Promise} or value
  14535. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  14536. * the mapped output values.
  14537. */
  14538. function map(promise, mapFunc) {
  14539. return when(promise, function(array) {
  14540. var results, len, toResolve, resolve, i, d;
  14541. // Since we know the resulting length, we can preallocate the results
  14542. // array to avoid array expansions.
  14543. toResolve = len = array.length >>> 0;
  14544. results = [];
  14545. d = defer();
  14546. if(!toResolve) {
  14547. d.resolve(results);
  14548. } else {
  14549. resolve = function resolveOne(item, i) {
  14550. when(item, mapFunc).then(function(mapped) {
  14551. results[i] = mapped;
  14552. if(!--toResolve) {
  14553. d.resolve(results);
  14554. }
  14555. }, d.reject);
  14556. };
  14557. // Since mapFunc may be async, get all invocations of it into flight
  14558. for(i = 0; i < len; i++) {
  14559. if(i in array) {
  14560. resolve(array[i], i);
  14561. } else {
  14562. --toResolve;
  14563. }
  14564. }
  14565. }
  14566. return d.promise;
  14567. });
  14568. }
  14569. /**
  14570. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  14571. * input may contain promises and/or values, and reduceFunc
  14572. * may return either a value or a promise, *and* initialValue may
  14573. * be a promise for the starting value.
  14574. *
  14575. * @param {Array|Promise} promise array or promise for an array of anything,
  14576. * may contain a mix of promises and values.
  14577. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  14578. * where total is the total number of items being reduced, and will be the same
  14579. * in each call to reduceFunc.
  14580. * @returns {Promise} that will resolve to the final reduced value
  14581. */
  14582. function reduce(promise, reduceFunc /*, initialValue */) {
  14583. var args = slice.call(arguments, 1);
  14584. return when(promise, function(array) {
  14585. var total;
  14586. total = array.length;
  14587. // Wrap the supplied reduceFunc with one that handles promises and then
  14588. // delegates to the supplied.
  14589. args[0] = function (current, val, i) {
  14590. return when(current, function (c) {
  14591. return when(val, function (value) {
  14592. return reduceFunc(c, value, i, total);
  14593. });
  14594. });
  14595. };
  14596. return reduceArray.apply(array, args);
  14597. });
  14598. }
  14599. /**
  14600. * Ensure that resolution of promiseOrValue will trigger resolver with the
  14601. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  14602. *
  14603. * @param promiseOrValue
  14604. * @param {Object} resolver
  14605. * @param {function} resolver.resolve
  14606. * @param {function} resolver.reject
  14607. * @param {*} [resolveValue]
  14608. * @returns {Promise}
  14609. */
  14610. function chain(promiseOrValue, resolver, resolveValue) {
  14611. var useResolveValue = arguments.length > 2;
  14612. return when(promiseOrValue,
  14613. function(val) {
  14614. val = useResolveValue ? resolveValue : val;
  14615. resolver.resolve(val);
  14616. return val;
  14617. },
  14618. function(reason) {
  14619. resolver.reject(reason);
  14620. return rejected(reason);
  14621. },
  14622. resolver.progress
  14623. );
  14624. }
  14625. //
  14626. // Utility functions
  14627. //
  14628. /**
  14629. * Apply all functions in queue to value
  14630. * @param {Array} queue array of functions to execute
  14631. * @param {*} value argument passed to each function
  14632. */
  14633. function processQueue(queue, value) {
  14634. var handler, i = 0;
  14635. while (handler = queue[i++]) {
  14636. handler(value);
  14637. }
  14638. }
  14639. /**
  14640. * Helper that checks arrayOfCallbacks to ensure that each element is either
  14641. * a function, or null or undefined.
  14642. * @private
  14643. * @param {number} start index at which to start checking items in arrayOfCallbacks
  14644. * @param {Array} arrayOfCallbacks array to check
  14645. * @throws {Error} if any element of arrayOfCallbacks is something other than
  14646. * a functions, null, or undefined.
  14647. */
  14648. function checkCallbacks(start, arrayOfCallbacks) {
  14649. // TODO: Promises/A+ update type checking and docs
  14650. var arg, i = arrayOfCallbacks.length;
  14651. while(i > start) {
  14652. arg = arrayOfCallbacks[--i];
  14653. if (arg != null && typeof arg != 'function') {
  14654. throw new Error('arg '+i+' must be a function');
  14655. }
  14656. }
  14657. }
  14658. /**
  14659. * No-Op function used in method replacement
  14660. * @private
  14661. */
  14662. function noop() {}
  14663. slice = [].slice;
  14664. // ES5 reduce implementation if native not available
  14665. // See: http://es5.github.com/#x15.4.4.21 as there are many
  14666. // specifics and edge cases.
  14667. reduceArray = [].reduce ||
  14668. function(reduceFunc /*, initialValue */) {
  14669. /*jshint maxcomplexity: 7*/
  14670. // ES5 dictates that reduce.length === 1
  14671. // This implementation deviates from ES5 spec in the following ways:
  14672. // 1. It does not check if reduceFunc is a Callable
  14673. var arr, args, reduced, len, i;
  14674. i = 0;
  14675. // This generates a jshint warning, despite being valid
  14676. // "Missing 'new' prefix when invoking a constructor."
  14677. // See https://github.com/jshint/jshint/issues/392
  14678. arr = Object(this);
  14679. len = arr.length >>> 0;
  14680. args = arguments;
  14681. // If no initialValue, use first item of array (we know length !== 0 here)
  14682. // and adjust i to start at second item
  14683. if(args.length <= 1) {
  14684. // Skip to the first real element in the array
  14685. for(;;) {
  14686. if(i in arr) {
  14687. reduced = arr[i++];
  14688. break;
  14689. }
  14690. // If we reached the end of the array without finding any real
  14691. // elements, it's a TypeError
  14692. if(++i >= len) {
  14693. throw new TypeError();
  14694. }
  14695. }
  14696. } else {
  14697. // If initialValue provided, use it
  14698. reduced = args[1];
  14699. }
  14700. // Do the actual reduce
  14701. for(;i < len; ++i) {
  14702. // Skip holes
  14703. if(i in arr) {
  14704. reduced = reduceFunc(reduced, arr[i], i, arr);
  14705. }
  14706. }
  14707. return reduced;
  14708. };
  14709. function identity(x) {
  14710. return x;
  14711. }
  14712. return when;
  14713. });
  14714. })(typeof define == 'function' && define.amd
  14715. ? define
  14716. : function (factory) { typeof exports === 'object'
  14717. ? (module.exports = factory())
  14718. : (this.when = factory());
  14719. }
  14720. // Boilerplate for AMD, Node, and browser global
  14721. );
  14722. /*global define*/
  14723. define('Core/oneTimeWarning',[
  14724. './defaultValue',
  14725. './defined',
  14726. './DeveloperError'
  14727. ], function(
  14728. defaultValue,
  14729. defined,
  14730. DeveloperError) {
  14731. "use strict";
  14732. var warnings = {};
  14733. /**
  14734. * Logs a one time message to the console. Use this function instead of
  14735. * <code>console.log</code> directly since this does not log duplicate messages
  14736. * unless it is called from multiple workers.
  14737. *
  14738. * @exports oneTimeWarning
  14739. *
  14740. * @param {String} identifier The unique identifier for this warning.
  14741. * @param {String} [message=identifier] The message to log to the console.
  14742. *
  14743. * @example
  14744. * for(var i=0;i<foo.length;++i) {
  14745. * if (!defined(foo[i].bar)) {
  14746. * // Something that can be recovered from but may happen a lot
  14747. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  14748. * foo[i].bar = 0;
  14749. * // ...
  14750. * }
  14751. * }
  14752. *
  14753. * @private
  14754. */
  14755. function oneTimeWarning(identifier, message) {
  14756. if (!defined(identifier)) {
  14757. throw new DeveloperError('identifier is required.');
  14758. }
  14759. if (!defined(warnings[identifier])) {
  14760. warnings[identifier] = true;
  14761. console.log(defaultValue(message, identifier));
  14762. }
  14763. }
  14764. 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.';
  14765. return oneTimeWarning;
  14766. });
  14767. /*global define*/
  14768. define('Core/deprecationWarning',[
  14769. './defined',
  14770. './DeveloperError',
  14771. './oneTimeWarning'
  14772. ], function(
  14773. defined,
  14774. DeveloperError,
  14775. oneTimeWarning) {
  14776. 'use strict';
  14777. /**
  14778. * Logs a deprecation message to the console. Use this function instead of
  14779. * <code>console.log</code> directly since this does not log duplicate messages
  14780. * unless it is called from multiple workers.
  14781. *
  14782. * @exports deprecationWarning
  14783. *
  14784. * @param {String} identifier The unique identifier for this deprecated API.
  14785. * @param {String} message The message to log to the console.
  14786. *
  14787. * @example
  14788. * // Deprecated function or class
  14789. * function Foo() {
  14790. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  14791. * // ...
  14792. * }
  14793. *
  14794. * // Deprecated function
  14795. * Bar.prototype.func = function() {
  14796. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  14797. * // ...
  14798. * };
  14799. *
  14800. * // Deprecated property
  14801. * defineProperties(Bar.prototype, {
  14802. * prop : {
  14803. * get : function() {
  14804. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  14805. * // ...
  14806. * },
  14807. * set : function(value) {
  14808. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  14809. * // ...
  14810. * }
  14811. * }
  14812. * });
  14813. *
  14814. * @private
  14815. */
  14816. function deprecationWarning(identifier, message) {
  14817. if (!defined(identifier) || !defined(message)) {
  14818. throw new DeveloperError('identifier and message are required.');
  14819. }
  14820. oneTimeWarning(identifier, message);
  14821. }
  14822. return deprecationWarning;
  14823. });
  14824. /*global define*/
  14825. define('Core/binarySearch',[
  14826. './defined',
  14827. './DeveloperError'
  14828. ], function(
  14829. defined,
  14830. DeveloperError) {
  14831. 'use strict';
  14832. /**
  14833. * Finds an item in a sorted array.
  14834. *
  14835. * @exports binarySearch
  14836. *
  14837. * @param {Array} array The sorted array to search.
  14838. * @param {Object} itemToFind The item to find in the array.
  14839. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  14840. * elements in the array.
  14841. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  14842. * does not exist, the return value is a negative number which is the bitwise complement (~)
  14843. * of the index before which the itemToFind should be inserted in order to maintain the
  14844. * sorted order of the array.
  14845. *
  14846. * @example
  14847. * // Create a comparator function to search through an array of numbers.
  14848. * function comparator(a, b) {
  14849. * return a - b;
  14850. * };
  14851. * var numbers = [0, 2, 4, 6, 8];
  14852. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  14853. */
  14854. function binarySearch(array, itemToFind, comparator) {
  14855. if (!defined(array)) {
  14856. throw new DeveloperError('array is required.');
  14857. }
  14858. if (!defined(itemToFind)) {
  14859. throw new DeveloperError('itemToFind is required.');
  14860. }
  14861. if (!defined(comparator)) {
  14862. throw new DeveloperError('comparator is required.');
  14863. }
  14864. var low = 0;
  14865. var high = array.length - 1;
  14866. var i;
  14867. var comparison;
  14868. while (low <= high) {
  14869. i = ~~((low + high) / 2);
  14870. comparison = comparator(array[i], itemToFind);
  14871. if (comparison < 0) {
  14872. low = i + 1;
  14873. continue;
  14874. }
  14875. if (comparison > 0) {
  14876. high = i - 1;
  14877. continue;
  14878. }
  14879. return i;
  14880. }
  14881. return ~(high + 1);
  14882. }
  14883. /**
  14884. * A function used to compare two items while performing a binary search.
  14885. * @callback binarySearch~Comparator
  14886. *
  14887. * @param {Object} a An item in the array.
  14888. * @param {Object} b The item being searched for.
  14889. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  14890. * a positive value if <code>a</code> is greater than <code>b</code>, or
  14891. * 0 if <code>a</code> is equal to <code>b</code>.
  14892. *
  14893. * @example
  14894. * function compareNumbers(a, b) {
  14895. * return a - b;
  14896. * }
  14897. */
  14898. return binarySearch;
  14899. });
  14900. /*global define*/
  14901. define('Core/EarthOrientationParametersSample',[],function() {
  14902. 'use strict';
  14903. /**
  14904. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  14905. *
  14906. * @alias EarthOrientationParametersSample
  14907. * @constructor
  14908. *
  14909. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  14910. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  14911. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  14912. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  14913. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  14914. *
  14915. * @private
  14916. */
  14917. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  14918. /**
  14919. * The pole wander about the X axis, in radians.
  14920. * @type {Number}
  14921. */
  14922. this.xPoleWander = xPoleWander;
  14923. /**
  14924. * The pole wander about the Y axis, in radians.
  14925. * @type {Number}
  14926. */
  14927. this.yPoleWander = yPoleWander;
  14928. /**
  14929. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  14930. * @type {Number}
  14931. */
  14932. this.xPoleOffset = xPoleOffset;
  14933. /**
  14934. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  14935. * @type {Number}
  14936. */
  14937. this.yPoleOffset = yPoleOffset;
  14938. /**
  14939. * The difference in time standards, UT1 - UTC, in seconds.
  14940. * @type {Number}
  14941. */
  14942. this.ut1MinusUtc = ut1MinusUtc;
  14943. }
  14944. return EarthOrientationParametersSample;
  14945. });
  14946. /**
  14947. @license
  14948. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  14949. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  14950. php.js is copyright 2012 Kevin van Zonneveld.
  14951. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  14952. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  14953. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  14954. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  14955. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  14956. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  14957. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  14958. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  14959. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  14960. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  14961. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  14962. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  14963. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  14964. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  14965. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  14966. (http://geekfg.blogspot.com), Andrea Giammarchi
  14967. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  14968. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  14969. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  14970. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  14971. Marc Palau, Martin
  14972. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  14973. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  14974. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  14975. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  14976. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  14977. Ariede (http://caioariede.com), Robin, Kankrelune
  14978. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  14979. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  14980. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  14981. David, Aman Gupta, Michael White, Public Domain
  14982. (http://www.json.org/json2.js), Steven Levithan
  14983. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  14984. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  14985. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  14986. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  14987. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  14988. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  14989. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  14990. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  14991. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  14992. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  14993. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  14994. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  14995. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  14996. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  14997. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  14998. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  14999. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  15000. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  15001. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  15002. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  15003. (http://yass.meetcweb.com), Peter-Paul Koch
  15004. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  15005. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  15006. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  15007. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  15008. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  15009. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  15010. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  15011. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  15012. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  15013. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  15014. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  15015. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  15016. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  15017. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  15018. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  15019. (http://www.premasolutions.com/), Philippe Jausions
  15020. (http://pear.php.net/user/jausions), Aidan Lister
  15021. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  15022. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  15023. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  15024. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  15025. (http://www.pedrotainha.com), James, Arnout Kazemier
  15026. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  15027. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  15028. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  15029. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  15030. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  15031. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  15032. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  15033. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  15034. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  15035. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  15036. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  15037. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  15038. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  15039. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  15040. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  15041. (http://benblume.co.uk/), DtTvB
  15042. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  15043. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  15044. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  15045. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  15046. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  15047. Bryan
  15048. Licensed under the MIT (MIT-LICENSE.txt) license.
  15049. Permission is hereby granted, free of charge, to any person obtaining a
  15050. copy of this software and associated documentation files (the
  15051. "Software"), to deal in the Software without restriction, including
  15052. without limitation the rights to use, copy, modify, merge, publish,
  15053. distribute, sublicense, and/or sell copies of the Software, and to
  15054. permit persons to whom the Software is furnished to do so, subject to
  15055. the following conditions:
  15056. The above copyright notice and this permission notice shall be included
  15057. in all copies or substantial portions of the Software.
  15058. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15059. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15060. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  15061. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  15062. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  15063. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  15064. OTHER DEALINGS IN THE SOFTWARE.
  15065. */
  15066. /*global define*/
  15067. define('ThirdParty/sprintf',[],function() {
  15068. function sprintf () {
  15069. // http://kevin.vanzonneveld.net
  15070. // + original by: Ash Searle (http://hexmen.com/blog/)
  15071. // + namespaced by: Michael White (http://getsprink.com)
  15072. // + tweaked by: Jack
  15073. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15074. // + input by: Paulo Freitas
  15075. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15076. // + input by: Brett Zamir (http://brett-zamir.me)
  15077. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  15078. // + improved by: Dj
  15079. // + improved by: Allidylls
  15080. // * example 1: sprintf("%01.2f", 123.1);
  15081. // * returns 1: 123.10
  15082. // * example 2: sprintf("[%10s]", 'monkey');
  15083. // * returns 2: '[ monkey]'
  15084. // * example 3: sprintf("[%'#10s]", 'monkey');
  15085. // * returns 3: '[####monkey]'
  15086. // * example 4: sprintf("%d", 123456789012345);
  15087. // * returns 4: '123456789012345'
  15088. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  15089. var a = arguments,
  15090. i = 0,
  15091. format = a[i++];
  15092. // pad()
  15093. var pad = function (str, len, chr, leftJustify) {
  15094. if (!chr) {
  15095. chr = ' ';
  15096. }
  15097. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  15098. return leftJustify ? str + padding : padding + str;
  15099. };
  15100. // justify()
  15101. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  15102. var diff = minWidth - value.length;
  15103. if (diff > 0) {
  15104. if (leftJustify || !zeroPad) {
  15105. value = pad(value, minWidth, customPadChar, leftJustify);
  15106. } else {
  15107. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  15108. }
  15109. }
  15110. return value;
  15111. };
  15112. // formatBaseX()
  15113. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  15114. // Note: casts negative numbers to positive ones
  15115. var number = value >>> 0;
  15116. prefix = prefix && number && {
  15117. '2': '0b',
  15118. '8': '0',
  15119. '16': '0x'
  15120. }[base] || '';
  15121. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  15122. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  15123. };
  15124. // formatString()
  15125. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  15126. if (precision != null) {
  15127. value = value.slice(0, precision);
  15128. }
  15129. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  15130. };
  15131. // doFormat()
  15132. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  15133. var number;
  15134. var prefix;
  15135. var method;
  15136. var textTransform;
  15137. var value;
  15138. if (substring == '%%') {
  15139. return '%';
  15140. }
  15141. // parse flags
  15142. var leftJustify = false,
  15143. positivePrefix = '',
  15144. zeroPad = false,
  15145. prefixBaseX = false,
  15146. customPadChar = ' ';
  15147. var flagsl = flags.length;
  15148. for (var j = 0; flags && j < flagsl; j++) {
  15149. switch (flags.charAt(j)) {
  15150. case ' ':
  15151. positivePrefix = ' ';
  15152. break;
  15153. case '+':
  15154. positivePrefix = '+';
  15155. break;
  15156. case '-':
  15157. leftJustify = true;
  15158. break;
  15159. case "'":
  15160. customPadChar = flags.charAt(j + 1);
  15161. break;
  15162. case '0':
  15163. zeroPad = true;
  15164. break;
  15165. case '#':
  15166. prefixBaseX = true;
  15167. break;
  15168. }
  15169. }
  15170. // parameters may be null, undefined, empty-string or real valued
  15171. // we want to ignore null, undefined and empty-string values
  15172. if (!minWidth) {
  15173. minWidth = 0;
  15174. } else if (minWidth == '*') {
  15175. minWidth = +a[i++];
  15176. } else if (minWidth.charAt(0) == '*') {
  15177. minWidth = +a[minWidth.slice(1, -1)];
  15178. } else {
  15179. minWidth = +minWidth;
  15180. }
  15181. // Note: undocumented perl feature:
  15182. if (minWidth < 0) {
  15183. minWidth = -minWidth;
  15184. leftJustify = true;
  15185. }
  15186. if (!isFinite(minWidth)) {
  15187. throw new Error('sprintf: (minimum-)width must be finite');
  15188. }
  15189. if (!precision) {
  15190. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  15191. } else if (precision == '*') {
  15192. precision = +a[i++];
  15193. } else if (precision.charAt(0) == '*') {
  15194. precision = +a[precision.slice(1, -1)];
  15195. } else {
  15196. precision = +precision;
  15197. }
  15198. // grab value using valueIndex if required?
  15199. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  15200. switch (type) {
  15201. case 's':
  15202. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  15203. case 'c':
  15204. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  15205. case 'b':
  15206. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  15207. case 'o':
  15208. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  15209. case 'x':
  15210. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  15211. case 'X':
  15212. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  15213. case 'u':
  15214. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  15215. case 'i':
  15216. case 'd':
  15217. number = +value || 0;
  15218. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  15219. prefix = number < 0 ? '-' : positivePrefix;
  15220. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  15221. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  15222. case 'e':
  15223. case 'E':
  15224. case 'f': // Should handle locales (as per setlocale)
  15225. case 'F':
  15226. case 'g':
  15227. case 'G':
  15228. number = +value;
  15229. prefix = number < 0 ? '-' : positivePrefix;
  15230. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  15231. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  15232. value = prefix + Math.abs(number)[method](precision);
  15233. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  15234. default:
  15235. return substring;
  15236. }
  15237. };
  15238. return format.replace(regex, doFormat);
  15239. }
  15240. return sprintf;
  15241. });
  15242. /*global define*/
  15243. define('Core/GregorianDate',[],function() {
  15244. 'use strict';
  15245. /**
  15246. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  15247. * In addition to submillisecond precision, this object can also represent leap seconds.
  15248. * @alias GregorianDate
  15249. * @constructor
  15250. *
  15251. * @see JulianDate#toGregorianDate
  15252. */
  15253. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  15254. /**
  15255. * Gets or sets the year as a whole number.
  15256. * @type {Number}
  15257. */
  15258. this.year = year;
  15259. /**
  15260. * Gets or sets the month as a whole number with range [1, 12].
  15261. * @type {Number}
  15262. */
  15263. this.month = month;
  15264. /**
  15265. * Gets or sets the day of the month as a whole number starting at 1.
  15266. * @type {Number}
  15267. */
  15268. this.day = day;
  15269. /**
  15270. * Gets or sets the hour as a whole number with range [0, 23].
  15271. * @type {Number}
  15272. */
  15273. this.hour = hour;
  15274. /**
  15275. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  15276. * @type {Number}
  15277. */
  15278. this.minute = minute;
  15279. /**
  15280. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  15281. * @type {Number}
  15282. */
  15283. this.second = second;
  15284. /**
  15285. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  15286. * @type {Number}
  15287. */
  15288. this.millisecond = millisecond;
  15289. /**
  15290. * Gets or sets whether this time is during a leap second.
  15291. * @type {Boolean}
  15292. */
  15293. this.isLeapSecond = isLeapSecond;
  15294. }
  15295. return GregorianDate;
  15296. });
  15297. /*global define*/
  15298. define('Core/isLeapYear',[
  15299. './DeveloperError'
  15300. ], function(
  15301. DeveloperError) {
  15302. 'use strict';
  15303. /**
  15304. * Determines if a given date is a leap year.
  15305. *
  15306. * @exports isLeapYear
  15307. *
  15308. * @param {Number} year The year to be tested.
  15309. * @returns {Boolean} True if <code>year</code> is a leap year.
  15310. *
  15311. * @example
  15312. * var leapYear = Cesium.isLeapYear(2000); // true
  15313. */
  15314. function isLeapYear(year) {
  15315. if (year === null || isNaN(year)) {
  15316. throw new DeveloperError('year is required and must be a number.');
  15317. }
  15318. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  15319. }
  15320. return isLeapYear;
  15321. });
  15322. /*global define*/
  15323. define('Core/LeapSecond',[],function() {
  15324. 'use strict';
  15325. /**
  15326. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  15327. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  15328. * @alias LeapSecond
  15329. * @constructor
  15330. *
  15331. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  15332. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  15333. */
  15334. function LeapSecond(date, offset) {
  15335. /**
  15336. * Gets or sets the date at which this leap second occurs.
  15337. * @type {JulianDate}
  15338. */
  15339. this.julianDate = date;
  15340. /**
  15341. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  15342. * of this leap second.
  15343. * @type {Number}
  15344. */
  15345. this.offset = offset;
  15346. }
  15347. return LeapSecond;
  15348. });
  15349. /*global define*/
  15350. define('Core/TimeConstants',[
  15351. './freezeObject'
  15352. ], function(
  15353. freezeObject) {
  15354. 'use strict';
  15355. /**
  15356. * Constants for time conversions like those done by {@link JulianDate}.
  15357. *
  15358. * @exports TimeConstants
  15359. *
  15360. * @see JulianDate
  15361. *
  15362. * @private
  15363. */
  15364. var TimeConstants = {
  15365. /**
  15366. * The number of seconds in one millisecond: <code>0.001</code>
  15367. * @type {Number}
  15368. * @constant
  15369. */
  15370. SECONDS_PER_MILLISECOND : 0.001,
  15371. /**
  15372. * The number of seconds in one minute: <code>60</code>.
  15373. * @type {Number}
  15374. * @constant
  15375. */
  15376. SECONDS_PER_MINUTE : 60.0,
  15377. /**
  15378. * The number of minutes in one hour: <code>60</code>.
  15379. * @type {Number}
  15380. * @constant
  15381. */
  15382. MINUTES_PER_HOUR : 60.0,
  15383. /**
  15384. * The number of hours in one day: <code>24</code>.
  15385. * @type {Number}
  15386. * @constant
  15387. */
  15388. HOURS_PER_DAY : 24.0,
  15389. /**
  15390. * The number of seconds in one hour: <code>3600</code>.
  15391. * @type {Number}
  15392. * @constant
  15393. */
  15394. SECONDS_PER_HOUR : 3600.0,
  15395. /**
  15396. * The number of minutes in one day: <code>1440</code>.
  15397. * @type {Number}
  15398. * @constant
  15399. */
  15400. MINUTES_PER_DAY : 1440.0,
  15401. /**
  15402. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  15403. * @type {Number}
  15404. * @constant
  15405. */
  15406. SECONDS_PER_DAY : 86400.0,
  15407. /**
  15408. * The number of days in one Julian century: <code>36525</code>.
  15409. * @type {Number}
  15410. * @constant
  15411. */
  15412. DAYS_PER_JULIAN_CENTURY : 36525.0,
  15413. /**
  15414. * One trillionth of a second.
  15415. * @type {Number}
  15416. * @constant
  15417. */
  15418. PICOSECOND : 0.000000001,
  15419. /**
  15420. * The number of days to subtract from a Julian date to determine the
  15421. * modified Julian date, which gives the number of days since midnight
  15422. * on November 17, 1858.
  15423. * @type {Number}
  15424. * @constant
  15425. */
  15426. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  15427. };
  15428. return freezeObject(TimeConstants);
  15429. });
  15430. /*global define*/
  15431. define('Core/TimeStandard',[
  15432. './freezeObject'
  15433. ], function(
  15434. freezeObject) {
  15435. 'use strict';
  15436. /**
  15437. * Provides the type of time standards which JulianDate can take as input.
  15438. *
  15439. * @exports TimeStandard
  15440. *
  15441. * @see JulianDate
  15442. */
  15443. var TimeStandard = {
  15444. /**
  15445. * Represents the coordinated Universal Time (UTC) time standard.
  15446. *
  15447. * UTC is related to TAI according to the relationship
  15448. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  15449. * seconds which have been introduced as of the time in TAI.
  15450. *
  15451. */
  15452. UTC : 0,
  15453. /**
  15454. * Represents the International Atomic Time (TAI) time standard.
  15455. * TAI is the principal time standard to which the other time standards are related.
  15456. */
  15457. TAI : 1
  15458. };
  15459. return freezeObject(TimeStandard);
  15460. });
  15461. /*global define*/
  15462. define('Core/JulianDate',[
  15463. '../ThirdParty/sprintf',
  15464. './binarySearch',
  15465. './defaultValue',
  15466. './defined',
  15467. './DeveloperError',
  15468. './GregorianDate',
  15469. './isLeapYear',
  15470. './LeapSecond',
  15471. './TimeConstants',
  15472. './TimeStandard'
  15473. ], function(
  15474. sprintf,
  15475. binarySearch,
  15476. defaultValue,
  15477. defined,
  15478. DeveloperError,
  15479. GregorianDate,
  15480. isLeapYear,
  15481. LeapSecond,
  15482. TimeConstants,
  15483. TimeStandard) {
  15484. 'use strict';
  15485. var gregorianDateScratch = new GregorianDate();
  15486. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  15487. var daysInLeapFeburary = 29;
  15488. function compareLeapSecondDates(leapSecond, dateToFind) {
  15489. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  15490. }
  15491. // we don't really need a leap second instance, anything with a julianDate property will do
  15492. var binarySearchScratchLeapSecond = new LeapSecond();
  15493. function convertUtcToTai(julianDate) {
  15494. //Even though julianDate is in UTC, we'll treat it as TAI and
  15495. //search the leap second table for it.
  15496. binarySearchScratchLeapSecond.julianDate = julianDate;
  15497. var leapSeconds = JulianDate.leapSeconds;
  15498. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  15499. if (index < 0) {
  15500. index = ~index;
  15501. }
  15502. if (index >= leapSeconds.length) {
  15503. index = leapSeconds.length - 1;
  15504. }
  15505. var offset = leapSeconds[index].offset;
  15506. if (index > 0) {
  15507. //Now we have the index of the closest leap second that comes on or after our UTC time.
  15508. //However, if the difference between the UTC date being converted and the TAI
  15509. //defined leap second is greater than the offset, we are off by one and need to use
  15510. //the previous leap second.
  15511. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  15512. if (difference > offset) {
  15513. index--;
  15514. offset = leapSeconds[index].offset;
  15515. }
  15516. }
  15517. JulianDate.addSeconds(julianDate, offset, julianDate);
  15518. }
  15519. function convertTaiToUtc(julianDate, result) {
  15520. binarySearchScratchLeapSecond.julianDate = julianDate;
  15521. var leapSeconds = JulianDate.leapSeconds;
  15522. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  15523. if (index < 0) {
  15524. index = ~index;
  15525. }
  15526. //All times before our first leap second get the first offset.
  15527. if (index === 0) {
  15528. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  15529. }
  15530. //All times after our leap second get the last offset.
  15531. if (index >= leapSeconds.length) {
  15532. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  15533. }
  15534. //Compute the difference between the found leap second and the time we are converting.
  15535. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  15536. if (difference === 0) {
  15537. //The date is in our leap second table.
  15538. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  15539. }
  15540. if (difference <= 1.0) {
  15541. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  15542. return undefined;
  15543. }
  15544. //The time is in between two leap seconds, index is the leap second after the date
  15545. //we're converting, so we subtract one to get the correct LeapSecond instance.
  15546. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  15547. }
  15548. function setComponents(wholeDays, secondsOfDay, julianDate) {
  15549. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  15550. wholeDays += extraDays;
  15551. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  15552. if (secondsOfDay < 0) {
  15553. wholeDays--;
  15554. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  15555. }
  15556. julianDate.dayNumber = wholeDays;
  15557. julianDate.secondsOfDay = secondsOfDay;
  15558. return julianDate;
  15559. }
  15560. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  15561. // Algorithm from page 604 of the Explanatory Supplement to the
  15562. // Astronomical Almanac (Seidelmann 1992).
  15563. var a = ((month - 14) / 12) | 0;
  15564. var b = year + 4800 + a;
  15565. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  15566. // JulianDates are noon-based
  15567. hour = hour - 12;
  15568. if (hour < 0) {
  15569. hour += 24;
  15570. }
  15571. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  15572. if (secondsOfDay >= 43200.0) {
  15573. dayNumber -= 1;
  15574. }
  15575. return [dayNumber, secondsOfDay];
  15576. }
  15577. //Regular expressions used for ISO8601 date parsing.
  15578. //YYYY
  15579. var matchCalendarYear = /^(\d{4})$/;
  15580. //YYYY-MM (YYYYMM is invalid)
  15581. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  15582. //YYYY-DDD or YYYYDDD
  15583. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  15584. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  15585. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  15586. //YYYY-MM-DD or YYYYMMDD
  15587. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  15588. // Match utc offset
  15589. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  15590. // Match hours HH or HH.xxxxx
  15591. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  15592. // Match hours/minutes HH:MM HHMM.xxxxx
  15593. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  15594. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  15595. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  15596. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  15597. /**
  15598. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  15599. * For increased precision, this class stores the whole number part of the date and the seconds
  15600. * part of the date in separate components. In order to be safe for arithmetic and represent
  15601. * leap seconds, the date is always stored in the International Atomic Time standard
  15602. * {@link TimeStandard.TAI}.
  15603. * @alias JulianDate
  15604. * @constructor
  15605. *
  15606. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  15607. * @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.
  15608. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  15609. */
  15610. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  15611. /**
  15612. * Gets or sets the number of whole days.
  15613. * @type {Number}
  15614. */
  15615. this.dayNumber = undefined;
  15616. /**
  15617. * Gets or sets the number of seconds into the current day.
  15618. * @type {Number}
  15619. */
  15620. this.secondsOfDay = undefined;
  15621. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  15622. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  15623. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  15624. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  15625. var wholeDays = julianDayNumber | 0;
  15626. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  15627. setComponents(wholeDays, secondsOfDay, this);
  15628. if (timeStandard === TimeStandard.UTC) {
  15629. convertUtcToTai(this);
  15630. }
  15631. }
  15632. /**
  15633. * Creates a new instance from a JavaScript Date.
  15634. *
  15635. * @param {Date} date A JavaScript Date.
  15636. * @param {JulianDate} [result] An existing instance to use for the result.
  15637. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15638. *
  15639. * @exception {DeveloperError} date must be a valid JavaScript Date.
  15640. */
  15641. JulianDate.fromDate = function(date, result) {
  15642. if (!(date instanceof Date) || isNaN(date.getTime())) {
  15643. throw new DeveloperError('date must be a valid JavaScript Date.');
  15644. }
  15645. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  15646. if (!defined(result)) {
  15647. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  15648. }
  15649. setComponents(components[0], components[1], result);
  15650. convertUtcToTai(result);
  15651. return result;
  15652. };
  15653. /**
  15654. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  15655. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  15656. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  15657. *
  15658. * @param {String} iso8601String An ISO 8601 date.
  15659. * @param {JulianDate} [result] An existing instance to use for the result.
  15660. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15661. *
  15662. * @exception {DeveloperError} Invalid ISO 8601 date.
  15663. */
  15664. JulianDate.fromIso8601 = function(iso8601String, result) {
  15665. if (typeof iso8601String !== 'string') {
  15666. throw new DeveloperError(iso8601ErrorMessage);
  15667. }
  15668. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  15669. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  15670. iso8601String = iso8601String.replace(',', '.');
  15671. //Split the string into its date and time components, denoted by a mandatory T
  15672. var tokens = iso8601String.split('T');
  15673. var year;
  15674. var month = 1;
  15675. var day = 1;
  15676. var hour = 0;
  15677. var minute = 0;
  15678. var second = 0;
  15679. var millisecond = 0;
  15680. //Lacking a time is okay, but a missing date is illegal.
  15681. var date = tokens[0];
  15682. var time = tokens[1];
  15683. var tmp;
  15684. var inLeapYear;
  15685. if (!defined(date)) {
  15686. throw new DeveloperError(iso8601ErrorMessage);
  15687. }
  15688. var dashCount;
  15689. //First match the date against possible regular expressions.
  15690. tokens = date.match(matchCalendarDate);
  15691. if (tokens !== null) {
  15692. dashCount = date.split('-').length - 1;
  15693. if (dashCount > 0 && dashCount !== 2) {
  15694. throw new DeveloperError(iso8601ErrorMessage);
  15695. }
  15696. year = +tokens[1];
  15697. month = +tokens[2];
  15698. day = +tokens[3];
  15699. } else {
  15700. tokens = date.match(matchCalendarMonth);
  15701. if (tokens !== null) {
  15702. year = +tokens[1];
  15703. month = +tokens[2];
  15704. } else {
  15705. tokens = date.match(matchCalendarYear);
  15706. if (tokens !== null) {
  15707. year = +tokens[1];
  15708. } else {
  15709. //Not a year/month/day so it must be an ordinal date.
  15710. var dayOfYear;
  15711. tokens = date.match(matchOrdinalDate);
  15712. if (tokens !== null) {
  15713. year = +tokens[1];
  15714. dayOfYear = +tokens[2];
  15715. inLeapYear = isLeapYear(year);
  15716. //This validation is only applicable for this format.
  15717. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  15718. throw new DeveloperError(iso8601ErrorMessage);
  15719. }
  15720. } else {
  15721. tokens = date.match(matchWeekDate);
  15722. if (tokens !== null) {
  15723. //ISO week date to ordinal date from
  15724. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  15725. year = +tokens[1];
  15726. var weekNumber = +tokens[2];
  15727. var dayOfWeek = +tokens[3] || 0;
  15728. dashCount = date.split('-').length - 1;
  15729. if (dashCount > 0 &&
  15730. ((!defined(tokens[3]) && dashCount !== 1) ||
  15731. (defined(tokens[3]) && dashCount !== 2))) {
  15732. throw new DeveloperError(iso8601ErrorMessage);
  15733. }
  15734. var january4 = new Date(Date.UTC(year, 0, 4));
  15735. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  15736. } else {
  15737. //None of our regular expressions succeeded in parsing the date properly.
  15738. throw new DeveloperError(iso8601ErrorMessage);
  15739. }
  15740. }
  15741. //Split an ordinal date into month/day.
  15742. tmp = new Date(Date.UTC(year, 0, 1));
  15743. tmp.setUTCDate(dayOfYear);
  15744. month = tmp.getUTCMonth() + 1;
  15745. day = tmp.getUTCDate();
  15746. }
  15747. }
  15748. }
  15749. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  15750. inLeapYear = isLeapYear(year);
  15751. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  15752. throw new DeveloperError(iso8601ErrorMessage);
  15753. }
  15754. //Not move onto the time string, which is much simpler.
  15755. var offsetIndex;
  15756. if (defined(time)) {
  15757. tokens = time.match(matchHoursMinutesSeconds);
  15758. if (tokens !== null) {
  15759. dashCount = time.split(':').length - 1;
  15760. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  15761. throw new DeveloperError(iso8601ErrorMessage);
  15762. }
  15763. hour = +tokens[1];
  15764. minute = +tokens[2];
  15765. second = +tokens[3];
  15766. millisecond = +(tokens[4] || 0) * 1000.0;
  15767. offsetIndex = 5;
  15768. } else {
  15769. tokens = time.match(matchHoursMinutes);
  15770. if (tokens !== null) {
  15771. dashCount = time.split(':').length - 1;
  15772. if (dashCount > 2) {
  15773. throw new DeveloperError(iso8601ErrorMessage);
  15774. }
  15775. hour = +tokens[1];
  15776. minute = +tokens[2];
  15777. second = +(tokens[3] || 0) * 60.0;
  15778. offsetIndex = 4;
  15779. } else {
  15780. tokens = time.match(matchHours);
  15781. if (tokens !== null) {
  15782. hour = +tokens[1];
  15783. minute = +(tokens[2] || 0) * 60.0;
  15784. offsetIndex = 3;
  15785. } else {
  15786. throw new DeveloperError(iso8601ErrorMessage);
  15787. }
  15788. }
  15789. }
  15790. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  15791. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  15792. throw new DeveloperError(iso8601ErrorMessage);
  15793. }
  15794. //Check the UTC offset value, if no value exists, use local time
  15795. //a Z indicates UTC, + or - are offsets.
  15796. var offset = tokens[offsetIndex];
  15797. var offsetHours = +(tokens[offsetIndex + 1]);
  15798. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  15799. switch (offset) {
  15800. case '+':
  15801. hour = hour - offsetHours;
  15802. minute = minute - offsetMinutes;
  15803. break;
  15804. case '-':
  15805. hour = hour + offsetHours;
  15806. minute = minute + offsetMinutes;
  15807. break;
  15808. case 'Z':
  15809. break;
  15810. default:
  15811. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  15812. break;
  15813. }
  15814. } else {
  15815. //If no time is specified, it is considered the beginning of the day, local time.
  15816. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  15817. }
  15818. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  15819. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  15820. //Then we add it back in after converting to TAI.
  15821. var isLeapSecond = second === 60;
  15822. if (isLeapSecond) {
  15823. second--;
  15824. }
  15825. //Even if we successfully parsed the string into its components, after applying UTC offset or
  15826. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  15827. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  15828. while (minute >= 60) {
  15829. minute -= 60;
  15830. hour++;
  15831. }
  15832. while (hour >= 24) {
  15833. hour -= 24;
  15834. day++;
  15835. }
  15836. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15837. while (day > tmp) {
  15838. day -= tmp;
  15839. month++;
  15840. if (month > 12) {
  15841. month -= 12;
  15842. year++;
  15843. }
  15844. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15845. }
  15846. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  15847. while (minute < 0) {
  15848. minute += 60;
  15849. hour--;
  15850. }
  15851. while (hour < 0) {
  15852. hour += 24;
  15853. day--;
  15854. }
  15855. while (day < 1) {
  15856. month--;
  15857. if (month < 1) {
  15858. month += 12;
  15859. year--;
  15860. }
  15861. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15862. day += tmp;
  15863. }
  15864. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  15865. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  15866. if (!defined(result)) {
  15867. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  15868. } else {
  15869. setComponents(components[0], components[1], result);
  15870. convertUtcToTai(result);
  15871. }
  15872. //If we were on a leap second, add it back.
  15873. if (isLeapSecond) {
  15874. JulianDate.addSeconds(result, 1, result);
  15875. }
  15876. return result;
  15877. };
  15878. /**
  15879. * Creates a new instance that represents the current system time.
  15880. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  15881. *
  15882. * @param {JulianDate} [result] An existing instance to use for the result.
  15883. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15884. */
  15885. JulianDate.now = function(result) {
  15886. return JulianDate.fromDate(new Date(), result);
  15887. };
  15888. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  15889. /**
  15890. * Creates a {@link GregorianDate} from the provided instance.
  15891. *
  15892. * @param {JulianDate} julianDate The date to be converted.
  15893. * @param {GregorianDate} [result] An existing instance to use for the result.
  15894. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  15895. */
  15896. JulianDate.toGregorianDate = function(julianDate, result) {
  15897. if (!defined(julianDate)) {
  15898. throw new DeveloperError('julianDate is required.');
  15899. }
  15900. var isLeapSecond = false;
  15901. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  15902. if (!defined(thisUtc)) {
  15903. //Conversion to UTC will fail if we are during a leap second.
  15904. //If that's the case, subtract a second and convert again.
  15905. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  15906. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  15907. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  15908. isLeapSecond = true;
  15909. }
  15910. var julianDayNumber = thisUtc.dayNumber;
  15911. var secondsOfDay = thisUtc.secondsOfDay;
  15912. if (secondsOfDay >= 43200.0) {
  15913. julianDayNumber += 1;
  15914. }
  15915. // Algorithm from page 604 of the Explanatory Supplement to the
  15916. // Astronomical Almanac (Seidelmann 1992).
  15917. var L = (julianDayNumber + 68569) | 0;
  15918. var N = (4 * L / 146097) | 0;
  15919. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  15920. var I = ((4000 * (L + 1)) / 1461001) | 0;
  15921. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  15922. var J = ((80 * L) / 2447) | 0;
  15923. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  15924. L = (J / 11) | 0;
  15925. var month = (J + 2 - 12 * L) | 0;
  15926. var year = (100 * (N - 49) + I + L) | 0;
  15927. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  15928. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  15929. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  15930. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  15931. var second = remainingSeconds | 0;
  15932. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  15933. // JulianDates are noon-based
  15934. hour += 12;
  15935. if (hour > 23) {
  15936. hour -= 24;
  15937. }
  15938. //If we were on a leap second, add it back.
  15939. if (isLeapSecond) {
  15940. second += 1;
  15941. }
  15942. if (!defined(result)) {
  15943. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  15944. }
  15945. result.year = year;
  15946. result.month = month;
  15947. result.day = day;
  15948. result.hour = hour;
  15949. result.minute = minute;
  15950. result.second = second;
  15951. result.millisecond = millisecond;
  15952. result.isLeapSecond = isLeapSecond;
  15953. return result;
  15954. };
  15955. /**
  15956. * Creates a JavaScript Date from the provided instance.
  15957. * Since JavaScript dates are only accurate to the nearest millisecond and
  15958. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  15959. * If the provided JulianDate is during a leap second, the previous second is used.
  15960. *
  15961. * @param {JulianDate} julianDate The date to be converted.
  15962. * @returns {Date} A new instance representing the provided date.
  15963. */
  15964. JulianDate.toDate = function(julianDate) {
  15965. if (!defined(julianDate)) {
  15966. throw new DeveloperError('julianDate is required.');
  15967. }
  15968. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  15969. var second = gDate.second;
  15970. if (gDate.isLeapSecond) {
  15971. second -= 1;
  15972. }
  15973. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  15974. };
  15975. /**
  15976. * Creates an ISO8601 representation of the provided date.
  15977. *
  15978. * @param {JulianDate} julianDate The date to be converted.
  15979. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  15980. * @returns {String} The ISO8601 representation of the provided date.
  15981. */
  15982. JulianDate.toIso8601 = function(julianDate, precision) {
  15983. if (!defined(julianDate)) {
  15984. throw new DeveloperError('julianDate is required.');
  15985. }
  15986. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  15987. var millisecondStr;
  15988. if (!defined(precision) && gDate.millisecond !== 0) {
  15989. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  15990. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  15991. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  15992. }
  15993. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  15994. if (!defined(precision) || precision === 0) {
  15995. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  15996. }
  15997. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  15998. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  15999. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  16000. };
  16001. /**
  16002. * Duplicates a JulianDate instance.
  16003. *
  16004. * @param {JulianDate} julianDate The date to duplicate.
  16005. * @param {JulianDate} [result] An existing instance to use for the result.
  16006. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  16007. */
  16008. JulianDate.clone = function(julianDate, result) {
  16009. if (!defined(julianDate)) {
  16010. return undefined;
  16011. }
  16012. if (!defined(result)) {
  16013. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  16014. }
  16015. result.dayNumber = julianDate.dayNumber;
  16016. result.secondsOfDay = julianDate.secondsOfDay;
  16017. return result;
  16018. };
  16019. /**
  16020. * Compares two instances.
  16021. *
  16022. * @param {JulianDate} left The first instance.
  16023. * @param {JulianDate} right The second instance.
  16024. * @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.
  16025. */
  16026. JulianDate.compare = function(left, right) {
  16027. if (!defined(left)) {
  16028. throw new DeveloperError('left is required.');
  16029. }
  16030. if (!defined(right)) {
  16031. throw new DeveloperError('right is required.');
  16032. }
  16033. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  16034. if (julianDayNumberDifference !== 0) {
  16035. return julianDayNumberDifference;
  16036. }
  16037. return left.secondsOfDay - right.secondsOfDay;
  16038. };
  16039. /**
  16040. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  16041. *
  16042. * @param {JulianDate} [left] The first instance.
  16043. * @param {JulianDate} [right] The second instance.
  16044. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  16045. */
  16046. JulianDate.equals = function(left, right) {
  16047. return (left === right) ||
  16048. (defined(left) &&
  16049. defined(right) &&
  16050. left.dayNumber === right.dayNumber &&
  16051. left.secondsOfDay === right.secondsOfDay);
  16052. };
  16053. /**
  16054. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  16055. * each other. That is, in order for the dates to be considered equal (and for
  16056. * this function to return <code>true</code>), the absolute value of the difference between them, in
  16057. * seconds, must be less than <code>epsilon</code>.
  16058. *
  16059. * @param {JulianDate} [left] The first instance.
  16060. * @param {JulianDate} [right] The second instance.
  16061. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  16062. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  16063. */
  16064. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  16065. if (!defined(epsilon)) {
  16066. throw new DeveloperError('epsilon is required.');
  16067. }
  16068. return (left === right) ||
  16069. (defined(left) &&
  16070. defined(right) &&
  16071. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  16072. };
  16073. /**
  16074. * Computes the total number of whole and fractional days represented by the provided instance.
  16075. *
  16076. * @param {JulianDate} julianDate The date.
  16077. * @returns {Number} The Julian date as single floating point number.
  16078. */
  16079. JulianDate.totalDays = function(julianDate) {
  16080. if (!defined(julianDate)) {
  16081. throw new DeveloperError('julianDate is required.');
  16082. }
  16083. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  16084. };
  16085. /**
  16086. * Computes the difference in seconds between the provided instance.
  16087. *
  16088. * @param {JulianDate} left The first instance.
  16089. * @param {JulianDate} right The second instance.
  16090. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  16091. */
  16092. JulianDate.secondsDifference = function(left, right) {
  16093. if (!defined(left)) {
  16094. throw new DeveloperError('left is required.');
  16095. }
  16096. if (!defined(right)) {
  16097. throw new DeveloperError('right is required.');
  16098. }
  16099. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  16100. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  16101. };
  16102. /**
  16103. * Computes the difference in days between the provided instance.
  16104. *
  16105. * @param {JulianDate} left The first instance.
  16106. * @param {JulianDate} right The second instance.
  16107. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  16108. */
  16109. JulianDate.daysDifference = function(left, right) {
  16110. if (!defined(left)) {
  16111. throw new DeveloperError('left is required.');
  16112. }
  16113. if (!defined(right)) {
  16114. throw new DeveloperError('right is required.');
  16115. }
  16116. var dayDifference = (left.dayNumber - right.dayNumber);
  16117. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  16118. return dayDifference + secondDifference;
  16119. };
  16120. /**
  16121. * Computes the number of seconds the provided instance is ahead of UTC.
  16122. *
  16123. * @param {JulianDate} julianDate The date.
  16124. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  16125. */
  16126. JulianDate.computeTaiMinusUtc = function(julianDate) {
  16127. binarySearchScratchLeapSecond.julianDate = julianDate;
  16128. var leapSeconds = JulianDate.leapSeconds;
  16129. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  16130. if (index < 0) {
  16131. index = ~index;
  16132. --index;
  16133. if (index < 0) {
  16134. index = 0;
  16135. }
  16136. }
  16137. return leapSeconds[index].offset;
  16138. };
  16139. /**
  16140. * Adds the provided number of seconds to the provided date instance.
  16141. *
  16142. * @param {JulianDate} julianDate The date.
  16143. * @param {Number} seconds The number of seconds to add or subtract.
  16144. * @param {JulianDate} result An existing instance to use for the result.
  16145. * @returns {JulianDate} The modified result parameter.
  16146. */
  16147. JulianDate.addSeconds = function(julianDate, seconds, result) {
  16148. if (!defined(julianDate)) {
  16149. throw new DeveloperError('julianDate is required.');
  16150. }
  16151. if (!defined(seconds)) {
  16152. throw new DeveloperError('seconds is required.');
  16153. }
  16154. if (!defined(result)) {
  16155. throw new DeveloperError('result is required.');
  16156. }
  16157. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  16158. };
  16159. /**
  16160. * Adds the provided number of minutes to the provided date instance.
  16161. *
  16162. * @param {JulianDate} julianDate The date.
  16163. * @param {Number} minutes The number of minutes to add or subtract.
  16164. * @param {JulianDate} result An existing instance to use for the result.
  16165. * @returns {JulianDate} The modified result parameter.
  16166. */
  16167. JulianDate.addMinutes = function(julianDate, minutes, result) {
  16168. if (!defined(julianDate)) {
  16169. throw new DeveloperError('julianDate is required.');
  16170. }
  16171. if (!defined(minutes)) {
  16172. throw new DeveloperError('minutes is required.');
  16173. }
  16174. if (!defined(result)) {
  16175. throw new DeveloperError('result is required.');
  16176. }
  16177. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  16178. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  16179. };
  16180. /**
  16181. * Adds the provided number of hours to the provided date instance.
  16182. *
  16183. * @param {JulianDate} julianDate The date.
  16184. * @param {Number} hours The number of hours to add or subtract.
  16185. * @param {JulianDate} result An existing instance to use for the result.
  16186. * @returns {JulianDate} The modified result parameter.
  16187. */
  16188. JulianDate.addHours = function(julianDate, hours, result) {
  16189. if (!defined(julianDate)) {
  16190. throw new DeveloperError('julianDate is required.');
  16191. }
  16192. if (!defined(hours)) {
  16193. throw new DeveloperError('hours is required.');
  16194. }
  16195. if (!defined(result)) {
  16196. throw new DeveloperError('result is required.');
  16197. }
  16198. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  16199. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  16200. };
  16201. /**
  16202. * Adds the provided number of days to the provided date instance.
  16203. *
  16204. * @param {JulianDate} julianDate The date.
  16205. * @param {Number} days The number of days to add or subtract.
  16206. * @param {JulianDate} result An existing instance to use for the result.
  16207. * @returns {JulianDate} The modified result parameter.
  16208. */
  16209. JulianDate.addDays = function(julianDate, days, result) {
  16210. if (!defined(julianDate)) {
  16211. throw new DeveloperError('julianDate is required.');
  16212. }
  16213. if (!defined(days)) {
  16214. throw new DeveloperError('days is required.');
  16215. }
  16216. if (!defined(result)) {
  16217. throw new DeveloperError('result is required.');
  16218. }
  16219. var newJulianDayNumber = julianDate.dayNumber + days;
  16220. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  16221. };
  16222. /**
  16223. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  16224. *
  16225. * @param {JulianDate} left The first instance.
  16226. * @param {JulianDate} right The second instance.
  16227. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  16228. */
  16229. JulianDate.lessThan = function(left, right) {
  16230. return JulianDate.compare(left, right) < 0;
  16231. };
  16232. /**
  16233. * 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.
  16234. *
  16235. * @param {JulianDate} left The first instance.
  16236. * @param {JulianDate} right The second instance.
  16237. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  16238. */
  16239. JulianDate.lessThanOrEquals = function(left, right) {
  16240. return JulianDate.compare(left, right) <= 0;
  16241. };
  16242. /**
  16243. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  16244. *
  16245. * @param {JulianDate} left The first instance.
  16246. * @param {JulianDate} right The second instance.
  16247. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  16248. */
  16249. JulianDate.greaterThan = function(left, right) {
  16250. return JulianDate.compare(left, right) > 0;
  16251. };
  16252. /**
  16253. * 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.
  16254. *
  16255. * @param {JulianDate} left The first instance.
  16256. * @param {JulianDate} right The second instance.
  16257. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  16258. */
  16259. JulianDate.greaterThanOrEquals = function(left, right) {
  16260. return JulianDate.compare(left, right) >= 0;
  16261. };
  16262. /**
  16263. * Duplicates this instance.
  16264. *
  16265. * @param {JulianDate} [result] An existing instance to use for the result.
  16266. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  16267. */
  16268. JulianDate.prototype.clone = function(result) {
  16269. return JulianDate.clone(this, result);
  16270. };
  16271. /**
  16272. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  16273. *
  16274. * @param {JulianDate} [right] The second instance.
  16275. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  16276. */
  16277. JulianDate.prototype.equals = function(right) {
  16278. return JulianDate.equals(this, right);
  16279. };
  16280. /**
  16281. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  16282. * each other. That is, in order for the dates to be considered equal (and for
  16283. * this function to return <code>true</code>), the absolute value of the difference between them, in
  16284. * seconds, must be less than <code>epsilon</code>.
  16285. *
  16286. * @param {JulianDate} [right] The second instance.
  16287. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  16288. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  16289. */
  16290. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  16291. return JulianDate.equalsEpsilon(this, right, epsilon);
  16292. };
  16293. /**
  16294. * Creates a string representing this date in ISO8601 format.
  16295. *
  16296. * @returns {String} A string representing this date in ISO8601 format.
  16297. */
  16298. JulianDate.prototype.toString = function() {
  16299. return JulianDate.toIso8601(this);
  16300. };
  16301. /**
  16302. * Gets or sets the list of leap seconds used throughout Cesium.
  16303. * @memberof JulianDate
  16304. * @type {LeapSecond[]}
  16305. */
  16306. JulianDate.leapSeconds = [
  16307. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  16308. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  16309. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  16310. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  16311. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  16312. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  16313. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  16314. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  16315. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  16316. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  16317. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  16318. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  16319. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  16320. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  16321. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  16322. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  16323. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  16324. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  16325. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  16326. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  16327. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  16328. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  16329. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  16330. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  16331. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  16332. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  16333. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  16334. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  16335. ];
  16336. return JulianDate;
  16337. });
  16338. /*global define*/
  16339. define('Core/clone',[
  16340. './defaultValue'
  16341. ], function(
  16342. defaultValue) {
  16343. 'use strict';
  16344. /**
  16345. * Clones an object, returning a new object containing the same properties.
  16346. *
  16347. * @exports clone
  16348. *
  16349. * @param {Object} object The object to clone.
  16350. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  16351. * @returns {Object} The cloned object.
  16352. */
  16353. function clone(object, deep) {
  16354. if (object === null || typeof object !== 'object') {
  16355. return object;
  16356. }
  16357. deep = defaultValue(deep, false);
  16358. var result = new object.constructor();
  16359. for ( var propertyName in object) {
  16360. if (object.hasOwnProperty(propertyName)) {
  16361. var value = object[propertyName];
  16362. if (deep) {
  16363. value = clone(value, deep);
  16364. }
  16365. result[propertyName] = value;
  16366. }
  16367. }
  16368. return result;
  16369. }
  16370. return clone;
  16371. });
  16372. /*global define*/
  16373. define('Core/parseResponseHeaders',[], function() {
  16374. 'use strict';
  16375. /**
  16376. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  16377. * a dictionary.
  16378. *
  16379. * @exports parseResponseHeaders
  16380. *
  16381. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  16382. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  16383. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  16384. * is that header's value.
  16385. *
  16386. * @private
  16387. */
  16388. function parseResponseHeaders(headerString) {
  16389. var headers = {};
  16390. if (!headerString) {
  16391. return headers;
  16392. }
  16393. var headerPairs = headerString.split('\u000d\u000a');
  16394. for (var i = 0; i < headerPairs.length; ++i) {
  16395. var headerPair = headerPairs[i];
  16396. // Can't use split() here because it does the wrong thing
  16397. // if the header value has the string ": " in it.
  16398. var index = headerPair.indexOf('\u003a\u0020');
  16399. if (index > 0) {
  16400. var key = headerPair.substring(0, index);
  16401. var val = headerPair.substring(index + 2);
  16402. headers[key] = val;
  16403. }
  16404. }
  16405. return headers;
  16406. }
  16407. return parseResponseHeaders;
  16408. });
  16409. /*global define*/
  16410. define('Core/RequestErrorEvent',[
  16411. './defined',
  16412. './parseResponseHeaders'
  16413. ], function(
  16414. defined,
  16415. parseResponseHeaders) {
  16416. 'use strict';
  16417. /**
  16418. * An event that is raised when a request encounters an error.
  16419. *
  16420. * @constructor
  16421. * @alias RequestErrorEvent
  16422. *
  16423. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  16424. * @param {Object} [response] The response included along with the error.
  16425. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  16426. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  16427. */
  16428. function RequestErrorEvent(statusCode, response, responseHeaders) {
  16429. /**
  16430. * The HTTP error status code, such as 404. If the error does not have a particular
  16431. * HTTP code, this property will be undefined.
  16432. *
  16433. * @type {Number}
  16434. */
  16435. this.statusCode = statusCode;
  16436. /**
  16437. * The response included along with the error. If the error does not include a response,
  16438. * this property will be undefined.
  16439. *
  16440. * @type {Object}
  16441. */
  16442. this.response = response;
  16443. /**
  16444. * The headers included in the response, represented as an object literal of key/value pairs.
  16445. * If the error does not include any headers, this property will be undefined.
  16446. *
  16447. * @type {Object}
  16448. */
  16449. this.responseHeaders = responseHeaders;
  16450. if (typeof this.responseHeaders === 'string') {
  16451. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  16452. }
  16453. }
  16454. /**
  16455. * Creates a string representing this RequestErrorEvent.
  16456. * @memberof RequestErrorEvent
  16457. *
  16458. * @returns {String} A string representing the provided RequestErrorEvent.
  16459. */
  16460. RequestErrorEvent.prototype.toString = function() {
  16461. var str = 'Request has failed.';
  16462. if (defined(this.statusCode)) {
  16463. str += ' Status Code: ' + this.statusCode;
  16464. }
  16465. return str;
  16466. };
  16467. return RequestErrorEvent;
  16468. });
  16469. /**
  16470. * @license
  16471. *
  16472. * Grauw URI utilities
  16473. *
  16474. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  16475. *
  16476. * @author Laurens Holst (http://www.grauw.nl/)
  16477. *
  16478. * Copyright 2012 Laurens Holst
  16479. *
  16480. * Licensed under the Apache License, Version 2.0 (the "License");
  16481. * you may not use this file except in compliance with the License.
  16482. * You may obtain a copy of the License at
  16483. *
  16484. * http://www.apache.org/licenses/LICENSE-2.0
  16485. *
  16486. * Unless required by applicable law or agreed to in writing, software
  16487. * distributed under the License is distributed on an "AS IS" BASIS,
  16488. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16489. * See the License for the specific language governing permissions and
  16490. * limitations under the License.
  16491. *
  16492. */
  16493. /*global define*/
  16494. define('ThirdParty/Uri',[],function() {
  16495. /**
  16496. * Constructs a URI object.
  16497. * @constructor
  16498. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  16499. * @param {string|URI} uri A string or URI object to create the object from.
  16500. */
  16501. function URI(uri) {
  16502. if (uri instanceof URI) { // copy constructor
  16503. this.scheme = uri.scheme;
  16504. this.authority = uri.authority;
  16505. this.path = uri.path;
  16506. this.query = uri.query;
  16507. this.fragment = uri.fragment;
  16508. } else if (uri) { // uri is URI string or cast to string
  16509. var c = parseRegex.exec(uri);
  16510. this.scheme = c[1];
  16511. this.authority = c[2];
  16512. this.path = c[3];
  16513. this.query = c[4];
  16514. this.fragment = c[5];
  16515. }
  16516. }
  16517. // Initial values on the prototype
  16518. URI.prototype.scheme = null;
  16519. URI.prototype.authority = null;
  16520. URI.prototype.path = '';
  16521. URI.prototype.query = null;
  16522. URI.prototype.fragment = null;
  16523. // Regular expression from RFC 3986 appendix B
  16524. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  16525. /**
  16526. * Returns the scheme part of the URI.
  16527. * In "http://example.com:80/a/b?x#y" this is "http".
  16528. */
  16529. URI.prototype.getScheme = function() {
  16530. return this.scheme;
  16531. };
  16532. /**
  16533. * Returns the authority part of the URI.
  16534. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  16535. */
  16536. URI.prototype.getAuthority = function() {
  16537. return this.authority;
  16538. };
  16539. /**
  16540. * Returns the path part of the URI.
  16541. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  16542. * In "mailto:mike@example.com" this is "mike@example.com".
  16543. */
  16544. URI.prototype.getPath = function() {
  16545. return this.path;
  16546. };
  16547. /**
  16548. * Returns the query part of the URI.
  16549. * In "http://example.com:80/a/b?x#y" this is "x".
  16550. */
  16551. URI.prototype.getQuery = function() {
  16552. return this.query;
  16553. };
  16554. /**
  16555. * Returns the fragment part of the URI.
  16556. * In "http://example.com:80/a/b?x#y" this is "y".
  16557. */
  16558. URI.prototype.getFragment = function() {
  16559. return this.fragment;
  16560. };
  16561. /**
  16562. * Tests whether the URI is an absolute URI.
  16563. * See RFC 3986 section 4.3.
  16564. */
  16565. URI.prototype.isAbsolute = function() {
  16566. return !!this.scheme && !this.fragment;
  16567. };
  16568. ///**
  16569. //* Extensive validation of the URI against the ABNF in RFC 3986
  16570. //*/
  16571. //URI.prototype.validate
  16572. /**
  16573. * Tests whether the URI is a same-document reference.
  16574. * See RFC 3986 section 4.4.
  16575. *
  16576. * To perform more thorough comparison, you can normalise the URI objects.
  16577. */
  16578. URI.prototype.isSameDocumentAs = function(uri) {
  16579. return uri.scheme == this.scheme &&
  16580. uri.authority == this.authority &&
  16581. uri.path == this.path &&
  16582. uri.query == this.query;
  16583. };
  16584. /**
  16585. * Simple String Comparison of two URIs.
  16586. * See RFC 3986 section 6.2.1.
  16587. *
  16588. * To perform more thorough comparison, you can normalise the URI objects.
  16589. */
  16590. URI.prototype.equals = function(uri) {
  16591. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  16592. };
  16593. /**
  16594. * Normalizes the URI using syntax-based normalization.
  16595. * This includes case normalization, percent-encoding normalization and path segment normalization.
  16596. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  16597. * (Although that would not be a valid URI in the first place. See validate().)
  16598. * See RFC 3986 section 6.2.2.
  16599. */
  16600. URI.prototype.normalize = function() {
  16601. this.removeDotSegments();
  16602. if (this.scheme)
  16603. this.scheme = this.scheme.toLowerCase();
  16604. if (this.authority)
  16605. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  16606. replace(caseRegex, replaceCase);
  16607. if (this.path)
  16608. this.path = this.path.replace(caseRegex, replaceCase);
  16609. if (this.query)
  16610. this.query = this.query.replace(caseRegex, replaceCase);
  16611. if (this.fragment)
  16612. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  16613. };
  16614. var caseRegex = /%[0-9a-z]{2}/gi;
  16615. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  16616. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  16617. function replaceCase(str) {
  16618. var dec = unescape(str);
  16619. return percentRegex.test(dec) ? dec : str.toUpperCase();
  16620. }
  16621. function replaceAuthority(str, p1, p2, p3) {
  16622. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  16623. }
  16624. /**
  16625. * Resolve a relative URI (this) against a base URI.
  16626. * The base URI must be an absolute URI.
  16627. * See RFC 3986 section 5.2
  16628. */
  16629. URI.prototype.resolve = function(baseURI) {
  16630. var uri = new URI();
  16631. if (this.scheme) {
  16632. uri.scheme = this.scheme;
  16633. uri.authority = this.authority;
  16634. uri.path = this.path;
  16635. uri.query = this.query;
  16636. } else {
  16637. uri.scheme = baseURI.scheme;
  16638. if (this.authority) {
  16639. uri.authority = this.authority;
  16640. uri.path = this.path;
  16641. uri.query = this.query;
  16642. } else {
  16643. uri.authority = baseURI.authority;
  16644. if (this.path == '') {
  16645. uri.path = baseURI.path;
  16646. uri.query = this.query || baseURI.query;
  16647. } else {
  16648. if (this.path.charAt(0) == '/') {
  16649. uri.path = this.path;
  16650. uri.removeDotSegments();
  16651. } else {
  16652. if (baseURI.authority && baseURI.path == '') {
  16653. uri.path = '/' + this.path;
  16654. } else {
  16655. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  16656. }
  16657. uri.removeDotSegments();
  16658. }
  16659. uri.query = this.query;
  16660. }
  16661. }
  16662. }
  16663. uri.fragment = this.fragment;
  16664. return uri;
  16665. };
  16666. /**
  16667. * Remove dot segments from path.
  16668. * See RFC 3986 section 5.2.4
  16669. * @private
  16670. */
  16671. URI.prototype.removeDotSegments = function() {
  16672. var input = this.path.split('/'),
  16673. output = [],
  16674. segment,
  16675. absPath = input[0] == '';
  16676. if (absPath)
  16677. input.shift();
  16678. var sFirst = input[0] == '' ? input.shift() : null;
  16679. while (input.length) {
  16680. segment = input.shift();
  16681. if (segment == '..') {
  16682. output.pop();
  16683. } else if (segment != '.') {
  16684. output.push(segment);
  16685. }
  16686. }
  16687. if (segment == '.' || segment == '..')
  16688. output.push('');
  16689. if (absPath)
  16690. output.unshift('');
  16691. this.path = output.join('/');
  16692. };
  16693. // We don't like this function because it builds up a cache that is never cleared.
  16694. // /**
  16695. // * Resolves a relative URI against an absolute base URI.
  16696. // * Convenience method.
  16697. // * @param {String} uri the relative URI to resolve
  16698. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  16699. // */
  16700. // URI.resolve = function(sURI, sBaseURI) {
  16701. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  16702. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  16703. // return uri.resolve(baseURI).toString();
  16704. // };
  16705. // var cache = {};
  16706. /**
  16707. * Serialises the URI to a string.
  16708. */
  16709. URI.prototype.toString = function() {
  16710. var result = '';
  16711. if (this.scheme)
  16712. result += this.scheme + ':';
  16713. if (this.authority)
  16714. result += '//' + this.authority;
  16715. result += this.path;
  16716. if (this.query)
  16717. result += '?' + this.query;
  16718. if (this.fragment)
  16719. result += '#' + this.fragment;
  16720. return result;
  16721. };
  16722. return URI;
  16723. });
  16724. /*global define*/
  16725. define('Core/TrustedServers',[
  16726. '../ThirdParty/Uri',
  16727. './defined',
  16728. './DeveloperError'
  16729. ], function(
  16730. Uri,
  16731. defined,
  16732. DeveloperError) {
  16733. 'use strict';
  16734. /**
  16735. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  16736. * any requests to these servers.
  16737. *
  16738. * @exports TrustedServers
  16739. *
  16740. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16741. */
  16742. var TrustedServers = {};
  16743. var _servers = {};
  16744. /**
  16745. * Adds a trusted server to the registry
  16746. *
  16747. * @param {String} host The host to be added.
  16748. * @param {Number} port The port used to access the host.
  16749. *
  16750. * @example
  16751. * // Add a trusted server
  16752. * TrustedServers.add('my.server.com', 80);
  16753. */
  16754. TrustedServers.add = function(host, port) {
  16755. if (!defined(host)) {
  16756. throw new DeveloperError('host is required.');
  16757. }
  16758. if (!defined(port) || port <= 0) {
  16759. throw new DeveloperError('port is required to be greater than 0.');
  16760. }
  16761. var authority = host.toLowerCase() + ':' + port;
  16762. if (!defined(_servers[authority])) {
  16763. _servers[authority] = true;
  16764. }
  16765. };
  16766. /**
  16767. * Removes a trusted server from the registry
  16768. *
  16769. * @param {String} host The host to be removed.
  16770. * @param {Number} port The port used to access the host.
  16771. *
  16772. * @example
  16773. * // Remove a trusted server
  16774. * TrustedServers.remove('my.server.com', 80);
  16775. */
  16776. TrustedServers.remove = function(host, port) {
  16777. if (!defined(host)) {
  16778. throw new DeveloperError('host is required.');
  16779. }
  16780. if (!defined(port) || port <= 0) {
  16781. throw new DeveloperError('port is required to be greater than 0.');
  16782. }
  16783. var authority = host.toLowerCase() + ':' + port;
  16784. if (defined(_servers[authority])) {
  16785. delete _servers[authority];
  16786. }
  16787. };
  16788. function getAuthority(url) {
  16789. var uri = new Uri(url);
  16790. uri.normalize();
  16791. // Removes username:password@ so we just have host[:port]
  16792. var authority = uri.getAuthority();
  16793. if (!defined(authority)) {
  16794. return undefined; // Relative URL
  16795. }
  16796. if (authority.indexOf('@') !== -1) {
  16797. var parts = authority.split('@');
  16798. authority = parts[1];
  16799. }
  16800. // If the port is missing add one based on the scheme
  16801. if (authority.indexOf(':') === -1) {
  16802. var scheme = uri.getScheme();
  16803. if (!defined(scheme)) {
  16804. scheme = window.location.protocol;
  16805. scheme = scheme.substring(0, scheme.length-1);
  16806. }
  16807. if (scheme === 'http') {
  16808. authority += ':80';
  16809. } else if (scheme === 'https') {
  16810. authority += ':443';
  16811. } else {
  16812. return undefined;
  16813. }
  16814. }
  16815. return authority;
  16816. }
  16817. /**
  16818. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  16819. *
  16820. * @param {String} url The url to be tested against the trusted list
  16821. *
  16822. * @returns {boolean} Returns true if url is trusted, false otherwise.
  16823. *
  16824. * @example
  16825. * // Add server
  16826. * TrustedServers.add('my.server.com', 81);
  16827. *
  16828. * // Check if server is trusted
  16829. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  16830. * // my.server.com:81 is trusted
  16831. * }
  16832. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  16833. * // my.server.com isn't trusted
  16834. * }
  16835. */
  16836. TrustedServers.contains = function(url) {
  16837. if (!defined(url)) {
  16838. throw new DeveloperError('url is required.');
  16839. }
  16840. var authority = getAuthority(url);
  16841. if (defined(authority) && defined(_servers[authority])) {
  16842. return true;
  16843. }
  16844. return false;
  16845. };
  16846. /**
  16847. * Clears the registry
  16848. *
  16849. * @example
  16850. * // Remove a trusted server
  16851. * TrustedServers.clear();
  16852. */
  16853. TrustedServers.clear = function() {
  16854. _servers = {};
  16855. };
  16856. return TrustedServers;
  16857. });
  16858. /*global define*/
  16859. define('Core/loadWithXhr',[
  16860. '../ThirdParty/when',
  16861. './defaultValue',
  16862. './defined',
  16863. './DeveloperError',
  16864. './RequestErrorEvent',
  16865. './RuntimeError',
  16866. './TrustedServers'
  16867. ], function(
  16868. when,
  16869. defaultValue,
  16870. defined,
  16871. DeveloperError,
  16872. RequestErrorEvent,
  16873. RuntimeError,
  16874. TrustedServers) {
  16875. 'use strict';
  16876. /**
  16877. * Asynchronously loads the given URL. Returns a promise that will resolve to
  16878. * the result once loaded, or reject if the URL failed to load. The data is loaded
  16879. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16880. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  16881. *
  16882. * @exports loadWithXhr
  16883. *
  16884. * @param {Object} options Object with the following properties:
  16885. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  16886. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  16887. * @param {String} [options.method='GET'] The HTTP method to use.
  16888. * @param {String} [options.data] The data to send with the request, if any.
  16889. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  16890. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  16891. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  16892. *
  16893. *
  16894. * @example
  16895. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  16896. * Cesium.loadWithXhr({
  16897. * url : 'some/url',
  16898. * responseType : 'blob'
  16899. * }).then(function(blob) {
  16900. * // use the data
  16901. * }).otherwise(function(error) {
  16902. * // an error occurred
  16903. * });
  16904. *
  16905. * @see loadArrayBuffer
  16906. * @see loadBlob
  16907. * @see loadJson
  16908. * @see loadText
  16909. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16910. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16911. */
  16912. function loadWithXhr(options) {
  16913. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16914. if (!defined(options.url)) {
  16915. throw new DeveloperError('options.url is required.');
  16916. }
  16917. var responseType = options.responseType;
  16918. var method = defaultValue(options.method, 'GET');
  16919. var data = options.data;
  16920. var headers = options.headers;
  16921. var overrideMimeType = options.overrideMimeType;
  16922. return when(options.url, function(url) {
  16923. var deferred = when.defer();
  16924. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  16925. return deferred.promise;
  16926. });
  16927. }
  16928. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  16929. function decodeDataUriText(isBase64, data) {
  16930. var result = decodeURIComponent(data);
  16931. if (isBase64) {
  16932. return atob(result);
  16933. }
  16934. return result;
  16935. }
  16936. function decodeDataUriArrayBuffer(isBase64, data) {
  16937. var byteString = decodeDataUriText(isBase64, data);
  16938. var buffer = new ArrayBuffer(byteString.length);
  16939. var view = new Uint8Array(buffer);
  16940. for (var i = 0; i < byteString.length; i++) {
  16941. view[i] = byteString.charCodeAt(i);
  16942. }
  16943. return buffer;
  16944. }
  16945. function decodeDataUri(dataUriRegexResult, responseType) {
  16946. responseType = defaultValue(responseType, '');
  16947. var mimeType = dataUriRegexResult[1];
  16948. var isBase64 = !!dataUriRegexResult[2];
  16949. var data = dataUriRegexResult[3];
  16950. switch (responseType) {
  16951. case '':
  16952. case 'text':
  16953. return decodeDataUriText(isBase64, data);
  16954. case 'arraybuffer':
  16955. return decodeDataUriArrayBuffer(isBase64, data);
  16956. case 'blob':
  16957. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  16958. return new Blob([buffer], {
  16959. type : mimeType
  16960. });
  16961. case 'document':
  16962. var parser = new DOMParser();
  16963. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  16964. case 'json':
  16965. return JSON.parse(decodeDataUriText(isBase64, data));
  16966. default:
  16967. throw new DeveloperError('Unhandled responseType: ' + responseType);
  16968. }
  16969. }
  16970. // This is broken out into a separate function so that it can be mocked for testing purposes.
  16971. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  16972. var dataUriRegexResult = dataUriRegex.exec(url);
  16973. if (dataUriRegexResult !== null) {
  16974. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  16975. return;
  16976. }
  16977. var xhr = new XMLHttpRequest();
  16978. if (TrustedServers.contains(url)) {
  16979. xhr.withCredentials = true;
  16980. }
  16981. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  16982. xhr.overrideMimeType(overrideMimeType);
  16983. }
  16984. xhr.open(method, url, true);
  16985. if (defined(headers)) {
  16986. for (var key in headers) {
  16987. if (headers.hasOwnProperty(key)) {
  16988. xhr.setRequestHeader(key, headers[key]);
  16989. }
  16990. }
  16991. }
  16992. if (defined(responseType)) {
  16993. xhr.responseType = responseType;
  16994. }
  16995. xhr.onload = function() {
  16996. if (xhr.status < 200 || xhr.status >= 300) {
  16997. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  16998. return;
  16999. }
  17000. var response = xhr.response;
  17001. var browserResponseType = xhr.responseType;
  17002. //All modern browsers will go into either the first if block or last else block.
  17003. //Other code paths support older browsers that either do not support the supplied responseType
  17004. //or do not support the xhr.response property.
  17005. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  17006. deferred.resolve(response);
  17007. } else if ((responseType === 'json') && typeof response === 'string') {
  17008. try {
  17009. deferred.resolve(JSON.parse(response));
  17010. } catch (e) {
  17011. deferred.reject(e);
  17012. }
  17013. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  17014. deferred.resolve(xhr.responseXML);
  17015. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  17016. deferred.resolve(xhr.responseText);
  17017. } else {
  17018. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  17019. }
  17020. };
  17021. xhr.onerror = function(e) {
  17022. deferred.reject(new RequestErrorEvent());
  17023. };
  17024. xhr.send(data);
  17025. };
  17026. loadWithXhr.defaultLoad = loadWithXhr.load;
  17027. return loadWithXhr;
  17028. });
  17029. /*global define*/
  17030. define('Core/loadText',[
  17031. './loadWithXhr'
  17032. ], function(
  17033. loadWithXhr) {
  17034. 'use strict';
  17035. /**
  17036. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  17037. * a String once loaded, or reject if the URL failed to load. The data is loaded
  17038. * using XMLHttpRequest, which means that in order to make requests to another origin,
  17039. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  17040. *
  17041. * @exports loadText
  17042. *
  17043. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  17044. * @param {Object} [headers] HTTP headers to send with the request.
  17045. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  17046. *
  17047. *
  17048. * @example
  17049. * // load text from a URL, setting a custom header
  17050. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  17051. * 'X-Custom-Header' : 'some value'
  17052. * }).then(function(text) {
  17053. * // Do something with the text
  17054. * }).otherwise(function(error) {
  17055. * // an error occurred
  17056. * });
  17057. *
  17058. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  17059. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  17060. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  17061. */
  17062. function loadText(url, headers) {
  17063. return loadWithXhr({
  17064. url : url,
  17065. headers : headers
  17066. });
  17067. }
  17068. return loadText;
  17069. });
  17070. /*global define*/
  17071. define('Core/loadJson',[
  17072. './clone',
  17073. './defined',
  17074. './DeveloperError',
  17075. './loadText'
  17076. ], function(
  17077. clone,
  17078. defined,
  17079. DeveloperError,
  17080. loadText) {
  17081. 'use strict';
  17082. var defaultHeaders = {
  17083. Accept : 'application/json,*/*;q=0.01'
  17084. };
  17085. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  17086. /**
  17087. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  17088. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  17089. * using XMLHttpRequest, which means that in order to make requests to another origin,
  17090. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  17091. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  17092. * already specified.
  17093. *
  17094. * @exports loadJson
  17095. *
  17096. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  17097. * @param {Object} [headers] HTTP headers to send with the request.
  17098. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  17099. * if not specified.
  17100. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  17101. *
  17102. *
  17103. * @example
  17104. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  17105. * // Do something with the JSON object
  17106. * }).otherwise(function(error) {
  17107. * // an error occurred
  17108. * });
  17109. *
  17110. * @see loadText
  17111. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  17112. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  17113. */
  17114. function loadJson(url, headers) {
  17115. if (!defined(url)) {
  17116. throw new DeveloperError('url is required.');
  17117. }
  17118. if (!defined(headers)) {
  17119. headers = defaultHeaders;
  17120. } else if (!defined(headers.Accept)) {
  17121. // clone before adding the Accept header
  17122. headers = clone(headers);
  17123. headers.Accept = defaultHeaders.Accept;
  17124. }
  17125. return loadText(url, headers).then(function(value) {
  17126. return JSON.parse(value);
  17127. });
  17128. }
  17129. return loadJson;
  17130. });
  17131. /*global define*/
  17132. define('Core/EarthOrientationParameters',[
  17133. '../ThirdParty/when',
  17134. './binarySearch',
  17135. './defaultValue',
  17136. './defined',
  17137. './EarthOrientationParametersSample',
  17138. './freezeObject',
  17139. './JulianDate',
  17140. './LeapSecond',
  17141. './loadJson',
  17142. './RuntimeError',
  17143. './TimeConstants',
  17144. './TimeStandard'
  17145. ], function(
  17146. when,
  17147. binarySearch,
  17148. defaultValue,
  17149. defined,
  17150. EarthOrientationParametersSample,
  17151. freezeObject,
  17152. JulianDate,
  17153. LeapSecond,
  17154. loadJson,
  17155. RuntimeError,
  17156. TimeConstants,
  17157. TimeStandard) {
  17158. 'use strict';
  17159. /**
  17160. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  17161. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  17162. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  17163. * Reference Frame (ITRF).
  17164. *
  17165. * @alias EarthOrientationParameters
  17166. * @constructor
  17167. *
  17168. * @param {Object} [options] Object with the following properties:
  17169. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  17170. * parameter nor options.data is specified, all EOP values are assumed
  17171. * to be 0.0. If options.data is specified, this parameter is
  17172. * ignored.
  17173. * @param {Object} [options.data] The actual EOP data. If neither this
  17174. * parameter nor options.data is specified, all EOP values are assumed
  17175. * to be 0.0.
  17176. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  17177. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  17178. * should be added to {@link JulianDate.leapSeconds}. False if
  17179. * new leap seconds should be handled correctly in the context
  17180. * of the EOP data but otherwise ignored.
  17181. *
  17182. * @example
  17183. * // An example EOP data file, EOP.json:
  17184. * {
  17185. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  17186. * "samples" : [
  17187. * "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,
  17188. * "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,
  17189. * "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
  17190. * ]
  17191. * }
  17192. *
  17193. * @example
  17194. * // Loading the EOP data
  17195. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  17196. * Cesium.Transforms.earthOrientationParameters = eop;
  17197. *
  17198. * @private
  17199. */
  17200. function EarthOrientationParameters(options) {
  17201. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  17202. this._dates = undefined;
  17203. this._samples = undefined;
  17204. this._dateColumn = -1;
  17205. this._xPoleWanderRadiansColumn = -1;
  17206. this._yPoleWanderRadiansColumn = -1;
  17207. this._ut1MinusUtcSecondsColumn = -1;
  17208. this._xCelestialPoleOffsetRadiansColumn = -1;
  17209. this._yCelestialPoleOffsetRadiansColumn = -1;
  17210. this._taiMinusUtcSecondsColumn = -1;
  17211. this._columnCount = 0;
  17212. this._lastIndex = -1;
  17213. this._downloadPromise = undefined;
  17214. this._dataError = undefined;
  17215. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  17216. if (defined(options.data)) {
  17217. // Use supplied EOP data.
  17218. onDataReady(this, options.data);
  17219. } else if (defined(options.url)) {
  17220. // Download EOP data.
  17221. var that = this;
  17222. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  17223. onDataReady(that, eopData);
  17224. }, function() {
  17225. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  17226. });
  17227. } else {
  17228. // Use all zeros for EOP data.
  17229. onDataReady(this, {
  17230. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  17231. 'samples' : []
  17232. });
  17233. }
  17234. }
  17235. /**
  17236. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  17237. */
  17238. EarthOrientationParameters.NONE = freezeObject({
  17239. getPromiseToLoad : function() {
  17240. return when();
  17241. },
  17242. compute : function(date, result) {
  17243. if (!defined(result)) {
  17244. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  17245. } else {
  17246. result.xPoleWander = 0.0;
  17247. result.yPoleWander = 0.0;
  17248. result.xPoleOffset = 0.0;
  17249. result.yPoleOffset = 0.0;
  17250. result.ut1MinusUtc = 0.0;
  17251. }
  17252. return result;
  17253. }
  17254. });
  17255. /**
  17256. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  17257. * ready to use.
  17258. *
  17259. * @returns {Promise.<undefined>} The promise.
  17260. *
  17261. * @see when
  17262. */
  17263. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  17264. return when(this._downloadPromise);
  17265. };
  17266. /**
  17267. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  17268. * If the EOP data has not yet been download, this method returns undefined.
  17269. *
  17270. * @param {JulianDate} date The date for each to evaluate the EOP.
  17271. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  17272. * If this parameter is undefined, a new instance is created and returned.
  17273. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  17274. * undefined if the data necessary to evaluate EOP at the date has not yet been
  17275. * downloaded.
  17276. *
  17277. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  17278. *
  17279. * @see EarthOrientationParameters#getPromiseToLoad
  17280. */
  17281. EarthOrientationParameters.prototype.compute = function(date, result) {
  17282. // We cannot compute until the samples are available.
  17283. if (!defined(this._samples)) {
  17284. if (defined(this._dataError)) {
  17285. throw new RuntimeError(this._dataError);
  17286. }
  17287. return undefined;
  17288. }
  17289. if (!defined(result)) {
  17290. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  17291. }
  17292. if (this._samples.length === 0) {
  17293. result.xPoleWander = 0.0;
  17294. result.yPoleWander = 0.0;
  17295. result.xPoleOffset = 0.0;
  17296. result.yPoleOffset = 0.0;
  17297. result.ut1MinusUtc = 0.0;
  17298. return result;
  17299. }
  17300. var dates = this._dates;
  17301. var lastIndex = this._lastIndex;
  17302. var before = 0;
  17303. var after = 0;
  17304. if (defined(lastIndex)) {
  17305. var previousIndexDate = dates[lastIndex];
  17306. var nextIndexDate = dates[lastIndex + 1];
  17307. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  17308. var isAfterLastSample = !defined(nextIndexDate);
  17309. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  17310. if (isAfterPrevious && isBeforeNext) {
  17311. before = lastIndex;
  17312. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  17313. ++before;
  17314. }
  17315. after = before + 1;
  17316. interpolate(this, dates, this._samples, date, before, after, result);
  17317. return result;
  17318. }
  17319. }
  17320. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  17321. if (index >= 0) {
  17322. // If the next entry is the same date, use the later entry. This way, if two entries
  17323. // describe the same moment, one before a leap second and the other after, then we will use
  17324. // the post-leap second data.
  17325. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  17326. ++index;
  17327. }
  17328. before = index;
  17329. after = index;
  17330. } else {
  17331. after = ~index;
  17332. before = after - 1;
  17333. // Use the first entry if the date requested is before the beginning of the data.
  17334. if (before < 0) {
  17335. before = 0;
  17336. }
  17337. }
  17338. this._lastIndex = before;
  17339. interpolate(this, dates, this._samples, date, before, after, result);
  17340. return result;
  17341. };
  17342. function compareLeapSecondDates(leapSecond, dateToFind) {
  17343. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  17344. }
  17345. function onDataReady(eop, eopData) {
  17346. if (!defined(eopData.columnNames)) {
  17347. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  17348. return;
  17349. }
  17350. if (!defined(eopData.samples)) {
  17351. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  17352. return;
  17353. }
  17354. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  17355. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  17356. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  17357. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  17358. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  17359. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  17360. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  17361. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  17362. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  17363. return;
  17364. }
  17365. var samples = eop._samples = eopData.samples;
  17366. var dates = eop._dates = [];
  17367. eop._dateColumn = dateColumn;
  17368. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  17369. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  17370. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  17371. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  17372. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  17373. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  17374. eop._columnCount = eopData.columnNames.length;
  17375. eop._lastIndex = undefined;
  17376. var lastTaiMinusUtc;
  17377. var addNewLeapSeconds = eop._addNewLeapSeconds;
  17378. // Convert the ISO8601 dates to JulianDates.
  17379. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  17380. var mjd = samples[i + dateColumn];
  17381. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  17382. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  17383. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  17384. dates.push(date);
  17385. if (addNewLeapSeconds) {
  17386. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  17387. // We crossed a leap second boundary, so add the leap second
  17388. // if it does not already exist.
  17389. var leapSeconds = JulianDate.leapSeconds;
  17390. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  17391. if (leapSecondIndex < 0) {
  17392. var leapSecond = new LeapSecond(date, taiMinusUtc);
  17393. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  17394. }
  17395. }
  17396. lastTaiMinusUtc = taiMinusUtc;
  17397. }
  17398. }
  17399. }
  17400. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  17401. var start = index * columnCount;
  17402. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  17403. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  17404. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  17405. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  17406. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  17407. }
  17408. function linearInterp(dx, y1, y2) {
  17409. return y1 + dx * (y2 - y1);
  17410. }
  17411. function interpolate(eop, dates, samples, date, before, after, result) {
  17412. var columnCount = eop._columnCount;
  17413. // First check the bounds on the EOP data
  17414. // If we are after the bounds of the data, return zeros.
  17415. // The 'before' index should never be less than zero.
  17416. if (after > dates.length - 1) {
  17417. result.xPoleWander = 0;
  17418. result.yPoleWander = 0;
  17419. result.xPoleOffset = 0;
  17420. result.yPoleOffset = 0;
  17421. result.ut1MinusUtc = 0;
  17422. return result;
  17423. }
  17424. var beforeDate = dates[before];
  17425. var afterDate = dates[after];
  17426. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  17427. fillResultFromIndex(eop, samples, before, columnCount, result);
  17428. return result;
  17429. } else if (date.equals(afterDate)) {
  17430. fillResultFromIndex(eop, samples, after, columnCount, result);
  17431. return result;
  17432. }
  17433. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  17434. var startBefore = before * columnCount;
  17435. var startAfter = after * columnCount;
  17436. // Handle UT1 leap second edge case
  17437. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  17438. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  17439. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  17440. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  17441. // The absolute difference between the values is more than 0.5, so we may have
  17442. // crossed a leap second. Check if this is the case and, if so, adjust the
  17443. // afterValue to account for the leap second. This way, our interpolation will
  17444. // produce reasonable results.
  17445. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  17446. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  17447. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  17448. if (afterDate.equals(date)) {
  17449. // If we are at the end of the leap second interval, take the second value
  17450. // Otherwise, the interpolation below will yield the wrong side of the
  17451. // discontinuity
  17452. // At the end of the leap second, we need to start accounting for the jump
  17453. beforeUt1MinusUtc = afterUt1MinusUtc;
  17454. } else {
  17455. // Otherwise, remove the leap second so that the interpolation is correct
  17456. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  17457. }
  17458. }
  17459. }
  17460. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  17461. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  17462. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  17463. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  17464. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  17465. return result;
  17466. }
  17467. return EarthOrientationParameters;
  17468. });
  17469. /*global define*/
  17470. define('Core/HeadingPitchRoll',[
  17471. './defaultValue',
  17472. './defined',
  17473. './DeveloperError',
  17474. './Math'
  17475. ], function(
  17476. defaultValue,
  17477. defined,
  17478. DeveloperError,
  17479. CesiumMath) {
  17480. "use strict";
  17481. /**
  17482. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  17483. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  17484. * the positive x axis.
  17485. * @alias HeadingPitchRoll
  17486. * @constructor
  17487. *
  17488. * @param {Number} [heading=0.0] The heading component in radians.
  17489. * @param {Number} [pitch=0.0] The pitch component in radians.
  17490. * @param {Number} [roll=0.0] The roll component in radians.
  17491. */
  17492. function HeadingPitchRoll(heading, pitch, roll) {
  17493. this.heading = defaultValue(heading, 0.0);
  17494. this.pitch = defaultValue(pitch, 0.0);
  17495. this.roll = defaultValue(roll, 0.0);
  17496. }
  17497. /**
  17498. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  17499. *
  17500. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  17501. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  17502. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  17503. */
  17504. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  17505. if (!defined(quaternion)) {
  17506. throw new DeveloperError('quaternion is required');
  17507. }
  17508. if (!defined(result)) {
  17509. result = new HeadingPitchRoll();
  17510. }
  17511. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  17512. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  17513. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  17514. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  17515. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  17516. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  17517. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  17518. result.pitch = -Math.asin(test);
  17519. return result;
  17520. };
  17521. /**
  17522. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  17523. *
  17524. * @param {Number} heading the heading in degrees
  17525. * @param {Number} pitch the pitch in degrees
  17526. * @param {Number} roll the heading in degrees
  17527. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  17528. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  17529. */
  17530. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  17531. if (!defined(heading)) {
  17532. throw new DeveloperError('heading is required');
  17533. }
  17534. if (!defined(pitch)) {
  17535. throw new DeveloperError('pitch is required');
  17536. }
  17537. if (!defined(roll)) {
  17538. throw new DeveloperError('roll is required');
  17539. }
  17540. if (!defined(result)) {
  17541. result = new HeadingPitchRoll();
  17542. }
  17543. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  17544. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  17545. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  17546. return result;
  17547. };
  17548. /**
  17549. * Duplicates a HeadingPitchRoll instance.
  17550. *
  17551. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  17552. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  17553. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  17554. */
  17555. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  17556. if (!defined(headingPitchRoll)) {
  17557. return undefined;
  17558. }
  17559. if (!defined(result)) {
  17560. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  17561. }
  17562. result.heading = headingPitchRoll.heading;
  17563. result.pitch = headingPitchRoll.pitch;
  17564. result.roll = headingPitchRoll.roll;
  17565. return result;
  17566. };
  17567. /**
  17568. * Compares the provided HeadingPitchRolls componentwise and returns
  17569. * <code>true</code> if they are equal, <code>false</code> otherwise.
  17570. *
  17571. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  17572. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  17573. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  17574. */
  17575. HeadingPitchRoll.equals = function(left, right) {
  17576. return (left === right) ||
  17577. ((defined(left)) &&
  17578. (defined(right)) &&
  17579. (left.heading === right.heading) &&
  17580. (left.pitch === right.pitch) &&
  17581. (left.roll === right.roll));
  17582. };
  17583. /**
  17584. * Compares the provided HeadingPitchRolls componentwise and returns
  17585. * <code>true</code> if they pass an absolute or relative tolerance test,
  17586. * <code>false</code> otherwise.
  17587. *
  17588. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  17589. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  17590. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  17591. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  17592. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  17593. */
  17594. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  17595. return (left === right) ||
  17596. (defined(left) &&
  17597. defined(right) &&
  17598. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  17599. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  17600. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  17601. };
  17602. /**
  17603. * Duplicates this HeadingPitchRoll instance.
  17604. *
  17605. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  17606. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  17607. */
  17608. HeadingPitchRoll.prototype.clone = function(result) {
  17609. return HeadingPitchRoll.clone(this, result);
  17610. };
  17611. /**
  17612. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  17613. * <code>true</code> if they are equal, <code>false</code> otherwise.
  17614. *
  17615. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  17616. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  17617. */
  17618. HeadingPitchRoll.prototype.equals = function(right) {
  17619. return HeadingPitchRoll.equals(this, right);
  17620. };
  17621. /**
  17622. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  17623. * <code>true</code> if they pass an absolute or relative tolerance test,
  17624. * <code>false</code> otherwise.
  17625. *
  17626. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  17627. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  17628. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  17629. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  17630. */
  17631. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  17632. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  17633. };
  17634. /**
  17635. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  17636. *
  17637. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  17638. */
  17639. HeadingPitchRoll.prototype.toString = function() {
  17640. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  17641. };
  17642. return HeadingPitchRoll;
  17643. });
  17644. /*global define*/
  17645. define('Core/getAbsoluteUri',[
  17646. '../ThirdParty/Uri',
  17647. './defaultValue',
  17648. './defined',
  17649. './DeveloperError'
  17650. ], function(
  17651. Uri,
  17652. defaultValue,
  17653. defined,
  17654. DeveloperError) {
  17655. 'use strict';
  17656. /**
  17657. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  17658. * @exports getAbsoluteUri
  17659. *
  17660. * @param {String} relative The relative Uri.
  17661. * @param {String} [base] The base Uri.
  17662. * @returns {String} The absolute Uri of the given relative Uri.
  17663. *
  17664. * @example
  17665. * //absolute Uri will be "https://test.com/awesome.png";
  17666. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  17667. */
  17668. function getAbsoluteUri(relative, base) {
  17669. if (!defined(relative)) {
  17670. throw new DeveloperError('relative uri is required.');
  17671. }
  17672. base = defaultValue(base, document.location.href);
  17673. var baseUri = new Uri(base);
  17674. var relativeUri = new Uri(relative);
  17675. return relativeUri.resolve(baseUri).toString();
  17676. }
  17677. return getAbsoluteUri;
  17678. });
  17679. /*global define*/
  17680. define('Core/joinUrls',[
  17681. '../ThirdParty/Uri',
  17682. './defaultValue',
  17683. './defined',
  17684. './DeveloperError'
  17685. ], function(
  17686. Uri,
  17687. defaultValue,
  17688. defined,
  17689. DeveloperError) {
  17690. 'use strict';
  17691. /**
  17692. * Function for joining URLs in a manner that is aware of query strings and fragments.
  17693. * This is useful when the base URL has a query string that needs to be maintained
  17694. * (e.g. a presigned base URL).
  17695. * @param {String|Uri} first The base URL.
  17696. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  17697. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  17698. * @private
  17699. */
  17700. function joinUrls(first, second, appendSlash) {
  17701. if (!defined(first)) {
  17702. throw new DeveloperError('first is required');
  17703. }
  17704. if (!defined(second)) {
  17705. throw new DeveloperError('second is required');
  17706. }
  17707. appendSlash = defaultValue(appendSlash, true);
  17708. if (!(first instanceof Uri)) {
  17709. first = new Uri(first);
  17710. }
  17711. if (!(second instanceof Uri)) {
  17712. second = new Uri(second);
  17713. }
  17714. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  17715. // not a scheme, add a scheme matching the page's scheme.
  17716. if (defined(second.authority) && !defined(second.scheme)) {
  17717. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  17718. second.scheme = new Uri(document.location.href).scheme;
  17719. } else {
  17720. // Not in a browser? Use the first URL's scheme instead.
  17721. second.scheme = first.scheme;
  17722. }
  17723. }
  17724. // If the second URL is absolute, use it for the scheme, authority, and path.
  17725. var baseUri = first;
  17726. if (second.isAbsolute()) {
  17727. baseUri = second;
  17728. }
  17729. var url = '';
  17730. if (defined(baseUri.scheme)) {
  17731. url += baseUri.scheme + ':';
  17732. }
  17733. if (defined(baseUri.authority)) {
  17734. url += '//' + baseUri.authority;
  17735. if (baseUri.path !== '' && baseUri.path !== '/') {
  17736. url = url.replace(/\/?$/, '/');
  17737. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  17738. }
  17739. }
  17740. // Combine the paths (only if second is relative).
  17741. if (baseUri === first) {
  17742. if (appendSlash) {
  17743. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  17744. } else {
  17745. url += first.path + second.path;
  17746. }
  17747. } else {
  17748. url += second.path;
  17749. }
  17750. // Combine the queries and fragments.
  17751. var hasFirstQuery = defined(first.query);
  17752. var hasSecondQuery = defined(second.query);
  17753. if (hasFirstQuery && hasSecondQuery) {
  17754. url += '?' + first.query + '&' + second.query;
  17755. } else if (hasFirstQuery && !hasSecondQuery) {
  17756. url += '?' + first.query;
  17757. } else if (!hasFirstQuery && hasSecondQuery) {
  17758. url += '?' + second.query;
  17759. }
  17760. var hasSecondFragment = defined(second.fragment);
  17761. if (defined(first.fragment) && !hasSecondFragment) {
  17762. url += '#' + first.fragment;
  17763. } else if (hasSecondFragment) {
  17764. url += '#' + second.fragment;
  17765. }
  17766. return url;
  17767. }
  17768. return joinUrls;
  17769. });
  17770. /*global define*/
  17771. define('Core/buildModuleUrl',[
  17772. '../ThirdParty/Uri',
  17773. './defined',
  17774. './DeveloperError',
  17775. './getAbsoluteUri',
  17776. './joinUrls',
  17777. 'require'
  17778. ], function(
  17779. Uri,
  17780. defined,
  17781. DeveloperError,
  17782. getAbsoluteUri,
  17783. joinUrls,
  17784. require) {
  17785. 'use strict';
  17786. /*global CESIUM_BASE_URL*/
  17787. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  17788. function getBaseUrlFromCesiumScript() {
  17789. var scripts = document.getElementsByTagName('script');
  17790. for ( var i = 0, len = scripts.length; i < len; ++i) {
  17791. var src = scripts[i].getAttribute('src');
  17792. var result = cesiumScriptRegex.exec(src);
  17793. if (result !== null) {
  17794. return result[1];
  17795. }
  17796. }
  17797. return undefined;
  17798. }
  17799. var baseUrl;
  17800. function getCesiumBaseUrl() {
  17801. if (defined(baseUrl)) {
  17802. return baseUrl;
  17803. }
  17804. var baseUrlString;
  17805. if (typeof CESIUM_BASE_URL !== 'undefined') {
  17806. baseUrlString = CESIUM_BASE_URL;
  17807. } else {
  17808. baseUrlString = getBaseUrlFromCesiumScript();
  17809. }
  17810. if (!defined(baseUrlString)) {
  17811. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  17812. }
  17813. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  17814. return baseUrl;
  17815. }
  17816. function buildModuleUrlFromRequireToUrl(moduleID) {
  17817. //moduleID will be non-relative, so require it relative to this module, in Core.
  17818. return require.toUrl('../' + moduleID);
  17819. }
  17820. function buildModuleUrlFromBaseUrl(moduleID) {
  17821. return joinUrls(getCesiumBaseUrl(), moduleID);
  17822. }
  17823. var implementation;
  17824. var a;
  17825. /**
  17826. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  17827. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  17828. * the base URL of the Cesium.js script.
  17829. *
  17830. * @private
  17831. */
  17832. function buildModuleUrl(moduleID) {
  17833. if (!defined(implementation)) {
  17834. //select implementation
  17835. if (defined(require.toUrl)) {
  17836. implementation = buildModuleUrlFromRequireToUrl;
  17837. } else {
  17838. implementation = buildModuleUrlFromBaseUrl;
  17839. }
  17840. }
  17841. if (!defined(a)) {
  17842. a = document.createElement('a');
  17843. }
  17844. var url = implementation(moduleID);
  17845. a.href = url;
  17846. a.href = a.href; // IE only absolutizes href on get, not set
  17847. return a.href;
  17848. }
  17849. // exposed for testing
  17850. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  17851. /**
  17852. * Sets the base URL for resolving modules.
  17853. * @param {String} value The new base URL.
  17854. */
  17855. buildModuleUrl.setBaseUrl = function(value) {
  17856. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  17857. };
  17858. return buildModuleUrl;
  17859. });
  17860. /*global define*/
  17861. define('Core/Iau2006XysSample',[],function() {
  17862. 'use strict';
  17863. /**
  17864. * An IAU 2006 XYS value sampled at a particular time.
  17865. *
  17866. * @alias Iau2006XysSample
  17867. * @constructor
  17868. *
  17869. * @param {Number} x The X value.
  17870. * @param {Number} y The Y value.
  17871. * @param {Number} s The S value.
  17872. *
  17873. * @private
  17874. */
  17875. function Iau2006XysSample(x, y, s) {
  17876. /**
  17877. * The X value.
  17878. * @type {Number}
  17879. */
  17880. this.x = x;
  17881. /**
  17882. * The Y value.
  17883. * @type {Number}
  17884. */
  17885. this.y = y;
  17886. /**
  17887. * The S value.
  17888. * @type {Number}
  17889. */
  17890. this.s = s;
  17891. }
  17892. return Iau2006XysSample;
  17893. });
  17894. /*global define*/
  17895. define('Core/Iau2006XysData',[
  17896. '../ThirdParty/when',
  17897. './buildModuleUrl',
  17898. './defaultValue',
  17899. './defined',
  17900. './Iau2006XysSample',
  17901. './JulianDate',
  17902. './loadJson',
  17903. './TimeStandard'
  17904. ], function(
  17905. when,
  17906. buildModuleUrl,
  17907. defaultValue,
  17908. defined,
  17909. Iau2006XysSample,
  17910. JulianDate,
  17911. loadJson,
  17912. TimeStandard) {
  17913. 'use strict';
  17914. /**
  17915. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  17916. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  17917. *
  17918. * @alias Iau2006XysData
  17919. * @constructor
  17920. *
  17921. * @param {Object} [options] Object with the following properties:
  17922. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  17923. * `{0}` will be replaced with the file index.
  17924. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  17925. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  17926. * first XYS sample.
  17927. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  17928. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  17929. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  17930. *
  17931. * @private
  17932. */
  17933. function Iau2006XysData(options) {
  17934. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  17935. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  17936. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  17937. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  17938. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  17939. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  17940. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  17941. this._totalSamples = defaultValue(options.totalSamples, 27426);
  17942. this._samples = new Array(this._totalSamples * 3);
  17943. this._chunkDownloadsInProgress = [];
  17944. var order = this._interpolationOrder;
  17945. // Compute denominators and X values for interpolation.
  17946. var denom = this._denominators = new Array(order + 1);
  17947. var xTable = this._xTable = new Array(order + 1);
  17948. var stepN = Math.pow(this._stepSizeDays, order);
  17949. for ( var i = 0; i <= order; ++i) {
  17950. denom[i] = stepN;
  17951. xTable[i] = i * this._stepSizeDays;
  17952. for ( var j = 0; j <= order; ++j) {
  17953. if (j !== i) {
  17954. denom[i] *= (i - j);
  17955. }
  17956. }
  17957. denom[i] = 1.0 / denom[i];
  17958. }
  17959. // Allocate scratch arrays for interpolation.
  17960. this._work = new Array(order + 1);
  17961. this._coef = new Array(order + 1);
  17962. }
  17963. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  17964. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  17965. var dateTT = julianDateScratch;
  17966. dateTT.dayNumber = dayTT;
  17967. dateTT.secondsOfDay = secondTT;
  17968. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  17969. }
  17970. /**
  17971. * Preloads XYS data for a specified date range.
  17972. *
  17973. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  17974. * the Terrestrial Time (TT) time standard.
  17975. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  17976. * the Terrestrial Time (TT) time standard.
  17977. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  17978. * the Terrestrial Time (TT) time standard.
  17979. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  17980. * the Terrestrial Time (TT) time standard.
  17981. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  17982. * preloaded.
  17983. */
  17984. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  17985. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  17986. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  17987. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  17988. if (startIndex < 0) {
  17989. startIndex = 0;
  17990. }
  17991. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  17992. if (stopIndex >= this._totalSamples) {
  17993. stopIndex = this._totalSamples - 1;
  17994. }
  17995. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  17996. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  17997. var promises = [];
  17998. for ( var i = startChunk; i <= stopChunk; ++i) {
  17999. promises.push(requestXysChunk(this, i));
  18000. }
  18001. return when.all(promises);
  18002. };
  18003. /**
  18004. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  18005. * this method will return undefined.
  18006. *
  18007. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  18008. * the Terrestrial Time (TT) time standard.
  18009. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  18010. * the Terrestrial Time (TT) time standard.
  18011. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  18012. * is undefined, a new instance is allocated and returned.
  18013. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  18014. * computation has not yet been downloaded.
  18015. *
  18016. * @see Iau2006XysData#preload
  18017. */
  18018. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  18019. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  18020. if (daysSinceEpoch < 0.0) {
  18021. // Can't evaluate prior to the epoch of the data.
  18022. return undefined;
  18023. }
  18024. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  18025. if (centerIndex >= this._totalSamples) {
  18026. // Can't evaluate after the last sample in the data.
  18027. return undefined;
  18028. }
  18029. var degree = this._interpolationOrder;
  18030. var firstIndex = centerIndex - ((degree / 2) | 0);
  18031. if (firstIndex < 0) {
  18032. firstIndex = 0;
  18033. }
  18034. var lastIndex = firstIndex + degree;
  18035. if (lastIndex >= this._totalSamples) {
  18036. lastIndex = this._totalSamples - 1;
  18037. firstIndex = lastIndex - degree;
  18038. if (firstIndex < 0) {
  18039. firstIndex = 0;
  18040. }
  18041. }
  18042. // Are all the samples we need present?
  18043. // We can assume so if the first and last are present
  18044. var isDataMissing = false;
  18045. var samples = this._samples;
  18046. if (!defined(samples[firstIndex * 3])) {
  18047. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  18048. isDataMissing = true;
  18049. }
  18050. if (!defined(samples[lastIndex * 3])) {
  18051. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  18052. isDataMissing = true;
  18053. }
  18054. if (isDataMissing) {
  18055. return undefined;
  18056. }
  18057. if (!defined(result)) {
  18058. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  18059. } else {
  18060. result.x = 0.0;
  18061. result.y = 0.0;
  18062. result.s = 0.0;
  18063. }
  18064. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  18065. var work = this._work;
  18066. var denom = this._denominators;
  18067. var coef = this._coef;
  18068. var xTable = this._xTable;
  18069. var i, j;
  18070. for (i = 0; i <= degree; ++i) {
  18071. work[i] = x - xTable[i];
  18072. }
  18073. for (i = 0; i <= degree; ++i) {
  18074. coef[i] = 1.0;
  18075. for (j = 0; j <= degree; ++j) {
  18076. if (j !== i) {
  18077. coef[i] *= work[j];
  18078. }
  18079. }
  18080. coef[i] *= denom[i];
  18081. var sampleIndex = (firstIndex + i) * 3;
  18082. result.x += coef[i] * samples[sampleIndex++];
  18083. result.y += coef[i] * samples[sampleIndex++];
  18084. result.s += coef[i] * samples[sampleIndex];
  18085. }
  18086. return result;
  18087. };
  18088. function requestXysChunk(xysData, chunkIndex) {
  18089. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  18090. // Chunk has already been requested.
  18091. return xysData._chunkDownloadsInProgress[chunkIndex];
  18092. }
  18093. var deferred = when.defer();
  18094. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  18095. var chunkUrl;
  18096. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  18097. if (defined(xysFileUrlTemplate)) {
  18098. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  18099. } else {
  18100. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  18101. }
  18102. when(loadJson(chunkUrl), function(chunk) {
  18103. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  18104. var samples = xysData._samples;
  18105. var newSamples = chunk.samples;
  18106. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  18107. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  18108. samples[startIndex + i] = newSamples[i];
  18109. }
  18110. deferred.resolve();
  18111. });
  18112. return deferred.promise;
  18113. }
  18114. return Iau2006XysData;
  18115. });
  18116. /*global define*/
  18117. define('Core/Quaternion',[
  18118. './Cartesian3',
  18119. './defaultValue',
  18120. './defined',
  18121. './DeveloperError',
  18122. './FeatureDetection',
  18123. './freezeObject',
  18124. './Math',
  18125. './Matrix3'
  18126. ], function(
  18127. Cartesian3,
  18128. defaultValue,
  18129. defined,
  18130. DeveloperError,
  18131. FeatureDetection,
  18132. freezeObject,
  18133. CesiumMath,
  18134. Matrix3) {
  18135. 'use strict';
  18136. /**
  18137. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  18138. * @alias Quaternion
  18139. * @constructor
  18140. *
  18141. * @param {Number} [x=0.0] The X component.
  18142. * @param {Number} [y=0.0] The Y component.
  18143. * @param {Number} [z=0.0] The Z component.
  18144. * @param {Number} [w=0.0] The W component.
  18145. *
  18146. * @see PackableForInterpolation
  18147. */
  18148. function Quaternion(x, y, z, w) {
  18149. /**
  18150. * The X component.
  18151. * @type {Number}
  18152. * @default 0.0
  18153. */
  18154. this.x = defaultValue(x, 0.0);
  18155. /**
  18156. * The Y component.
  18157. * @type {Number}
  18158. * @default 0.0
  18159. */
  18160. this.y = defaultValue(y, 0.0);
  18161. /**
  18162. * The Z component.
  18163. * @type {Number}
  18164. * @default 0.0
  18165. */
  18166. this.z = defaultValue(z, 0.0);
  18167. /**
  18168. * The W component.
  18169. * @type {Number}
  18170. * @default 0.0
  18171. */
  18172. this.w = defaultValue(w, 0.0);
  18173. }
  18174. var fromAxisAngleScratch = new Cartesian3();
  18175. /**
  18176. * Computes a quaternion representing a rotation around an axis.
  18177. *
  18178. * @param {Cartesian3} axis The axis of rotation.
  18179. * @param {Number} angle The angle in radians to rotate around the axis.
  18180. * @param {Quaternion} [result] The object onto which to store the result.
  18181. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18182. */
  18183. Quaternion.fromAxisAngle = function(axis, angle, result) {
  18184. if (!defined(axis)) {
  18185. throw new DeveloperError('axis is required.');
  18186. }
  18187. if (typeof angle !== 'number') {
  18188. throw new DeveloperError('angle is required and must be a number.');
  18189. }
  18190. var halfAngle = angle / 2.0;
  18191. var s = Math.sin(halfAngle);
  18192. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  18193. var x = fromAxisAngleScratch.x * s;
  18194. var y = fromAxisAngleScratch.y * s;
  18195. var z = fromAxisAngleScratch.z * s;
  18196. var w = Math.cos(halfAngle);
  18197. if (!defined(result)) {
  18198. return new Quaternion(x, y, z, w);
  18199. }
  18200. result.x = x;
  18201. result.y = y;
  18202. result.z = z;
  18203. result.w = w;
  18204. return result;
  18205. };
  18206. var fromRotationMatrixNext = [1, 2, 0];
  18207. var fromRotationMatrixQuat = new Array(3);
  18208. /**
  18209. * Computes a Quaternion from the provided Matrix3 instance.
  18210. *
  18211. * @param {Matrix3} matrix The rotation matrix.
  18212. * @param {Quaternion} [result] The object onto which to store the result.
  18213. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18214. *
  18215. * @see Matrix3.fromQuaternion
  18216. */
  18217. Quaternion.fromRotationMatrix = function(matrix, result) {
  18218. if (!defined(matrix)) {
  18219. throw new DeveloperError('matrix is required.');
  18220. }
  18221. var root;
  18222. var x;
  18223. var y;
  18224. var z;
  18225. var w;
  18226. var m00 = matrix[Matrix3.COLUMN0ROW0];
  18227. var m11 = matrix[Matrix3.COLUMN1ROW1];
  18228. var m22 = matrix[Matrix3.COLUMN2ROW2];
  18229. var trace = m00 + m11 + m22;
  18230. if (trace > 0.0) {
  18231. // |w| > 1/2, may as well choose w > 1/2
  18232. root = Math.sqrt(trace + 1.0); // 2w
  18233. w = 0.5 * root;
  18234. root = 0.5 / root; // 1/(4w)
  18235. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  18236. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  18237. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  18238. } else {
  18239. // |w| <= 1/2
  18240. var next = fromRotationMatrixNext;
  18241. var i = 0;
  18242. if (m11 > m00) {
  18243. i = 1;
  18244. }
  18245. if (m22 > m00 && m22 > m11) {
  18246. i = 2;
  18247. }
  18248. var j = next[i];
  18249. var k = next[j];
  18250. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  18251. var quat = fromRotationMatrixQuat;
  18252. quat[i] = 0.5 * root;
  18253. root = 0.5 / root;
  18254. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  18255. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  18256. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  18257. x = -quat[0];
  18258. y = -quat[1];
  18259. z = -quat[2];
  18260. }
  18261. if (!defined(result)) {
  18262. return new Quaternion(x, y, z, w);
  18263. }
  18264. result.x = x;
  18265. result.y = y;
  18266. result.z = z;
  18267. result.w = w;
  18268. return result;
  18269. };
  18270. var scratchHPRQuaternion = new Quaternion();
  18271. /**
  18272. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  18273. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  18274. * the positive x axis.
  18275. *
  18276. * @param {Number} heading The heading angle in radians.
  18277. * @param {Number} pitch The pitch angle in radians.
  18278. * @param {Number} roll The roll angle in radians.
  18279. * @param {Quaternion} [result] The object onto which to store the result.
  18280. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  18281. */
  18282. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  18283. if (!defined(heading)) {
  18284. throw new DeveloperError('heading is required.');
  18285. }
  18286. if (!defined(pitch)) {
  18287. throw new DeveloperError('pitch is required.');
  18288. }
  18289. if (!defined(roll)) {
  18290. throw new DeveloperError('roll is required.');
  18291. }
  18292. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  18293. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  18294. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  18295. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  18296. return Quaternion.multiply(headingQuaternion, result, result);
  18297. };
  18298. var sampledQuaternionAxis = new Cartesian3();
  18299. var sampledQuaternionRotation = new Cartesian3();
  18300. var sampledQuaternionTempQuaternion = new Quaternion();
  18301. var sampledQuaternionQuaternion0 = new Quaternion();
  18302. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  18303. /**
  18304. * The number of elements used to pack the object into an array.
  18305. * @type {Number}
  18306. */
  18307. Quaternion.packedLength = 4;
  18308. /**
  18309. * Stores the provided instance into the provided array.
  18310. *
  18311. * @param {Quaternion} value The value to pack.
  18312. * @param {Number[]} array The array to pack into.
  18313. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  18314. *
  18315. * @returns {Number[]} The array that was packed into
  18316. */
  18317. Quaternion.pack = function(value, array, startingIndex) {
  18318. if (!defined(value)) {
  18319. throw new DeveloperError('value is required');
  18320. }
  18321. if (!defined(array)) {
  18322. throw new DeveloperError('array is required');
  18323. }
  18324. startingIndex = defaultValue(startingIndex, 0);
  18325. array[startingIndex++] = value.x;
  18326. array[startingIndex++] = value.y;
  18327. array[startingIndex++] = value.z;
  18328. array[startingIndex] = value.w;
  18329. return array;
  18330. };
  18331. /**
  18332. * Retrieves an instance from a packed array.
  18333. *
  18334. * @param {Number[]} array The packed array.
  18335. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  18336. * @param {Quaternion} [result] The object into which to store the result.
  18337. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18338. */
  18339. Quaternion.unpack = function(array, startingIndex, result) {
  18340. if (!defined(array)) {
  18341. throw new DeveloperError('array is required');
  18342. }
  18343. startingIndex = defaultValue(startingIndex, 0);
  18344. if (!defined(result)) {
  18345. result = new Quaternion();
  18346. }
  18347. result.x = array[startingIndex];
  18348. result.y = array[startingIndex + 1];
  18349. result.z = array[startingIndex + 2];
  18350. result.w = array[startingIndex + 3];
  18351. return result;
  18352. };
  18353. /**
  18354. * The number of elements used to store the object into an array in its interpolatable form.
  18355. * @type {Number}
  18356. */
  18357. Quaternion.packedInterpolationLength = 3;
  18358. /**
  18359. * Converts a packed array into a form suitable for interpolation.
  18360. *
  18361. * @param {Number[]} packedArray The packed array.
  18362. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  18363. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  18364. * @param {Number[]} result The object into which to store the result.
  18365. */
  18366. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  18367. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  18368. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  18369. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  18370. var offset = i * 3;
  18371. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  18372. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  18373. if (sampledQuaternionTempQuaternion.w < 0) {
  18374. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  18375. }
  18376. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  18377. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  18378. result[offset] = sampledQuaternionAxis.x * angle;
  18379. result[offset + 1] = sampledQuaternionAxis.y * angle;
  18380. result[offset + 2] = sampledQuaternionAxis.z * angle;
  18381. }
  18382. };
  18383. /**
  18384. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  18385. *
  18386. * @param {Number[]} array The array previously packed for interpolation.
  18387. * @param {Number[]} sourceArray The original packed array.
  18388. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  18389. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  18390. * @param {Quaternion} [result] The object into which to store the result.
  18391. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18392. */
  18393. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  18394. if (!defined(result)) {
  18395. result = new Quaternion();
  18396. }
  18397. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  18398. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  18399. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  18400. if (magnitude === 0) {
  18401. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  18402. } else {
  18403. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  18404. }
  18405. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  18406. };
  18407. /**
  18408. * Duplicates a Quaternion instance.
  18409. *
  18410. * @param {Quaternion} quaternion The quaternion to duplicate.
  18411. * @param {Quaternion} [result] The object onto which to store the result.
  18412. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  18413. */
  18414. Quaternion.clone = function(quaternion, result) {
  18415. if (!defined(quaternion)) {
  18416. return undefined;
  18417. }
  18418. if (!defined(result)) {
  18419. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  18420. }
  18421. result.x = quaternion.x;
  18422. result.y = quaternion.y;
  18423. result.z = quaternion.z;
  18424. result.w = quaternion.w;
  18425. return result;
  18426. };
  18427. /**
  18428. * Computes the conjugate of the provided quaternion.
  18429. *
  18430. * @param {Quaternion} quaternion The quaternion to conjugate.
  18431. * @param {Quaternion} result The object onto which to store the result.
  18432. * @returns {Quaternion} The modified result parameter.
  18433. */
  18434. Quaternion.conjugate = function(quaternion, result) {
  18435. if (!defined(quaternion)) {
  18436. throw new DeveloperError('quaternion is required');
  18437. }
  18438. if (!defined(result)) {
  18439. throw new DeveloperError('result is required');
  18440. }
  18441. result.x = -quaternion.x;
  18442. result.y = -quaternion.y;
  18443. result.z = -quaternion.z;
  18444. result.w = quaternion.w;
  18445. return result;
  18446. };
  18447. /**
  18448. * Computes magnitude squared for the provided quaternion.
  18449. *
  18450. * @param {Quaternion} quaternion The quaternion to conjugate.
  18451. * @returns {Number} The magnitude squared.
  18452. */
  18453. Quaternion.magnitudeSquared = function(quaternion) {
  18454. if (!defined(quaternion)) {
  18455. throw new DeveloperError('quaternion is required');
  18456. }
  18457. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  18458. };
  18459. /**
  18460. * Computes magnitude for the provided quaternion.
  18461. *
  18462. * @param {Quaternion} quaternion The quaternion to conjugate.
  18463. * @returns {Number} The magnitude.
  18464. */
  18465. Quaternion.magnitude = function(quaternion) {
  18466. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  18467. };
  18468. /**
  18469. * Computes the normalized form of the provided quaternion.
  18470. *
  18471. * @param {Quaternion} quaternion The quaternion to normalize.
  18472. * @param {Quaternion} result The object onto which to store the result.
  18473. * @returns {Quaternion} The modified result parameter.
  18474. */
  18475. Quaternion.normalize = function(quaternion, result) {
  18476. if (!defined(result)) {
  18477. throw new DeveloperError('result is required');
  18478. }
  18479. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  18480. var x = quaternion.x * inverseMagnitude;
  18481. var y = quaternion.y * inverseMagnitude;
  18482. var z = quaternion.z * inverseMagnitude;
  18483. var w = quaternion.w * inverseMagnitude;
  18484. result.x = x;
  18485. result.y = y;
  18486. result.z = z;
  18487. result.w = w;
  18488. return result;
  18489. };
  18490. /**
  18491. * Computes the inverse of the provided quaternion.
  18492. *
  18493. * @param {Quaternion} quaternion The quaternion to normalize.
  18494. * @param {Quaternion} result The object onto which to store the result.
  18495. * @returns {Quaternion} The modified result parameter.
  18496. */
  18497. Quaternion.inverse = function(quaternion, result) {
  18498. if (!defined(result)) {
  18499. throw new DeveloperError('result is required');
  18500. }
  18501. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  18502. result = Quaternion.conjugate(quaternion, result);
  18503. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  18504. };
  18505. /**
  18506. * Computes the componentwise sum of two quaternions.
  18507. *
  18508. * @param {Quaternion} left The first quaternion.
  18509. * @param {Quaternion} right The second quaternion.
  18510. * @param {Quaternion} result The object onto which to store the result.
  18511. * @returns {Quaternion} The modified result parameter.
  18512. */
  18513. Quaternion.add = function(left, right, result) {
  18514. if (!defined(left)) {
  18515. throw new DeveloperError('left is required');
  18516. }
  18517. if (!defined(right)) {
  18518. throw new DeveloperError('right is required');
  18519. }
  18520. if (!defined(result)) {
  18521. throw new DeveloperError('result is required');
  18522. }
  18523. result.x = left.x + right.x;
  18524. result.y = left.y + right.y;
  18525. result.z = left.z + right.z;
  18526. result.w = left.w + right.w;
  18527. return result;
  18528. };
  18529. /**
  18530. * Computes the componentwise difference of two quaternions.
  18531. *
  18532. * @param {Quaternion} left The first quaternion.
  18533. * @param {Quaternion} right The second quaternion.
  18534. * @param {Quaternion} result The object onto which to store the result.
  18535. * @returns {Quaternion} The modified result parameter.
  18536. */
  18537. Quaternion.subtract = function(left, right, result) {
  18538. if (!defined(left)) {
  18539. throw new DeveloperError('left is required');
  18540. }
  18541. if (!defined(right)) {
  18542. throw new DeveloperError('right is required');
  18543. }
  18544. if (!defined(result)) {
  18545. throw new DeveloperError('result is required');
  18546. }
  18547. result.x = left.x - right.x;
  18548. result.y = left.y - right.y;
  18549. result.z = left.z - right.z;
  18550. result.w = left.w - right.w;
  18551. return result;
  18552. };
  18553. /**
  18554. * Negates the provided quaternion.
  18555. *
  18556. * @param {Quaternion} quaternion The quaternion to be negated.
  18557. * @param {Quaternion} result The object onto which to store the result.
  18558. * @returns {Quaternion} The modified result parameter.
  18559. */
  18560. Quaternion.negate = function(quaternion, result) {
  18561. if (!defined(quaternion)) {
  18562. throw new DeveloperError('quaternion is required');
  18563. }
  18564. if (!defined(result)) {
  18565. throw new DeveloperError('result is required');
  18566. }
  18567. result.x = -quaternion.x;
  18568. result.y = -quaternion.y;
  18569. result.z = -quaternion.z;
  18570. result.w = -quaternion.w;
  18571. return result;
  18572. };
  18573. /**
  18574. * Computes the dot (scalar) product of two quaternions.
  18575. *
  18576. * @param {Quaternion} left The first quaternion.
  18577. * @param {Quaternion} right The second quaternion.
  18578. * @returns {Number} The dot product.
  18579. */
  18580. Quaternion.dot = function(left, right) {
  18581. if (!defined(left)) {
  18582. throw new DeveloperError('left is required');
  18583. }
  18584. if (!defined(right)) {
  18585. throw new DeveloperError('right is required');
  18586. }
  18587. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  18588. };
  18589. /**
  18590. * Computes the product of two quaternions.
  18591. *
  18592. * @param {Quaternion} left The first quaternion.
  18593. * @param {Quaternion} right The second quaternion.
  18594. * @param {Quaternion} result The object onto which to store the result.
  18595. * @returns {Quaternion} The modified result parameter.
  18596. */
  18597. Quaternion.multiply = function(left, right, result) {
  18598. if (!defined(left)) {
  18599. throw new DeveloperError('left is required');
  18600. }
  18601. if (!defined(right)) {
  18602. throw new DeveloperError('right is required');
  18603. }
  18604. if (!defined(result)) {
  18605. throw new DeveloperError('result is required');
  18606. }
  18607. var leftX = left.x;
  18608. var leftY = left.y;
  18609. var leftZ = left.z;
  18610. var leftW = left.w;
  18611. var rightX = right.x;
  18612. var rightY = right.y;
  18613. var rightZ = right.z;
  18614. var rightW = right.w;
  18615. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  18616. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  18617. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  18618. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  18619. result.x = x;
  18620. result.y = y;
  18621. result.z = z;
  18622. result.w = w;
  18623. return result;
  18624. };
  18625. /**
  18626. * Multiplies the provided quaternion componentwise by the provided scalar.
  18627. *
  18628. * @param {Quaternion} quaternion The quaternion to be scaled.
  18629. * @param {Number} scalar The scalar to multiply with.
  18630. * @param {Quaternion} result The object onto which to store the result.
  18631. * @returns {Quaternion} The modified result parameter.
  18632. */
  18633. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  18634. if (!defined(quaternion)) {
  18635. throw new DeveloperError('quaternion is required');
  18636. }
  18637. if (typeof scalar !== 'number') {
  18638. throw new DeveloperError('scalar is required and must be a number.');
  18639. }
  18640. if (!defined(result)) {
  18641. throw new DeveloperError('result is required');
  18642. }
  18643. result.x = quaternion.x * scalar;
  18644. result.y = quaternion.y * scalar;
  18645. result.z = quaternion.z * scalar;
  18646. result.w = quaternion.w * scalar;
  18647. return result;
  18648. };
  18649. /**
  18650. * Divides the provided quaternion componentwise by the provided scalar.
  18651. *
  18652. * @param {Quaternion} quaternion The quaternion to be divided.
  18653. * @param {Number} scalar The scalar to divide by.
  18654. * @param {Quaternion} result The object onto which to store the result.
  18655. * @returns {Quaternion} The modified result parameter.
  18656. */
  18657. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  18658. if (!defined(quaternion)) {
  18659. throw new DeveloperError('quaternion is required');
  18660. }
  18661. if (typeof scalar !== 'number') {
  18662. throw new DeveloperError('scalar is required and must be a number.');
  18663. }
  18664. if (!defined(result)) {
  18665. throw new DeveloperError('result is required');
  18666. }
  18667. result.x = quaternion.x / scalar;
  18668. result.y = quaternion.y / scalar;
  18669. result.z = quaternion.z / scalar;
  18670. result.w = quaternion.w / scalar;
  18671. return result;
  18672. };
  18673. /**
  18674. * Computes the axis of rotation of the provided quaternion.
  18675. *
  18676. * @param {Quaternion} quaternion The quaternion to use.
  18677. * @param {Cartesian3} result The object onto which to store the result.
  18678. * @returns {Cartesian3} The modified result parameter.
  18679. */
  18680. Quaternion.computeAxis = function(quaternion, result) {
  18681. if (!defined(quaternion)) {
  18682. throw new DeveloperError('quaternion is required');
  18683. }
  18684. if (!defined(result)) {
  18685. throw new DeveloperError('result is required');
  18686. }
  18687. var w = quaternion.w;
  18688. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  18689. result.x = result.y = result.z = 0;
  18690. return result;
  18691. }
  18692. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  18693. result.x = quaternion.x * scalar;
  18694. result.y = quaternion.y * scalar;
  18695. result.z = quaternion.z * scalar;
  18696. return result;
  18697. };
  18698. /**
  18699. * Computes the angle of rotation of the provided quaternion.
  18700. *
  18701. * @param {Quaternion} quaternion The quaternion to use.
  18702. * @returns {Number} The angle of rotation.
  18703. */
  18704. Quaternion.computeAngle = function(quaternion) {
  18705. if (!defined(quaternion)) {
  18706. throw new DeveloperError('quaternion is required');
  18707. }
  18708. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  18709. return 0.0;
  18710. }
  18711. return 2.0 * Math.acos(quaternion.w);
  18712. };
  18713. var lerpScratch = new Quaternion();
  18714. /**
  18715. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  18716. *
  18717. * @param {Quaternion} start The value corresponding to t at 0.0.
  18718. * @param {Quaternion} end The value corresponding to t at 1.0.
  18719. * @param {Number} t The point along t at which to interpolate.
  18720. * @param {Quaternion} result The object onto which to store the result.
  18721. * @returns {Quaternion} The modified result parameter.
  18722. */
  18723. Quaternion.lerp = function(start, end, t, result) {
  18724. if (!defined(start)) {
  18725. throw new DeveloperError('start is required.');
  18726. }
  18727. if (!defined(end)) {
  18728. throw new DeveloperError('end is required.');
  18729. }
  18730. if (typeof t !== 'number') {
  18731. throw new DeveloperError('t is required and must be a number.');
  18732. }
  18733. if (!defined(result)) {
  18734. throw new DeveloperError('result is required');
  18735. }
  18736. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  18737. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  18738. return Quaternion.add(lerpScratch, result, result);
  18739. };
  18740. var slerpEndNegated = new Quaternion();
  18741. var slerpScaledP = new Quaternion();
  18742. var slerpScaledR = new Quaternion();
  18743. /**
  18744. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  18745. *
  18746. * @param {Quaternion} start The value corresponding to t at 0.0.
  18747. * @param {Quaternion} end The value corresponding to t at 1.0.
  18748. * @param {Number} t The point along t at which to interpolate.
  18749. * @param {Quaternion} result The object onto which to store the result.
  18750. * @returns {Quaternion} The modified result parameter.
  18751. *
  18752. * @see Quaternion#fastSlerp
  18753. */
  18754. Quaternion.slerp = function(start, end, t, result) {
  18755. if (!defined(start)) {
  18756. throw new DeveloperError('start is required.');
  18757. }
  18758. if (!defined(end)) {
  18759. throw new DeveloperError('end is required.');
  18760. }
  18761. if (typeof t !== 'number') {
  18762. throw new DeveloperError('t is required and must be a number.');
  18763. }
  18764. if (!defined(result)) {
  18765. throw new DeveloperError('result is required');
  18766. }
  18767. var dot = Quaternion.dot(start, end);
  18768. // The angle between start must be acute. Since q and -q represent
  18769. // the same rotation, negate q to get the acute angle.
  18770. var r = end;
  18771. if (dot < 0.0) {
  18772. dot = -dot;
  18773. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  18774. }
  18775. // dot > 0, as the dot product approaches 1, the angle between the
  18776. // quaternions vanishes. use linear interpolation.
  18777. if (1.0 - dot < CesiumMath.EPSILON6) {
  18778. return Quaternion.lerp(start, r, t, result);
  18779. }
  18780. var theta = Math.acos(dot);
  18781. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  18782. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  18783. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  18784. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  18785. };
  18786. /**
  18787. * The logarithmic quaternion function.
  18788. *
  18789. * @param {Quaternion} quaternion The unit quaternion.
  18790. * @param {Cartesian3} result The object onto which to store the result.
  18791. * @returns {Cartesian3} The modified result parameter.
  18792. */
  18793. Quaternion.log = function(quaternion, result) {
  18794. if (!defined(quaternion)) {
  18795. throw new DeveloperError('quaternion is required.');
  18796. }
  18797. if (!defined(result)) {
  18798. throw new DeveloperError('result is required');
  18799. }
  18800. var theta = CesiumMath.acosClamped(quaternion.w);
  18801. var thetaOverSinTheta = 0.0;
  18802. if (theta !== 0.0) {
  18803. thetaOverSinTheta = theta / Math.sin(theta);
  18804. }
  18805. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  18806. };
  18807. /**
  18808. * The exponential quaternion function.
  18809. *
  18810. * @param {Cartesian3} cartesian The cartesian.
  18811. * @param {Quaternion} result The object onto which to store the result.
  18812. * @returns {Quaternion} The modified result parameter.
  18813. */
  18814. Quaternion.exp = function(cartesian, result) {
  18815. if (!defined(cartesian)) {
  18816. throw new DeveloperError('cartesian is required.');
  18817. }
  18818. if (!defined(result)) {
  18819. throw new DeveloperError('result is required');
  18820. }
  18821. var theta = Cartesian3.magnitude(cartesian);
  18822. var sinThetaOverTheta = 0.0;
  18823. if (theta !== 0.0) {
  18824. sinThetaOverTheta = Math.sin(theta) / theta;
  18825. }
  18826. result.x = cartesian.x * sinThetaOverTheta;
  18827. result.y = cartesian.y * sinThetaOverTheta;
  18828. result.z = cartesian.z * sinThetaOverTheta;
  18829. result.w = Math.cos(theta);
  18830. return result;
  18831. };
  18832. var squadScratchCartesian0 = new Cartesian3();
  18833. var squadScratchCartesian1 = new Cartesian3();
  18834. var squadScratchQuaternion0 = new Quaternion();
  18835. var squadScratchQuaternion1 = new Quaternion();
  18836. /**
  18837. * Computes an inner quadrangle point.
  18838. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  18839. *
  18840. * @param {Quaternion} q0 The first quaternion.
  18841. * @param {Quaternion} q1 The second quaternion.
  18842. * @param {Quaternion} q2 The third quaternion.
  18843. * @param {Quaternion} result The object onto which to store the result.
  18844. * @returns {Quaternion} The modified result parameter.
  18845. *
  18846. * @see Quaternion#squad
  18847. */
  18848. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  18849. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  18850. throw new DeveloperError('q0, q1, and q2 are required.');
  18851. }
  18852. if (!defined(result)) {
  18853. throw new DeveloperError('result is required');
  18854. }
  18855. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  18856. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  18857. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  18858. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  18859. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  18860. Cartesian3.add(cart0, cart1, cart0);
  18861. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  18862. Cartesian3.negate(cart0, cart0);
  18863. Quaternion.exp(cart0, squadScratchQuaternion0);
  18864. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  18865. };
  18866. /**
  18867. * Computes the spherical quadrangle interpolation between quaternions.
  18868. *
  18869. * @param {Quaternion} q0 The first quaternion.
  18870. * @param {Quaternion} q1 The second quaternion.
  18871. * @param {Quaternion} s0 The first inner quadrangle.
  18872. * @param {Quaternion} s1 The second inner quadrangle.
  18873. * @param {Number} t The time in [0,1] used to interpolate.
  18874. * @param {Quaternion} result The object onto which to store the result.
  18875. * @returns {Quaternion} The modified result parameter.
  18876. *
  18877. *
  18878. * @example
  18879. * // 1. compute the squad interpolation between two quaternions on a curve
  18880. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  18881. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  18882. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  18883. *
  18884. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  18885. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  18886. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  18887. *
  18888. * @see Quaternion#computeInnerQuadrangle
  18889. */
  18890. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  18891. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18892. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18893. }
  18894. if (typeof t !== 'number') {
  18895. throw new DeveloperError('t is required and must be a number.');
  18896. }
  18897. if (!defined(result)) {
  18898. throw new DeveloperError('result is required');
  18899. }
  18900. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  18901. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  18902. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18903. };
  18904. var fastSlerpScratchQuaternion = new Quaternion();
  18905. var opmu = 1.90110745351730037;
  18906. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18907. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18908. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18909. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18910. for (var i = 0; i < 7; ++i) {
  18911. var s = i + 1.0;
  18912. var t = 2.0 * s + 1.0;
  18913. u[i] = 1.0 / (s * t);
  18914. v[i] = s / t;
  18915. }
  18916. u[7] = opmu / (8.0 * 17.0);
  18917. v[7] = opmu * 8.0 / 17.0;
  18918. /**
  18919. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  18920. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  18921. *
  18922. * @param {Quaternion} start The value corresponding to t at 0.0.
  18923. * @param {Quaternion} end The value corresponding to t at 1.0.
  18924. * @param {Number} t The point along t at which to interpolate.
  18925. * @param {Quaternion} result The object onto which to store the result.
  18926. * @returns {Quaternion} The modified result parameter.
  18927. *
  18928. * @see Quaternion#slerp
  18929. */
  18930. Quaternion.fastSlerp = function(start, end, t, result) {
  18931. if (!defined(start)) {
  18932. throw new DeveloperError('start is required.');
  18933. }
  18934. if (!defined(end)) {
  18935. throw new DeveloperError('end is required.');
  18936. }
  18937. if (typeof t !== 'number') {
  18938. throw new DeveloperError('t is required and must be a number.');
  18939. }
  18940. if (!defined(result)) {
  18941. throw new DeveloperError('result is required');
  18942. }
  18943. var x = Quaternion.dot(start, end);
  18944. var sign;
  18945. if (x >= 0) {
  18946. sign = 1.0;
  18947. } else {
  18948. sign = -1.0;
  18949. x = -x;
  18950. }
  18951. var xm1 = x - 1.0;
  18952. var d = 1.0 - t;
  18953. var sqrT = t * t;
  18954. var sqrD = d * d;
  18955. for (var i = 7; i >= 0; --i) {
  18956. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  18957. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  18958. }
  18959. var cT = sign * t * (
  18960. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  18961. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  18962. var cD = d * (
  18963. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  18964. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  18965. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  18966. Quaternion.multiplyByScalar(end, cT, result);
  18967. return Quaternion.add(temp, result, result);
  18968. };
  18969. /**
  18970. * Computes the spherical quadrangle interpolation between quaternions.
  18971. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  18972. *
  18973. * @param {Quaternion} q0 The first quaternion.
  18974. * @param {Quaternion} q1 The second quaternion.
  18975. * @param {Quaternion} s0 The first inner quadrangle.
  18976. * @param {Quaternion} s1 The second inner quadrangle.
  18977. * @param {Number} t The time in [0,1] used to interpolate.
  18978. * @param {Quaternion} result The object onto which to store the result.
  18979. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  18980. *
  18981. * @see Quaternion#squad
  18982. */
  18983. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  18984. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18985. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18986. }
  18987. if (typeof t !== 'number') {
  18988. throw new DeveloperError('t is required and must be a number.');
  18989. }
  18990. if (!defined(result)) {
  18991. throw new DeveloperError('result is required');
  18992. }
  18993. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  18994. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  18995. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18996. };
  18997. /**
  18998. * Compares the provided quaternions componentwise and returns
  18999. * <code>true</code> if they are equal, <code>false</code> otherwise.
  19000. *
  19001. * @param {Quaternion} [left] The first quaternion.
  19002. * @param {Quaternion} [right] The second quaternion.
  19003. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  19004. */
  19005. Quaternion.equals = function(left, right) {
  19006. return (left === right) ||
  19007. ((defined(left)) &&
  19008. (defined(right)) &&
  19009. (left.x === right.x) &&
  19010. (left.y === right.y) &&
  19011. (left.z === right.z) &&
  19012. (left.w === right.w));
  19013. };
  19014. /**
  19015. * Compares the provided quaternions componentwise and returns
  19016. * <code>true</code> if they are within the provided epsilon,
  19017. * <code>false</code> otherwise.
  19018. *
  19019. * @param {Quaternion} [left] The first quaternion.
  19020. * @param {Quaternion} [right] The second quaternion.
  19021. * @param {Number} epsilon The epsilon to use for equality testing.
  19022. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  19023. */
  19024. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  19025. if (typeof epsilon !== 'number') {
  19026. throw new DeveloperError('epsilon is required and must be a number.');
  19027. }
  19028. return (left === right) ||
  19029. ((defined(left)) &&
  19030. (defined(right)) &&
  19031. (Math.abs(left.x - right.x) <= epsilon) &&
  19032. (Math.abs(left.y - right.y) <= epsilon) &&
  19033. (Math.abs(left.z - right.z) <= epsilon) &&
  19034. (Math.abs(left.w - right.w) <= epsilon));
  19035. };
  19036. /**
  19037. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  19038. *
  19039. * @type {Quaternion}
  19040. * @constant
  19041. */
  19042. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  19043. /**
  19044. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  19045. *
  19046. * @type {Quaternion}
  19047. * @constant
  19048. */
  19049. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  19050. /**
  19051. * Duplicates this Quaternion instance.
  19052. *
  19053. * @param {Quaternion} [result] The object onto which to store the result.
  19054. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  19055. */
  19056. Quaternion.prototype.clone = function(result) {
  19057. return Quaternion.clone(this, result);
  19058. };
  19059. /**
  19060. * Compares this and the provided quaternion componentwise and returns
  19061. * <code>true</code> if they are equal, <code>false</code> otherwise.
  19062. *
  19063. * @param {Quaternion} [right] The right hand side quaternion.
  19064. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  19065. */
  19066. Quaternion.prototype.equals = function(right) {
  19067. return Quaternion.equals(this, right);
  19068. };
  19069. /**
  19070. * Compares this and the provided quaternion componentwise and returns
  19071. * <code>true</code> if they are within the provided epsilon,
  19072. * <code>false</code> otherwise.
  19073. *
  19074. * @param {Quaternion} [right] The right hand side quaternion.
  19075. * @param {Number} epsilon The epsilon to use for equality testing.
  19076. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  19077. */
  19078. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  19079. return Quaternion.equalsEpsilon(this, right, epsilon);
  19080. };
  19081. /**
  19082. * Returns a string representing this quaternion in the format (x, y, z, w).
  19083. *
  19084. * @returns {String} A string representing this Quaternion.
  19085. */
  19086. Quaternion.prototype.toString = function() {
  19087. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  19088. };
  19089. return Quaternion;
  19090. });
  19091. /*global define*/
  19092. define('Core/Transforms',[
  19093. '../ThirdParty/when',
  19094. './Cartesian2',
  19095. './Cartesian3',
  19096. './Cartesian4',
  19097. './Cartographic',
  19098. './defaultValue',
  19099. './defined',
  19100. './deprecationWarning',
  19101. './DeveloperError',
  19102. './EarthOrientationParameters',
  19103. './EarthOrientationParametersSample',
  19104. './Ellipsoid',
  19105. './HeadingPitchRoll',
  19106. './Iau2006XysData',
  19107. './Iau2006XysSample',
  19108. './JulianDate',
  19109. './Math',
  19110. './Matrix3',
  19111. './Matrix4',
  19112. './Quaternion',
  19113. './TimeConstants'
  19114. ], function(
  19115. when,
  19116. Cartesian2,
  19117. Cartesian3,
  19118. Cartesian4,
  19119. Cartographic,
  19120. defaultValue,
  19121. defined,
  19122. deprecationWarning,
  19123. DeveloperError,
  19124. EarthOrientationParameters,
  19125. EarthOrientationParametersSample,
  19126. Ellipsoid,
  19127. HeadingPitchRoll,
  19128. Iau2006XysData,
  19129. Iau2006XysSample,
  19130. JulianDate,
  19131. CesiumMath,
  19132. Matrix3,
  19133. Matrix4,
  19134. Quaternion,
  19135. TimeConstants) {
  19136. 'use strict';
  19137. /**
  19138. * Contains functions for transforming positions to various reference frames.
  19139. *
  19140. * @exports Transforms
  19141. */
  19142. var Transforms = {};
  19143. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  19144. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  19145. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  19146. /**
  19147. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  19148. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19149. * The local axes are defined as:
  19150. * <ul>
  19151. * <li>The <code>x</code> axis points in the local east direction.</li>
  19152. * <li>The <code>y</code> axis points in the local north direction.</li>
  19153. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19154. * </ul>
  19155. *
  19156. * @param {Cartesian3} origin The center point of the local reference frame.
  19157. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19158. * @param {Matrix4} [result] The object onto which to store the result.
  19159. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19160. *
  19161. * @example
  19162. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  19163. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19164. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  19165. */
  19166. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  19167. if (!defined(origin)) {
  19168. throw new DeveloperError('origin is required.');
  19169. }
  19170. // If x and y are zero, assume origin is at a pole, which is a special case.
  19171. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19172. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19173. var sign = CesiumMath.sign(origin.z);
  19174. if (!defined(result)) {
  19175. return new Matrix4(
  19176. 0.0, -sign, 0.0, origin.x,
  19177. 1.0, 0.0, 0.0, origin.y,
  19178. 0.0, 0.0, sign, origin.z,
  19179. 0.0, 0.0, 0.0, 1.0);
  19180. }
  19181. result[0] = 0.0;
  19182. result[1] = 1.0;
  19183. result[2] = 0.0;
  19184. result[3] = 0.0;
  19185. result[4] = -sign;
  19186. result[5] = 0.0;
  19187. result[6] = 0.0;
  19188. result[7] = 0.0;
  19189. result[8] = 0.0;
  19190. result[9] = 0.0;
  19191. result[10] = sign;
  19192. result[11] = 0.0;
  19193. result[12] = origin.x;
  19194. result[13] = origin.y;
  19195. result[14] = origin.z;
  19196. result[15] = 1.0;
  19197. return result;
  19198. }
  19199. var normal = eastNorthUpToFixedFrameNormal;
  19200. var tangent = eastNorthUpToFixedFrameTangent;
  19201. var bitangent = eastNorthUpToFixedFrameBitangent;
  19202. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19203. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19204. tangent.x = -origin.y;
  19205. tangent.y = origin.x;
  19206. tangent.z = 0.0;
  19207. Cartesian3.normalize(tangent, tangent);
  19208. Cartesian3.cross(normal, tangent, bitangent);
  19209. if (!defined(result)) {
  19210. return new Matrix4(
  19211. tangent.x, bitangent.x, normal.x, origin.x,
  19212. tangent.y, bitangent.y, normal.y, origin.y,
  19213. tangent.z, bitangent.z, normal.z, origin.z,
  19214. 0.0, 0.0, 0.0, 1.0);
  19215. }
  19216. result[0] = tangent.x;
  19217. result[1] = tangent.y;
  19218. result[2] = tangent.z;
  19219. result[3] = 0.0;
  19220. result[4] = bitangent.x;
  19221. result[5] = bitangent.y;
  19222. result[6] = bitangent.z;
  19223. result[7] = 0.0;
  19224. result[8] = normal.x;
  19225. result[9] = normal.y;
  19226. result[10] = normal.z;
  19227. result[11] = 0.0;
  19228. result[12] = origin.x;
  19229. result[13] = origin.y;
  19230. result[14] = origin.z;
  19231. result[15] = 1.0;
  19232. return result;
  19233. };
  19234. var northEastDownToFixedFrameNormal = new Cartesian3();
  19235. var northEastDownToFixedFrameTangent = new Cartesian3();
  19236. var northEastDownToFixedFrameBitangent = new Cartesian3();
  19237. /**
  19238. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  19239. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19240. * The local axes are defined as:
  19241. * <ul>
  19242. * <li>The <code>x</code> axis points in the local north direction.</li>
  19243. * <li>The <code>y</code> axis points in the local east direction.</li>
  19244. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  19245. * </ul>
  19246. *
  19247. * @param {Cartesian3} origin The center point of the local reference frame.
  19248. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19249. * @param {Matrix4} [result] The object onto which to store the result.
  19250. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19251. *
  19252. * @example
  19253. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  19254. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19255. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  19256. */
  19257. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  19258. if (!defined(origin)) {
  19259. throw new DeveloperError('origin is required.');
  19260. }
  19261. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19262. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19263. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  19264. var sign = CesiumMath.sign(origin.z);
  19265. if (!defined(result)) {
  19266. return new Matrix4(
  19267. -sign, 0.0, 0.0, origin.x,
  19268. 0.0, 1.0, 0.0, origin.y,
  19269. 0.0, 0.0, -sign, origin.z,
  19270. 0.0, 0.0, 0.0, 1.0);
  19271. }
  19272. result[0] = -sign;
  19273. result[1] = 0.0;
  19274. result[2] = 0.0;
  19275. result[3] = 0.0;
  19276. result[4] = 0.0;
  19277. result[5] = 1.0;
  19278. result[6] = 0.0;
  19279. result[7] = 0.0;
  19280. result[8] = 0.0;
  19281. result[9] = 0.0;
  19282. result[10] = -sign;
  19283. result[11] = 0.0;
  19284. result[12] = origin.x;
  19285. result[13] = origin.y;
  19286. result[14] = origin.z;
  19287. result[15] = 1.0;
  19288. return result;
  19289. }
  19290. var normal = northEastDownToFixedFrameNormal;
  19291. var tangent = northEastDownToFixedFrameTangent;
  19292. var bitangent = northEastDownToFixedFrameBitangent;
  19293. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19294. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19295. tangent.x = -origin.y;
  19296. tangent.y = origin.x;
  19297. tangent.z = 0.0;
  19298. Cartesian3.normalize(tangent, tangent);
  19299. Cartesian3.cross(normal, tangent, bitangent);
  19300. if (!defined(result)) {
  19301. return new Matrix4(
  19302. bitangent.x, tangent.x, -normal.x, origin.x,
  19303. bitangent.y, tangent.y, -normal.y, origin.y,
  19304. bitangent.z, tangent.z, -normal.z, origin.z,
  19305. 0.0, 0.0, 0.0, 1.0);
  19306. }
  19307. result[0] = bitangent.x;
  19308. result[1] = bitangent.y;
  19309. result[2] = bitangent.z;
  19310. result[3] = 0.0;
  19311. result[4] = tangent.x;
  19312. result[5] = tangent.y;
  19313. result[6] = tangent.z;
  19314. result[7] = 0.0;
  19315. result[8] = -normal.x;
  19316. result[9] = -normal.y;
  19317. result[10] = -normal.z;
  19318. result[11] = 0.0;
  19319. result[12] = origin.x;
  19320. result[13] = origin.y;
  19321. result[14] = origin.z;
  19322. result[15] = 1.0;
  19323. return result;
  19324. };
  19325. /**
  19326. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  19327. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19328. * The local axes are defined as:
  19329. * <ul>
  19330. * <li>The <code>x</code> axis points in the local north direction.</li>
  19331. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19332. * <li>The <code>z</code> axis points in the local east direction.</li>
  19333. * </ul>
  19334. *
  19335. * @param {Cartesian3} origin The center point of the local reference frame.
  19336. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19337. * @param {Matrix4} [result] The object onto which to store the result.
  19338. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19339. *
  19340. * @example
  19341. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  19342. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19343. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  19344. */
  19345. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  19346. if (!defined(origin)) {
  19347. throw new DeveloperError('origin is required.');
  19348. }
  19349. // If x and y are zero, assume origin is at a pole, which is a special case.
  19350. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19351. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19352. var sign = CesiumMath.sign(origin.z);
  19353. if (!defined(result)) {
  19354. return new Matrix4(
  19355. -sign, 0.0, 0.0, origin.x,
  19356. 0.0, 0.0, 1.0, origin.y,
  19357. 0.0, sign, 0.0, origin.z,
  19358. 0.0, 0.0, 0.0, 1.0);
  19359. }
  19360. result[0] = -sign;
  19361. result[1] = 0.0;
  19362. result[2] = 0.0;
  19363. result[3] = 0.0;
  19364. result[4] = 0.0;
  19365. result[5] = 0.0;
  19366. result[6] = sign;
  19367. result[7] = 0.0;
  19368. result[8] = 0.0;
  19369. result[9] = 1.0;
  19370. result[10] = 0.0;
  19371. result[11] = 0.0;
  19372. result[12] = origin.x;
  19373. result[13] = origin.y;
  19374. result[14] = origin.z;
  19375. result[15] = 1.0;
  19376. return result;
  19377. }
  19378. var normal = eastNorthUpToFixedFrameNormal;
  19379. var tangent = eastNorthUpToFixedFrameTangent;
  19380. var bitangent = eastNorthUpToFixedFrameBitangent;
  19381. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19382. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19383. tangent.x = -origin.y;
  19384. tangent.y = origin.x;
  19385. tangent.z = 0.0;
  19386. Cartesian3.normalize(tangent, tangent);
  19387. Cartesian3.cross(normal, tangent, bitangent);
  19388. if (!defined(result)) {
  19389. return new Matrix4(
  19390. bitangent.x, normal.x, tangent.x, origin.x,
  19391. bitangent.y, normal.y, tangent.y, origin.y,
  19392. bitangent.z, normal.z, tangent.z, origin.z,
  19393. 0.0, 0.0, 0.0, 1.0);
  19394. }
  19395. result[0] = bitangent.x;
  19396. result[1] = bitangent.y;
  19397. result[2] = bitangent.z;
  19398. result[3] = 0.0;
  19399. result[4] = normal.x;
  19400. result[5] = normal.y;
  19401. result[6] = normal.z;
  19402. result[7] = 0.0;
  19403. result[8] = tangent.x;
  19404. result[9] = tangent.y;
  19405. result[10] = tangent.z;
  19406. result[11] = 0.0;
  19407. result[12] = origin.x;
  19408. result[13] = origin.y;
  19409. result[14] = origin.z;
  19410. result[15] = 1.0;
  19411. return result;
  19412. };
  19413. /**
  19414. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  19415. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19416. * The local axes are defined as:
  19417. * <ul>
  19418. * <li>The <code>x</code> axis points in the local north direction.</li>
  19419. * <li>The <code>y</code> axis points in the local west direction.</li>
  19420. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19421. * </ul>
  19422. *
  19423. * @param {Cartesian3} origin The center point of the local reference frame.
  19424. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19425. * @param {Matrix4} [result] The object onto which to store the result.
  19426. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19427. *
  19428. * @example
  19429. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  19430. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19431. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  19432. */
  19433. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  19434. if (!defined(origin)) {
  19435. throw new DeveloperError('origin is required.');
  19436. }
  19437. // If x and y are zero, assume origin is at a pole, which is a special case.
  19438. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19439. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19440. var sign = CesiumMath.sign(origin.z);
  19441. if (!defined(result)) {
  19442. return new Matrix4(
  19443. -sign, 0.0, 0.0, origin.x,
  19444. 0.0, -1.0, 0.0, origin.y,
  19445. 0.0, 0.0, sign, origin.z,
  19446. 0.0, 0.0, 0.0, 1.0);
  19447. }
  19448. result[0] = -sign;
  19449. result[1] = 0.0;
  19450. result[2] = 0.0;
  19451. result[3] = 0.0;
  19452. result[4] = 0.0;
  19453. result[5] = -1.0;
  19454. result[6] = 0.0;
  19455. result[7] = 0.0;
  19456. result[8] = 0.0;
  19457. result[9] = 0.0;
  19458. result[10] = sign;
  19459. result[11] = 0.0;
  19460. result[12] = origin.x;
  19461. result[13] = origin.y;
  19462. result[14] = origin.z;
  19463. result[15] = 1.0;
  19464. return result;
  19465. }
  19466. var normal = eastNorthUpToFixedFrameNormal;//Up
  19467. var tangent = eastNorthUpToFixedFrameTangent;//East
  19468. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  19469. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19470. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19471. tangent.x = -origin.y;
  19472. tangent.y = origin.x;
  19473. tangent.z = 0.0;
  19474. Cartesian3.normalize(tangent, tangent);
  19475. Cartesian3.cross(normal, tangent, bitangent);
  19476. if (!defined(result)) {
  19477. return new Matrix4(
  19478. bitangent.x, -tangent.x, normal.x, origin.x,
  19479. bitangent.y, -tangent.y, normal.y, origin.y,
  19480. bitangent.z, -tangent.z, normal.z, origin.z,
  19481. 0.0, 0.0, 0.0, 1.0);
  19482. }
  19483. result[0] = bitangent.x;
  19484. result[1] = bitangent.y;
  19485. result[2] = bitangent.z;
  19486. result[3] = 0.0;
  19487. result[4] = -tangent.x;
  19488. result[5] = -tangent.y;
  19489. result[6] = -tangent.z;
  19490. result[7] = 0.0;
  19491. result[8] = normal.x;
  19492. result[9] = normal.y;
  19493. result[10] = normal.z;
  19494. result[11] = 0.0;
  19495. result[12] = origin.x;
  19496. result[13] = origin.y;
  19497. result[14] = origin.z;
  19498. result[15] = 1.0;
  19499. return result;
  19500. };
  19501. var scratchHPRQuaternion = new Quaternion();
  19502. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  19503. var scratchHPRMatrix4 = new Matrix4();
  19504. /**
  19505. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  19506. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  19507. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  19508. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  19509. *
  19510. * @param {Cartesian3} origin The center point of the local reference frame.
  19511. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  19512. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19513. * @param {Matrix4} [result] The object onto which to store the result.
  19514. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19515. *
  19516. * @example
  19517. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  19518. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19519. * var heading = -Cesium.Math.PI_OVER_TWO;
  19520. * var pitch = Cesium.Math.PI_OVER_FOUR;
  19521. * var roll = 0.0;
  19522. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  19523. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  19524. */
  19525. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  19526. var heading;
  19527. if (typeof headingPitchRoll === 'object') {
  19528. // Shift arguments using assignments to encourage JIT optimization.
  19529. ellipsoid = pitch;
  19530. result = roll;
  19531. heading = headingPitchRoll.heading;
  19532. pitch = headingPitchRoll.pitch;
  19533. roll = headingPitchRoll.roll;
  19534. } else {
  19535. 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.');
  19536. heading = headingPitchRoll;
  19537. }
  19538. // checks for required parameters happen in the called functions
  19539. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  19540. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  19541. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  19542. return Matrix4.multiply(result, hprMatrix, result);
  19543. };
  19544. var scratchHPR = new HeadingPitchRoll();
  19545. var scratchENUMatrix4 = new Matrix4();
  19546. var scratchHPRMatrix3 = new Matrix3();
  19547. /**
  19548. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  19549. * centered at the provided origin. Heading is the rotation from the local north
  19550. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  19551. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  19552. *
  19553. * @param {Cartesian3} origin The center point of the local reference frame.
  19554. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  19555. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19556. * @param {Quaternion} [result] The object onto which to store the result.
  19557. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  19558. *
  19559. * @example
  19560. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  19561. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19562. * var heading = -Cesium.Math.PI_OVER_TWO;
  19563. * var pitch = Cesium.Math.PI_OVER_FOUR;
  19564. * var roll = 0.0;
  19565. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  19566. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  19567. */
  19568. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  19569. var hpr;
  19570. if (typeof headingPitchRoll === 'object') {
  19571. // Shift arguments using assignment to encourage JIT optimization.
  19572. hpr = headingPitchRoll;
  19573. ellipsoid = pitch;
  19574. result = roll;
  19575. } else {
  19576. 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.');
  19577. scratchHPR.heading = headingPitchRoll;
  19578. scratchHPR.pitch = pitch;
  19579. scratchHPR.roll = roll;
  19580. hpr = scratchHPR;
  19581. }
  19582. // checks for required parameters happen in the called functions
  19583. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  19584. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  19585. return Quaternion.fromRotationMatrix(rotation, result);
  19586. };
  19587. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  19588. var gmstConstant1 = 8640184.812866;
  19589. var gmstConstant2 = 0.093104;
  19590. var gmstConstant3 = -6.2E-6;
  19591. var rateCoef = 1.1772758384668e-19;
  19592. var wgs84WRPrecessing = 7.2921158553E-5;
  19593. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  19594. var dateInUtc = new JulianDate();
  19595. /**
  19596. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  19597. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  19598. *
  19599. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19600. * @param {Matrix3} [result] The object onto which to store the result.
  19601. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  19602. *
  19603. * @example
  19604. * //Set the view to in the inertial frame.
  19605. * scene.preRender.addEventListener(function(scene, time) {
  19606. * var now = Cesium.JulianDate.now();
  19607. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  19608. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  19609. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  19610. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  19611. * camera.lookAtTransform(transform, offset);
  19612. * });
  19613. */
  19614. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  19615. if (!defined(date)) {
  19616. throw new DeveloperError('date is required.');
  19617. }
  19618. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  19619. // We do not want to use the function like convertTaiToUtc in JulianDate because
  19620. // we explicitly do not want to fail when inside the leap second.
  19621. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  19622. var utcDayNumber = dateInUtc.dayNumber;
  19623. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  19624. var t;
  19625. var diffDays = utcDayNumber - 2451545;
  19626. if (utcSecondsIntoDay >= 43200.0) {
  19627. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  19628. } else {
  19629. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  19630. }
  19631. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  19632. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  19633. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  19634. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  19635. var gha = angle + (ratio * secondsSinceMidnight);
  19636. var cosGha = Math.cos(gha);
  19637. var sinGha = Math.sin(gha);
  19638. if (!defined(result)) {
  19639. return new Matrix3(cosGha, sinGha, 0.0,
  19640. -sinGha, cosGha, 0.0,
  19641. 0.0, 0.0, 1.0);
  19642. }
  19643. result[0] = cosGha;
  19644. result[1] = -sinGha;
  19645. result[2] = 0.0;
  19646. result[3] = sinGha;
  19647. result[4] = cosGha;
  19648. result[5] = 0.0;
  19649. result[6] = 0.0;
  19650. result[7] = 0.0;
  19651. result[8] = 1.0;
  19652. return result;
  19653. };
  19654. /**
  19655. * The source of IAU 2006 XYS data, used for computing the transformation between the
  19656. * Fixed and ICRF axes.
  19657. * @type {Iau2006XysData}
  19658. *
  19659. * @see Transforms.computeIcrfToFixedMatrix
  19660. * @see Transforms.computeFixedToIcrfMatrix
  19661. *
  19662. * @private
  19663. */
  19664. Transforms.iau2006XysData = new Iau2006XysData();
  19665. /**
  19666. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  19667. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  19668. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  19669. * @type {EarthOrientationParameters}
  19670. *
  19671. * @see Transforms.computeIcrfToFixedMatrix
  19672. * @see Transforms.computeFixedToIcrfMatrix
  19673. *
  19674. * @private
  19675. */
  19676. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  19677. var ttMinusTai = 32.184;
  19678. var j2000ttDays = 2451545.0;
  19679. /**
  19680. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  19681. * direction, over a given interval. This function returns a promise that, when resolved,
  19682. * indicates that the preload has completed.
  19683. *
  19684. * @param {TimeInterval} timeInterval The interval to preload.
  19685. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  19686. * and evaluation of the transformation between the fixed and ICRF axes will
  19687. * no longer return undefined for a time inside the interval.
  19688. *
  19689. *
  19690. * @example
  19691. * var interval = new Cesium.TimeInterval(...);
  19692. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  19693. * // the data is now loaded
  19694. * });
  19695. *
  19696. * @see Transforms.computeIcrfToFixedMatrix
  19697. * @see Transforms.computeFixedToIcrfMatrix
  19698. * @see when
  19699. */
  19700. Transforms.preloadIcrfFixed = function(timeInterval) {
  19701. var startDayTT = timeInterval.start.dayNumber;
  19702. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  19703. var stopDayTT = timeInterval.stop.dayNumber;
  19704. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  19705. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  19706. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  19707. return when.all([xysPromise, eopPromise]);
  19708. };
  19709. /**
  19710. * Computes a rotation matrix to transform a point or vector from the International Celestial
  19711. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  19712. * at a given time. This function may return undefined if the data necessary to
  19713. * do the transformation is not yet loaded.
  19714. *
  19715. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19716. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  19717. * not specified, a new instance is created and returned.
  19718. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  19719. * transformation is not yet loaded.
  19720. *
  19721. *
  19722. * @example
  19723. * scene.preRender.addEventListener(function(scene, time) {
  19724. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  19725. * if (Cesium.defined(icrfToFixed)) {
  19726. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  19727. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  19728. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  19729. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  19730. * camera.lookAtTransform(transform, offset);
  19731. * }
  19732. * });
  19733. *
  19734. * @see Transforms.preloadIcrfFixed
  19735. */
  19736. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  19737. if (!defined(date)) {
  19738. throw new DeveloperError('date is required.');
  19739. }
  19740. if (!defined(result)) {
  19741. result = new Matrix3();
  19742. }
  19743. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  19744. if (!defined(fixedToIcrfMtx)) {
  19745. return undefined;
  19746. }
  19747. return Matrix3.transpose(fixedToIcrfMtx, result);
  19748. };
  19749. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  19750. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  19751. var rotation1Scratch = new Matrix3();
  19752. var rotation2Scratch = new Matrix3();
  19753. /**
  19754. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  19755. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  19756. * at a given time. This function may return undefined if the data necessary to
  19757. * do the transformation is not yet loaded.
  19758. *
  19759. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19760. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  19761. * not specified, a new instance is created and returned.
  19762. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  19763. * transformation is not yet loaded.
  19764. *
  19765. *
  19766. * @example
  19767. * // Transform a point from the ICRF axes to the Fixed axes.
  19768. * var now = Cesium.JulianDate.now();
  19769. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19770. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  19771. * var pointInInertial = new Cesium.Cartesian3();
  19772. * if (Cesium.defined(fixedToIcrf)) {
  19773. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  19774. * }
  19775. *
  19776. * @see Transforms.preloadIcrfFixed
  19777. */
  19778. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  19779. if (!defined(date)) {
  19780. throw new DeveloperError('date is required.');
  19781. }
  19782. if (!defined(result)) {
  19783. result = new Matrix3();
  19784. }
  19785. // Compute pole wander
  19786. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  19787. if (!defined(eop)) {
  19788. return undefined;
  19789. }
  19790. // There is no external conversion to Terrestrial Time (TT).
  19791. // So use International Atomic Time (TAI) and convert using offsets.
  19792. // Here we are assuming that dayTT and secondTT are positive
  19793. var dayTT = date.dayNumber;
  19794. // It's possible here that secondTT could roll over 86400
  19795. // This does not seem to affect the precision (unit tests check for this)
  19796. var secondTT = date.secondsOfDay + ttMinusTai;
  19797. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  19798. if (!defined(xys)) {
  19799. return undefined;
  19800. }
  19801. var x = xys.x + eop.xPoleOffset;
  19802. var y = xys.y + eop.yPoleOffset;
  19803. // Compute XYS rotation
  19804. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  19805. var rotation1 = rotation1Scratch;
  19806. rotation1[0] = 1.0 - a * x * x;
  19807. rotation1[3] = -a * x * y;
  19808. rotation1[6] = x;
  19809. rotation1[1] = -a * x * y;
  19810. rotation1[4] = 1 - a * y * y;
  19811. rotation1[7] = y;
  19812. rotation1[2] = -x;
  19813. rotation1[5] = -y;
  19814. rotation1[8] = 1 - a * (x * x + y * y);
  19815. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  19816. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  19817. // Similar to TT conversions above
  19818. // It's possible here that secondTT could roll over 86400
  19819. // This does not seem to affect the precision (unit tests check for this)
  19820. var dateUt1day = date.dayNumber;
  19821. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  19822. // Compute Earth rotation angle
  19823. // The IERS standard for era is
  19824. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  19825. // where
  19826. // Tu = JulianDateInUt1 - 2451545.0
  19827. // However, you get much more precision if you make the following simplification
  19828. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  19829. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  19830. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  19831. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  19832. var daysSinceJ2000 = dateUt1day - 2451545;
  19833. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  19834. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  19835. era = (era % 1.0) * CesiumMath.TWO_PI;
  19836. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  19837. // pseudoFixed to ICRF
  19838. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  19839. // Compute pole wander matrix
  19840. var cosxp = Math.cos(eop.xPoleWander);
  19841. var cosyp = Math.cos(eop.yPoleWander);
  19842. var sinxp = Math.sin(eop.xPoleWander);
  19843. var sinyp = Math.sin(eop.yPoleWander);
  19844. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  19845. ttt /= 36525.0;
  19846. // approximate sp value in rad
  19847. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  19848. var cossp = Math.cos(sp);
  19849. var sinsp = Math.sin(sp);
  19850. var fToPfMtx = rotation2Scratch;
  19851. fToPfMtx[0] = cosxp * cossp;
  19852. fToPfMtx[1] = cosxp * sinsp;
  19853. fToPfMtx[2] = sinxp;
  19854. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  19855. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  19856. fToPfMtx[5] = -sinyp * cosxp;
  19857. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  19858. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  19859. fToPfMtx[8] = cosyp * cosxp;
  19860. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  19861. };
  19862. var pointToWindowCoordinatesTemp = new Cartesian4();
  19863. /**
  19864. * Transform a point from model coordinates to window coordinates.
  19865. *
  19866. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  19867. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  19868. * @param {Cartesian3} point The point to transform.
  19869. * @param {Cartesian2} [result] The object onto which to store the result.
  19870. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  19871. */
  19872. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  19873. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  19874. result.y = 2.0 * viewportTransformation[5] - result.y;
  19875. return result;
  19876. };
  19877. /**
  19878. * @private
  19879. */
  19880. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  19881. if (!defined(modelViewProjectionMatrix)) {
  19882. throw new DeveloperError('modelViewProjectionMatrix is required.');
  19883. }
  19884. if (!defined(viewportTransformation)) {
  19885. throw new DeveloperError('viewportTransformation is required.');
  19886. }
  19887. if (!defined(point)) {
  19888. throw new DeveloperError('point is required.');
  19889. }
  19890. if (!defined(result)) {
  19891. result = new Cartesian2();
  19892. }
  19893. var tmp = pointToWindowCoordinatesTemp;
  19894. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  19895. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  19896. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  19897. return Cartesian2.fromCartesian4(tmp, result);
  19898. };
  19899. var normalScratch = new Cartesian3();
  19900. var rightScratch = new Cartesian3();
  19901. var upScratch = new Cartesian3();
  19902. /**
  19903. * @private
  19904. */
  19905. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  19906. if (!defined(position)) {
  19907. throw new DeveloperError('position is required.');
  19908. }
  19909. if (!defined(velocity)) {
  19910. throw new DeveloperError('velocity is required.');
  19911. }
  19912. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  19913. var right = Cartesian3.cross(velocity, normal, rightScratch);
  19914. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  19915. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  19916. }
  19917. var up = Cartesian3.cross(right, velocity, upScratch);
  19918. Cartesian3.cross(velocity, up, right);
  19919. Cartesian3.negate(right, right);
  19920. if (!defined(result)) {
  19921. result = new Matrix3();
  19922. }
  19923. result[0] = velocity.x;
  19924. result[1] = velocity.y;
  19925. result[2] = velocity.z;
  19926. result[3] = right.x;
  19927. result[4] = right.y;
  19928. result[5] = right.z;
  19929. result[6] = up.x;
  19930. result[7] = up.y;
  19931. result[8] = up.z;
  19932. return result;
  19933. };
  19934. var scratchCartographic = new Cartographic();
  19935. var scratchCartesian3Projection = new Cartesian3();
  19936. var scratchCartesian3 = new Cartesian3();
  19937. var scratchCartesian4Origin = new Cartesian4();
  19938. var scratchCartesian4NewOrigin = new Cartesian4();
  19939. var scratchCartesian4NewXAxis = new Cartesian4();
  19940. var scratchCartesian4NewYAxis = new Cartesian4();
  19941. var scratchCartesian4NewZAxis = new Cartesian4();
  19942. var scratchFromENU = new Matrix4();
  19943. var scratchToENU = new Matrix4();
  19944. /**
  19945. * @private
  19946. */
  19947. Transforms.basisTo2D = function(projection, matrix, result) {
  19948. if (!defined(projection)) {
  19949. throw new DeveloperError('projection is required.');
  19950. }
  19951. if (!defined(matrix)) {
  19952. throw new DeveloperError('matrix is required.');
  19953. }
  19954. if (!defined(result)) {
  19955. throw new DeveloperError('result is required.');
  19956. }
  19957. var ellipsoid = projection.ellipsoid;
  19958. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  19959. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  19960. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  19961. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  19962. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  19963. var newOrigin = scratchCartesian4NewOrigin;
  19964. newOrigin.x = projectedPosition.z;
  19965. newOrigin.y = projectedPosition.x;
  19966. newOrigin.z = projectedPosition.y;
  19967. newOrigin.w = 1.0;
  19968. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  19969. var xScale = Cartesian3.magnitude(xAxis);
  19970. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  19971. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  19972. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  19973. var yScale = Cartesian3.magnitude(yAxis);
  19974. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  19975. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  19976. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  19977. var zScale = Cartesian3.magnitude(zAxis);
  19978. var newZAxis = scratchCartesian4NewZAxis;
  19979. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  19980. Cartesian3.normalize(newZAxis, newZAxis);
  19981. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  19982. Cartesian3.normalize(newXAxis, newXAxis);
  19983. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  19984. Cartesian3.normalize(newYAxis, newYAxis);
  19985. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  19986. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  19987. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  19988. Matrix4.setColumn(result, 0, newXAxis, result);
  19989. Matrix4.setColumn(result, 1, newYAxis, result);
  19990. Matrix4.setColumn(result, 2, newZAxis, result);
  19991. Matrix4.setColumn(result, 3, newOrigin, result);
  19992. return result;
  19993. };
  19994. return Transforms;
  19995. });
  19996. /*global define*/
  19997. define('Core/EllipsoidTangentPlane',[
  19998. './AxisAlignedBoundingBox',
  19999. './Cartesian2',
  20000. './Cartesian3',
  20001. './Cartesian4',
  20002. './defaultValue',
  20003. './defined',
  20004. './defineProperties',
  20005. './DeveloperError',
  20006. './Ellipsoid',
  20007. './IntersectionTests',
  20008. './Matrix4',
  20009. './Plane',
  20010. './Ray',
  20011. './Transforms'
  20012. ], function(
  20013. AxisAlignedBoundingBox,
  20014. Cartesian2,
  20015. Cartesian3,
  20016. Cartesian4,
  20017. defaultValue,
  20018. defined,
  20019. defineProperties,
  20020. DeveloperError,
  20021. Ellipsoid,
  20022. IntersectionTests,
  20023. Matrix4,
  20024. Plane,
  20025. Ray,
  20026. Transforms) {
  20027. 'use strict';
  20028. var scratchCart4 = new Cartesian4();
  20029. /**
  20030. * A plane tangent to the provided ellipsoid at the provided origin.
  20031. * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
  20032. * If origin is at the center of the ellipsoid, an exception will be thrown.
  20033. * @alias EllipsoidTangentPlane
  20034. * @constructor
  20035. *
  20036. * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
  20037. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  20038. *
  20039. * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
  20040. */
  20041. function EllipsoidTangentPlane(origin, ellipsoid) {
  20042. if (!defined(origin)) {
  20043. throw new DeveloperError('origin is required.');
  20044. }
  20045. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  20046. origin = ellipsoid.scaleToGeodeticSurface(origin);
  20047. if (!defined(origin)) {
  20048. throw new DeveloperError('origin must not be at the center of the ellipsoid.');
  20049. }
  20050. var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
  20051. this._ellipsoid = ellipsoid;
  20052. this._origin = origin;
  20053. this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0, scratchCart4));
  20054. this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1, scratchCart4));
  20055. var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2, scratchCart4));
  20056. this._plane = Plane.fromPointNormal(origin, normal);
  20057. }
  20058. defineProperties(EllipsoidTangentPlane.prototype, {
  20059. /**
  20060. * Gets the ellipsoid.
  20061. * @memberof EllipsoidTangentPlane.prototype
  20062. * @type {Ellipsoid}
  20063. */
  20064. ellipsoid : {
  20065. get : function() {
  20066. return this._ellipsoid;
  20067. }
  20068. },
  20069. /**
  20070. * Gets the origin.
  20071. * @memberof EllipsoidTangentPlane.prototype
  20072. * @type {Cartesian3}
  20073. */
  20074. origin : {
  20075. get : function() {
  20076. return this._origin;
  20077. }
  20078. },
  20079. /**
  20080. * Gets the plane which is tangent to the ellipsoid.
  20081. * @memberof EllipsoidTangentPlane.prototype
  20082. * @readonly
  20083. * @type {Plane}
  20084. */
  20085. plane : {
  20086. get : function() {
  20087. return this._plane;
  20088. }
  20089. },
  20090. /**
  20091. * Gets the local X-axis (east) of the tangent plane.
  20092. * @memberof EllipsoidTangentPlane.prototype
  20093. * @readonly
  20094. * @type {Cartesian3}
  20095. */
  20096. xAxis : {
  20097. get : function() {
  20098. return this._xAxis;
  20099. }
  20100. },
  20101. /**
  20102. * Gets the local Y-axis (north) of the tangent plane.
  20103. * @memberof EllipsoidTangentPlane.prototype
  20104. * @readonly
  20105. * @type {Cartesian3}
  20106. */
  20107. yAxis : {
  20108. get : function() {
  20109. return this._yAxis;
  20110. }
  20111. },
  20112. /**
  20113. * Gets the local Z-axis (up) of the tangent plane.
  20114. * @member EllipsoidTangentPlane.prototype
  20115. * @readonly
  20116. * @type {Cartesian3}
  20117. */
  20118. zAxis : {
  20119. get : function() {
  20120. return this._plane.normal;
  20121. }
  20122. }
  20123. });
  20124. var tmp = new AxisAlignedBoundingBox();
  20125. /**
  20126. * Creates a new instance from the provided ellipsoid and the center
  20127. * point of the provided Cartesians.
  20128. *
  20129. * @param {Ellipsoid} ellipsoid The ellipsoid to use.
  20130. * @param {Cartesian3} cartesians The list of positions surrounding the center point.
  20131. */
  20132. EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
  20133. if (!defined(cartesians)) {
  20134. throw new DeveloperError('cartesians is required.');
  20135. }
  20136. var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
  20137. return new EllipsoidTangentPlane(box.center, ellipsoid);
  20138. };
  20139. var scratchProjectPointOntoPlaneRay = new Ray();
  20140. var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();
  20141. /**
  20142. * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
  20143. *
  20144. * @param {Cartesian3} cartesian The point to project.
  20145. * @param {Cartesian2} [result] The object onto which to store the result.
  20146. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
  20147. */
  20148. EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
  20149. if (!defined(cartesian)) {
  20150. throw new DeveloperError('cartesian is required.');
  20151. }
  20152. var ray = scratchProjectPointOntoPlaneRay;
  20153. ray.origin = cartesian;
  20154. Cartesian3.normalize(cartesian, ray.direction);
  20155. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  20156. if (!defined(intersectionPoint)) {
  20157. Cartesian3.negate(ray.direction, ray.direction);
  20158. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  20159. }
  20160. if (defined(intersectionPoint)) {
  20161. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  20162. var x = Cartesian3.dot(this._xAxis, v);
  20163. var y = Cartesian3.dot(this._yAxis, v);
  20164. if (!defined(result)) {
  20165. return new Cartesian2(x, y);
  20166. }
  20167. result.x = x;
  20168. result.y = y;
  20169. return result;
  20170. }
  20171. return undefined;
  20172. };
  20173. /**
  20174. * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
  20175. * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
  20176. *
  20177. * @see EllipsoidTangentPlane.projectPointOntoPlane
  20178. *
  20179. * @param {Cartesian3[]} cartesians The array of points to project.
  20180. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  20181. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
  20182. */
  20183. EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
  20184. if (!defined(cartesians)) {
  20185. throw new DeveloperError('cartesians is required.');
  20186. }
  20187. if (!defined(result)) {
  20188. result = [];
  20189. }
  20190. var count = 0;
  20191. var length = cartesians.length;
  20192. for ( var i = 0; i < length; i++) {
  20193. var p = this.projectPointOntoPlane(cartesians[i], result[count]);
  20194. if (defined(p)) {
  20195. result[count] = p;
  20196. count++;
  20197. }
  20198. }
  20199. result.length = count;
  20200. return result;
  20201. };
  20202. /**
  20203. * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
  20204. *
  20205. * @param {Cartesian3} cartesian The point to project.
  20206. * @param {Cartesian2} [result] The object onto which to store the result.
  20207. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  20208. */
  20209. EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian, result) {
  20210. if (!defined(cartesian)) {
  20211. throw new DeveloperError('cartesian is required.');
  20212. }
  20213. if (!defined(result)) {
  20214. result = new Cartesian2();
  20215. }
  20216. var ray = scratchProjectPointOntoPlaneRay;
  20217. ray.origin = cartesian;
  20218. Cartesian3.clone(this._plane.normal, ray.direction);
  20219. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  20220. if (!defined(intersectionPoint)) {
  20221. Cartesian3.negate(ray.direction, ray.direction);
  20222. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  20223. }
  20224. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  20225. var x = Cartesian3.dot(this._xAxis, v);
  20226. var y = Cartesian3.dot(this._yAxis, v);
  20227. result.x = x;
  20228. result.y = y;
  20229. return result;
  20230. };
  20231. /**
  20232. * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
  20233. *
  20234. * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
  20235. *
  20236. * @param {Cartesian3[]} cartesians The array of points to project.
  20237. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  20238. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided. This will have the same length as <code>cartesians</code>.
  20239. */
  20240. EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
  20241. if (!defined(cartesians)) {
  20242. throw new DeveloperError('cartesians is required.');
  20243. }
  20244. if (!defined(result)) {
  20245. result = [];
  20246. }
  20247. var length = cartesians.length;
  20248. result.length = length;
  20249. for (var i = 0; i < length; i++) {
  20250. result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
  20251. }
  20252. return result;
  20253. };
  20254. var projectPointsOntoEllipsoidScratch = new Cartesian3();
  20255. /**
  20256. * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
  20257. *
  20258. * @param {Cartesian2[]} cartesians The array of points to project.
  20259. * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
  20260. * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
  20261. */
  20262. EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
  20263. if (!defined(cartesians)) {
  20264. throw new DeveloperError('cartesians is required.');
  20265. }
  20266. var length = cartesians.length;
  20267. if (!defined(result)) {
  20268. result = new Array(length);
  20269. } else {
  20270. result.length = length;
  20271. }
  20272. var ellipsoid = this._ellipsoid;
  20273. var origin = this._origin;
  20274. var xAxis = this._xAxis;
  20275. var yAxis = this._yAxis;
  20276. var tmp = projectPointsOntoEllipsoidScratch;
  20277. for ( var i = 0; i < length; ++i) {
  20278. var position = cartesians[i];
  20279. Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
  20280. if (!defined(result[i])) {
  20281. result[i] = new Cartesian3();
  20282. }
  20283. var point = Cartesian3.add(origin, tmp, result[i]);
  20284. Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
  20285. Cartesian3.add(point, tmp, point);
  20286. ellipsoid.scaleToGeocentricSurface(point, point);
  20287. }
  20288. return result;
  20289. };
  20290. return EllipsoidTangentPlane;
  20291. });
  20292. /*global define*/
  20293. define('Core/GeometryType',[
  20294. './freezeObject'
  20295. ], function(
  20296. freezeObject) {
  20297. 'use strict';
  20298. /**
  20299. * @private
  20300. */
  20301. var GeometryType = {
  20302. NONE : 0,
  20303. TRIANGLES : 1,
  20304. LINES : 2,
  20305. POLYLINES : 3
  20306. };
  20307. return freezeObject(GeometryType);
  20308. });
  20309. /*global define*/
  20310. define('Core/PrimitiveType',[
  20311. './freezeObject',
  20312. './WebGLConstants'
  20313. ], function(
  20314. freezeObject,
  20315. WebGLConstants) {
  20316. 'use strict';
  20317. /**
  20318. * The type of a geometric primitive, i.e., points, lines, and triangles.
  20319. *
  20320. * @exports PrimitiveType
  20321. */
  20322. var PrimitiveType = {
  20323. /**
  20324. * Points primitive where each vertex (or index) is a separate point.
  20325. *
  20326. * @type {Number}
  20327. * @constant
  20328. */
  20329. POINTS : WebGLConstants.POINTS,
  20330. /**
  20331. * Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
  20332. *
  20333. * @type {Number}
  20334. * @constant
  20335. */
  20336. LINES : WebGLConstants.LINES,
  20337. /**
  20338. * Line loop primitive where each vertex (or index) after the first connects a line to
  20339. * the previous vertex, and the last vertex implicitly connects to the first.
  20340. *
  20341. * @type {Number}
  20342. * @constant
  20343. */
  20344. LINE_LOOP : WebGLConstants.LINE_LOOP,
  20345. /**
  20346. * Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
  20347. *
  20348. * @type {Number}
  20349. * @constant
  20350. */
  20351. LINE_STRIP : WebGLConstants.LINE_STRIP,
  20352. /**
  20353. * Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
  20354. *
  20355. * @type {Number}
  20356. * @constant
  20357. */
  20358. TRIANGLES : WebGLConstants.TRIANGLES,
  20359. /**
  20360. * Triangle strip primitive where each vertex (or index) after the first two connect to
  20361. * the previous two vertices forming a triangle. For example, this can be used to model a wall.
  20362. *
  20363. * @type {Number}
  20364. * @constant
  20365. */
  20366. TRIANGLE_STRIP : WebGLConstants.TRIANGLE_STRIP,
  20367. /**
  20368. * Triangle fan primitive where each vertex (or index) after the first two connect to
  20369. * the previous vertex and the first vertex forming a triangle. For example, this can be used
  20370. * to model a cone or circle.
  20371. *
  20372. * @type {Number}
  20373. * @constant
  20374. */
  20375. TRIANGLE_FAN : WebGLConstants.TRIANGLE_FAN,
  20376. /**
  20377. * @private
  20378. */
  20379. validate : function(primitiveType) {
  20380. return primitiveType === PrimitiveType.POINTS ||
  20381. primitiveType === PrimitiveType.LINES ||
  20382. primitiveType === PrimitiveType.LINE_LOOP ||
  20383. primitiveType === PrimitiveType.LINE_STRIP ||
  20384. primitiveType === PrimitiveType.TRIANGLES ||
  20385. primitiveType === PrimitiveType.TRIANGLE_STRIP ||
  20386. primitiveType === PrimitiveType.TRIANGLE_FAN;
  20387. }
  20388. };
  20389. return freezeObject(PrimitiveType);
  20390. });
  20391. /*global define*/
  20392. define('Core/Geometry',[
  20393. './defaultValue',
  20394. './defined',
  20395. './DeveloperError',
  20396. './GeometryType',
  20397. './PrimitiveType'
  20398. ], function(
  20399. defaultValue,
  20400. defined,
  20401. DeveloperError,
  20402. GeometryType,
  20403. PrimitiveType) {
  20404. 'use strict';
  20405. /**
  20406. * A geometry representation with attributes forming vertices and optional index data
  20407. * defining primitives. Geometries and an {@link Appearance}, which describes the shading,
  20408. * can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
  20409. * be created from many heterogeneous - in many cases - geometries for performance.
  20410. * <p>
  20411. * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
  20412. * </p>
  20413. *
  20414. * @alias Geometry
  20415. * @constructor
  20416. *
  20417. * @param {Object} options Object with the following properties:
  20418. * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
  20419. * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
  20420. * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
  20421. * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
  20422. *
  20423. * @see PolygonGeometry
  20424. * @see RectangleGeometry
  20425. * @see EllipseGeometry
  20426. * @see CircleGeometry
  20427. * @see WallGeometry
  20428. * @see SimplePolylineGeometry
  20429. * @see BoxGeometry
  20430. * @see EllipsoidGeometry
  20431. *
  20432. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
  20433. *
  20434. * @example
  20435. * // Create geometry with a position attribute and indexed lines.
  20436. * var positions = new Float64Array([
  20437. * 0.0, 0.0, 0.0,
  20438. * 7500000.0, 0.0, 0.0,
  20439. * 0.0, 7500000.0, 0.0
  20440. * ]);
  20441. *
  20442. * var geometry = new Cesium.Geometry({
  20443. * attributes : {
  20444. * position : new Cesium.GeometryAttribute({
  20445. * componentDatatype : Cesium.ComponentDatatype.DOUBLE,
  20446. * componentsPerAttribute : 3,
  20447. * values : positions
  20448. * })
  20449. * },
  20450. * indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
  20451. * primitiveType : Cesium.PrimitiveType.LINES,
  20452. * boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
  20453. * });
  20454. */
  20455. function Geometry(options) {
  20456. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20457. if (!defined(options.attributes)) {
  20458. throw new DeveloperError('options.attributes is required.');
  20459. }
  20460. /**
  20461. * Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
  20462. * {@link GeometryAttribute} containing the attribute's data.
  20463. * <p>
  20464. * Attributes are always stored non-interleaved in a Geometry.
  20465. * </p>
  20466. * <p>
  20467. * There are reserved attribute names with well-known semantics. The following attributes
  20468. * are created by a Geometry (depending on the provided {@link VertexFormat}.
  20469. * <ul>
  20470. * <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
  20471. * <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
  20472. * <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
  20473. * <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>
  20474. * <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>
  20475. * </ul>
  20476. * </p>
  20477. * <p>
  20478. * The following attribute names are generally not created by a Geometry, but are added
  20479. * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
  20480. * the geometry for rendering.
  20481. * <ul>
  20482. * <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>
  20483. * <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>
  20484. * <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>
  20485. * <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>
  20486. * <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
  20487. * <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
  20488. * </ul>
  20489. * </p>
  20490. *
  20491. * @type GeometryAttributes
  20492. *
  20493. * @default undefined
  20494. *
  20495. *
  20496. * @example
  20497. * geometry.attributes.position = new Cesium.GeometryAttribute({
  20498. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  20499. * componentsPerAttribute : 3,
  20500. * values : new Float32Array(0)
  20501. * });
  20502. *
  20503. * @see GeometryAttribute
  20504. * @see VertexFormat
  20505. */
  20506. this.attributes = options.attributes;
  20507. /**
  20508. * Optional index data that - along with {@link Geometry#primitiveType} -
  20509. * determines the primitives in the geometry.
  20510. *
  20511. * @type Array
  20512. *
  20513. * @default undefined
  20514. */
  20515. this.indices = options.indices;
  20516. /**
  20517. * The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
  20518. * but can varying based on the specific geometry.
  20519. *
  20520. * @type PrimitiveType
  20521. *
  20522. * @default undefined
  20523. */
  20524. this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
  20525. /**
  20526. * An optional bounding sphere that fully encloses the geometry. This is
  20527. * commonly used for culling.
  20528. *
  20529. * @type BoundingSphere
  20530. *
  20531. * @default undefined
  20532. */
  20533. this.boundingSphere = options.boundingSphere;
  20534. /**
  20535. * @private
  20536. */
  20537. this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
  20538. /**
  20539. * @private
  20540. */
  20541. this.boundingSphereCV = options.boundingSphereCV;
  20542. }
  20543. /**
  20544. * Computes the number of vertices in a geometry. The runtime is linear with
  20545. * respect to the number of attributes in a vertex, not the number of vertices.
  20546. *
  20547. * @param {Geometry} geometry The geometry.
  20548. * @returns {Number} The number of vertices in the geometry.
  20549. *
  20550. * @example
  20551. * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
  20552. */
  20553. Geometry.computeNumberOfVertices = function(geometry) {
  20554. if (!defined(geometry)) {
  20555. throw new DeveloperError('geometry is required.');
  20556. }
  20557. var numberOfVertices = -1;
  20558. for ( var property in geometry.attributes) {
  20559. if (geometry.attributes.hasOwnProperty(property) &&
  20560. defined(geometry.attributes[property]) &&
  20561. defined(geometry.attributes[property].values)) {
  20562. var attribute = geometry.attributes[property];
  20563. var num = attribute.values.length / attribute.componentsPerAttribute;
  20564. if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
  20565. throw new DeveloperError('All attribute lists must have the same number of attributes.');
  20566. }
  20567. numberOfVertices = num;
  20568. }
  20569. }
  20570. return numberOfVertices;
  20571. };
  20572. return Geometry;
  20573. });
  20574. /*global define*/
  20575. define('Core/GeometryAttribute',[
  20576. './defaultValue',
  20577. './defined',
  20578. './DeveloperError'
  20579. ], function(
  20580. defaultValue,
  20581. defined,
  20582. DeveloperError) {
  20583. 'use strict';
  20584. /**
  20585. * Values and type information for geometry attributes. A {@link Geometry}
  20586. * generally contains one or more attributes. All attributes together form
  20587. * the geometry's vertices.
  20588. *
  20589. * @alias GeometryAttribute
  20590. * @constructor
  20591. *
  20592. * @param {Object} [options] Object with the following properties:
  20593. * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
  20594. * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
  20595. * @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.
  20596. * @param {TypedArray} [options.values] The values for the attributes stored in a typed array.
  20597. *
  20598. * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
  20599. *
  20600. *
  20601. * @example
  20602. * var geometry = new Cesium.Geometry({
  20603. * attributes : {
  20604. * position : new Cesium.GeometryAttribute({
  20605. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  20606. * componentsPerAttribute : 3,
  20607. * values : new Float32Array([
  20608. * 0.0, 0.0, 0.0,
  20609. * 7500000.0, 0.0, 0.0,
  20610. * 0.0, 7500000.0, 0.0
  20611. * ])
  20612. * })
  20613. * },
  20614. * primitiveType : Cesium.PrimitiveType.LINE_LOOP
  20615. * });
  20616. *
  20617. * @see Geometry
  20618. */
  20619. function GeometryAttribute(options) {
  20620. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20621. if (!defined(options.componentDatatype)) {
  20622. throw new DeveloperError('options.componentDatatype is required.');
  20623. }
  20624. if (!defined(options.componentsPerAttribute)) {
  20625. throw new DeveloperError('options.componentsPerAttribute is required.');
  20626. }
  20627. if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
  20628. throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
  20629. }
  20630. if (!defined(options.values)) {
  20631. throw new DeveloperError('options.values is required.');
  20632. }
  20633. /**
  20634. * The datatype of each component in the attribute, e.g., individual elements in
  20635. * {@link GeometryAttribute#values}.
  20636. *
  20637. * @type ComponentDatatype
  20638. *
  20639. * @default undefined
  20640. */
  20641. this.componentDatatype = options.componentDatatype;
  20642. /**
  20643. * A number between 1 and 4 that defines the number of components in an attributes.
  20644. * For example, a position attribute with x, y, and z components would have 3 as
  20645. * shown in the code example.
  20646. *
  20647. * @type Number
  20648. *
  20649. * @default undefined
  20650. *
  20651. * @example
  20652. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  20653. * attribute.componentsPerAttribute = 3;
  20654. * attribute.values = new Float32Array([
  20655. * 0.0, 0.0, 0.0,
  20656. * 7500000.0, 0.0, 0.0,
  20657. * 0.0, 7500000.0, 0.0
  20658. * ]);
  20659. */
  20660. this.componentsPerAttribute = options.componentsPerAttribute;
  20661. /**
  20662. * When <code>true</code> and <code>componentDatatype</code> is an integer format,
  20663. * indicate that the components should be mapped to the range [0, 1] (unsigned)
  20664. * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  20665. * <p>
  20666. * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
  20667. * </p>
  20668. *
  20669. * @type Boolean
  20670. *
  20671. * @default false
  20672. *
  20673. * @example
  20674. * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
  20675. * attribute.componentsPerAttribute = 4;
  20676. * attribute.normalize = true;
  20677. * attribute.values = new Uint8Array([
  20678. * Cesium.Color.floatToByte(color.red),
  20679. * Cesium.Color.floatToByte(color.green),
  20680. * Cesium.Color.floatToByte(color.blue),
  20681. * Cesium.Color.floatToByte(color.alpha)
  20682. * ]);
  20683. */
  20684. this.normalize = defaultValue(options.normalize, false);
  20685. /**
  20686. * The values for the attributes stored in a typed array. In the code example,
  20687. * every three elements in <code>values</code> defines one attributes since
  20688. * <code>componentsPerAttribute</code> is 3.
  20689. *
  20690. * @type TypedArray
  20691. *
  20692. * @default undefined
  20693. *
  20694. * @example
  20695. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  20696. * attribute.componentsPerAttribute = 3;
  20697. * attribute.values = new Float32Array([
  20698. * 0.0, 0.0, 0.0,
  20699. * 7500000.0, 0.0, 0.0,
  20700. * 0.0, 7500000.0, 0.0
  20701. * ]);
  20702. */
  20703. this.values = options.values;
  20704. }
  20705. return GeometryAttribute;
  20706. });
  20707. /*global define*/
  20708. define('Core/GeometryInstance',[
  20709. './defaultValue',
  20710. './defined',
  20711. './DeveloperError',
  20712. './Matrix4'
  20713. ], function(
  20714. defaultValue,
  20715. defined,
  20716. DeveloperError,
  20717. Matrix4) {
  20718. 'use strict';
  20719. /**
  20720. * Geometry instancing allows one {@link Geometry} object to be positions in several
  20721. * different locations and colored uniquely. For example, one {@link BoxGeometry} can
  20722. * be instanced several times, each with a different <code>modelMatrix</code> to change
  20723. * its position, rotation, and scale.
  20724. *
  20725. * @alias GeometryInstance
  20726. * @constructor
  20727. *
  20728. * @param {Object} options Object with the following properties:
  20729. * @param {Geometry} options.geometry The geometry to instance.
  20730. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The model matrix that transforms to transform the geometry from model to world coordinates.
  20731. * @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}.
  20732. * @param {Object} [options.attributes] Per-instance attributes like a show or color attribute shown in the example below.
  20733. *
  20734. *
  20735. * @example
  20736. * // Create geometry for a box, and two instances that refer to it.
  20737. * // One instance positions the box on the bottom and colored aqua.
  20738. * // The other instance positions the box on the top and color white.
  20739. * var geometry = Cesium.BoxGeometry.fromDimensions({
  20740. * vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL,
  20741. * dimensions : new Cesium.Cartesian3(1000000.0, 1000000.0, 500000.0)
  20742. * });
  20743. * var instanceBottom = new Cesium.GeometryInstance({
  20744. * geometry : geometry,
  20745. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  20746. * Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
  20747. * attributes : {
  20748. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  20749. * },
  20750. * id : 'bottom'
  20751. * });
  20752. * var instanceTop = new Cesium.GeometryInstance({
  20753. * geometry : geometry,
  20754. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  20755. * Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 3000000.0), new Cesium.Matrix4()),
  20756. * attributes : {
  20757. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  20758. * },
  20759. * id : 'top'
  20760. * });
  20761. *
  20762. * @see Geometry
  20763. */
  20764. function GeometryInstance(options) {
  20765. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20766. if (!defined(options.geometry)) {
  20767. throw new DeveloperError('options.geometry is required.');
  20768. }
  20769. /**
  20770. * The geometry being instanced.
  20771. *
  20772. * @type Geometry
  20773. *
  20774. * @default undefined
  20775. */
  20776. this.geometry = options.geometry;
  20777. /**
  20778. * The 4x4 transformation matrix that transforms the geometry from model to world coordinates.
  20779. * When this is the identity matrix, the geometry is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
  20780. * Local reference frames can be used by providing a different transformation matrix, like that returned
  20781. * by {@link Transforms.eastNorthUpToFixedFrame}.
  20782. *
  20783. * @type Matrix4
  20784. *
  20785. * @default Matrix4.IDENTITY
  20786. */
  20787. this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
  20788. /**
  20789. * User-defined object returned when the instance is picked or used to get/set per-instance attributes.
  20790. *
  20791. * @type Object
  20792. *
  20793. * @default undefined
  20794. *
  20795. * @see Scene#pick
  20796. * @see Primitive#getGeometryInstanceAttributes
  20797. */
  20798. this.id = options.id;
  20799. /**
  20800. * Used for picking primitives that wrap geometry instances.
  20801. *
  20802. * @private
  20803. */
  20804. this.pickPrimitive = options.pickPrimitive;
  20805. /**
  20806. * Per-instance attributes like {@link ColorGeometryInstanceAttribute} or {@link ShowGeometryInstanceAttribute}.
  20807. * {@link Geometry} attributes varying per vertex; these attributes are constant for the entire instance.
  20808. *
  20809. * @type Object
  20810. *
  20811. * @default undefined
  20812. */
  20813. this.attributes = defaultValue(options.attributes, {});
  20814. /**
  20815. * @private
  20816. */
  20817. this.westHemisphereGeometry = undefined;
  20818. /**
  20819. * @private
  20820. */
  20821. this.eastHemisphereGeometry = undefined;
  20822. }
  20823. return GeometryInstance;
  20824. });
  20825. /*global define*/
  20826. define('Core/AttributeCompression',[
  20827. './Cartesian2',
  20828. './Cartesian3',
  20829. './defined',
  20830. './DeveloperError',
  20831. './Math'
  20832. ], function(
  20833. Cartesian2,
  20834. Cartesian3,
  20835. defined,
  20836. DeveloperError,
  20837. CesiumMath) {
  20838. 'use strict';
  20839. /**
  20840. * Attribute compression and decompression functions.
  20841. *
  20842. * @exports AttributeCompression
  20843. *
  20844. * @private
  20845. */
  20846. var AttributeCompression = {};
  20847. /**
  20848. * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
  20849. *
  20850. * Oct encoding is a compact representation of unit length vectors.
  20851. * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
  20852. * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
  20853. *
  20854. * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
  20855. * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
  20856. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  20857. * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
  20858. *
  20859. * @exception {DeveloperError} vector must be normalized.
  20860. *
  20861. * @see AttributeCompression.octDecodeInRange
  20862. */
  20863. AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
  20864. if (!defined(vector)) {
  20865. throw new DeveloperError('vector is required.');
  20866. }
  20867. if (!defined(result)) {
  20868. throw new DeveloperError('result is required.');
  20869. }
  20870. var magSquared = Cartesian3.magnitudeSquared(vector);
  20871. if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
  20872. throw new DeveloperError('vector must be normalized.');
  20873. }
  20874. result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  20875. result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  20876. if (vector.z < 0) {
  20877. var x = result.x;
  20878. var y = result.y;
  20879. result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
  20880. result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
  20881. }
  20882. result.x = CesiumMath.toSNorm(result.x, rangeMax);
  20883. result.y = CesiumMath.toSNorm(result.y, rangeMax);
  20884. return result;
  20885. };
  20886. /**
  20887. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
  20888. *
  20889. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  20890. * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
  20891. * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
  20892. *
  20893. * @exception {DeveloperError} vector must be normalized.
  20894. *
  20895. * @see AttributeCompression.octEncodeInRange
  20896. * @see AttributeCompression.octDecode
  20897. */
  20898. AttributeCompression.octEncode = function(vector, result) {
  20899. return AttributeCompression.octEncodeInRange(vector, 255, result);
  20900. };
  20901. /**
  20902. * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
  20903. *
  20904. * @param {Number} x The x component of the oct-encoded unit length vector.
  20905. * @param {Number} y The y component of the oct-encoded unit length vector.
  20906. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  20907. * @param {Cartesian3} result The decoded and normalized vector
  20908. * @returns {Cartesian3} The decoded and normalized vector.
  20909. *
  20910. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and rangeMax.
  20911. *
  20912. * @see AttributeCompression.octEncodeInRange
  20913. */
  20914. AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
  20915. if (!defined(result)) {
  20916. throw new DeveloperError('result is required.');
  20917. }
  20918. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  20919. throw new DeveloperError('x and y must be a signed normalized integer between 0 and ' + rangeMax);
  20920. }
  20921. result.x = CesiumMath.fromSNorm(x, rangeMax);
  20922. result.y = CesiumMath.fromSNorm(y, rangeMax);
  20923. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  20924. if (result.z < 0.0)
  20925. {
  20926. var oldVX = result.x;
  20927. result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
  20928. result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
  20929. }
  20930. return Cartesian3.normalize(result, result);
  20931. };
  20932. /**
  20933. * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
  20934. *
  20935. * @param {Number} x The x component of the oct-encoded unit length vector.
  20936. * @param {Number} y The y component of the oct-encoded unit length vector.
  20937. * @param {Cartesian3} result The decoded and normalized vector.
  20938. * @returns {Cartesian3} The decoded and normalized vector.
  20939. *
  20940. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
  20941. *
  20942. * @see AttributeCompression.octDecodeInRange
  20943. */
  20944. AttributeCompression.octDecode = function(x, y, result) {
  20945. return AttributeCompression.octDecodeInRange(x, y, 255, result);
  20946. };
  20947. /**
  20948. * Packs an oct encoded vector into a single floating-point number.
  20949. *
  20950. * @param {Cartesian2} encoded The oct encoded vector.
  20951. * @returns {Number} The oct encoded vector packed into a single float.
  20952. *
  20953. */
  20954. AttributeCompression.octPackFloat = function(encoded) {
  20955. if (!defined(encoded)) {
  20956. throw new DeveloperError('encoded is required.');
  20957. }
  20958. return 256.0 * encoded.x + encoded.y;
  20959. };
  20960. var scratchEncodeCart2 = new Cartesian2();
  20961. /**
  20962. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
  20963. * stores those values in a single float-point number.
  20964. *
  20965. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  20966. * @returns {Number} The 2 byte oct-encoded unit length vector.
  20967. *
  20968. * @exception {DeveloperError} vector must be normalized.
  20969. */
  20970. AttributeCompression.octEncodeFloat = function(vector) {
  20971. AttributeCompression.octEncode(vector, scratchEncodeCart2);
  20972. return AttributeCompression.octPackFloat(scratchEncodeCart2);
  20973. };
  20974. /**
  20975. * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
  20976. *
  20977. * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
  20978. * @param {Cartesian3} result The decoded and normalized vector
  20979. * @returns {Cartesian3} The decoded and normalized vector.
  20980. *
  20981. */
  20982. AttributeCompression.octDecodeFloat = function(value, result) {
  20983. if (!defined(value)) {
  20984. throw new DeveloperError('value is required.');
  20985. }
  20986. var temp = value / 256.0;
  20987. var x = Math.floor(temp);
  20988. var y = (temp - x) * 256.0;
  20989. return AttributeCompression.octDecode(x, y, result);
  20990. };
  20991. /**
  20992. * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
  20993. * packs those into two floating-point numbers.
  20994. *
  20995. * @param {Cartesian3} v1 A normalized vector to be compressed.
  20996. * @param {Cartesian3} v2 A normalized vector to be compressed.
  20997. * @param {Cartesian3} v3 A normalized vector to be compressed.
  20998. * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
  20999. * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
  21000. *
  21001. */
  21002. AttributeCompression.octPack = function(v1, v2, v3, result) {
  21003. if (!defined(v1)) {
  21004. throw new DeveloperError('v1 is required.');
  21005. }
  21006. if (!defined(v2)) {
  21007. throw new DeveloperError('v2 is required.');
  21008. }
  21009. if (!defined(v3)) {
  21010. throw new DeveloperError('v3 is required.');
  21011. }
  21012. if (!defined(result)) {
  21013. throw new DeveloperError('result is required.');
  21014. }
  21015. var encoded1 = AttributeCompression.octEncodeFloat(v1);
  21016. var encoded2 = AttributeCompression.octEncodeFloat(v2);
  21017. var encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
  21018. result.x = 65536.0 * encoded3.x + encoded1;
  21019. result.y = 65536.0 * encoded3.y + encoded2;
  21020. return result;
  21021. };
  21022. /**
  21023. * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
  21024. *
  21025. * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
  21026. * @param {Cartesian3} v1 One decoded and normalized vector.
  21027. * @param {Cartesian3} v2 One decoded and normalized vector.
  21028. * @param {Cartesian3} v3 One decoded and normalized vector.
  21029. */
  21030. AttributeCompression.octUnpack = function(packed, v1, v2, v3) {
  21031. if (!defined(packed)) {
  21032. throw new DeveloperError('packed is required.');
  21033. }
  21034. if (!defined(v1)) {
  21035. throw new DeveloperError('v1 is required.');
  21036. }
  21037. if (!defined(v2)) {
  21038. throw new DeveloperError('v2 is required.');
  21039. }
  21040. if (!defined(v3)) {
  21041. throw new DeveloperError('v3 is required.');
  21042. }
  21043. var temp = packed.x / 65536.0;
  21044. var x = Math.floor(temp);
  21045. var encodedFloat1 = (temp - x) * 65536.0;
  21046. temp = packed.y / 65536.0;
  21047. var y = Math.floor(temp);
  21048. var encodedFloat2 = (temp - y) * 65536.0;
  21049. AttributeCompression.octDecodeFloat(encodedFloat1, v1);
  21050. AttributeCompression.octDecodeFloat(encodedFloat2, v2);
  21051. AttributeCompression.octDecode(x, y, v3);
  21052. };
  21053. /**
  21054. * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
  21055. *
  21056. * @param {Cartesian2} textureCoordinates The texture coordinates to compress. Both coordinates must be in the range 0.0-1.0.
  21057. * @returns {Number} The packed texture coordinates.
  21058. *
  21059. */
  21060. AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
  21061. if (!defined(textureCoordinates)) {
  21062. throw new DeveloperError('textureCoordinates is required.');
  21063. }
  21064. // Move x and y to the range 0-4095;
  21065. var x = (textureCoordinates.x * 4095.0) | 0;
  21066. var y = (textureCoordinates.y * 4095.0) | 0;
  21067. return 4096.0 * x + y;
  21068. };
  21069. /**
  21070. * Decompresses texture coordinates that were packed into a single float.
  21071. *
  21072. * @param {Number} compressed The compressed texture coordinates.
  21073. * @param {Cartesian2} result The decompressed texture coordinates.
  21074. * @returns {Cartesian2} The modified result parameter.
  21075. *
  21076. */
  21077. AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
  21078. if (!defined(compressed)) {
  21079. throw new DeveloperError('compressed is required.');
  21080. }
  21081. if (!defined(result)) {
  21082. throw new DeveloperError('result is required.');
  21083. }
  21084. var temp = compressed / 4096.0;
  21085. var xZeroTo4095 = Math.floor(temp);
  21086. result.x = xZeroTo4095 / 4095.0;
  21087. result.y = (compressed - xZeroTo4095 * 4096) / 4095;
  21088. return result;
  21089. };
  21090. return AttributeCompression;
  21091. });
  21092. /*global define*/
  21093. define('Core/barycentricCoordinates',[
  21094. './Cartesian2',
  21095. './Cartesian3',
  21096. './defined',
  21097. './DeveloperError'
  21098. ], function(
  21099. Cartesian2,
  21100. Cartesian3,
  21101. defined,
  21102. DeveloperError) {
  21103. 'use strict';
  21104. var scratchCartesian1 = new Cartesian3();
  21105. var scratchCartesian2 = new Cartesian3();
  21106. var scratchCartesian3 = new Cartesian3();
  21107. /**
  21108. * Computes the barycentric coordinates for a point with respect to a triangle.
  21109. *
  21110. * @exports barycentricCoordinates
  21111. *
  21112. * @param {Cartesian2|Cartesian3} point The point to test.
  21113. * @param {Cartesian2|Cartesian3} p0 The first point of the triangle, corresponding to the barycentric x-axis.
  21114. * @param {Cartesian2|Cartesian3} p1 The second point of the triangle, corresponding to the barycentric y-axis.
  21115. * @param {Cartesian2|Cartesian3} p2 The third point of the triangle, corresponding to the barycentric z-axis.
  21116. * @param {Cartesian3} [result] The object onto which to store the result.
  21117. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  21118. *
  21119. * @example
  21120. * // Returns Cartesian3.UNIT_X
  21121. * var p = new Cesium.Cartesian3(-1.0, 0.0, 0.0);
  21122. * var b = Cesium.barycentricCoordinates(p,
  21123. * new Cesium.Cartesian3(-1.0, 0.0, 0.0),
  21124. * new Cesium.Cartesian3( 1.0, 0.0, 0.0),
  21125. * new Cesium.Cartesian3( 0.0, 1.0, 1.0));
  21126. */
  21127. function barycentricCoordinates(point, p0, p1, p2, result) {
  21128. if (!defined(point) || !defined(p0) || !defined(p1) || !defined(p2)) {
  21129. throw new DeveloperError('point, p0, p1, and p2 are required.');
  21130. }
  21131. if (!defined(result)) {
  21132. result = new Cartesian3();
  21133. }
  21134. // Implementation based on http://www.blackpawn.com/texts/pointinpoly/default.html.
  21135. var v0, v1, v2;
  21136. var dot00, dot01, dot02, dot11, dot12;
  21137. if(!defined(p0.z)) {
  21138. v0 = Cartesian2.subtract(p1, p0, scratchCartesian1);
  21139. v1 = Cartesian2.subtract(p2, p0, scratchCartesian2);
  21140. v2 = Cartesian2.subtract(point, p0, scratchCartesian3);
  21141. dot00 = Cartesian2.dot(v0, v0);
  21142. dot01 = Cartesian2.dot(v0, v1);
  21143. dot02 = Cartesian2.dot(v0, v2);
  21144. dot11 = Cartesian2.dot(v1, v1);
  21145. dot12 = Cartesian2.dot(v1, v2);
  21146. } else {
  21147. v0 = Cartesian3.subtract(p1, p0, scratchCartesian1);
  21148. v1 = Cartesian3.subtract(p2, p0, scratchCartesian2);
  21149. v2 = Cartesian3.subtract(point, p0, scratchCartesian3);
  21150. dot00 = Cartesian3.dot(v0, v0);
  21151. dot01 = Cartesian3.dot(v0, v1);
  21152. dot02 = Cartesian3.dot(v0, v2);
  21153. dot11 = Cartesian3.dot(v1, v1);
  21154. dot12 = Cartesian3.dot(v1, v2);
  21155. }
  21156. var q = 1.0 / (dot00 * dot11 - dot01 * dot01);
  21157. result.y = (dot11 * dot02 - dot01 * dot12) * q;
  21158. result.z = (dot00 * dot12 - dot01 * dot02) * q;
  21159. result.x = 1.0 - result.y - result.z;
  21160. return result;
  21161. }
  21162. return barycentricCoordinates;
  21163. });
  21164. /*global define*/
  21165. define('Core/EncodedCartesian3',[
  21166. './Cartesian3',
  21167. './defined',
  21168. './DeveloperError'
  21169. ], function(
  21170. Cartesian3,
  21171. defined,
  21172. DeveloperError) {
  21173. 'use strict';
  21174. /**
  21175. * A fixed-point encoding of a {@link Cartesian3} with 64-bit floating-point components, as two {@link Cartesian3}
  21176. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  21177. * <p>
  21178. * This is used to encode positions in vertex buffers for rendering without jittering artifacts
  21179. * as described in {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  21180. * </p>
  21181. *
  21182. * @alias EncodedCartesian3
  21183. * @constructor
  21184. *
  21185. * @private
  21186. */
  21187. function EncodedCartesian3() {
  21188. /**
  21189. * The high bits for each component. Bits 0 to 22 store the whole value. Bits 23 to 31 are not used.
  21190. *
  21191. * @type {Cartesian3}
  21192. * @default {@link Cartesian3.ZERO}
  21193. */
  21194. this.high = Cartesian3.clone(Cartesian3.ZERO);
  21195. /**
  21196. * 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.
  21197. *
  21198. * @type {Cartesian3}
  21199. * @default {@link Cartesian3.ZERO}
  21200. */
  21201. this.low = Cartesian3.clone(Cartesian3.ZERO);
  21202. }
  21203. /**
  21204. * Encodes a 64-bit floating-point value as two floating-point values that, when converted to
  21205. * 32-bit floating-point and added, approximate the original input. The returned object
  21206. * has <code>high</code> and <code>low</code> properties for the high and low bits, respectively.
  21207. * <p>
  21208. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  21209. * </p>
  21210. *
  21211. * @param {Number} value The floating-point value to encode.
  21212. * @param {Object} [result] The object onto which to store the result.
  21213. * @returns {Object} The modified result parameter or a new instance if one was not provided.
  21214. *
  21215. * @example
  21216. * var value = 1234567.1234567;
  21217. * var splitValue = Cesium.EncodedCartesian3.encode(value);
  21218. */
  21219. EncodedCartesian3.encode = function(value, result) {
  21220. if (!defined(value)) {
  21221. throw new DeveloperError('value is required');
  21222. }
  21223. if (!defined(result)) {
  21224. result = {
  21225. high : 0.0,
  21226. low : 0.0
  21227. };
  21228. }
  21229. var doubleHigh;
  21230. if (value >= 0.0) {
  21231. doubleHigh = Math.floor(value / 65536.0) * 65536.0;
  21232. result.high = doubleHigh;
  21233. result.low = value - doubleHigh;
  21234. } else {
  21235. doubleHigh = Math.floor(-value / 65536.0) * 65536.0;
  21236. result.high = -doubleHigh;
  21237. result.low = value + doubleHigh;
  21238. }
  21239. return result;
  21240. };
  21241. var scratchEncode = {
  21242. high : 0.0,
  21243. low : 0.0
  21244. };
  21245. /**
  21246. * Encodes a {@link Cartesian3} with 64-bit floating-point components as two {@link Cartesian3}
  21247. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  21248. * <p>
  21249. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  21250. * </p>
  21251. *
  21252. * @param {Cartesian3} cartesian The cartesian to encode.
  21253. * @param {EncodedCartesian3} [result] The object onto which to store the result.
  21254. * @returns {EncodedCartesian3} The modified result parameter or a new EncodedCartesian3 instance if one was not provided.
  21255. *
  21256. * @example
  21257. * var cart = new Cesium.Cartesian3(-10000000.0, 0.0, 10000000.0);
  21258. * var encoded = Cesium.EncodedCartesian3.fromCartesian(cart);
  21259. */
  21260. EncodedCartesian3.fromCartesian = function(cartesian, result) {
  21261. if (!defined(cartesian)) {
  21262. throw new DeveloperError('cartesian is required');
  21263. }
  21264. if (!defined(result)) {
  21265. result = new EncodedCartesian3();
  21266. }
  21267. var high = result.high;
  21268. var low = result.low;
  21269. EncodedCartesian3.encode(cartesian.x, scratchEncode);
  21270. high.x = scratchEncode.high;
  21271. low.x = scratchEncode.low;
  21272. EncodedCartesian3.encode(cartesian.y, scratchEncode);
  21273. high.y = scratchEncode.high;
  21274. low.y = scratchEncode.low;
  21275. EncodedCartesian3.encode(cartesian.z, scratchEncode);
  21276. high.z = scratchEncode.high;
  21277. low.z = scratchEncode.low;
  21278. return result;
  21279. };
  21280. var encodedP = new EncodedCartesian3();
  21281. /**
  21282. * Encodes the provided <code>cartesian</code>, and writes it to an array with <code>high</code>
  21283. * components followed by <code>low</code> components, i.e. <code>[high.x, high.y, high.z, low.x, low.y, low.z]</code>.
  21284. * <p>
  21285. * This is used to create interleaved high-precision position vertex attributes.
  21286. * </p>
  21287. *
  21288. * @param {Cartesian3} cartesian The cartesian to encode.
  21289. * @param {Number[]} cartesianArray The array to write to.
  21290. * @param {Number} index The index into the array to start writing. Six elements will be written.
  21291. *
  21292. * @exception {DeveloperError} index must be a number greater than or equal to 0.
  21293. *
  21294. * @example
  21295. * var positions = [
  21296. * new Cesium.Cartesian3(),
  21297. * // ...
  21298. * ];
  21299. * var encodedPositions = new Float32Array(2 * 3 * positions.length);
  21300. * var j = 0;
  21301. * for (var i = 0; i < positions.length; ++i) {
  21302. * Cesium.EncodedCartesian3.writeElement(positions[i], encodedPositions, j);
  21303. * j += 6;
  21304. * }
  21305. */
  21306. EncodedCartesian3.writeElements = function(cartesian, cartesianArray, index) {
  21307. if (!defined(cartesian)) {
  21308. throw new DeveloperError('cartesian is required');
  21309. }
  21310. if (!defined(cartesianArray)) {
  21311. throw new DeveloperError('cartesianArray is required');
  21312. }
  21313. if (typeof index !== 'number' || index < 0) {
  21314. throw new DeveloperError('index must be a number greater than or equal to 0.');
  21315. }
  21316. EncodedCartesian3.fromCartesian(cartesian, encodedP);
  21317. var high = encodedP.high;
  21318. var low = encodedP.low;
  21319. cartesianArray[index] = high.x;
  21320. cartesianArray[index + 1] = high.y;
  21321. cartesianArray[index + 2] = high.z;
  21322. cartesianArray[index + 3] = low.x;
  21323. cartesianArray[index + 4] = low.y;
  21324. cartesianArray[index + 5] = low.z;
  21325. };
  21326. return EncodedCartesian3;
  21327. });
  21328. /*global define*/
  21329. define('Core/IndexDatatype',[
  21330. './defined',
  21331. './DeveloperError',
  21332. './freezeObject',
  21333. './Math',
  21334. './WebGLConstants'
  21335. ], function(
  21336. defined,
  21337. DeveloperError,
  21338. freezeObject,
  21339. CesiumMath,
  21340. WebGLConstants) {
  21341. 'use strict';
  21342. /**
  21343. * Constants for WebGL index datatypes. These corresponds to the
  21344. * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
  21345. *
  21346. * @exports IndexDatatype
  21347. */
  21348. var IndexDatatype = {
  21349. /**
  21350. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  21351. * of an element in <code>Uint8Array</code>.
  21352. *
  21353. * @type {Number}
  21354. * @constant
  21355. */
  21356. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  21357. /**
  21358. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  21359. * of an element in <code>Uint16Array</code>.
  21360. *
  21361. * @type {Number}
  21362. * @constant
  21363. */
  21364. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  21365. /**
  21366. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  21367. * of an element in <code>Uint32Array</code>.
  21368. *
  21369. * @type {Number}
  21370. * @constant
  21371. */
  21372. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
  21373. };
  21374. /**
  21375. * Returns the size, in bytes, of the corresponding datatype.
  21376. *
  21377. * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
  21378. * @returns {Number} The size in bytes.
  21379. *
  21380. * @example
  21381. * // Returns 2
  21382. * var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
  21383. */
  21384. IndexDatatype.getSizeInBytes = function(indexDatatype) {
  21385. switch(indexDatatype) {
  21386. case IndexDatatype.UNSIGNED_BYTE:
  21387. return Uint8Array.BYTES_PER_ELEMENT;
  21388. case IndexDatatype.UNSIGNED_SHORT:
  21389. return Uint16Array.BYTES_PER_ELEMENT;
  21390. case IndexDatatype.UNSIGNED_INT:
  21391. return Uint32Array.BYTES_PER_ELEMENT;
  21392. }
  21393. throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
  21394. };
  21395. /**
  21396. * Validates that the provided index datatype is a valid {@link IndexDatatype}.
  21397. *
  21398. * @param {IndexDatatype} indexDatatype The index datatype to validate.
  21399. * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
  21400. *
  21401. * @example
  21402. * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
  21403. * throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
  21404. * }
  21405. */
  21406. IndexDatatype.validate = function(indexDatatype) {
  21407. return defined(indexDatatype) &&
  21408. (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
  21409. indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
  21410. indexDatatype === IndexDatatype.UNSIGNED_INT);
  21411. };
  21412. /**
  21413. * Creates a typed array that will store indices, using either <code><Uint16Array</code>
  21414. * or <code>Uint32Array</code> depending on the number of vertices.
  21415. *
  21416. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  21417. * @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
  21418. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
  21419. *
  21420. * @example
  21421. * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
  21422. */
  21423. IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
  21424. if (!defined(numberOfVertices)) {
  21425. throw new DeveloperError('numberOfVertices is required.');
  21426. }
  21427. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  21428. return new Uint32Array(indicesLengthOrArray);
  21429. }
  21430. return new Uint16Array(indicesLengthOrArray);
  21431. };
  21432. /**
  21433. * Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
  21434. * or <code>Uint32Array</code> depending on the number of vertices.
  21435. *
  21436. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  21437. * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
  21438. * @param {Number} byteOffset Passed through to the typed array constructor.
  21439. * @param {Number} length Passed through to the typed array constructor.
  21440. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
  21441. *
  21442. */
  21443. IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
  21444. if (!defined(numberOfVertices)) {
  21445. throw new DeveloperError('numberOfVertices is required.');
  21446. }
  21447. if (!defined(sourceArray)) {
  21448. throw new DeveloperError('sourceArray is required.');
  21449. }
  21450. if (!defined(byteOffset)) {
  21451. throw new DeveloperError('byteOffset is required.');
  21452. }
  21453. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  21454. return new Uint32Array(sourceArray, byteOffset, length);
  21455. }
  21456. return new Uint16Array(sourceArray, byteOffset, length);
  21457. };
  21458. return freezeObject(IndexDatatype);
  21459. });
  21460. /*global define*/
  21461. define('Core/Tipsify',[
  21462. './defaultValue',
  21463. './defined',
  21464. './DeveloperError'
  21465. ], function(
  21466. defaultValue,
  21467. defined,
  21468. DeveloperError) {
  21469. 'use strict';
  21470. /**
  21471. * Encapsulates an algorithm to optimize triangles for the post
  21472. * vertex-shader cache. This is based on the 2007 SIGGRAPH paper
  21473. * 'Fast Triangle Reordering for Vertex Locality and Reduced Overdraw.'
  21474. * The runtime is linear but several passes are made.
  21475. *
  21476. * @exports Tipsify
  21477. *
  21478. * @see <a href='http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf'>
  21479. * Fast Triangle Reordering for Vertex Locality and Reduced Overdraw</a>
  21480. * by Sander, Nehab, and Barczak
  21481. *
  21482. * @private
  21483. */
  21484. var Tipsify = {};
  21485. /**
  21486. * Calculates the average cache miss ratio (ACMR) for a given set of indices.
  21487. *
  21488. * @param {Object} options Object with the following properties:
  21489. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  21490. * in the vertex buffer that define the geometry's triangles.
  21491. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  21492. * If not supplied, this value will be computed.
  21493. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  21494. * @returns {Number} The average cache miss ratio (ACMR).
  21495. *
  21496. * @exception {DeveloperError} indices length must be a multiple of three.
  21497. * @exception {DeveloperError} cacheSize must be greater than two.
  21498. *
  21499. * @example
  21500. * var indices = [0, 1, 2, 3, 4, 5];
  21501. * var maxIndex = 5;
  21502. * var cacheSize = 3;
  21503. * var acmr = Cesium.Tipsify.calculateACMR({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  21504. */
  21505. Tipsify.calculateACMR = function(options) {
  21506. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21507. var indices = options.indices;
  21508. var maximumIndex = options.maximumIndex;
  21509. var cacheSize = defaultValue(options.cacheSize, 24);
  21510. if (!defined(indices)) {
  21511. throw new DeveloperError('indices is required.');
  21512. }
  21513. var numIndices = indices.length;
  21514. if (numIndices < 3 || numIndices % 3 !== 0) {
  21515. throw new DeveloperError('indices length must be a multiple of three.');
  21516. }
  21517. if (maximumIndex <= 0) {
  21518. throw new DeveloperError('maximumIndex must be greater than zero.');
  21519. }
  21520. if (cacheSize < 3) {
  21521. throw new DeveloperError('cacheSize must be greater than two.');
  21522. }
  21523. // Compute the maximumIndex if not given
  21524. if (!defined(maximumIndex)) {
  21525. maximumIndex = 0;
  21526. var currentIndex = 0;
  21527. var intoIndices = indices[currentIndex];
  21528. while (currentIndex < numIndices) {
  21529. if (intoIndices > maximumIndex) {
  21530. maximumIndex = intoIndices;
  21531. }
  21532. ++currentIndex;
  21533. intoIndices = indices[currentIndex];
  21534. }
  21535. }
  21536. // Vertex time stamps
  21537. var vertexTimeStamps = [];
  21538. for ( var i = 0; i < maximumIndex + 1; i++) {
  21539. vertexTimeStamps[i] = 0;
  21540. }
  21541. // Cache processing
  21542. var s = cacheSize + 1;
  21543. for ( var j = 0; j < numIndices; ++j) {
  21544. if ((s - vertexTimeStamps[indices[j]]) > cacheSize) {
  21545. vertexTimeStamps[indices[j]] = s;
  21546. ++s;
  21547. }
  21548. }
  21549. return (s - cacheSize + 1) / (numIndices / 3);
  21550. };
  21551. /**
  21552. * Optimizes triangles for the post-vertex shader cache.
  21553. *
  21554. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  21555. * in the vertex buffer that define the geometry's triangles.
  21556. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  21557. * If not supplied, this value will be computed.
  21558. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  21559. * @returns {Number[]} A list of the input indices in an optimized order.
  21560. *
  21561. * @exception {DeveloperError} indices length must be a multiple of three.
  21562. * @exception {DeveloperError} cacheSize must be greater than two.
  21563. *
  21564. * @example
  21565. * var indices = [0, 1, 2, 3, 4, 5];
  21566. * var maxIndex = 5;
  21567. * var cacheSize = 3;
  21568. * var reorderedIndices = Cesium.Tipsify.tipsify({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  21569. */
  21570. Tipsify.tipsify = function(options) {
  21571. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21572. var indices = options.indices;
  21573. var maximumIndex = options.maximumIndex;
  21574. var cacheSize = defaultValue(options.cacheSize, 24);
  21575. var cursor;
  21576. function skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne) {
  21577. while (deadEnd.length >= 1) {
  21578. // while the stack is not empty
  21579. var d = deadEnd[deadEnd.length - 1]; // top of the stack
  21580. deadEnd.splice(deadEnd.length - 1, 1); // pop the stack
  21581. if (vertices[d].numLiveTriangles > 0) {
  21582. return d;
  21583. }
  21584. }
  21585. while (cursor < maximumIndexPlusOne) {
  21586. if (vertices[cursor].numLiveTriangles > 0) {
  21587. ++cursor;
  21588. return cursor - 1;
  21589. }
  21590. ++cursor;
  21591. }
  21592. return -1;
  21593. }
  21594. function getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne) {
  21595. var n = -1;
  21596. var p;
  21597. var m = -1;
  21598. var itOneRing = 0;
  21599. while (itOneRing < oneRing.length) {
  21600. var index = oneRing[itOneRing];
  21601. if (vertices[index].numLiveTriangles) {
  21602. p = 0;
  21603. if ((s - vertices[index].timeStamp + (2 * vertices[index].numLiveTriangles)) <= cacheSize) {
  21604. p = s - vertices[index].timeStamp;
  21605. }
  21606. if ((p > m) || (m === -1)) {
  21607. m = p;
  21608. n = index;
  21609. }
  21610. }
  21611. ++itOneRing;
  21612. }
  21613. if (n === -1) {
  21614. return skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne);
  21615. }
  21616. return n;
  21617. }
  21618. if (!defined(indices)) {
  21619. throw new DeveloperError('indices is required.');
  21620. }
  21621. var numIndices = indices.length;
  21622. if (numIndices < 3 || numIndices % 3 !== 0) {
  21623. throw new DeveloperError('indices length must be a multiple of three.');
  21624. }
  21625. if (maximumIndex <= 0) {
  21626. throw new DeveloperError('maximumIndex must be greater than zero.');
  21627. }
  21628. if (cacheSize < 3) {
  21629. throw new DeveloperError('cacheSize must be greater than two.');
  21630. }
  21631. // Determine maximum index
  21632. var maximumIndexPlusOne = 0;
  21633. var currentIndex = 0;
  21634. var intoIndices = indices[currentIndex];
  21635. var endIndex = numIndices;
  21636. if (defined(maximumIndex)) {
  21637. maximumIndexPlusOne = maximumIndex + 1;
  21638. } else {
  21639. while (currentIndex < endIndex) {
  21640. if (intoIndices > maximumIndexPlusOne) {
  21641. maximumIndexPlusOne = intoIndices;
  21642. }
  21643. ++currentIndex;
  21644. intoIndices = indices[currentIndex];
  21645. }
  21646. if (maximumIndexPlusOne === -1) {
  21647. return 0;
  21648. }
  21649. ++maximumIndexPlusOne;
  21650. }
  21651. // Vertices
  21652. var vertices = [];
  21653. for ( var i = 0; i < maximumIndexPlusOne; i++) {
  21654. vertices[i] = {
  21655. numLiveTriangles : 0,
  21656. timeStamp : 0,
  21657. vertexTriangles : []
  21658. };
  21659. }
  21660. currentIndex = 0;
  21661. var triangle = 0;
  21662. while (currentIndex < endIndex) {
  21663. vertices[indices[currentIndex]].vertexTriangles.push(triangle);
  21664. ++(vertices[indices[currentIndex]]).numLiveTriangles;
  21665. vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
  21666. ++(vertices[indices[currentIndex + 1]]).numLiveTriangles;
  21667. vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
  21668. ++(vertices[indices[currentIndex + 2]]).numLiveTriangles;
  21669. ++triangle;
  21670. currentIndex += 3;
  21671. }
  21672. // Starting index
  21673. var f = 0;
  21674. // Time Stamp
  21675. var s = cacheSize + 1;
  21676. cursor = 1;
  21677. // Process
  21678. var oneRing = [];
  21679. var deadEnd = []; //Stack
  21680. var vertex;
  21681. var intoVertices;
  21682. var currentOutputIndex = 0;
  21683. var outputIndices = [];
  21684. var numTriangles = numIndices / 3;
  21685. var triangleEmitted = [];
  21686. for (i = 0; i < numTriangles; i++) {
  21687. triangleEmitted[i] = false;
  21688. }
  21689. var index;
  21690. var limit;
  21691. while (f !== -1) {
  21692. oneRing = [];
  21693. intoVertices = vertices[f];
  21694. limit = intoVertices.vertexTriangles.length;
  21695. for ( var k = 0; k < limit; ++k) {
  21696. triangle = intoVertices.vertexTriangles[k];
  21697. if (!triangleEmitted[triangle]) {
  21698. triangleEmitted[triangle] = true;
  21699. currentIndex = triangle + triangle + triangle;
  21700. for ( var j = 0; j < 3; ++j) {
  21701. // Set this index as a possible next index
  21702. index = indices[currentIndex];
  21703. oneRing.push(index);
  21704. deadEnd.push(index);
  21705. // Output index
  21706. outputIndices[currentOutputIndex] = index;
  21707. ++currentOutputIndex;
  21708. // Cache processing
  21709. vertex = vertices[index];
  21710. --vertex.numLiveTriangles;
  21711. if ((s - vertex.timeStamp) > cacheSize) {
  21712. vertex.timeStamp = s;
  21713. ++s;
  21714. }
  21715. ++currentIndex;
  21716. }
  21717. }
  21718. }
  21719. f = getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne);
  21720. }
  21721. return outputIndices;
  21722. };
  21723. return Tipsify;
  21724. });
  21725. /*global define*/
  21726. define('Core/GeometryPipeline',[
  21727. './AttributeCompression',
  21728. './barycentricCoordinates',
  21729. './BoundingSphere',
  21730. './Cartesian2',
  21731. './Cartesian3',
  21732. './Cartesian4',
  21733. './Cartographic',
  21734. './ComponentDatatype',
  21735. './defaultValue',
  21736. './defined',
  21737. './DeveloperError',
  21738. './EncodedCartesian3',
  21739. './GeographicProjection',
  21740. './Geometry',
  21741. './GeometryAttribute',
  21742. './GeometryType',
  21743. './IndexDatatype',
  21744. './Intersect',
  21745. './IntersectionTests',
  21746. './Math',
  21747. './Matrix3',
  21748. './Matrix4',
  21749. './Plane',
  21750. './PrimitiveType',
  21751. './Tipsify'
  21752. ], function(
  21753. AttributeCompression,
  21754. barycentricCoordinates,
  21755. BoundingSphere,
  21756. Cartesian2,
  21757. Cartesian3,
  21758. Cartesian4,
  21759. Cartographic,
  21760. ComponentDatatype,
  21761. defaultValue,
  21762. defined,
  21763. DeveloperError,
  21764. EncodedCartesian3,
  21765. GeographicProjection,
  21766. Geometry,
  21767. GeometryAttribute,
  21768. GeometryType,
  21769. IndexDatatype,
  21770. Intersect,
  21771. IntersectionTests,
  21772. CesiumMath,
  21773. Matrix3,
  21774. Matrix4,
  21775. Plane,
  21776. PrimitiveType,
  21777. Tipsify) {
  21778. 'use strict';
  21779. /**
  21780. * Content pipeline functions for geometries.
  21781. *
  21782. * @exports GeometryPipeline
  21783. *
  21784. * @see Geometry
  21785. */
  21786. var GeometryPipeline = {};
  21787. function addTriangle(lines, index, i0, i1, i2) {
  21788. lines[index++] = i0;
  21789. lines[index++] = i1;
  21790. lines[index++] = i1;
  21791. lines[index++] = i2;
  21792. lines[index++] = i2;
  21793. lines[index] = i0;
  21794. }
  21795. function trianglesToLines(triangles) {
  21796. var count = triangles.length;
  21797. var size = (count / 3) * 6;
  21798. var lines = IndexDatatype.createTypedArray(count, size);
  21799. var index = 0;
  21800. for ( var i = 0; i < count; i += 3, index += 6) {
  21801. addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
  21802. }
  21803. return lines;
  21804. }
  21805. function triangleStripToLines(triangles) {
  21806. var count = triangles.length;
  21807. if (count >= 3) {
  21808. var size = (count - 2) * 6;
  21809. var lines = IndexDatatype.createTypedArray(count, size);
  21810. addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
  21811. var index = 6;
  21812. for ( var i = 3; i < count; ++i, index += 6) {
  21813. addTriangle(lines, index, triangles[i - 1], triangles[i], triangles[i - 2]);
  21814. }
  21815. return lines;
  21816. }
  21817. return new Uint16Array();
  21818. }
  21819. function triangleFanToLines(triangles) {
  21820. if (triangles.length > 0) {
  21821. var count = triangles.length - 1;
  21822. var size = (count - 1) * 6;
  21823. var lines = IndexDatatype.createTypedArray(count, size);
  21824. var base = triangles[0];
  21825. var index = 0;
  21826. for ( var i = 1; i < count; ++i, index += 6) {
  21827. addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
  21828. }
  21829. return lines;
  21830. }
  21831. return new Uint16Array();
  21832. }
  21833. /**
  21834. * Converts a geometry's triangle indices to line indices. If the geometry has an <code>indices</code>
  21835. * and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>,
  21836. * <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed.
  21837. * <p>
  21838. * This is commonly used to create a wireframe geometry for visual debugging.
  21839. * </p>
  21840. *
  21841. * @param {Geometry} geometry The geometry to modify.
  21842. * @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines.
  21843. *
  21844. * @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.
  21845. *
  21846. * @example
  21847. * geometry = Cesium.GeometryPipeline.toWireframe(geometry);
  21848. */
  21849. GeometryPipeline.toWireframe = function(geometry) {
  21850. if (!defined(geometry)) {
  21851. throw new DeveloperError('geometry is required.');
  21852. }
  21853. var indices = geometry.indices;
  21854. if (defined(indices)) {
  21855. switch (geometry.primitiveType) {
  21856. case PrimitiveType.TRIANGLES:
  21857. geometry.indices = trianglesToLines(indices);
  21858. break;
  21859. case PrimitiveType.TRIANGLE_STRIP:
  21860. geometry.indices = triangleStripToLines(indices);
  21861. break;
  21862. case PrimitiveType.TRIANGLE_FAN:
  21863. geometry.indices = triangleFanToLines(indices);
  21864. break;
  21865. default:
  21866. throw new DeveloperError('geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.');
  21867. }
  21868. geometry.primitiveType = PrimitiveType.LINES;
  21869. }
  21870. return geometry;
  21871. };
  21872. /**
  21873. * Creates a new {@link Geometry} with <code>LINES</code> representing the provided
  21874. * attribute (<code>attributeName</code>) for the provided geometry. This is used to
  21875. * visualize vector attributes like normals, binormals, and tangents.
  21876. *
  21877. * @param {Geometry} geometry The <code>Geometry</code> instance with the attribute.
  21878. * @param {String} [attributeName='normal'] The name of the attribute.
  21879. * @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.
  21880. * @returns {Geometry} A new <code>Geometry</code> instance with line segments for the vector.
  21881. *
  21882. * @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter.
  21883. *
  21884. * @example
  21885. * var geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'binormal', 100000.0);
  21886. */
  21887. GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length) {
  21888. attributeName = defaultValue(attributeName, 'normal');
  21889. if (!defined(geometry)) {
  21890. throw new DeveloperError('geometry is required.');
  21891. }
  21892. if (!defined(geometry.attributes.position)) {
  21893. throw new DeveloperError('geometry.attributes.position is required.');
  21894. }
  21895. if (!defined(geometry.attributes[attributeName])) {
  21896. throw new DeveloperError('geometry.attributes must have an attribute with the same name as the attributeName parameter, ' + attributeName + '.');
  21897. }
  21898. length = defaultValue(length, 10000.0);
  21899. var positions = geometry.attributes.position.values;
  21900. var vectors = geometry.attributes[attributeName].values;
  21901. var positionsLength = positions.length;
  21902. var newPositions = new Float64Array(2 * positionsLength);
  21903. var j = 0;
  21904. for (var i = 0; i < positionsLength; i += 3) {
  21905. newPositions[j++] = positions[i];
  21906. newPositions[j++] = positions[i + 1];
  21907. newPositions[j++] = positions[i + 2];
  21908. newPositions[j++] = positions[i] + (vectors[i] * length);
  21909. newPositions[j++] = positions[i + 1] + (vectors[i + 1] * length);
  21910. newPositions[j++] = positions[i + 2] + (vectors[i + 2] * length);
  21911. }
  21912. var newBoundingSphere;
  21913. var bs = geometry.boundingSphere;
  21914. if (defined(bs)) {
  21915. newBoundingSphere = new BoundingSphere(bs.center, bs.radius + length);
  21916. }
  21917. return new Geometry({
  21918. attributes : {
  21919. position : new GeometryAttribute({
  21920. componentDatatype : ComponentDatatype.DOUBLE,
  21921. componentsPerAttribute : 3,
  21922. values : newPositions
  21923. })
  21924. },
  21925. primitiveType : PrimitiveType.LINES,
  21926. boundingSphere : newBoundingSphere
  21927. });
  21928. };
  21929. /**
  21930. * Creates an object that maps attribute names to unique locations (indices)
  21931. * for matching vertex attributes and shader programs.
  21932. *
  21933. * @param {Geometry} geometry The geometry, which is not modified, to create the object for.
  21934. * @returns {Object} An object with attribute name / index pairs.
  21935. *
  21936. * @example
  21937. * var attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry);
  21938. * // Example output
  21939. * // {
  21940. * // 'position' : 0,
  21941. * // 'normal' : 1
  21942. * // }
  21943. */
  21944. GeometryPipeline.createAttributeLocations = function(geometry) {
  21945. if (!defined(geometry)) {
  21946. throw new DeveloperError('geometry is required.');
  21947. }
  21948. // There can be a WebGL performance hit when attribute 0 is disabled, so
  21949. // assign attribute locations to well-known attributes.
  21950. var semantics = [
  21951. 'position',
  21952. 'positionHigh',
  21953. 'positionLow',
  21954. // From VertexFormat.position - after 2D projection and high-precision encoding
  21955. 'position3DHigh',
  21956. 'position3DLow',
  21957. 'position2DHigh',
  21958. 'position2DLow',
  21959. // From Primitive
  21960. 'pickColor',
  21961. // From VertexFormat
  21962. 'normal',
  21963. 'st',
  21964. 'binormal',
  21965. 'tangent',
  21966. // From compressing texture coordinates and normals
  21967. 'compressedAttributes'
  21968. ];
  21969. var attributes = geometry.attributes;
  21970. var indices = {};
  21971. var j = 0;
  21972. var i;
  21973. var len = semantics.length;
  21974. // Attribute locations for well-known attributes
  21975. for (i = 0; i < len; ++i) {
  21976. var semantic = semantics[i];
  21977. if (defined(attributes[semantic])) {
  21978. indices[semantic] = j++;
  21979. }
  21980. }
  21981. // Locations for custom attributes
  21982. for (var name in attributes) {
  21983. if (attributes.hasOwnProperty(name) && (!defined(indices[name]))) {
  21984. indices[name] = j++;
  21985. }
  21986. }
  21987. return indices;
  21988. };
  21989. /**
  21990. * Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache.
  21991. *
  21992. * @param {Geometry} geometry The geometry to modify.
  21993. * @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache.
  21994. *
  21995. * @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes.
  21996. *
  21997. *
  21998. * @example
  21999. * geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry);
  22000. *
  22001. * @see GeometryPipeline.reorderForPostVertexCache
  22002. */
  22003. GeometryPipeline.reorderForPreVertexCache = function(geometry) {
  22004. if (!defined(geometry)) {
  22005. throw new DeveloperError('geometry is required.');
  22006. }
  22007. var numVertices = Geometry.computeNumberOfVertices(geometry);
  22008. var indices = geometry.indices;
  22009. if (defined(indices)) {
  22010. var indexCrossReferenceOldToNew = new Int32Array(numVertices);
  22011. for ( var i = 0; i < numVertices; i++) {
  22012. indexCrossReferenceOldToNew[i] = -1;
  22013. }
  22014. // Construct cross reference and reorder indices
  22015. var indicesIn = indices;
  22016. var numIndices = indicesIn.length;
  22017. var indicesOut = IndexDatatype.createTypedArray(numVertices, numIndices);
  22018. var intoIndicesIn = 0;
  22019. var intoIndicesOut = 0;
  22020. var nextIndex = 0;
  22021. var tempIndex;
  22022. while (intoIndicesIn < numIndices) {
  22023. tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
  22024. if (tempIndex !== -1) {
  22025. indicesOut[intoIndicesOut] = tempIndex;
  22026. } else {
  22027. tempIndex = indicesIn[intoIndicesIn];
  22028. indexCrossReferenceOldToNew[tempIndex] = nextIndex;
  22029. indicesOut[intoIndicesOut] = nextIndex;
  22030. ++nextIndex;
  22031. }
  22032. ++intoIndicesIn;
  22033. ++intoIndicesOut;
  22034. }
  22035. geometry.indices = indicesOut;
  22036. // Reorder attributes
  22037. var attributes = geometry.attributes;
  22038. for ( var property in attributes) {
  22039. if (attributes.hasOwnProperty(property) &&
  22040. defined(attributes[property]) &&
  22041. defined(attributes[property].values)) {
  22042. var attribute = attributes[property];
  22043. var elementsIn = attribute.values;
  22044. var intoElementsIn = 0;
  22045. var numComponents = attribute.componentsPerAttribute;
  22046. var elementsOut = ComponentDatatype.createTypedArray(attribute.componentDatatype, nextIndex * numComponents);
  22047. while (intoElementsIn < numVertices) {
  22048. var temp = indexCrossReferenceOldToNew[intoElementsIn];
  22049. if (temp !== -1) {
  22050. for (i = 0; i < numComponents; i++) {
  22051. elementsOut[numComponents * temp + i] = elementsIn[numComponents * intoElementsIn + i];
  22052. }
  22053. }
  22054. ++intoElementsIn;
  22055. }
  22056. attribute.values = elementsOut;
  22057. }
  22058. }
  22059. }
  22060. return geometry;
  22061. };
  22062. /**
  22063. * Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's
  22064. * post vertex-shader cache by using the Tipsify algorithm. If the geometry <code>primitiveType</code>
  22065. * is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect.
  22066. *
  22067. * @param {Geometry} geometry The geometry to modify.
  22068. * @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache.
  22069. * @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache.
  22070. *
  22071. * @exception {DeveloperError} cacheCapacity must be greater than two.
  22072. *
  22073. *
  22074. * @example
  22075. * geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry);
  22076. *
  22077. * @see GeometryPipeline.reorderForPreVertexCache
  22078. * @see {@link http://gfx.cs.princ0eton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw}
  22079. * by Sander, Nehab, and Barczak
  22080. */
  22081. GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) {
  22082. if (!defined(geometry)) {
  22083. throw new DeveloperError('geometry is required.');
  22084. }
  22085. var indices = geometry.indices;
  22086. if ((geometry.primitiveType === PrimitiveType.TRIANGLES) && (defined(indices))) {
  22087. var numIndices = indices.length;
  22088. var maximumIndex = 0;
  22089. for ( var j = 0; j < numIndices; j++) {
  22090. if (indices[j] > maximumIndex) {
  22091. maximumIndex = indices[j];
  22092. }
  22093. }
  22094. geometry.indices = Tipsify.tipsify({
  22095. indices : indices,
  22096. maximumIndex : maximumIndex,
  22097. cacheSize : cacheCapacity
  22098. });
  22099. }
  22100. return geometry;
  22101. };
  22102. function copyAttributesDescriptions(attributes) {
  22103. var newAttributes = {};
  22104. for ( var attribute in attributes) {
  22105. if (attributes.hasOwnProperty(attribute) &&
  22106. defined(attributes[attribute]) &&
  22107. defined(attributes[attribute].values)) {
  22108. var attr = attributes[attribute];
  22109. newAttributes[attribute] = new GeometryAttribute({
  22110. componentDatatype : attr.componentDatatype,
  22111. componentsPerAttribute : attr.componentsPerAttribute,
  22112. normalize : attr.normalize,
  22113. values : []
  22114. });
  22115. }
  22116. }
  22117. return newAttributes;
  22118. }
  22119. function copyVertex(destinationAttributes, sourceAttributes, index) {
  22120. for ( var attribute in sourceAttributes) {
  22121. if (sourceAttributes.hasOwnProperty(attribute) &&
  22122. defined(sourceAttributes[attribute]) &&
  22123. defined(sourceAttributes[attribute].values)) {
  22124. var attr = sourceAttributes[attribute];
  22125. for ( var k = 0; k < attr.componentsPerAttribute; ++k) {
  22126. destinationAttributes[attribute].values.push(attr.values[(index * attr.componentsPerAttribute) + k]);
  22127. }
  22128. }
  22129. }
  22130. }
  22131. /**
  22132. * Splits a geometry into multiple geometries, if necessary, to ensure that indices in the
  22133. * <code>indices</code> fit into unsigned shorts. This is used to meet the WebGL requirements
  22134. * when unsigned int indices are not supported.
  22135. * <p>
  22136. * If the geometry does not have any <code>indices</code>, this function has no effect.
  22137. * </p>
  22138. *
  22139. * @param {Geometry} geometry The geometry to be split into multiple geometries.
  22140. * @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts.
  22141. *
  22142. * @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS
  22143. * @exception {DeveloperError} All geometry attribute lists must have the same number of attributes.
  22144. *
  22145. * @example
  22146. * var geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry);
  22147. */
  22148. GeometryPipeline.fitToUnsignedShortIndices = function(geometry) {
  22149. if (!defined(geometry)) {
  22150. throw new DeveloperError('geometry is required.');
  22151. }
  22152. if ((defined(geometry.indices)) &&
  22153. ((geometry.primitiveType !== PrimitiveType.TRIANGLES) &&
  22154. (geometry.primitiveType !== PrimitiveType.LINES) &&
  22155. (geometry.primitiveType !== PrimitiveType.POINTS))) {
  22156. throw new DeveloperError('geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS.');
  22157. }
  22158. var geometries = [];
  22159. // If there's an index list and more than 64K attributes, it is possible that
  22160. // some indices are outside the range of unsigned short [0, 64K - 1]
  22161. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22162. if (defined(geometry.indices) && (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES)) {
  22163. var oldToNewIndex = [];
  22164. var newIndices = [];
  22165. var currentIndex = 0;
  22166. var newAttributes = copyAttributesDescriptions(geometry.attributes);
  22167. var originalIndices = geometry.indices;
  22168. var numberOfIndices = originalIndices.length;
  22169. var indicesPerPrimitive;
  22170. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  22171. indicesPerPrimitive = 3;
  22172. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  22173. indicesPerPrimitive = 2;
  22174. } else if (geometry.primitiveType === PrimitiveType.POINTS) {
  22175. indicesPerPrimitive = 1;
  22176. }
  22177. for ( var j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
  22178. for (var k = 0; k < indicesPerPrimitive; ++k) {
  22179. var x = originalIndices[j + k];
  22180. var i = oldToNewIndex[x];
  22181. if (!defined(i)) {
  22182. i = currentIndex++;
  22183. oldToNewIndex[x] = i;
  22184. copyVertex(newAttributes, geometry.attributes, x);
  22185. }
  22186. newIndices.push(i);
  22187. }
  22188. if (currentIndex + indicesPerPrimitive >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  22189. geometries.push(new Geometry({
  22190. attributes : newAttributes,
  22191. indices : newIndices,
  22192. primitiveType : geometry.primitiveType,
  22193. boundingSphere : geometry.boundingSphere,
  22194. boundingSphereCV : geometry.boundingSphereCV
  22195. }));
  22196. // Reset for next vertex-array
  22197. oldToNewIndex = [];
  22198. newIndices = [];
  22199. currentIndex = 0;
  22200. newAttributes = copyAttributesDescriptions(geometry.attributes);
  22201. }
  22202. }
  22203. if (newIndices.length !== 0) {
  22204. geometries.push(new Geometry({
  22205. attributes : newAttributes,
  22206. indices : newIndices,
  22207. primitiveType : geometry.primitiveType,
  22208. boundingSphere : geometry.boundingSphere,
  22209. boundingSphereCV : geometry.boundingSphereCV
  22210. }));
  22211. }
  22212. } else {
  22213. // No need to split into multiple geometries
  22214. geometries.push(geometry);
  22215. }
  22216. return geometries;
  22217. };
  22218. var scratchProjectTo2DCartesian3 = new Cartesian3();
  22219. var scratchProjectTo2DCartographic = new Cartographic();
  22220. /**
  22221. * Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code>
  22222. * attribute with separate <code>position3D</code> and <code>position2D</code> attributes.
  22223. * <p>
  22224. * If the geometry does not have a <code>position</code>, this function has no effect.
  22225. * </p>
  22226. *
  22227. * @param {Geometry} geometry The geometry to modify.
  22228. * @param {String} attributeName The name of the attribute.
  22229. * @param {String} attributeName3D The name of the attribute in 3D.
  22230. * @param {String} attributeName2D The name of the attribute in 2D.
  22231. * @param {Object} [projection=new GeographicProjection()] The projection to use.
  22232. * @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes.
  22233. *
  22234. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  22235. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  22236. * @exception {DeveloperError} Could not project a point to 2D.
  22237. *
  22238. * @example
  22239. * geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D');
  22240. */
  22241. GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) {
  22242. if (!defined(geometry)) {
  22243. throw new DeveloperError('geometry is required.');
  22244. }
  22245. if (!defined(attributeName)) {
  22246. throw new DeveloperError('attributeName is required.');
  22247. }
  22248. if (!defined(attributeName3D)) {
  22249. throw new DeveloperError('attributeName3D is required.');
  22250. }
  22251. if (!defined(attributeName2D)) {
  22252. throw new DeveloperError('attributeName2D is required.');
  22253. }
  22254. if (!defined(geometry.attributes[attributeName])) {
  22255. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  22256. }
  22257. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  22258. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  22259. }
  22260. var attribute = geometry.attributes[attributeName];
  22261. projection = (defined(projection)) ? projection : new GeographicProjection();
  22262. var ellipsoid = projection.ellipsoid;
  22263. // Project original values to 2D.
  22264. var values3D = attribute.values;
  22265. var projectedValues = new Float64Array(values3D.length);
  22266. var index = 0;
  22267. for ( var i = 0; i < values3D.length; i += 3) {
  22268. var value = Cartesian3.fromArray(values3D, i, scratchProjectTo2DCartesian3);
  22269. var lonLat = ellipsoid.cartesianToCartographic(value, scratchProjectTo2DCartographic);
  22270. if (!defined(lonLat)) {
  22271. throw new DeveloperError('Could not project point (' + value.x + ', ' + value.y + ', ' + value.z + ') to 2D.');
  22272. }
  22273. var projectedLonLat = projection.project(lonLat, scratchProjectTo2DCartesian3);
  22274. projectedValues[index++] = projectedLonLat.x;
  22275. projectedValues[index++] = projectedLonLat.y;
  22276. projectedValues[index++] = projectedLonLat.z;
  22277. }
  22278. // Rename original cartesians to WGS84 cartesians.
  22279. geometry.attributes[attributeName3D] = attribute;
  22280. // Replace original cartesians with 2D projected cartesians
  22281. geometry.attributes[attributeName2D] = new GeometryAttribute({
  22282. componentDatatype : ComponentDatatype.DOUBLE,
  22283. componentsPerAttribute : 3,
  22284. values : projectedValues
  22285. });
  22286. delete geometry.attributes[attributeName];
  22287. return geometry;
  22288. };
  22289. var encodedResult = {
  22290. high : 0.0,
  22291. low : 0.0
  22292. };
  22293. /**
  22294. * Encodes floating-point geometry attribute values as two separate attributes to improve
  22295. * rendering precision.
  22296. * <p>
  22297. * This is commonly used to create high-precision position vertex attributes.
  22298. * </p>
  22299. *
  22300. * @param {Geometry} geometry The geometry to modify.
  22301. * @param {String} attributeName The name of the attribute.
  22302. * @param {String} attributeHighName The name of the attribute for the encoded high bits.
  22303. * @param {String} attributeLowName The name of the attribute for the encoded low bits.
  22304. * @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute.
  22305. *
  22306. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  22307. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  22308. *
  22309. * @example
  22310. * geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow');
  22311. */
  22312. GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) {
  22313. if (!defined(geometry)) {
  22314. throw new DeveloperError('geometry is required.');
  22315. }
  22316. if (!defined(attributeName)) {
  22317. throw new DeveloperError('attributeName is required.');
  22318. }
  22319. if (!defined(attributeHighName)) {
  22320. throw new DeveloperError('attributeHighName is required.');
  22321. }
  22322. if (!defined(attributeLowName)) {
  22323. throw new DeveloperError('attributeLowName is required.');
  22324. }
  22325. if (!defined(geometry.attributes[attributeName])) {
  22326. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  22327. }
  22328. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  22329. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  22330. }
  22331. var attribute = geometry.attributes[attributeName];
  22332. var values = attribute.values;
  22333. var length = values.length;
  22334. var highValues = new Float32Array(length);
  22335. var lowValues = new Float32Array(length);
  22336. for (var i = 0; i < length; ++i) {
  22337. EncodedCartesian3.encode(values[i], encodedResult);
  22338. highValues[i] = encodedResult.high;
  22339. lowValues[i] = encodedResult.low;
  22340. }
  22341. var componentsPerAttribute = attribute.componentsPerAttribute;
  22342. geometry.attributes[attributeHighName] = new GeometryAttribute({
  22343. componentDatatype : ComponentDatatype.FLOAT,
  22344. componentsPerAttribute : componentsPerAttribute,
  22345. values : highValues
  22346. });
  22347. geometry.attributes[attributeLowName] = new GeometryAttribute({
  22348. componentDatatype : ComponentDatatype.FLOAT,
  22349. componentsPerAttribute : componentsPerAttribute,
  22350. values : lowValues
  22351. });
  22352. delete geometry.attributes[attributeName];
  22353. return geometry;
  22354. };
  22355. var scratchCartesian3 = new Cartesian3();
  22356. function transformPoint(matrix, attribute) {
  22357. if (defined(attribute)) {
  22358. var values = attribute.values;
  22359. var length = values.length;
  22360. for (var i = 0; i < length; i += 3) {
  22361. Cartesian3.unpack(values, i, scratchCartesian3);
  22362. Matrix4.multiplyByPoint(matrix, scratchCartesian3, scratchCartesian3);
  22363. Cartesian3.pack(scratchCartesian3, values, i);
  22364. }
  22365. }
  22366. }
  22367. function transformVector(matrix, attribute) {
  22368. if (defined(attribute)) {
  22369. var values = attribute.values;
  22370. var length = values.length;
  22371. for (var i = 0; i < length; i += 3) {
  22372. Cartesian3.unpack(values, i, scratchCartesian3);
  22373. Matrix3.multiplyByVector(matrix, scratchCartesian3, scratchCartesian3);
  22374. scratchCartesian3 = Cartesian3.normalize(scratchCartesian3, scratchCartesian3);
  22375. Cartesian3.pack(scratchCartesian3, values, i);
  22376. }
  22377. }
  22378. }
  22379. var inverseTranspose = new Matrix4();
  22380. var normalMatrix = new Matrix3();
  22381. /**
  22382. * Transforms a geometry instance to world coordinates. This changes
  22383. * the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the
  22384. * following attributes if they are present: <code>position</code>, <code>normal</code>,
  22385. * <code>binormal</code>, and <code>tangent</code>.
  22386. *
  22387. * @param {GeometryInstance} instance The geometry instance to modify.
  22388. * @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates.
  22389. *
  22390. * @example
  22391. * Cesium.GeometryPipeline.transformToWorldCoordinates(instance);
  22392. */
  22393. GeometryPipeline.transformToWorldCoordinates = function(instance) {
  22394. if (!defined(instance)) {
  22395. throw new DeveloperError('instance is required.');
  22396. }
  22397. var modelMatrix = instance.modelMatrix;
  22398. if (Matrix4.equals(modelMatrix, Matrix4.IDENTITY)) {
  22399. // Already in world coordinates
  22400. return instance;
  22401. }
  22402. var attributes = instance.geometry.attributes;
  22403. // Transform attributes in known vertex formats
  22404. transformPoint(modelMatrix, attributes.position);
  22405. transformPoint(modelMatrix, attributes.prevPosition);
  22406. transformPoint(modelMatrix, attributes.nextPosition);
  22407. if ((defined(attributes.normal)) ||
  22408. (defined(attributes.binormal)) ||
  22409. (defined(attributes.tangent))) {
  22410. Matrix4.inverse(modelMatrix, inverseTranspose);
  22411. Matrix4.transpose(inverseTranspose, inverseTranspose);
  22412. Matrix4.getRotation(inverseTranspose, normalMatrix);
  22413. transformVector(normalMatrix, attributes.normal);
  22414. transformVector(normalMatrix, attributes.binormal);
  22415. transformVector(normalMatrix, attributes.tangent);
  22416. }
  22417. var boundingSphere = instance.geometry.boundingSphere;
  22418. if (defined(boundingSphere)) {
  22419. instance.geometry.boundingSphere = BoundingSphere.transform(boundingSphere, modelMatrix, boundingSphere);
  22420. }
  22421. instance.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
  22422. return instance;
  22423. };
  22424. function findAttributesInAllGeometries(instances, propertyName) {
  22425. var length = instances.length;
  22426. var attributesInAllGeometries = {};
  22427. var attributes0 = instances[0][propertyName].attributes;
  22428. var name;
  22429. for (name in attributes0) {
  22430. if (attributes0.hasOwnProperty(name) &&
  22431. defined(attributes0[name]) &&
  22432. defined(attributes0[name].values)) {
  22433. var attribute = attributes0[name];
  22434. var numberOfComponents = attribute.values.length;
  22435. var inAllGeometries = true;
  22436. // Does this same attribute exist in all geometries?
  22437. for (var i = 1; i < length; ++i) {
  22438. var otherAttribute = instances[i][propertyName].attributes[name];
  22439. if ((!defined(otherAttribute)) ||
  22440. (attribute.componentDatatype !== otherAttribute.componentDatatype) ||
  22441. (attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute) ||
  22442. (attribute.normalize !== otherAttribute.normalize)) {
  22443. inAllGeometries = false;
  22444. break;
  22445. }
  22446. numberOfComponents += otherAttribute.values.length;
  22447. }
  22448. if (inAllGeometries) {
  22449. attributesInAllGeometries[name] = new GeometryAttribute({
  22450. componentDatatype : attribute.componentDatatype,
  22451. componentsPerAttribute : attribute.componentsPerAttribute,
  22452. normalize : attribute.normalize,
  22453. values : ComponentDatatype.createTypedArray(attribute.componentDatatype, numberOfComponents)
  22454. });
  22455. }
  22456. }
  22457. }
  22458. return attributesInAllGeometries;
  22459. }
  22460. var tempScratch = new Cartesian3();
  22461. function combineGeometries(instances, propertyName) {
  22462. var length = instances.length;
  22463. var name;
  22464. var i;
  22465. var j;
  22466. var k;
  22467. var m = instances[0].modelMatrix;
  22468. var haveIndices = (defined(instances[0][propertyName].indices));
  22469. var primitiveType = instances[0][propertyName].primitiveType;
  22470. for (i = 1; i < length; ++i) {
  22471. if (!Matrix4.equals(instances[i].modelMatrix, m)) {
  22472. throw new DeveloperError('All instances must have the same modelMatrix.');
  22473. }
  22474. if ((defined(instances[i][propertyName].indices)) !== haveIndices) {
  22475. throw new DeveloperError('All instance geometries must have an indices or not have one.');
  22476. }
  22477. if (instances[i][propertyName].primitiveType !== primitiveType) {
  22478. throw new DeveloperError('All instance geometries must have the same primitiveType.');
  22479. }
  22480. }
  22481. // Find subset of attributes in all geometries
  22482. var attributes = findAttributesInAllGeometries(instances, propertyName);
  22483. var values;
  22484. var sourceValues;
  22485. var sourceValuesLength;
  22486. // Combine attributes from each geometry into a single typed array
  22487. for (name in attributes) {
  22488. if (attributes.hasOwnProperty(name)) {
  22489. values = attributes[name].values;
  22490. k = 0;
  22491. for (i = 0; i < length; ++i) {
  22492. sourceValues = instances[i][propertyName].attributes[name].values;
  22493. sourceValuesLength = sourceValues.length;
  22494. for (j = 0; j < sourceValuesLength; ++j) {
  22495. values[k++] = sourceValues[j];
  22496. }
  22497. }
  22498. }
  22499. }
  22500. // Combine index lists
  22501. var indices;
  22502. if (haveIndices) {
  22503. var numberOfIndices = 0;
  22504. for (i = 0; i < length; ++i) {
  22505. numberOfIndices += instances[i][propertyName].indices.length;
  22506. }
  22507. var numberOfVertices = Geometry.computeNumberOfVertices(new Geometry({
  22508. attributes : attributes,
  22509. primitiveType : PrimitiveType.POINTS
  22510. }));
  22511. var destIndices = IndexDatatype.createTypedArray(numberOfVertices, numberOfIndices);
  22512. var destOffset = 0;
  22513. var offset = 0;
  22514. for (i = 0; i < length; ++i) {
  22515. var sourceIndices = instances[i][propertyName].indices;
  22516. var sourceIndicesLen = sourceIndices.length;
  22517. for (k = 0; k < sourceIndicesLen; ++k) {
  22518. destIndices[destOffset++] = offset + sourceIndices[k];
  22519. }
  22520. offset += Geometry.computeNumberOfVertices(instances[i][propertyName]);
  22521. }
  22522. indices = destIndices;
  22523. }
  22524. // Create bounding sphere that includes all instances
  22525. var center = new Cartesian3();
  22526. var radius = 0.0;
  22527. var bs;
  22528. for (i = 0; i < length; ++i) {
  22529. bs = instances[i][propertyName].boundingSphere;
  22530. if (!defined(bs)) {
  22531. // If any geometries have an undefined bounding sphere, then so does the combined geometry
  22532. center = undefined;
  22533. break;
  22534. }
  22535. Cartesian3.add(bs.center, center, center);
  22536. }
  22537. if (defined(center)) {
  22538. Cartesian3.divideByScalar(center, length, center);
  22539. for (i = 0; i < length; ++i) {
  22540. bs = instances[i][propertyName].boundingSphere;
  22541. var tempRadius = Cartesian3.magnitude(Cartesian3.subtract(bs.center, center, tempScratch)) + bs.radius;
  22542. if (tempRadius > radius) {
  22543. radius = tempRadius;
  22544. }
  22545. }
  22546. }
  22547. return new Geometry({
  22548. attributes : attributes,
  22549. indices : indices,
  22550. primitiveType : primitiveType,
  22551. boundingSphere : (defined(center)) ? new BoundingSphere(center, radius) : undefined
  22552. });
  22553. }
  22554. /**
  22555. * Combines geometry from several {@link GeometryInstance} objects into one geometry.
  22556. * This concatenates the attributes, concatenates and adjusts the indices, and creates
  22557. * a bounding sphere encompassing all instances.
  22558. * <p>
  22559. * If the instances do not have the same attributes, a subset of attributes common
  22560. * to all instances is used, and the others are ignored.
  22561. * </p>
  22562. * <p>
  22563. * This is used by {@link Primitive} to efficiently render a large amount of static data.
  22564. * </p>
  22565. *
  22566. * @private
  22567. *
  22568. * @param {GeometryInstance[]} [instances] The array of {@link GeometryInstance} objects whose geometry will be combined.
  22569. * @returns {Geometry} A single geometry created from the provided geometry instances.
  22570. *
  22571. * @exception {DeveloperError} All instances must have the same modelMatrix.
  22572. * @exception {DeveloperError} All instance geometries must have an indices or not have one.
  22573. * @exception {DeveloperError} All instance geometries must have the same primitiveType.
  22574. *
  22575. *
  22576. * @example
  22577. * for (var i = 0; i < instances.length; ++i) {
  22578. * Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]);
  22579. * }
  22580. * var geometries = Cesium.GeometryPipeline.combineInstances(instances);
  22581. *
  22582. * @see GeometryPipeline.transformToWorldCoordinates
  22583. */
  22584. GeometryPipeline.combineInstances = function(instances) {
  22585. if ((!defined(instances)) || (instances.length < 1)) {
  22586. throw new DeveloperError('instances is required and must have length greater than zero.');
  22587. }
  22588. var instanceGeometry = [];
  22589. var instanceSplitGeometry = [];
  22590. var length = instances.length;
  22591. for (var i = 0; i < length; ++i) {
  22592. var instance = instances[i];
  22593. if (defined(instance.geometry)) {
  22594. instanceGeometry.push(instance);
  22595. } else if (defined(instance.westHemisphereGeometry) && defined(instance.eastHemisphereGeometry)) {
  22596. instanceSplitGeometry.push(instance);
  22597. }
  22598. }
  22599. var geometries = [];
  22600. if (instanceGeometry.length > 0) {
  22601. geometries.push(combineGeometries(instanceGeometry, 'geometry'));
  22602. }
  22603. if (instanceSplitGeometry.length > 0) {
  22604. geometries.push(combineGeometries(instanceSplitGeometry, 'westHemisphereGeometry'));
  22605. geometries.push(combineGeometries(instanceSplitGeometry, 'eastHemisphereGeometry'));
  22606. }
  22607. return geometries;
  22608. };
  22609. var normal = new Cartesian3();
  22610. var v0 = new Cartesian3();
  22611. var v1 = new Cartesian3();
  22612. var v2 = new Cartesian3();
  22613. /**
  22614. * Computes per-vertex normals for a geometry containing <code>TRIANGLES</code> by averaging the normals of
  22615. * all triangles incident to the vertex. The result is a new <code>normal</code> attribute added to the geometry.
  22616. * This assumes a counter-clockwise winding order.
  22617. *
  22618. * @param {Geometry} geometry The geometry to modify.
  22619. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>normal</code> attribute.
  22620. *
  22621. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  22622. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  22623. *
  22624. * @example
  22625. * Cesium.GeometryPipeline.computeNormal(geometry);
  22626. */
  22627. GeometryPipeline.computeNormal = function(geometry) {
  22628. if (!defined(geometry)) {
  22629. throw new DeveloperError('geometry is required.');
  22630. }
  22631. if (!defined(geometry.attributes.position) || !defined(geometry.attributes.position.values)) {
  22632. throw new DeveloperError('geometry.attributes.position.values is required.');
  22633. }
  22634. if (!defined(geometry.indices)) {
  22635. throw new DeveloperError('geometry.indices is required.');
  22636. }
  22637. if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
  22638. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  22639. }
  22640. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  22641. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  22642. }
  22643. var indices = geometry.indices;
  22644. var attributes = geometry.attributes;
  22645. var vertices = attributes.position.values;
  22646. var numVertices = attributes.position.values.length / 3;
  22647. var numIndices = indices.length;
  22648. var normalsPerVertex = new Array(numVertices);
  22649. var normalsPerTriangle = new Array(numIndices / 3);
  22650. var normalIndices = new Array(numIndices);
  22651. for ( var i = 0; i < numVertices; i++) {
  22652. normalsPerVertex[i] = {
  22653. indexOffset : 0,
  22654. count : 0,
  22655. currentCount : 0
  22656. };
  22657. }
  22658. var j = 0;
  22659. for (i = 0; i < numIndices; i += 3) {
  22660. var i0 = indices[i];
  22661. var i1 = indices[i + 1];
  22662. var i2 = indices[i + 2];
  22663. var i03 = i0 * 3;
  22664. var i13 = i1 * 3;
  22665. var i23 = i2 * 3;
  22666. v0.x = vertices[i03];
  22667. v0.y = vertices[i03 + 1];
  22668. v0.z = vertices[i03 + 2];
  22669. v1.x = vertices[i13];
  22670. v1.y = vertices[i13 + 1];
  22671. v1.z = vertices[i13 + 2];
  22672. v2.x = vertices[i23];
  22673. v2.y = vertices[i23 + 1];
  22674. v2.z = vertices[i23 + 2];
  22675. normalsPerVertex[i0].count++;
  22676. normalsPerVertex[i1].count++;
  22677. normalsPerVertex[i2].count++;
  22678. Cartesian3.subtract(v1, v0, v1);
  22679. Cartesian3.subtract(v2, v0, v2);
  22680. normalsPerTriangle[j] = Cartesian3.cross(v1, v2, new Cartesian3());
  22681. j++;
  22682. }
  22683. var indexOffset = 0;
  22684. for (i = 0; i < numVertices; i++) {
  22685. normalsPerVertex[i].indexOffset += indexOffset;
  22686. indexOffset += normalsPerVertex[i].count;
  22687. }
  22688. j = 0;
  22689. var vertexNormalData;
  22690. for (i = 0; i < numIndices; i += 3) {
  22691. vertexNormalData = normalsPerVertex[indices[i]];
  22692. var index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  22693. normalIndices[index] = j;
  22694. vertexNormalData.currentCount++;
  22695. vertexNormalData = normalsPerVertex[indices[i + 1]];
  22696. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  22697. normalIndices[index] = j;
  22698. vertexNormalData.currentCount++;
  22699. vertexNormalData = normalsPerVertex[indices[i + 2]];
  22700. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  22701. normalIndices[index] = j;
  22702. vertexNormalData.currentCount++;
  22703. j++;
  22704. }
  22705. var normalValues = new Float32Array(numVertices * 3);
  22706. for (i = 0; i < numVertices; i++) {
  22707. var i3 = i * 3;
  22708. vertexNormalData = normalsPerVertex[i];
  22709. if (vertexNormalData.count > 0) {
  22710. Cartesian3.clone(Cartesian3.ZERO, normal);
  22711. for (j = 0; j < vertexNormalData.count; j++) {
  22712. Cartesian3.add(normal, normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]], normal);
  22713. }
  22714. Cartesian3.normalize(normal, normal);
  22715. normalValues[i3] = normal.x;
  22716. normalValues[i3 + 1] = normal.y;
  22717. normalValues[i3 + 2] = normal.z;
  22718. } else {
  22719. normalValues[i3] = 0.0;
  22720. normalValues[i3 + 1] = 0.0;
  22721. normalValues[i3 + 2] = 1.0;
  22722. }
  22723. }
  22724. geometry.attributes.normal = new GeometryAttribute({
  22725. componentDatatype : ComponentDatatype.FLOAT,
  22726. componentsPerAttribute : 3,
  22727. values : normalValues
  22728. });
  22729. return geometry;
  22730. };
  22731. var normalScratch = new Cartesian3();
  22732. var normalScale = new Cartesian3();
  22733. var tScratch = new Cartesian3();
  22734. /**
  22735. * Computes per-vertex binormals and tangents for a geometry containing <code>TRIANGLES</code>.
  22736. * The result is new <code>binormal</code> and <code>tangent</code> attributes added to the geometry.
  22737. * This assumes a counter-clockwise winding order.
  22738. * <p>
  22739. * Based on <a href="http://www.terathon.com/code/tangent.html">Computing Tangent Space Basis Vectors
  22740. * for an Arbitrary Mesh</a> by Eric Lengyel.
  22741. * </p>
  22742. *
  22743. * @param {Geometry} geometry The geometry to modify.
  22744. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>binormal</code> and <code>tangent</code> attributes.
  22745. *
  22746. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  22747. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  22748. *
  22749. * @example
  22750. * Cesium.GeometryPipeline.computeBinormalAndTangent(geometry);
  22751. */
  22752. GeometryPipeline.computeBinormalAndTangent = function(geometry) {
  22753. if (!defined(geometry)) {
  22754. throw new DeveloperError('geometry is required.');
  22755. }
  22756. var attributes = geometry.attributes;
  22757. var indices = geometry.indices;
  22758. if (!defined(attributes.position) || !defined(attributes.position.values)) {
  22759. throw new DeveloperError('geometry.attributes.position.values is required.');
  22760. }
  22761. if (!defined(attributes.normal) || !defined(attributes.normal.values)) {
  22762. throw new DeveloperError('geometry.attributes.normal.values is required.');
  22763. }
  22764. if (!defined(attributes.st) || !defined(attributes.st.values)) {
  22765. throw new DeveloperError('geometry.attributes.st.values is required.');
  22766. }
  22767. if (!defined(indices)) {
  22768. throw new DeveloperError('geometry.indices is required.');
  22769. }
  22770. if (indices.length < 2 || indices.length % 3 !== 0) {
  22771. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  22772. }
  22773. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  22774. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  22775. }
  22776. var vertices = geometry.attributes.position.values;
  22777. var normals = geometry.attributes.normal.values;
  22778. var st = geometry.attributes.st.values;
  22779. var numVertices = geometry.attributes.position.values.length / 3;
  22780. var numIndices = indices.length;
  22781. var tan1 = new Array(numVertices * 3);
  22782. for ( var i = 0; i < tan1.length; i++) {
  22783. tan1[i] = 0;
  22784. }
  22785. var i03;
  22786. var i13;
  22787. var i23;
  22788. for (i = 0; i < numIndices; i += 3) {
  22789. var i0 = indices[i];
  22790. var i1 = indices[i + 1];
  22791. var i2 = indices[i + 2];
  22792. i03 = i0 * 3;
  22793. i13 = i1 * 3;
  22794. i23 = i2 * 3;
  22795. var i02 = i0 * 2;
  22796. var i12 = i1 * 2;
  22797. var i22 = i2 * 2;
  22798. var ux = vertices[i03];
  22799. var uy = vertices[i03 + 1];
  22800. var uz = vertices[i03 + 2];
  22801. var wx = st[i02];
  22802. var wy = st[i02 + 1];
  22803. var t1 = st[i12 + 1] - wy;
  22804. var t2 = st[i22 + 1] - wy;
  22805. var r = 1.0 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
  22806. var sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r;
  22807. var sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r;
  22808. var sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r;
  22809. tan1[i03] += sdirx;
  22810. tan1[i03 + 1] += sdiry;
  22811. tan1[i03 + 2] += sdirz;
  22812. tan1[i13] += sdirx;
  22813. tan1[i13 + 1] += sdiry;
  22814. tan1[i13 + 2] += sdirz;
  22815. tan1[i23] += sdirx;
  22816. tan1[i23 + 1] += sdiry;
  22817. tan1[i23 + 2] += sdirz;
  22818. }
  22819. var binormalValues = new Float32Array(numVertices * 3);
  22820. var tangentValues = new Float32Array(numVertices * 3);
  22821. for (i = 0; i < numVertices; i++) {
  22822. i03 = i * 3;
  22823. i13 = i03 + 1;
  22824. i23 = i03 + 2;
  22825. var n = Cartesian3.fromArray(normals, i03, normalScratch);
  22826. var t = Cartesian3.fromArray(tan1, i03, tScratch);
  22827. var scalar = Cartesian3.dot(n, t);
  22828. Cartesian3.multiplyByScalar(n, scalar, normalScale);
  22829. Cartesian3.normalize(Cartesian3.subtract(t, normalScale, t), t);
  22830. tangentValues[i03] = t.x;
  22831. tangentValues[i13] = t.y;
  22832. tangentValues[i23] = t.z;
  22833. Cartesian3.normalize(Cartesian3.cross(n, t, t), t);
  22834. binormalValues[i03] = t.x;
  22835. binormalValues[i13] = t.y;
  22836. binormalValues[i23] = t.z;
  22837. }
  22838. geometry.attributes.tangent = new GeometryAttribute({
  22839. componentDatatype : ComponentDatatype.FLOAT,
  22840. componentsPerAttribute : 3,
  22841. values : tangentValues
  22842. });
  22843. geometry.attributes.binormal = new GeometryAttribute({
  22844. componentDatatype : ComponentDatatype.FLOAT,
  22845. componentsPerAttribute : 3,
  22846. values : binormalValues
  22847. });
  22848. return geometry;
  22849. };
  22850. var scratchCartesian2 = new Cartesian2();
  22851. var toEncode1 = new Cartesian3();
  22852. var toEncode2 = new Cartesian3();
  22853. var toEncode3 = new Cartesian3();
  22854. /**
  22855. * Compresses and packs geometry normal attribute values to save memory.
  22856. *
  22857. * @param {Geometry} geometry The geometry to modify.
  22858. * @returns {Geometry} The modified <code>geometry</code> argument, with its normals compressed and packed.
  22859. *
  22860. * @example
  22861. * geometry = Cesium.GeometryPipeline.compressVertices(geometry);
  22862. */
  22863. GeometryPipeline.compressVertices = function(geometry) {
  22864. if (!defined(geometry)) {
  22865. throw new DeveloperError('geometry is required.');
  22866. }
  22867. var normalAttribute = geometry.attributes.normal;
  22868. var stAttribute = geometry.attributes.st;
  22869. if (!defined(normalAttribute) && !defined(stAttribute)) {
  22870. return geometry;
  22871. }
  22872. var tangentAttribute = geometry.attributes.tangent;
  22873. var binormalAttribute = geometry.attributes.binormal;
  22874. var normals;
  22875. var st;
  22876. var tangents;
  22877. var binormals;
  22878. if (defined(normalAttribute)) {
  22879. normals = normalAttribute.values;
  22880. }
  22881. if (defined(stAttribute)) {
  22882. st = stAttribute.values;
  22883. }
  22884. if (defined(tangentAttribute)) {
  22885. tangents = tangentAttribute.values;
  22886. }
  22887. if (binormalAttribute) {
  22888. binormals = binormalAttribute.values;
  22889. }
  22890. var length = defined(normals) ? normals.length : st.length;
  22891. var numComponents = defined(normals) ? 3.0 : 2.0;
  22892. var numVertices = length / numComponents;
  22893. var compressedLength = numVertices;
  22894. var numCompressedComponents = defined(st) && defined(normals) ? 2.0 : 1.0;
  22895. numCompressedComponents += defined(tangents) || defined(binormals) ? 1.0 : 0.0;
  22896. compressedLength *= numCompressedComponents;
  22897. var compressedAttributes = new Float32Array(compressedLength);
  22898. var normalIndex = 0;
  22899. for (var i = 0; i < numVertices; ++i) {
  22900. if (defined(st)) {
  22901. Cartesian2.fromArray(st, i * 2.0, scratchCartesian2);
  22902. compressedAttributes[normalIndex++] = AttributeCompression.compressTextureCoordinates(scratchCartesian2);
  22903. }
  22904. var index = i * 3.0;
  22905. if (defined(normals) && defined(tangents) && defined(binormals)) {
  22906. Cartesian3.fromArray(normals, index, toEncode1);
  22907. Cartesian3.fromArray(tangents, index, toEncode2);
  22908. Cartesian3.fromArray(binormals, index, toEncode3);
  22909. AttributeCompression.octPack(toEncode1, toEncode2, toEncode3, scratchCartesian2);
  22910. compressedAttributes[normalIndex++] = scratchCartesian2.x;
  22911. compressedAttributes[normalIndex++] = scratchCartesian2.y;
  22912. } else {
  22913. if (defined(normals)) {
  22914. Cartesian3.fromArray(normals, index, toEncode1);
  22915. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  22916. }
  22917. if (defined(tangents)) {
  22918. Cartesian3.fromArray(tangents, index, toEncode1);
  22919. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  22920. }
  22921. if (defined(binormals)) {
  22922. Cartesian3.fromArray(binormals, index, toEncode1);
  22923. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  22924. }
  22925. }
  22926. }
  22927. geometry.attributes.compressedAttributes = new GeometryAttribute({
  22928. componentDatatype : ComponentDatatype.FLOAT,
  22929. componentsPerAttribute : numCompressedComponents,
  22930. values : compressedAttributes
  22931. });
  22932. if (defined(normals)) {
  22933. delete geometry.attributes.normal;
  22934. }
  22935. if (defined(st)) {
  22936. delete geometry.attributes.st;
  22937. }
  22938. if (defined(tangents)) {
  22939. delete geometry.attributes.tangent;
  22940. }
  22941. if (defined(binormals)) {
  22942. delete geometry.attributes.binormal;
  22943. }
  22944. return geometry;
  22945. };
  22946. function indexTriangles(geometry) {
  22947. if (defined(geometry.indices)) {
  22948. return geometry;
  22949. }
  22950. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22951. if (numberOfVertices < 3) {
  22952. throw new DeveloperError('The number of vertices must be at least three.');
  22953. }
  22954. if (numberOfVertices % 3 !== 0) {
  22955. throw new DeveloperError('The number of vertices must be a multiple of three.');
  22956. }
  22957. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  22958. for (var i = 0; i < numberOfVertices; ++i) {
  22959. indices[i] = i;
  22960. }
  22961. geometry.indices = indices;
  22962. return geometry;
  22963. }
  22964. function indexTriangleFan(geometry) {
  22965. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22966. if (numberOfVertices < 3) {
  22967. throw new DeveloperError('The number of vertices must be at least three.');
  22968. }
  22969. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  22970. indices[0] = 1;
  22971. indices[1] = 0;
  22972. indices[2] = 2;
  22973. var indicesIndex = 3;
  22974. for (var i = 3; i < numberOfVertices; ++i) {
  22975. indices[indicesIndex++] = i - 1;
  22976. indices[indicesIndex++] = 0;
  22977. indices[indicesIndex++] = i;
  22978. }
  22979. geometry.indices = indices;
  22980. geometry.primitiveType = PrimitiveType.TRIANGLES;
  22981. return geometry;
  22982. }
  22983. function indexTriangleStrip(geometry) {
  22984. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22985. if (numberOfVertices < 3) {
  22986. throw new DeveloperError('The number of vertices must be at least 3.');
  22987. }
  22988. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  22989. indices[0] = 0;
  22990. indices[1] = 1;
  22991. indices[2] = 2;
  22992. if (numberOfVertices > 3) {
  22993. indices[3] = 0;
  22994. indices[4] = 2;
  22995. indices[5] = 3;
  22996. }
  22997. var indicesIndex = 6;
  22998. for (var i = 3; i < numberOfVertices - 1; i += 2) {
  22999. indices[indicesIndex++] = i;
  23000. indices[indicesIndex++] = i - 1;
  23001. indices[indicesIndex++] = i + 1;
  23002. if (i + 2 < numberOfVertices) {
  23003. indices[indicesIndex++] = i;
  23004. indices[indicesIndex++] = i + 1;
  23005. indices[indicesIndex++] = i + 2;
  23006. }
  23007. }
  23008. geometry.indices = indices;
  23009. geometry.primitiveType = PrimitiveType.TRIANGLES;
  23010. return geometry;
  23011. }
  23012. function indexLines(geometry) {
  23013. if (defined(geometry.indices)) {
  23014. return geometry;
  23015. }
  23016. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  23017. if (numberOfVertices < 2) {
  23018. throw new DeveloperError('The number of vertices must be at least two.');
  23019. }
  23020. if (numberOfVertices % 2 !== 0) {
  23021. throw new DeveloperError('The number of vertices must be a multiple of 2.');
  23022. }
  23023. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  23024. for (var i = 0; i < numberOfVertices; ++i) {
  23025. indices[i] = i;
  23026. }
  23027. geometry.indices = indices;
  23028. return geometry;
  23029. }
  23030. function indexLineStrip(geometry) {
  23031. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  23032. if (numberOfVertices < 2) {
  23033. throw new DeveloperError('The number of vertices must be at least two.');
  23034. }
  23035. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 1) * 2);
  23036. indices[0] = 0;
  23037. indices[1] = 1;
  23038. var indicesIndex = 2;
  23039. for (var i = 2; i < numberOfVertices; ++i) {
  23040. indices[indicesIndex++] = i - 1;
  23041. indices[indicesIndex++] = i;
  23042. }
  23043. geometry.indices = indices;
  23044. geometry.primitiveType = PrimitiveType.LINES;
  23045. return geometry;
  23046. }
  23047. function indexLineLoop(geometry) {
  23048. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  23049. if (numberOfVertices < 2) {
  23050. throw new DeveloperError('The number of vertices must be at least two.');
  23051. }
  23052. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices * 2);
  23053. indices[0] = 0;
  23054. indices[1] = 1;
  23055. var indicesIndex = 2;
  23056. for (var i = 2; i < numberOfVertices; ++i) {
  23057. indices[indicesIndex++] = i - 1;
  23058. indices[indicesIndex++] = i;
  23059. }
  23060. indices[indicesIndex++] = numberOfVertices - 1;
  23061. indices[indicesIndex] = 0;
  23062. geometry.indices = indices;
  23063. geometry.primitiveType = PrimitiveType.LINES;
  23064. return geometry;
  23065. }
  23066. function indexPrimitive(geometry) {
  23067. switch (geometry.primitiveType) {
  23068. case PrimitiveType.TRIANGLE_FAN:
  23069. return indexTriangleFan(geometry);
  23070. case PrimitiveType.TRIANGLE_STRIP:
  23071. return indexTriangleStrip(geometry);
  23072. case PrimitiveType.TRIANGLES:
  23073. return indexTriangles(geometry);
  23074. case PrimitiveType.LINE_STRIP:
  23075. return indexLineStrip(geometry);
  23076. case PrimitiveType.LINE_LOOP:
  23077. return indexLineLoop(geometry);
  23078. case PrimitiveType.LINES:
  23079. return indexLines(geometry);
  23080. }
  23081. return geometry;
  23082. }
  23083. function offsetPointFromXZPlane(p, isBehind) {
  23084. if (Math.abs(p.y) < CesiumMath.EPSILON6){
  23085. if (isBehind) {
  23086. p.y = -CesiumMath.EPSILON6;
  23087. } else {
  23088. p.y = CesiumMath.EPSILON6;
  23089. }
  23090. }
  23091. }
  23092. function offsetTriangleFromXZPlane(p0, p1, p2) {
  23093. if (p0.y !== 0.0 && p1.y !== 0.0 && p2.y !== 0.0) {
  23094. offsetPointFromXZPlane(p0, p0.y < 0.0);
  23095. offsetPointFromXZPlane(p1, p1.y < 0.0);
  23096. offsetPointFromXZPlane(p2, p2.y < 0.0);
  23097. return;
  23098. }
  23099. var p0y = Math.abs(p0.y);
  23100. var p1y = Math.abs(p1.y);
  23101. var p2y = Math.abs(p2.y);
  23102. var sign;
  23103. if (p0y > p1y) {
  23104. if (p0y > p2y) {
  23105. sign = CesiumMath.sign(p0.y);
  23106. } else {
  23107. sign = CesiumMath.sign(p2.y);
  23108. }
  23109. } else if (p1y > p2y) {
  23110. sign = CesiumMath.sign(p1.y);
  23111. } else {
  23112. sign = CesiumMath.sign(p2.y);
  23113. }
  23114. var isBehind = sign < 0.0;
  23115. offsetPointFromXZPlane(p0, isBehind);
  23116. offsetPointFromXZPlane(p1, isBehind);
  23117. offsetPointFromXZPlane(p2, isBehind);
  23118. }
  23119. var c3 = new Cartesian3();
  23120. function getXZIntersectionOffsetPoints(p, p1, u1, v1) {
  23121. Cartesian3.add(p, Cartesian3.multiplyByScalar(Cartesian3.subtract(p1, p, c3), p.y/(p.y-p1.y), c3), u1);
  23122. Cartesian3.clone(u1, v1);
  23123. offsetPointFromXZPlane(u1, true);
  23124. offsetPointFromXZPlane(v1, false);
  23125. }
  23126. var u1 = new Cartesian3();
  23127. var u2 = new Cartesian3();
  23128. var q1 = new Cartesian3();
  23129. var q2 = new Cartesian3();
  23130. var splitTriangleResult = {
  23131. positions : new Array(7),
  23132. indices : new Array(3 * 3)
  23133. };
  23134. function splitTriangle(p0, p1, p2) {
  23135. // In WGS84 coordinates, for a triangle approximately on the
  23136. // ellipsoid to cross the IDL, first it needs to be on the
  23137. // negative side of the plane x = 0.
  23138. if ((p0.x >= 0.0) || (p1.x >= 0.0) || (p2.x >= 0.0)) {
  23139. return undefined;
  23140. }
  23141. offsetTriangleFromXZPlane(p0, p1, p2);
  23142. var p0Behind = p0.y < 0.0;
  23143. var p1Behind = p1.y < 0.0;
  23144. var p2Behind = p2.y < 0.0;
  23145. var numBehind = 0;
  23146. numBehind += p0Behind ? 1 : 0;
  23147. numBehind += p1Behind ? 1 : 0;
  23148. numBehind += p2Behind ? 1 : 0;
  23149. var indices = splitTriangleResult.indices;
  23150. if (numBehind === 1) {
  23151. indices[1] = 3;
  23152. indices[2] = 4;
  23153. indices[5] = 6;
  23154. indices[7] = 6;
  23155. indices[8] = 5;
  23156. if (p0Behind) {
  23157. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  23158. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  23159. indices[0] = 0;
  23160. indices[3] = 1;
  23161. indices[4] = 2;
  23162. indices[6] = 1;
  23163. } else if (p1Behind) {
  23164. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  23165. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  23166. indices[0] = 1;
  23167. indices[3] = 2;
  23168. indices[4] = 0;
  23169. indices[6] = 2;
  23170. } else if (p2Behind) {
  23171. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  23172. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  23173. indices[0] = 2;
  23174. indices[3] = 0;
  23175. indices[4] = 1;
  23176. indices[6] = 0;
  23177. }
  23178. } else if (numBehind === 2) {
  23179. indices[2] = 4;
  23180. indices[4] = 4;
  23181. indices[5] = 3;
  23182. indices[7] = 5;
  23183. indices[8] = 6;
  23184. if (!p0Behind) {
  23185. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  23186. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  23187. indices[0] = 1;
  23188. indices[1] = 2;
  23189. indices[3] = 1;
  23190. indices[6] = 0;
  23191. } else if (!p1Behind) {
  23192. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  23193. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  23194. indices[0] = 2;
  23195. indices[1] = 0;
  23196. indices[3] = 2;
  23197. indices[6] = 1;
  23198. } else if (!p2Behind) {
  23199. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  23200. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  23201. indices[0] = 0;
  23202. indices[1] = 1;
  23203. indices[3] = 0;
  23204. indices[6] = 2;
  23205. }
  23206. }
  23207. var positions = splitTriangleResult.positions;
  23208. positions[0] = p0;
  23209. positions[1] = p1;
  23210. positions[2] = p2;
  23211. positions.length = 3;
  23212. if (numBehind === 1 || numBehind === 2) {
  23213. positions[3] = u1;
  23214. positions[4] = u2;
  23215. positions[5] = q1;
  23216. positions[6] = q2;
  23217. positions.length = 7;
  23218. }
  23219. return splitTriangleResult;
  23220. }
  23221. function updateGeometryAfterSplit(geometry, computeBoundingSphere) {
  23222. var attributes = geometry.attributes;
  23223. if (attributes.position.values.length === 0) {
  23224. return undefined;
  23225. }
  23226. for (var property in attributes) {
  23227. if (attributes.hasOwnProperty(property) &&
  23228. defined(attributes[property]) &&
  23229. defined(attributes[property].values)) {
  23230. var attribute = attributes[property];
  23231. attribute.values = ComponentDatatype.createTypedArray(attribute.componentDatatype, attribute.values);
  23232. }
  23233. }
  23234. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  23235. geometry.indices = IndexDatatype.createTypedArray(numberOfVertices, geometry.indices);
  23236. if (computeBoundingSphere) {
  23237. geometry.boundingSphere = BoundingSphere.fromVertices(attributes.position.values);
  23238. }
  23239. return geometry;
  23240. }
  23241. function copyGeometryForSplit(geometry) {
  23242. var attributes = geometry.attributes;
  23243. var copiedAttributes = {};
  23244. for (var property in attributes) {
  23245. if (attributes.hasOwnProperty(property) &&
  23246. defined(attributes[property]) &&
  23247. defined(attributes[property].values)) {
  23248. var attribute = attributes[property];
  23249. copiedAttributes[property] = new GeometryAttribute({
  23250. componentDatatype : attribute.componentDatatype,
  23251. componentsPerAttribute : attribute.componentsPerAttribute,
  23252. normalize : attribute.normalize,
  23253. values : []
  23254. });
  23255. }
  23256. }
  23257. return new Geometry({
  23258. attributes : copiedAttributes,
  23259. indices : [],
  23260. primitiveType : geometry.primitiveType
  23261. });
  23262. }
  23263. function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
  23264. var computeBoundingSphere = defined(instance.geometry.boundingSphere);
  23265. westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
  23266. eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);
  23267. if (defined(eastGeometry) && !defined(westGeometry)) {
  23268. instance.geometry = eastGeometry;
  23269. } else if (!defined(eastGeometry) && defined(westGeometry)) {
  23270. instance.geometry = westGeometry;
  23271. } else {
  23272. instance.westHemisphereGeometry = westGeometry;
  23273. instance.eastHemisphereGeometry = eastGeometry;
  23274. instance.geometry = undefined;
  23275. }
  23276. }
  23277. var p0Scratch = new Cartesian3();
  23278. var p1Scratch = new Cartesian3();
  23279. var p2Scratch = new Cartesian3();
  23280. var barycentricScratch = new Cartesian3();
  23281. var s0Scratch = new Cartesian2();
  23282. var s1Scratch = new Cartesian2();
  23283. var s2Scratch = new Cartesian2();
  23284. function computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex) {
  23285. if (!defined(normals) && !defined(binormals) && !defined(tangents) && !defined(texCoords)) {
  23286. return;
  23287. }
  23288. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  23289. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  23290. var p2 = Cartesian3.fromArray(positions, i2 * 3, p2Scratch);
  23291. var coords = barycentricCoordinates(point, p0, p1, p2, barycentricScratch);
  23292. if (defined(normals)) {
  23293. var n0 = Cartesian3.fromArray(normals, i0 * 3, p0Scratch);
  23294. var n1 = Cartesian3.fromArray(normals, i1 * 3, p1Scratch);
  23295. var n2 = Cartesian3.fromArray(normals, i2 * 3, p2Scratch);
  23296. Cartesian3.multiplyByScalar(n0, coords.x, n0);
  23297. Cartesian3.multiplyByScalar(n1, coords.y, n1);
  23298. Cartesian3.multiplyByScalar(n2, coords.z, n2);
  23299. var normal = Cartesian3.add(n0, n1, n0);
  23300. Cartesian3.add(normal, n2, normal);
  23301. Cartesian3.normalize(normal, normal);
  23302. Cartesian3.pack(normal, currentAttributes.normal.values, insertedIndex * 3);
  23303. }
  23304. if (defined(binormals)) {
  23305. var b0 = Cartesian3.fromArray(binormals, i0 * 3, p0Scratch);
  23306. var b1 = Cartesian3.fromArray(binormals, i1 * 3, p1Scratch);
  23307. var b2 = Cartesian3.fromArray(binormals, i2 * 3, p2Scratch);
  23308. Cartesian3.multiplyByScalar(b0, coords.x, b0);
  23309. Cartesian3.multiplyByScalar(b1, coords.y, b1);
  23310. Cartesian3.multiplyByScalar(b2, coords.z, b2);
  23311. var binormal = Cartesian3.add(b0, b1, b0);
  23312. Cartesian3.add(binormal, b2, binormal);
  23313. Cartesian3.normalize(binormal, binormal);
  23314. Cartesian3.pack(binormal, currentAttributes.binormal.values, insertedIndex * 3);
  23315. }
  23316. if (defined(tangents)) {
  23317. var t0 = Cartesian3.fromArray(tangents, i0 * 3, p0Scratch);
  23318. var t1 = Cartesian3.fromArray(tangents, i1 * 3, p1Scratch);
  23319. var t2 = Cartesian3.fromArray(tangents, i2 * 3, p2Scratch);
  23320. Cartesian3.multiplyByScalar(t0, coords.x, t0);
  23321. Cartesian3.multiplyByScalar(t1, coords.y, t1);
  23322. Cartesian3.multiplyByScalar(t2, coords.z, t2);
  23323. var tangent = Cartesian3.add(t0, t1, t0);
  23324. Cartesian3.add(tangent, t2, tangent);
  23325. Cartesian3.normalize(tangent, tangent);
  23326. Cartesian3.pack(tangent, currentAttributes.tangent.values, insertedIndex * 3);
  23327. }
  23328. if (defined(texCoords)) {
  23329. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, s0Scratch);
  23330. var s1 = Cartesian2.fromArray(texCoords, i1 * 2, s1Scratch);
  23331. var s2 = Cartesian2.fromArray(texCoords, i2 * 2, s2Scratch);
  23332. Cartesian2.multiplyByScalar(s0, coords.x, s0);
  23333. Cartesian2.multiplyByScalar(s1, coords.y, s1);
  23334. Cartesian2.multiplyByScalar(s2, coords.z, s2);
  23335. var texCoord = Cartesian2.add(s0, s1, s0);
  23336. Cartesian2.add(texCoord, s2, texCoord);
  23337. Cartesian2.pack(texCoord, currentAttributes.st.values, insertedIndex * 2);
  23338. }
  23339. }
  23340. function insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, currentIndex, point) {
  23341. var insertIndex = currentAttributes.position.values.length / 3;
  23342. if (currentIndex !== -1) {
  23343. var prevIndex = indices[currentIndex];
  23344. var newIndex = currentIndexMap[prevIndex];
  23345. if (newIndex === -1) {
  23346. currentIndexMap[prevIndex] = insertIndex;
  23347. currentAttributes.position.values.push(point.x, point.y, point.z);
  23348. currentIndices.push(insertIndex);
  23349. return insertIndex;
  23350. }
  23351. currentIndices.push(newIndex);
  23352. return newIndex;
  23353. }
  23354. currentAttributes.position.values.push(point.x, point.y, point.z);
  23355. currentIndices.push(insertIndex);
  23356. return insertIndex;
  23357. }
  23358. function splitLongitudeTriangles(instance) {
  23359. var geometry = instance.geometry;
  23360. var attributes = geometry.attributes;
  23361. var positions = attributes.position.values;
  23362. var normals = (defined(attributes.normal)) ? attributes.normal.values : undefined;
  23363. var binormals = (defined(attributes.binormal)) ? attributes.binormal.values : undefined;
  23364. var tangents = (defined(attributes.tangent)) ? attributes.tangent.values : undefined;
  23365. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  23366. var indices = geometry.indices;
  23367. var eastGeometry = copyGeometryForSplit(geometry);
  23368. var westGeometry = copyGeometryForSplit(geometry);
  23369. var currentAttributes;
  23370. var currentIndices;
  23371. var currentIndexMap;
  23372. var insertedIndex;
  23373. var i;
  23374. var westGeometryIndexMap = [];
  23375. westGeometryIndexMap.length = positions.length / 3;
  23376. var eastGeometryIndexMap = [];
  23377. eastGeometryIndexMap.length = positions.length / 3;
  23378. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  23379. westGeometryIndexMap[i] = -1;
  23380. eastGeometryIndexMap[i] = -1;
  23381. }
  23382. var len = indices.length;
  23383. for (i = 0; i < len; i += 3) {
  23384. var i0 = indices[i];
  23385. var i1 = indices[i + 1];
  23386. var i2 = indices[i + 2];
  23387. var p0 = Cartesian3.fromArray(positions, i0 * 3);
  23388. var p1 = Cartesian3.fromArray(positions, i1 * 3);
  23389. var p2 = Cartesian3.fromArray(positions, i2 * 3);
  23390. var result = splitTriangle(p0, p1, p2);
  23391. if (defined(result) && result.positions.length > 3) {
  23392. var resultPositions = result.positions;
  23393. var resultIndices = result.indices;
  23394. var resultLength = resultIndices.length;
  23395. for (var j = 0; j < resultLength; ++j) {
  23396. var resultIndex = resultIndices[j];
  23397. var point = resultPositions[resultIndex];
  23398. if (point.y < 0.0) {
  23399. currentAttributes = westGeometry.attributes;
  23400. currentIndices = westGeometry.indices;
  23401. currentIndexMap = westGeometryIndexMap;
  23402. } else {
  23403. currentAttributes = eastGeometry.attributes;
  23404. currentIndices = eastGeometry.indices;
  23405. currentIndexMap = eastGeometryIndexMap;
  23406. }
  23407. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, resultIndex < 3 ? i + resultIndex : -1, point);
  23408. computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23409. }
  23410. } else {
  23411. if (defined(result)) {
  23412. p0 = result.positions[0];
  23413. p1 = result.positions[1];
  23414. p2 = result.positions[2];
  23415. }
  23416. if (p0.y < 0.0) {
  23417. currentAttributes = westGeometry.attributes;
  23418. currentIndices = westGeometry.indices;
  23419. currentIndexMap = westGeometryIndexMap;
  23420. } else {
  23421. currentAttributes = eastGeometry.attributes;
  23422. currentIndices = eastGeometry.indices;
  23423. currentIndexMap = eastGeometryIndexMap;
  23424. }
  23425. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  23426. computeTriangleAttributes(i0, i1, i2, p0, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23427. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  23428. computeTriangleAttributes(i0, i1, i2, p1, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23429. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 2, p2);
  23430. computeTriangleAttributes(i0, i1, i2, p2, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23431. }
  23432. }
  23433. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  23434. }
  23435. var xzPlane = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y);
  23436. var offsetScratch = new Cartesian3();
  23437. var offsetPointScratch = new Cartesian3();
  23438. function splitLongitudeLines(instance) {
  23439. var geometry = instance.geometry;
  23440. var attributes = geometry.attributes;
  23441. var positions = attributes.position.values;
  23442. var indices = geometry.indices;
  23443. var eastGeometry = copyGeometryForSplit(geometry);
  23444. var westGeometry = copyGeometryForSplit(geometry);
  23445. var i;
  23446. var length = indices.length;
  23447. var westGeometryIndexMap = [];
  23448. westGeometryIndexMap.length = positions.length / 3;
  23449. var eastGeometryIndexMap = [];
  23450. eastGeometryIndexMap.length = positions.length / 3;
  23451. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  23452. westGeometryIndexMap[i] = -1;
  23453. eastGeometryIndexMap[i] = -1;
  23454. }
  23455. for (i = 0; i < length; i += 2) {
  23456. var i0 = indices[i];
  23457. var i1 = indices[i + 1];
  23458. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  23459. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  23460. if (Math.abs(p0.y) < CesiumMath.EPSILON6){
  23461. if (p0.y < 0.0) {
  23462. p0.y = -CesiumMath.EPSILON6;
  23463. } else {
  23464. p0.y = CesiumMath.EPSILON6;
  23465. }
  23466. }
  23467. if (Math.abs(p1.y) < CesiumMath.EPSILON6){
  23468. if (p1.y < 0.0) {
  23469. p1.y = -CesiumMath.EPSILON6;
  23470. } else {
  23471. p1.y = CesiumMath.EPSILON6;
  23472. }
  23473. }
  23474. var p0Attributes = eastGeometry.attributes;
  23475. var p0Indices = eastGeometry.indices;
  23476. var p0IndexMap = eastGeometryIndexMap;
  23477. var p1Attributes = westGeometry.attributes;
  23478. var p1Indices = westGeometry.indices;
  23479. var p1IndexMap = westGeometryIndexMap;
  23480. var intersection = IntersectionTests.lineSegmentPlane(p0, p1, xzPlane, p2Scratch);
  23481. if (defined(intersection)) {
  23482. // move point on the xz-plane slightly away from the plane
  23483. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, 5.0 * CesiumMath.EPSILON9, offsetScratch);
  23484. if (p0.y < 0.0) {
  23485. Cartesian3.negate(offset, offset);
  23486. p0Attributes = westGeometry.attributes;
  23487. p0Indices = westGeometry.indices;
  23488. p0IndexMap = westGeometryIndexMap;
  23489. p1Attributes = eastGeometry.attributes;
  23490. p1Indices = eastGeometry.indices;
  23491. p1IndexMap = eastGeometryIndexMap;
  23492. }
  23493. var offsetPoint = Cartesian3.add(intersection, offset, offsetPointScratch);
  23494. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, i, p0);
  23495. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, -1, offsetPoint);
  23496. Cartesian3.negate(offset, offset);
  23497. Cartesian3.add(intersection, offset, offsetPoint);
  23498. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, -1, offsetPoint);
  23499. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, i + 1, p1);
  23500. } else {
  23501. var currentAttributes;
  23502. var currentIndices;
  23503. var currentIndexMap;
  23504. if (p0.y < 0.0) {
  23505. currentAttributes = westGeometry.attributes;
  23506. currentIndices = westGeometry.indices;
  23507. currentIndexMap = westGeometryIndexMap;
  23508. } else {
  23509. currentAttributes = eastGeometry.attributes;
  23510. currentIndices = eastGeometry.indices;
  23511. currentIndexMap = eastGeometryIndexMap;
  23512. }
  23513. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  23514. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  23515. }
  23516. }
  23517. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  23518. }
  23519. var cartesian2Scratch0 = new Cartesian2();
  23520. var cartesian2Scratch1 = new Cartesian2();
  23521. var cartesian3Scratch0 = new Cartesian3();
  23522. var cartesian3Scratch2 = new Cartesian3();
  23523. var cartesian3Scratch3 = new Cartesian3();
  23524. var cartesian3Scratch4 = new Cartesian3();
  23525. var cartesian3Scratch5 = new Cartesian3();
  23526. var cartesian3Scratch6 = new Cartesian3();
  23527. var cartesian4Scratch0 = new Cartesian4();
  23528. function updateAdjacencyAfterSplit(geometry) {
  23529. var attributes = geometry.attributes;
  23530. var positions = attributes.position.values;
  23531. var prevPositions = attributes.prevPosition.values;
  23532. var nextPositions = attributes.nextPosition.values;
  23533. var length = positions.length;
  23534. for (var j = 0; j < length; j += 3) {
  23535. var position = Cartesian3.unpack(positions, j, cartesian3Scratch0);
  23536. if (position.x > 0.0) {
  23537. continue;
  23538. }
  23539. var prevPosition = Cartesian3.unpack(prevPositions, j, cartesian3Scratch2);
  23540. if ((position.y < 0.0 && prevPosition.y > 0.0) || (position.y > 0.0 && prevPosition.y < 0.0)) {
  23541. if (j - 3 > 0) {
  23542. prevPositions[j] = positions[j - 3];
  23543. prevPositions[j + 1] = positions[j - 2];
  23544. prevPositions[j + 2] = positions[j - 1];
  23545. } else {
  23546. Cartesian3.pack(position, prevPositions, j);
  23547. }
  23548. }
  23549. var nextPosition = Cartesian3.unpack(nextPositions, j, cartesian3Scratch3);
  23550. if ((position.y < 0.0 && nextPosition.y > 0.0) || (position.y > 0.0 && nextPosition.y < 0.0)) {
  23551. if (j + 3 < length) {
  23552. nextPositions[j] = positions[j + 3];
  23553. nextPositions[j + 1] = positions[j + 4];
  23554. nextPositions[j + 2] = positions[j + 5];
  23555. } else {
  23556. Cartesian3.pack(position, nextPositions, j);
  23557. }
  23558. }
  23559. }
  23560. }
  23561. var offsetScalar = 5.0 * CesiumMath.EPSILON9;
  23562. var coplanarOffset = CesiumMath.EPSILON6;
  23563. function splitLongitudePolyline(instance) {
  23564. var geometry = instance.geometry;
  23565. var attributes = geometry.attributes;
  23566. var positions = attributes.position.values;
  23567. var prevPositions = attributes.prevPosition.values;
  23568. var nextPositions = attributes.nextPosition.values;
  23569. var expandAndWidths = attributes.expandAndWidth.values;
  23570. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  23571. var colors = (defined(attributes.color)) ? attributes.color.values : undefined;
  23572. var eastGeometry = copyGeometryForSplit(geometry);
  23573. var westGeometry = copyGeometryForSplit(geometry);
  23574. var i;
  23575. var j;
  23576. var index;
  23577. var intersectionFound = false;
  23578. var length = positions.length / 3;
  23579. for (i = 0; i < length; i += 4) {
  23580. var i0 = i;
  23581. var i2 = i + 2;
  23582. var p0 = Cartesian3.fromArray(positions, i0 * 3, cartesian3Scratch0);
  23583. var p2 = Cartesian3.fromArray(positions, i2 * 3, cartesian3Scratch2);
  23584. // Offset points that are close to the 180 longitude and change the previous/next point
  23585. // to be the same offset point so it can be projected to 2D. There is special handling in the
  23586. // shader for when position == prevPosition || position == nextPosition.
  23587. if (Math.abs(p0.y) < coplanarOffset) {
  23588. p0.y = coplanarOffset * (p2.y < 0.0 ? -1.0 : 1.0);
  23589. positions[i * 3 + 1] = p0.y;
  23590. positions[(i + 1) * 3 + 1] = p0.y;
  23591. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  23592. prevPositions[j] = positions[i * 3];
  23593. prevPositions[j + 1] = positions[i * 3 + 1];
  23594. prevPositions[j + 2] = positions[i * 3 + 2];
  23595. }
  23596. }
  23597. // Do the same but for when the line crosses 180 longitude in the opposite direction.
  23598. if (Math.abs(p2.y) < coplanarOffset) {
  23599. p2.y = coplanarOffset * (p0.y < 0.0 ? -1.0 : 1.0);
  23600. positions[(i + 2) * 3 + 1] = p2.y;
  23601. positions[(i + 3) * 3 + 1] = p2.y;
  23602. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  23603. nextPositions[j] = positions[(i + 2) * 3];
  23604. nextPositions[j + 1] = positions[(i + 2) * 3 + 1];
  23605. nextPositions[j + 2] = positions[(i + 2) * 3 + 2];
  23606. }
  23607. }
  23608. var p0Attributes = eastGeometry.attributes;
  23609. var p0Indices = eastGeometry.indices;
  23610. var p2Attributes = westGeometry.attributes;
  23611. var p2Indices = westGeometry.indices;
  23612. var intersection = IntersectionTests.lineSegmentPlane(p0, p2, xzPlane, cartesian3Scratch4);
  23613. if (defined(intersection)) {
  23614. intersectionFound = true;
  23615. // move point on the xz-plane slightly away from the plane
  23616. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, offsetScalar, cartesian3Scratch5);
  23617. if (p0.y < 0.0) {
  23618. Cartesian3.negate(offset, offset);
  23619. p0Attributes = westGeometry.attributes;
  23620. p0Indices = westGeometry.indices;
  23621. p2Attributes = eastGeometry.attributes;
  23622. p2Indices = eastGeometry.indices;
  23623. }
  23624. var offsetPoint = Cartesian3.add(intersection, offset, cartesian3Scratch6);
  23625. p0Attributes.position.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  23626. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23627. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23628. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3], prevPositions[i0 * 3 + 1], prevPositions[i0 * 3 + 2]);
  23629. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3 + 3], prevPositions[i0 * 3 + 4], prevPositions[i0 * 3 + 5]);
  23630. p0Attributes.prevPosition.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  23631. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23632. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23633. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23634. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23635. Cartesian3.negate(offset, offset);
  23636. Cartesian3.add(intersection, offset, offsetPoint);
  23637. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23638. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23639. p2Attributes.position.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  23640. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23641. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23642. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23643. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23644. p2Attributes.nextPosition.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  23645. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3], nextPositions[i2 * 3 + 1], nextPositions[i2 * 3 + 2]);
  23646. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3 + 3], nextPositions[i2 * 3 + 4], nextPositions[i2 * 3 + 5]);
  23647. var ew0 = Cartesian2.fromArray(expandAndWidths, i0 * 2, cartesian2Scratch0);
  23648. var width = Math.abs(ew0.y);
  23649. p0Attributes.expandAndWidth.values.push(-1, width, 1, width);
  23650. p0Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  23651. p2Attributes.expandAndWidth.values.push(-1, width, 1, width);
  23652. p2Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  23653. var t = Cartesian3.magnitudeSquared(Cartesian3.subtract(intersection, p0, cartesian3Scratch3));
  23654. t /= Cartesian3.magnitudeSquared(Cartesian3.subtract(p2, p0, cartesian3Scratch3));
  23655. if (defined(colors)) {
  23656. var c0 = Cartesian4.fromArray(colors, i0 * 4, cartesian4Scratch0);
  23657. var c2 = Cartesian4.fromArray(colors, i2 * 4, cartesian4Scratch0);
  23658. var r = CesiumMath.lerp(c0.x, c2.x, t);
  23659. var g = CesiumMath.lerp(c0.y, c2.y, t);
  23660. var b = CesiumMath.lerp(c0.z, c2.z, t);
  23661. var a = CesiumMath.lerp(c0.w, c2.w, t);
  23662. for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
  23663. p0Attributes.color.values.push(colors[j]);
  23664. }
  23665. p0Attributes.color.values.push(r, g, b, a);
  23666. p0Attributes.color.values.push(r, g, b, a);
  23667. p2Attributes.color.values.push(r, g, b, a);
  23668. p2Attributes.color.values.push(r, g, b, a);
  23669. for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
  23670. p2Attributes.color.values.push(colors[j]);
  23671. }
  23672. }
  23673. if (defined(texCoords)) {
  23674. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
  23675. var s3 = Cartesian2.fromArray(texCoords, (i + 3) * 2, cartesian2Scratch1);
  23676. var sx = CesiumMath.lerp(s0.x, s3.x, t);
  23677. for (j = i0 * 2; j < i0 * 2 + 2 * 2; ++j) {
  23678. p0Attributes.st.values.push(texCoords[j]);
  23679. }
  23680. p0Attributes.st.values.push(sx, s0.y);
  23681. p0Attributes.st.values.push(sx, s3.y);
  23682. p2Attributes.st.values.push(sx, s0.y);
  23683. p2Attributes.st.values.push(sx, s3.y);
  23684. for (j = i2 * 2; j < i2 * 2 + 2 * 2; ++j) {
  23685. p2Attributes.st.values.push(texCoords[j]);
  23686. }
  23687. }
  23688. index = p0Attributes.position.values.length / 3 - 4;
  23689. p0Indices.push(index, index + 2, index + 1);
  23690. p0Indices.push(index + 1, index + 2, index + 3);
  23691. index = p2Attributes.position.values.length / 3 - 4;
  23692. p2Indices.push(index, index + 2, index + 1);
  23693. p2Indices.push(index + 1, index + 2, index + 3);
  23694. } else {
  23695. var currentAttributes;
  23696. var currentIndices;
  23697. if (p0.y < 0.0) {
  23698. currentAttributes = westGeometry.attributes;
  23699. currentIndices = westGeometry.indices;
  23700. } else {
  23701. currentAttributes = eastGeometry.attributes;
  23702. currentIndices = eastGeometry.indices;
  23703. }
  23704. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  23705. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  23706. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  23707. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  23708. for (j = i * 3; j < i * 3 + 4 * 3; ++j) {
  23709. currentAttributes.prevPosition.values.push(prevPositions[j]);
  23710. currentAttributes.nextPosition.values.push(nextPositions[j]);
  23711. }
  23712. for (j = i * 2; j < i * 2 + 4 * 2; ++j) {
  23713. currentAttributes.expandAndWidth.values.push(expandAndWidths[j]);
  23714. if (defined(texCoords)) {
  23715. currentAttributes.st.values.push(texCoords[j]);
  23716. }
  23717. }
  23718. if (defined(colors)) {
  23719. for (j = i * 4; j < i * 4 + 4 * 4; ++j) {
  23720. currentAttributes.color.values.push(colors[j]);
  23721. }
  23722. }
  23723. index = currentAttributes.position.values.length / 3 - 4;
  23724. currentIndices.push(index, index + 2, index + 1);
  23725. currentIndices.push(index + 1, index + 2, index + 3);
  23726. }
  23727. }
  23728. if (intersectionFound) {
  23729. updateAdjacencyAfterSplit(westGeometry);
  23730. updateAdjacencyAfterSplit(eastGeometry);
  23731. }
  23732. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  23733. }
  23734. /**
  23735. * Splits the instances's geometry, by introducing new vertices and indices,that
  23736. * intersect the International Date Line and Prime Meridian so that no primitives cross longitude
  23737. * -180/180 degrees. This is not required for 3D drawing, but is required for
  23738. * correcting drawing in 2D and Columbus view.
  23739. *
  23740. * @private
  23741. *
  23742. * @param {GeometryInstance} instance The instance to modify.
  23743. * @returns {GeometryInstance} The modified <code>instance</code> argument, with it's geometry split at the International Date Line.
  23744. *
  23745. * @example
  23746. * instance = Cesium.GeometryPipeline.splitLongitude(instance);
  23747. */
  23748. GeometryPipeline.splitLongitude = function(instance) {
  23749. if (!defined(instance)) {
  23750. throw new DeveloperError('instance is required.');
  23751. }
  23752. var geometry = instance.geometry;
  23753. var boundingSphere = geometry.boundingSphere;
  23754. if (defined(boundingSphere)) {
  23755. var minX = boundingSphere.center.x - boundingSphere.radius;
  23756. if (minX > 0 || BoundingSphere.intersectPlane(boundingSphere, Plane.ORIGIN_ZX_PLANE) !== Intersect.INTERSECTING) {
  23757. return instance;
  23758. }
  23759. }
  23760. if (geometry.geometryType !== GeometryType.NONE) {
  23761. switch (geometry.geometryType) {
  23762. case GeometryType.POLYLINES:
  23763. splitLongitudePolyline(instance);
  23764. break;
  23765. case GeometryType.TRIANGLES:
  23766. splitLongitudeTriangles(instance);
  23767. break;
  23768. case GeometryType.LINES:
  23769. splitLongitudeLines(instance);
  23770. break;
  23771. }
  23772. } else {
  23773. indexPrimitive(geometry);
  23774. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  23775. splitLongitudeTriangles(instance);
  23776. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  23777. splitLongitudeLines(instance);
  23778. }
  23779. }
  23780. return instance;
  23781. };
  23782. return GeometryPipeline;
  23783. });
  23784. /*global define*/
  23785. define('Core/arrayRemoveDuplicates',[
  23786. './defaultValue',
  23787. './defined',
  23788. './DeveloperError',
  23789. './Math'
  23790. ], function(
  23791. defaultValue,
  23792. defined,
  23793. DeveloperError,
  23794. CesiumMath) {
  23795. 'use strict';
  23796. var removeDuplicatesEpsilon = CesiumMath.EPSILON10;
  23797. /**
  23798. * Removes adjacent duplicate values in an array of values.
  23799. *
  23800. * @param {Object[]} [values] The array of values.
  23801. * @param {Function} equalsEpsilon Function to compare values with an epsilon. Boolean equalsEpsilon(left, right, epsilon).
  23802. * @param {Boolean} [wrapAround=false] Compare the last value in the array against the first value.
  23803. * @returns {Object[]|undefined} A new array of values with no adjacent duplicate values or the input array if no duplicates were found.
  23804. *
  23805. * @example
  23806. * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0), (1.0, 1.0, 1.0)]
  23807. * var values = [
  23808. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  23809. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  23810. * new Cesium.Cartesian3(2.0, 2.0, 2.0),
  23811. * new Cesium.Cartesian3(3.0, 3.0, 3.0),
  23812. * new Cesium.Cartesian3(1.0, 1.0, 1.0)];
  23813. * var nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon);
  23814. *
  23815. * @example
  23816. * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0)]
  23817. * var values = [
  23818. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  23819. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  23820. * new Cesium.Cartesian3(2.0, 2.0, 2.0),
  23821. * new Cesium.Cartesian3(3.0, 3.0, 3.0),
  23822. * new Cesium.Cartesian3(1.0, 1.0, 1.0)];
  23823. * var nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon, true);
  23824. *
  23825. * @private
  23826. */
  23827. function arrayRemoveDuplicates(values, equalsEpsilon, wrapAround) {
  23828. if (!defined(equalsEpsilon)) {
  23829. throw new DeveloperError('equalsEpsilon is required.');
  23830. }
  23831. if (!defined(values)) {
  23832. return undefined;
  23833. }
  23834. wrapAround = defaultValue(wrapAround, false);
  23835. var length = values.length;
  23836. if (length < 2) {
  23837. return values;
  23838. }
  23839. var i;
  23840. var v0;
  23841. var v1;
  23842. for (i = 1; i < length; ++i) {
  23843. v0 = values[i - 1];
  23844. v1 = values[i];
  23845. if (equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
  23846. break;
  23847. }
  23848. }
  23849. if (i === length) {
  23850. if (wrapAround && equalsEpsilon(values[0], values[values.length - 1], removeDuplicatesEpsilon)) {
  23851. return values.slice(1);
  23852. }
  23853. return values;
  23854. }
  23855. var cleanedvalues = values.slice(0, i);
  23856. for (; i < length; ++i) {
  23857. // v0 is set by either the previous loop, or the previous clean point.
  23858. v1 = values[i];
  23859. if (!equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
  23860. cleanedvalues.push(v1);
  23861. v0 = v1;
  23862. }
  23863. }
  23864. if (wrapAround && cleanedvalues.length > 1 && equalsEpsilon(cleanedvalues[0], cleanedvalues[cleanedvalues.length - 1], removeDuplicatesEpsilon)) {
  23865. cleanedvalues.shift();
  23866. }
  23867. return cleanedvalues;
  23868. }
  23869. return arrayRemoveDuplicates;
  23870. });
  23871. /*global define*/
  23872. define('Core/GeometryAttributes',[
  23873. './defaultValue'
  23874. ], function(
  23875. defaultValue) {
  23876. 'use strict';
  23877. /**
  23878. * Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
  23879. * {@link GeometryAttribute} containing the attribute's data.
  23880. * <p>
  23881. * Attributes are always stored non-interleaved in a Geometry.
  23882. * </p>
  23883. *
  23884. * @alias GeometryAttributes
  23885. * @constructor
  23886. */
  23887. function GeometryAttributes(options) {
  23888. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  23889. /**
  23890. * The 3D position attribute.
  23891. * <p>
  23892. * 64-bit floating-point (for precision). 3 components per attribute.
  23893. * </p>
  23894. *
  23895. * @type GeometryAttribute
  23896. *
  23897. * @default undefined
  23898. */
  23899. this.position = options.position;
  23900. /**
  23901. * The normal attribute (normalized), which is commonly used for lighting.
  23902. * <p>
  23903. * 32-bit floating-point. 3 components per attribute.
  23904. * </p>
  23905. *
  23906. * @type GeometryAttribute
  23907. *
  23908. * @default undefined
  23909. */
  23910. this.normal = options.normal;
  23911. /**
  23912. * The 2D texture coordinate attribute.
  23913. * <p>
  23914. * 32-bit floating-point. 2 components per attribute
  23915. * </p>
  23916. *
  23917. * @type GeometryAttribute
  23918. *
  23919. * @default undefined
  23920. */
  23921. this.st = options.st;
  23922. /**
  23923. * The binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  23924. * <p>
  23925. * 32-bit floating-point. 3 components per attribute.
  23926. * </p>
  23927. *
  23928. * @type GeometryAttribute
  23929. *
  23930. * @default undefined
  23931. */
  23932. this.binormal = options.binormal;
  23933. /**
  23934. * The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  23935. * <p>
  23936. * 32-bit floating-point. 3 components per attribute.
  23937. * </p>
  23938. *
  23939. * @type GeometryAttribute
  23940. *
  23941. * @default undefined
  23942. */
  23943. this.tangent = options.tangent;
  23944. /**
  23945. * The color attribute.
  23946. * <p>
  23947. * 8-bit unsigned integer. 4 components per attribute.
  23948. * </p>
  23949. *
  23950. * @type GeometryAttribute
  23951. *
  23952. * @default undefined
  23953. */
  23954. this.color = options.color;
  23955. }
  23956. return GeometryAttributes;
  23957. });
  23958. /*global define*/
  23959. define('ThirdParty/earcut-2.1.1',[], function() {
  23960. 'use strict';
  23961. function earcut(data, holeIndices, dim) {
  23962. dim = dim || 2;
  23963. var hasHoles = holeIndices && holeIndices.length,
  23964. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  23965. outerNode = linkedList(data, 0, outerLen, dim, true),
  23966. triangles = [];
  23967. if (!outerNode) return triangles;
  23968. var minX, minY, maxX, maxY, x, y, size;
  23969. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  23970. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  23971. if (data.length > 80 * dim) {
  23972. minX = maxX = data[0];
  23973. minY = maxY = data[1];
  23974. for (var i = dim; i < outerLen; i += dim) {
  23975. x = data[i];
  23976. y = data[i + 1];
  23977. if (x < minX) minX = x;
  23978. if (y < minY) minY = y;
  23979. if (x > maxX) maxX = x;
  23980. if (y > maxY) maxY = y;
  23981. }
  23982. // minX, minY and size are later used to transform coords into integers for z-order calculation
  23983. size = Math.max(maxX - minX, maxY - minY);
  23984. }
  23985. earcutLinked(outerNode, triangles, dim, minX, minY, size);
  23986. return triangles;
  23987. }
  23988. // create a circular doubly linked list from polygon points in the specified winding order
  23989. function linkedList(data, start, end, dim, clockwise) {
  23990. var i, last;
  23991. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  23992. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  23993. } else {
  23994. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  23995. }
  23996. if (last && equals(last, last.next)) {
  23997. removeNode(last);
  23998. last = last.next;
  23999. }
  24000. return last;
  24001. }
  24002. // eliminate colinear or duplicate points
  24003. function filterPoints(start, end) {
  24004. if (!start) return start;
  24005. if (!end) end = start;
  24006. var p = start,
  24007. again;
  24008. do {
  24009. again = false;
  24010. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24011. removeNode(p);
  24012. p = end = p.prev;
  24013. if (p === p.next) return null;
  24014. again = true;
  24015. } else {
  24016. p = p.next;
  24017. }
  24018. } while (again || p !== end);
  24019. return end;
  24020. }
  24021. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24022. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  24023. if (!ear) return;
  24024. // interlink polygon nodes in z-order
  24025. if (!pass && size) indexCurve(ear, minX, minY, size);
  24026. var stop = ear,
  24027. prev, next;
  24028. // iterate through ears, slicing them one by one
  24029. while (ear.prev !== ear.next) {
  24030. prev = ear.prev;
  24031. next = ear.next;
  24032. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  24033. // cut off the triangle
  24034. triangles.push(prev.i / dim);
  24035. triangles.push(ear.i / dim);
  24036. triangles.push(next.i / dim);
  24037. removeNode(ear);
  24038. // skipping the next vertice leads to less sliver triangles
  24039. ear = next.next;
  24040. stop = next.next;
  24041. continue;
  24042. }
  24043. ear = next;
  24044. // if we looped through the whole remaining polygon and can't find any more ears
  24045. if (ear === stop) {
  24046. // try filtering points and slicing again
  24047. if (!pass) {
  24048. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
  24049. // if this didn't work, try curing all small self-intersections locally
  24050. } else if (pass === 1) {
  24051. ear = cureLocalIntersections(ear, triangles, dim);
  24052. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  24053. // as a last resort, try splitting the remaining polygon into two
  24054. } else if (pass === 2) {
  24055. splitEarcut(ear, triangles, dim, minX, minY, size);
  24056. }
  24057. break;
  24058. }
  24059. }
  24060. }
  24061. // check whether a polygon node forms a valid ear with adjacent nodes
  24062. function isEar(ear) {
  24063. var a = ear.prev,
  24064. b = ear,
  24065. c = ear.next;
  24066. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24067. // now make sure we don't have other points inside the potential ear
  24068. var p = ear.next.next;
  24069. while (p !== ear.prev) {
  24070. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  24071. area(p.prev, p, p.next) >= 0) return false;
  24072. p = p.next;
  24073. }
  24074. return true;
  24075. }
  24076. function isEarHashed(ear, minX, minY, size) {
  24077. var a = ear.prev,
  24078. b = ear,
  24079. c = ear.next;
  24080. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24081. // triangle bbox; min & max are calculated like this for speed
  24082. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  24083. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  24084. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  24085. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  24086. // z-order range for the current triangle bbox;
  24087. var minZ = zOrder(minTX, minTY, minX, minY, size),
  24088. maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  24089. // first look for points inside the triangle in increasing z-order
  24090. var p = ear.nextZ;
  24091. while (p && p.z <= maxZ) {
  24092. if (p !== ear.prev && p !== ear.next &&
  24093. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  24094. area(p.prev, p, p.next) >= 0) return false;
  24095. p = p.nextZ;
  24096. }
  24097. // then look for points in decreasing z-order
  24098. p = ear.prevZ;
  24099. while (p && p.z >= minZ) {
  24100. if (p !== ear.prev && p !== ear.next &&
  24101. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  24102. area(p.prev, p, p.next) >= 0) return false;
  24103. p = p.prevZ;
  24104. }
  24105. return true;
  24106. }
  24107. // go through all polygon nodes and cure small local self-intersections
  24108. function cureLocalIntersections(start, triangles, dim) {
  24109. var p = start;
  24110. do {
  24111. var a = p.prev,
  24112. b = p.next.next;
  24113. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24114. triangles.push(a.i / dim);
  24115. triangles.push(p.i / dim);
  24116. triangles.push(b.i / dim);
  24117. // remove two nodes involved
  24118. removeNode(p);
  24119. removeNode(p.next);
  24120. p = start = b;
  24121. }
  24122. p = p.next;
  24123. } while (p !== start);
  24124. return p;
  24125. }
  24126. // try splitting polygon into two and triangulate them independently
  24127. function splitEarcut(start, triangles, dim, minX, minY, size) {
  24128. // look for a valid diagonal that divides the polygon into two
  24129. var a = start;
  24130. do {
  24131. var b = a.next.next;
  24132. while (b !== a.prev) {
  24133. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24134. // split the polygon in two by the diagonal
  24135. var c = splitPolygon(a, b);
  24136. // filter colinear points around the cuts
  24137. a = filterPoints(a, a.next);
  24138. c = filterPoints(c, c.next);
  24139. // run earcut on each half
  24140. earcutLinked(a, triangles, dim, minX, minY, size);
  24141. earcutLinked(c, triangles, dim, minX, minY, size);
  24142. return;
  24143. }
  24144. b = b.next;
  24145. }
  24146. a = a.next;
  24147. } while (a !== start);
  24148. }
  24149. // link every hole into the outer loop, producing a single-ring polygon without holes
  24150. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24151. var queue = [],
  24152. i, len, start, end, list;
  24153. for (i = 0, len = holeIndices.length; i < len; i++) {
  24154. start = holeIndices[i] * dim;
  24155. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24156. list = linkedList(data, start, end, dim, false);
  24157. if (list === list.next) list.steiner = true;
  24158. queue.push(getLeftmost(list));
  24159. }
  24160. queue.sort(compareX);
  24161. // process holes from left to right
  24162. for (i = 0; i < queue.length; i++) {
  24163. eliminateHole(queue[i], outerNode);
  24164. outerNode = filterPoints(outerNode, outerNode.next);
  24165. }
  24166. return outerNode;
  24167. }
  24168. function compareX(a, b) {
  24169. return a.x - b.x;
  24170. }
  24171. // find a bridge between vertices that connects hole with an outer ring and and link it
  24172. function eliminateHole(hole, outerNode) {
  24173. outerNode = findHoleBridge(hole, outerNode);
  24174. if (outerNode) {
  24175. var b = splitPolygon(outerNode, hole);
  24176. filterPoints(b, b.next);
  24177. }
  24178. }
  24179. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24180. function findHoleBridge(hole, outerNode) {
  24181. var p = outerNode,
  24182. hx = hole.x,
  24183. hy = hole.y,
  24184. qx = -Infinity,
  24185. m;
  24186. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24187. // segment's endpoint with lesser x will be potential connection point
  24188. do {
  24189. if (hy <= p.y && hy >= p.next.y) {
  24190. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24191. if (x <= hx && x > qx) {
  24192. qx = x;
  24193. if (x === hx) {
  24194. if (hy === p.y) return p;
  24195. if (hy === p.next.y) return p.next;
  24196. }
  24197. m = p.x < p.next.x ? p : p.next;
  24198. }
  24199. }
  24200. p = p.next;
  24201. } while (p !== outerNode);
  24202. if (!m) return null;
  24203. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  24204. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24205. // if there are no points found, we have a valid connection;
  24206. // otherwise choose the point of the minimum angle with the ray as connection point
  24207. var stop = m,
  24208. mx = m.x,
  24209. my = m.y,
  24210. tanMin = Infinity,
  24211. tan;
  24212. p = m.next;
  24213. while (p !== stop) {
  24214. if (hx >= p.x && p.x >= mx &&
  24215. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24216. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24217. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  24218. m = p;
  24219. tanMin = tan;
  24220. }
  24221. }
  24222. p = p.next;
  24223. }
  24224. return m;
  24225. }
  24226. // interlink polygon nodes in z-order
  24227. function indexCurve(start, minX, minY, size) {
  24228. var p = start;
  24229. do {
  24230. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
  24231. p.prevZ = p.prev;
  24232. p.nextZ = p.next;
  24233. p = p.next;
  24234. } while (p !== start);
  24235. p.prevZ.nextZ = null;
  24236. p.prevZ = null;
  24237. sortLinked(p);
  24238. }
  24239. // Simon Tatham's linked list merge sort algorithm
  24240. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24241. function sortLinked(list) {
  24242. var i, p, q, e, tail, numMerges, pSize, qSize,
  24243. inSize = 1;
  24244. do {
  24245. p = list;
  24246. list = null;
  24247. tail = null;
  24248. numMerges = 0;
  24249. while (p) {
  24250. numMerges++;
  24251. q = p;
  24252. pSize = 0;
  24253. for (i = 0; i < inSize; i++) {
  24254. pSize++;
  24255. q = q.nextZ;
  24256. if (!q) break;
  24257. }
  24258. qSize = inSize;
  24259. while (pSize > 0 || (qSize > 0 && q)) {
  24260. if (pSize === 0) {
  24261. e = q;
  24262. q = q.nextZ;
  24263. qSize--;
  24264. } else if (qSize === 0 || !q) {
  24265. e = p;
  24266. p = p.nextZ;
  24267. pSize--;
  24268. } else if (p.z <= q.z) {
  24269. e = p;
  24270. p = p.nextZ;
  24271. pSize--;
  24272. } else {
  24273. e = q;
  24274. q = q.nextZ;
  24275. qSize--;
  24276. }
  24277. if (tail) tail.nextZ = e;
  24278. else list = e;
  24279. e.prevZ = tail;
  24280. tail = e;
  24281. }
  24282. p = q;
  24283. }
  24284. tail.nextZ = null;
  24285. inSize *= 2;
  24286. } while (numMerges > 1);
  24287. return list;
  24288. }
  24289. // z-order of a point given coords and size of the data bounding box
  24290. function zOrder(x, y, minX, minY, size) {
  24291. // coords are transformed into non-negative 15-bit integer range
  24292. x = 32767 * (x - minX) / size;
  24293. y = 32767 * (y - minY) / size;
  24294. x = (x | (x << 8)) & 0x00FF00FF;
  24295. x = (x | (x << 4)) & 0x0F0F0F0F;
  24296. x = (x | (x << 2)) & 0x33333333;
  24297. x = (x | (x << 1)) & 0x55555555;
  24298. y = (y | (y << 8)) & 0x00FF00FF;
  24299. y = (y | (y << 4)) & 0x0F0F0F0F;
  24300. y = (y | (y << 2)) & 0x33333333;
  24301. y = (y | (y << 1)) & 0x55555555;
  24302. return x | (y << 1);
  24303. }
  24304. // find the leftmost node of a polygon ring
  24305. function getLeftmost(start) {
  24306. var p = start,
  24307. leftmost = start;
  24308. do {
  24309. if (p.x < leftmost.x) leftmost = p;
  24310. p = p.next;
  24311. } while (p !== start);
  24312. return leftmost;
  24313. }
  24314. // check if a point lies within a convex triangle
  24315. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  24316. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  24317. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  24318. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  24319. }
  24320. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  24321. function isValidDiagonal(a, b) {
  24322. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
  24323. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  24324. }
  24325. // signed area of a triangle
  24326. function area(p, q, r) {
  24327. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  24328. }
  24329. // check if two points are equal
  24330. function equals(p1, p2) {
  24331. return p1.x === p2.x && p1.y === p2.y;
  24332. }
  24333. // check if two segments intersect
  24334. function intersects(p1, q1, p2, q2) {
  24335. if ((equals(p1, q1) && equals(p2, q2)) ||
  24336. (equals(p1, q2) && equals(p2, q1))) return true;
  24337. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  24338. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  24339. }
  24340. // check if a polygon diagonal intersects any polygon segments
  24341. function intersectsPolygon(a, b) {
  24342. var p = a;
  24343. do {
  24344. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  24345. intersects(p, p.next, a, b)) return true;
  24346. p = p.next;
  24347. } while (p !== a);
  24348. return false;
  24349. }
  24350. // check if a polygon diagonal is locally inside the polygon
  24351. function locallyInside(a, b) {
  24352. return area(a.prev, a, a.next) < 0 ?
  24353. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  24354. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24355. }
  24356. // check if the middle point of a polygon diagonal is inside the polygon
  24357. function middleInside(a, b) {
  24358. var p = a,
  24359. inside = false,
  24360. px = (a.x + b.x) / 2,
  24361. py = (a.y + b.y) / 2;
  24362. do {
  24363. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  24364. inside = !inside;
  24365. p = p.next;
  24366. } while (p !== a);
  24367. return inside;
  24368. }
  24369. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24370. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24371. function splitPolygon(a, b) {
  24372. var a2 = new Node(a.i, a.x, a.y),
  24373. b2 = new Node(b.i, b.x, b.y),
  24374. an = a.next,
  24375. bp = b.prev;
  24376. a.next = b;
  24377. b.prev = a;
  24378. a2.next = an;
  24379. an.prev = a2;
  24380. b2.next = a2;
  24381. a2.prev = b2;
  24382. bp.next = b2;
  24383. b2.prev = bp;
  24384. return b2;
  24385. }
  24386. // create a node and optionally link it with previous one (in a circular doubly linked list)
  24387. function insertNode(i, x, y, last) {
  24388. var p = new Node(i, x, y);
  24389. if (!last) {
  24390. p.prev = p;
  24391. p.next = p;
  24392. } else {
  24393. p.next = last.next;
  24394. p.prev = last;
  24395. last.next.prev = p;
  24396. last.next = p;
  24397. }
  24398. return p;
  24399. }
  24400. function removeNode(p) {
  24401. p.next.prev = p.prev;
  24402. p.prev.next = p.next;
  24403. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24404. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24405. }
  24406. function Node(i, x, y) {
  24407. // vertice index in coordinates array
  24408. this.i = i;
  24409. // vertex coordinates
  24410. this.x = x;
  24411. this.y = y;
  24412. // previous and next vertice nodes in a polygon ring
  24413. this.prev = null;
  24414. this.next = null;
  24415. // z-order curve value
  24416. this.z = null;
  24417. // previous and next nodes in z-order
  24418. this.prevZ = null;
  24419. this.nextZ = null;
  24420. // indicates whether this is a steiner point
  24421. this.steiner = false;
  24422. }
  24423. // return a percentage difference between the polygon area and its triangulation area;
  24424. // used to verify correctness of triangulation
  24425. earcut.deviation = function (data, holeIndices, dim, triangles) {
  24426. var hasHoles = holeIndices && holeIndices.length;
  24427. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24428. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  24429. if (hasHoles) {
  24430. for (var i = 0, len = holeIndices.length; i < len; i++) {
  24431. var start = holeIndices[i] * dim;
  24432. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24433. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  24434. }
  24435. }
  24436. var trianglesArea = 0;
  24437. for (i = 0; i < triangles.length; i += 3) {
  24438. var a = triangles[i] * dim;
  24439. var b = triangles[i + 1] * dim;
  24440. var c = triangles[i + 2] * dim;
  24441. trianglesArea += Math.abs(
  24442. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  24443. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  24444. }
  24445. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  24446. Math.abs((trianglesArea - polygonArea) / polygonArea);
  24447. };
  24448. function signedArea(data, start, end, dim) {
  24449. var sum = 0;
  24450. for (var i = start, j = end - dim; i < end; i += dim) {
  24451. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24452. j = i;
  24453. }
  24454. return sum;
  24455. }
  24456. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  24457. earcut.flatten = function (data) {
  24458. var dim = data[0][0].length,
  24459. result = {vertices: [], holes: [], dimensions: dim},
  24460. holeIndex = 0;
  24461. for (var i = 0; i < data.length; i++) {
  24462. for (var j = 0; j < data[i].length; j++) {
  24463. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  24464. }
  24465. if (i > 0) {
  24466. holeIndex += data[i - 1].length;
  24467. result.holes.push(holeIndex);
  24468. }
  24469. }
  24470. return result;
  24471. };
  24472. return earcut;
  24473. });
  24474. /*global define*/
  24475. define('Core/WindingOrder',[
  24476. './freezeObject',
  24477. './WebGLConstants'
  24478. ], function(
  24479. freezeObject,
  24480. WebGLConstants) {
  24481. 'use strict';
  24482. /**
  24483. * Winding order defines the order of vertices for a triangle to be considered front-facing.
  24484. *
  24485. * @exports WindingOrder
  24486. */
  24487. var WindingOrder = {
  24488. /**
  24489. * Vertices are in clockwise order.
  24490. *
  24491. * @type {Number}
  24492. * @constant
  24493. */
  24494. CLOCKWISE : WebGLConstants.CW,
  24495. /**
  24496. * Vertices are in counter-clockwise order.
  24497. *
  24498. * @type {Number}
  24499. * @constant
  24500. */
  24501. COUNTER_CLOCKWISE : WebGLConstants.CCW,
  24502. /**
  24503. * @private
  24504. */
  24505. validate : function(windingOrder) {
  24506. return windingOrder === WindingOrder.CLOCKWISE ||
  24507. windingOrder === WindingOrder.COUNTER_CLOCKWISE;
  24508. }
  24509. };
  24510. return freezeObject(WindingOrder);
  24511. });
  24512. /*global define*/
  24513. define('Core/PolygonPipeline',[
  24514. '../ThirdParty/earcut-2.1.1',
  24515. './Cartesian2',
  24516. './Cartesian3',
  24517. './ComponentDatatype',
  24518. './defaultValue',
  24519. './defined',
  24520. './DeveloperError',
  24521. './Ellipsoid',
  24522. './Geometry',
  24523. './GeometryAttribute',
  24524. './Math',
  24525. './PrimitiveType',
  24526. './WindingOrder'
  24527. ], function(
  24528. earcut,
  24529. Cartesian2,
  24530. Cartesian3,
  24531. ComponentDatatype,
  24532. defaultValue,
  24533. defined,
  24534. DeveloperError,
  24535. Ellipsoid,
  24536. Geometry,
  24537. GeometryAttribute,
  24538. CesiumMath,
  24539. PrimitiveType,
  24540. WindingOrder) {
  24541. 'use strict';
  24542. var scaleToGeodeticHeightN = new Cartesian3();
  24543. var scaleToGeodeticHeightP = new Cartesian3();
  24544. /**
  24545. * @private
  24546. */
  24547. var PolygonPipeline = {};
  24548. /**
  24549. * @exception {DeveloperError} At least three positions are required.
  24550. */
  24551. PolygonPipeline.computeArea2D = function(positions) {
  24552. if (!defined(positions)) {
  24553. throw new DeveloperError('positions is required.');
  24554. }
  24555. if (positions.length < 3) {
  24556. throw new DeveloperError('At least three positions are required.');
  24557. }
  24558. var length = positions.length;
  24559. var area = 0.0;
  24560. for ( var i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
  24561. var v0 = positions[i0];
  24562. var v1 = positions[i1];
  24563. area += (v0.x * v1.y) - (v1.x * v0.y);
  24564. }
  24565. return area * 0.5;
  24566. };
  24567. /**
  24568. * @returns {WindingOrder} The winding order.
  24569. *
  24570. * @exception {DeveloperError} At least three positions are required.
  24571. */
  24572. PolygonPipeline.computeWindingOrder2D = function(positions) {
  24573. var area = PolygonPipeline.computeArea2D(positions);
  24574. return (area > 0.0) ? WindingOrder.COUNTER_CLOCKWISE : WindingOrder.CLOCKWISE;
  24575. };
  24576. /**
  24577. * Triangulate a polygon.
  24578. *
  24579. * @param {Cartesian2[]} positions Cartesian2 array containing the vertices of the polygon
  24580. * @param {Number[]} [holes] An array of the staring indices of the holes.
  24581. * @returns {Number[]} Index array representing triangles that fill the polygon
  24582. */
  24583. PolygonPipeline.triangulate = function(positions, holes) {
  24584. if (!defined(positions)) {
  24585. throw new DeveloperError('positions is required.');
  24586. }
  24587. var flattenedPositions = Cartesian2.packArray(positions);
  24588. return earcut(flattenedPositions, holes, 2);
  24589. };
  24590. var subdivisionV0Scratch = new Cartesian3();
  24591. var subdivisionV1Scratch = new Cartesian3();
  24592. var subdivisionV2Scratch = new Cartesian3();
  24593. var subdivisionS0Scratch = new Cartesian3();
  24594. var subdivisionS1Scratch = new Cartesian3();
  24595. var subdivisionS2Scratch = new Cartesian3();
  24596. var subdivisionMidScratch = new Cartesian3();
  24597. /**
  24598. * Subdivides positions and raises points to the surface of the ellipsoid.
  24599. *
  24600. * @param {Ellipsoid} ellipsoid The ellipsoid the polygon in on.
  24601. * @param {Cartesian3[]} positions An array of {@link Cartesian3} positions of the polygon.
  24602. * @param {Number[]} indices An array of indices that determines the triangles in the polygon.
  24603. * @param {Number} [granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  24604. *
  24605. * @exception {DeveloperError} At least three indices are required.
  24606. * @exception {DeveloperError} The number of indices must be divisable by three.
  24607. * @exception {DeveloperError} Granularity must be greater than zero.
  24608. */
  24609. PolygonPipeline.computeSubdivision = function(ellipsoid, positions, indices, granularity) {
  24610. granularity = defaultValue(granularity, CesiumMath.RADIANS_PER_DEGREE);
  24611. if (!defined(ellipsoid)) {
  24612. throw new DeveloperError('ellipsoid is required.');
  24613. }
  24614. if (!defined(positions)) {
  24615. throw new DeveloperError('positions is required.');
  24616. }
  24617. if (!defined(indices)) {
  24618. throw new DeveloperError('indices is required.');
  24619. }
  24620. if (indices.length < 3) {
  24621. throw new DeveloperError('At least three indices are required.');
  24622. }
  24623. if (indices.length % 3 !== 0) {
  24624. throw new DeveloperError('The number of indices must be divisable by three.');
  24625. }
  24626. if (granularity <= 0.0) {
  24627. throw new DeveloperError('granularity must be greater than zero.');
  24628. }
  24629. // triangles that need (or might need) to be subdivided.
  24630. var triangles = indices.slice(0);
  24631. // New positions due to edge splits are appended to the positions list.
  24632. var i;
  24633. var length = positions.length;
  24634. var subdividedPositions = new Array(length * 3);
  24635. var q = 0;
  24636. for (i = 0; i < length; i++) {
  24637. var item = positions[i];
  24638. subdividedPositions[q++] = item.x;
  24639. subdividedPositions[q++] = item.y;
  24640. subdividedPositions[q++] = item.z;
  24641. }
  24642. var subdividedIndices = [];
  24643. // Used to make sure shared edges are not split more than once.
  24644. var edges = {};
  24645. var radius = ellipsoid.maximumRadius;
  24646. var minDistance = CesiumMath.chordLength(granularity, radius);
  24647. var minDistanceSqrd = minDistance * minDistance;
  24648. while (triangles.length > 0) {
  24649. var i2 = triangles.pop();
  24650. var i1 = triangles.pop();
  24651. var i0 = triangles.pop();
  24652. var v0 = Cartesian3.fromArray(subdividedPositions, i0 * 3, subdivisionV0Scratch);
  24653. var v1 = Cartesian3.fromArray(subdividedPositions, i1 * 3, subdivisionV1Scratch);
  24654. var v2 = Cartesian3.fromArray(subdividedPositions, i2 * 3, subdivisionV2Scratch);
  24655. var s0 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v0, subdivisionS0Scratch), radius, subdivisionS0Scratch);
  24656. var s1 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v1, subdivisionS1Scratch), radius, subdivisionS1Scratch);
  24657. var s2 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v2, subdivisionS2Scratch), radius, subdivisionS2Scratch);
  24658. var g0 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s0, s1, subdivisionMidScratch));
  24659. var g1 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s1, s2, subdivisionMidScratch));
  24660. var g2 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s2, s0, subdivisionMidScratch));
  24661. var max = Math.max(g0, g1, g2);
  24662. var edge;
  24663. var mid;
  24664. // if the max length squared of a triangle edge is greater than the chord length of squared
  24665. // of the granularity, subdivide the triangle
  24666. if (max > minDistanceSqrd) {
  24667. if (g0 === max) {
  24668. edge = Math.min(i0, i1) + ' ' + Math.max(i0, i1);
  24669. i = edges[edge];
  24670. if (!defined(i)) {
  24671. mid = Cartesian3.add(v0, v1, subdivisionMidScratch);
  24672. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  24673. subdividedPositions.push(mid.x, mid.y, mid.z);
  24674. i = subdividedPositions.length / 3 - 1;
  24675. edges[edge] = i;
  24676. }
  24677. triangles.push(i0, i, i2);
  24678. triangles.push(i, i1, i2);
  24679. } else if (g1 === max) {
  24680. edge = Math.min(i1, i2) + ' ' + Math.max(i1, i2);
  24681. i = edges[edge];
  24682. if (!defined(i)) {
  24683. mid = Cartesian3.add(v1, v2, subdivisionMidScratch);
  24684. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  24685. subdividedPositions.push(mid.x, mid.y, mid.z);
  24686. i = subdividedPositions.length / 3 - 1;
  24687. edges[edge] = i;
  24688. }
  24689. triangles.push(i1, i, i0);
  24690. triangles.push(i, i2, i0);
  24691. } else if (g2 === max) {
  24692. edge = Math.min(i2, i0) + ' ' + Math.max(i2, i0);
  24693. i = edges[edge];
  24694. if (!defined(i)) {
  24695. mid = Cartesian3.add(v2, v0, subdivisionMidScratch);
  24696. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  24697. subdividedPositions.push(mid.x, mid.y, mid.z);
  24698. i = subdividedPositions.length / 3 - 1;
  24699. edges[edge] = i;
  24700. }
  24701. triangles.push(i2, i, i1);
  24702. triangles.push(i, i0, i1);
  24703. }
  24704. } else {
  24705. subdividedIndices.push(i0);
  24706. subdividedIndices.push(i1);
  24707. subdividedIndices.push(i2);
  24708. }
  24709. }
  24710. return new Geometry({
  24711. attributes : {
  24712. position : new GeometryAttribute({
  24713. componentDatatype : ComponentDatatype.DOUBLE,
  24714. componentsPerAttribute : 3,
  24715. values : subdividedPositions
  24716. })
  24717. },
  24718. indices : subdividedIndices,
  24719. primitiveType : PrimitiveType.TRIANGLES
  24720. });
  24721. };
  24722. /**
  24723. * Scales each position of a geometry's position attribute to a height, in place.
  24724. *
  24725. * @param {Number[]} positions The array of numbers representing the positions to be scaled
  24726. * @param {Number} [height=0.0] The desired height to add to the positions
  24727. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  24728. * @param {Boolean} [scaleToSurface=true] <code>true</code> if the positions need to be scaled to the surface before the height is added.
  24729. * @returns {Number[]} The input array of positions, scaled to height
  24730. */
  24731. PolygonPipeline.scaleToGeodeticHeight = function(positions, height, ellipsoid, scaleToSurface) {
  24732. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  24733. var n = scaleToGeodeticHeightN;
  24734. var p = scaleToGeodeticHeightP;
  24735. height = defaultValue(height, 0.0);
  24736. scaleToSurface = defaultValue(scaleToSurface, true);
  24737. if (defined(positions)) {
  24738. var length = positions.length;
  24739. for ( var i = 0; i < length; i += 3) {
  24740. Cartesian3.fromArray(positions, i, p);
  24741. if (scaleToSurface) {
  24742. p = ellipsoid.scaleToGeodeticSurface(p, p);
  24743. }
  24744. if (height !== 0) {
  24745. n = ellipsoid.geodeticSurfaceNormal(p, n);
  24746. Cartesian3.multiplyByScalar(n, height, n);
  24747. Cartesian3.add(p, n, p);
  24748. }
  24749. positions[i] = p.x;
  24750. positions[i + 1] = p.y;
  24751. positions[i + 2] = p.z;
  24752. }
  24753. }
  24754. return positions;
  24755. };
  24756. return PolygonPipeline;
  24757. });
  24758. /*global define*/
  24759. define('Core/Queue',[
  24760. './defineProperties'
  24761. ], function(
  24762. defineProperties) {
  24763. 'use strict';
  24764. /**
  24765. * A queue that can enqueue items at the end, and dequeue items from the front.
  24766. *
  24767. * @alias Queue
  24768. * @constructor
  24769. */
  24770. function Queue() {
  24771. this._array = [];
  24772. this._offset = 0;
  24773. this._length = 0;
  24774. }
  24775. defineProperties(Queue.prototype, {
  24776. /**
  24777. * The length of the queue.
  24778. *
  24779. * @memberof Queue.prototype
  24780. *
  24781. * @type {Number}
  24782. * @readonly
  24783. */
  24784. length : {
  24785. get : function() {
  24786. return this._length;
  24787. }
  24788. }
  24789. });
  24790. /**
  24791. * Enqueues the specified item.
  24792. *
  24793. * @param {Object} item The item to enqueue.
  24794. */
  24795. Queue.prototype.enqueue = function(item) {
  24796. this._array.push(item);
  24797. this._length++;
  24798. };
  24799. /**
  24800. * Dequeues an item. Returns undefined if the queue is empty.
  24801. *
  24802. * @returns {Object} The the dequeued item.
  24803. */
  24804. Queue.prototype.dequeue = function() {
  24805. if (this._length === 0) {
  24806. return undefined;
  24807. }
  24808. var array = this._array;
  24809. var offset = this._offset;
  24810. var item = array[offset];
  24811. array[offset] = undefined;
  24812. offset++;
  24813. if ((offset > 10) && (offset * 2 > array.length)) {
  24814. //compact array
  24815. this._array = array.slice(offset);
  24816. offset = 0;
  24817. }
  24818. this._offset = offset;
  24819. this._length--;
  24820. return item;
  24821. };
  24822. /**
  24823. * Returns the item at the front of the queue. Returns undefined if the queue is empty.
  24824. *
  24825. * @returns {Object} The item at the front of the queue.
  24826. */
  24827. Queue.prototype.peek = function() {
  24828. if (this._length === 0) {
  24829. return undefined;
  24830. }
  24831. return this._array[this._offset];
  24832. };
  24833. /**
  24834. * Check whether this queue contains the specified item.
  24835. *
  24836. * @param {Object} item The item to search for.
  24837. */
  24838. Queue.prototype.contains = function(item) {
  24839. return this._array.indexOf(item) !== -1;
  24840. };
  24841. /**
  24842. * Remove all items from the queue.
  24843. */
  24844. Queue.prototype.clear = function() {
  24845. this._array.length = this._offset = this._length = 0;
  24846. };
  24847. /**
  24848. * Sort the items in the queue in-place.
  24849. *
  24850. * @param {Queue~Comparator} compareFunction A function that defines the sort order.
  24851. */
  24852. Queue.prototype.sort = function(compareFunction) {
  24853. if (this._offset > 0) {
  24854. //compact array
  24855. this._array = this._array.slice(this._offset);
  24856. this._offset = 0;
  24857. }
  24858. this._array.sort(compareFunction);
  24859. };
  24860. /**
  24861. * A function used to compare two items while sorting a queue.
  24862. * @callback Queue~Comparator
  24863. *
  24864. * @param {Object} a An item in the array.
  24865. * @param {Object} b An item in the array.
  24866. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  24867. * a positive value if <code>a</code> is greater than <code>b</code>, or
  24868. * 0 if <code>a</code> is equal to <code>b</code>.
  24869. *
  24870. * @example
  24871. * function compareNumbers(a, b) {
  24872. * return a - b;
  24873. * }
  24874. */
  24875. return Queue;
  24876. });
  24877. /*global define*/
  24878. define('Core/PolygonGeometryLibrary',[
  24879. './arrayRemoveDuplicates',
  24880. './Cartesian3',
  24881. './ComponentDatatype',
  24882. './defaultValue',
  24883. './defined',
  24884. './Ellipsoid',
  24885. './Geometry',
  24886. './GeometryAttribute',
  24887. './GeometryAttributes',
  24888. './GeometryPipeline',
  24889. './IndexDatatype',
  24890. './Math',
  24891. './PolygonPipeline',
  24892. './PrimitiveType',
  24893. './Queue',
  24894. './WindingOrder'
  24895. ], function(
  24896. arrayRemoveDuplicates,
  24897. Cartesian3,
  24898. ComponentDatatype,
  24899. defaultValue,
  24900. defined,
  24901. Ellipsoid,
  24902. Geometry,
  24903. GeometryAttribute,
  24904. GeometryAttributes,
  24905. GeometryPipeline,
  24906. IndexDatatype,
  24907. CesiumMath,
  24908. PolygonPipeline,
  24909. PrimitiveType,
  24910. Queue,
  24911. WindingOrder) {
  24912. 'use strict';
  24913. /**
  24914. * @private
  24915. */
  24916. var PolygonGeometryLibrary = {};
  24917. PolygonGeometryLibrary.computeHierarchyPackedLength = function(polygonHierarchy) {
  24918. var numComponents = 0;
  24919. var stack = [polygonHierarchy];
  24920. while (stack.length > 0) {
  24921. var hierarchy = stack.pop();
  24922. if (!defined(hierarchy)) {
  24923. continue;
  24924. }
  24925. numComponents += 2;
  24926. var positions = hierarchy.positions;
  24927. var holes = hierarchy.holes;
  24928. if (defined(positions)) {
  24929. numComponents += positions.length * Cartesian3.packedLength;
  24930. }
  24931. if (defined(holes)) {
  24932. var length = holes.length;
  24933. for (var i = 0; i < length; ++i) {
  24934. stack.push(holes[i]);
  24935. }
  24936. }
  24937. }
  24938. return numComponents;
  24939. };
  24940. PolygonGeometryLibrary.packPolygonHierarchy = function(polygonHierarchy, array, startingIndex) {
  24941. var stack = [polygonHierarchy];
  24942. while (stack.length > 0) {
  24943. var hierarchy = stack.pop();
  24944. if (!defined(hierarchy)) {
  24945. continue;
  24946. }
  24947. var positions = hierarchy.positions;
  24948. var holes = hierarchy.holes;
  24949. array[startingIndex++] = defined(positions) ? positions.length : 0;
  24950. array[startingIndex++] = defined(holes) ? holes.length : 0;
  24951. if (defined(positions)) {
  24952. var positionsLength = positions.length;
  24953. for (var i = 0; i < positionsLength; ++i, startingIndex += 3) {
  24954. Cartesian3.pack(positions[i], array, startingIndex);
  24955. }
  24956. }
  24957. if (defined(holes)) {
  24958. var holesLength = holes.length;
  24959. for (var j = 0; j < holesLength; ++j) {
  24960. stack.push(holes[j]);
  24961. }
  24962. }
  24963. }
  24964. return startingIndex;
  24965. };
  24966. PolygonGeometryLibrary.unpackPolygonHierarchy = function(array, startingIndex) {
  24967. var positionsLength = array[startingIndex++];
  24968. var holesLength = array[startingIndex++];
  24969. var positions = new Array(positionsLength);
  24970. var holes = holesLength > 0 ? new Array(holesLength) : undefined;
  24971. for (var i = 0; i < positionsLength; ++i, startingIndex += Cartesian3.packedLength) {
  24972. positions[i] = Cartesian3.unpack(array, startingIndex);
  24973. }
  24974. for (var j = 0; j < holesLength; ++j) {
  24975. holes[j] = PolygonGeometryLibrary.unpackPolygonHierarchy(array, startingIndex);
  24976. startingIndex = holes[j].startingIndex;
  24977. delete holes[j].startingIndex;
  24978. }
  24979. return {
  24980. positions : positions,
  24981. holes : holes,
  24982. startingIndex : startingIndex
  24983. };
  24984. };
  24985. var distanceScratch = new Cartesian3();
  24986. function getPointAtDistance(p0, p1, distance, length) {
  24987. Cartesian3.subtract(p1, p0, distanceScratch);
  24988. Cartesian3.multiplyByScalar(distanceScratch, distance / length, distanceScratch);
  24989. Cartesian3.add(p0, distanceScratch, distanceScratch);
  24990. return [distanceScratch.x, distanceScratch.y, distanceScratch.z];
  24991. }
  24992. PolygonGeometryLibrary.subdivideLineCount = function(p0, p1, minDistance) {
  24993. var distance = Cartesian3.distance(p0, p1);
  24994. var n = distance / minDistance;
  24995. var countDivide = Math.max(0, Math.ceil(Math.log(n) / Math.log(2)));
  24996. return Math.pow(2, countDivide);
  24997. };
  24998. PolygonGeometryLibrary.subdivideLine = function(p0, p1, minDistance, result) {
  24999. var numVertices = PolygonGeometryLibrary.subdivideLineCount(p0, p1, minDistance);
  25000. var length = Cartesian3.distance(p0, p1);
  25001. var distanceBetweenVertices = length / numVertices;
  25002. if (!defined(result)) {
  25003. result = [];
  25004. }
  25005. var positions = result;
  25006. positions.length = numVertices * 3;
  25007. var index = 0;
  25008. for ( var i = 0; i < numVertices; i++) {
  25009. var p = getPointAtDistance(p0, p1, i * distanceBetweenVertices, length);
  25010. positions[index++] = p[0];
  25011. positions[index++] = p[1];
  25012. positions[index++] = p[2];
  25013. }
  25014. return positions;
  25015. };
  25016. var scaleToGeodeticHeightN1 = new Cartesian3();
  25017. var scaleToGeodeticHeightN2 = new Cartesian3();
  25018. var scaleToGeodeticHeightP1 = new Cartesian3();
  25019. var scaleToGeodeticHeightP2 = new Cartesian3();
  25020. PolygonGeometryLibrary.scaleToGeodeticHeightExtruded = function(geometry, maxHeight, minHeight, ellipsoid, perPositionHeight) {
  25021. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  25022. var n1 = scaleToGeodeticHeightN1;
  25023. var n2 = scaleToGeodeticHeightN2;
  25024. var p = scaleToGeodeticHeightP1;
  25025. var p2 = scaleToGeodeticHeightP2;
  25026. if (defined(geometry) && defined(geometry.attributes) && defined(geometry.attributes.position)) {
  25027. var positions = geometry.attributes.position.values;
  25028. var length = positions.length / 2;
  25029. for ( var i = 0; i < length; i += 3) {
  25030. Cartesian3.fromArray(positions, i, p);
  25031. ellipsoid.geodeticSurfaceNormal(p, n1);
  25032. p2 = ellipsoid.scaleToGeodeticSurface(p, p2);
  25033. n2 = Cartesian3.multiplyByScalar(n1, minHeight, n2);
  25034. n2 = Cartesian3.add(p2, n2, n2);
  25035. positions[i + length] = n2.x;
  25036. positions[i + 1 + length] = n2.y;
  25037. positions[i + 2 + length] = n2.z;
  25038. if (perPositionHeight) {
  25039. p2 = Cartesian3.clone(p, p2);
  25040. }
  25041. n2 = Cartesian3.multiplyByScalar(n1, maxHeight, n2);
  25042. n2 = Cartesian3.add(p2, n2, n2);
  25043. positions[i] = n2.x;
  25044. positions[i + 1] = n2.y;
  25045. positions[i + 2] = n2.z;
  25046. }
  25047. }
  25048. return geometry;
  25049. };
  25050. PolygonGeometryLibrary.polygonsFromHierarchy = function(polygonHierarchy, perPositionHeight, tangentPlane, ellipsoid) {
  25051. // create from a polygon hierarchy
  25052. // Algorithm adapted from http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
  25053. var hierarchy = [];
  25054. var polygons = [];
  25055. var queue = new Queue();
  25056. queue.enqueue(polygonHierarchy);
  25057. while (queue.length !== 0) {
  25058. var outerNode = queue.dequeue();
  25059. var outerRing = outerNode.positions;
  25060. var holes = outerNode.holes;
  25061. outerRing = arrayRemoveDuplicates(outerRing, Cartesian3.equalsEpsilon, true);
  25062. if (outerRing.length < 3) {
  25063. continue;
  25064. }
  25065. var positions2D = tangentPlane.projectPointsOntoPlane(outerRing);
  25066. var holeIndices = [];
  25067. var originalWindingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  25068. if (originalWindingOrder === WindingOrder.CLOCKWISE) {
  25069. positions2D.reverse();
  25070. outerRing = outerRing.slice().reverse();
  25071. }
  25072. var positions = outerRing.slice();
  25073. var numChildren = defined(holes) ? holes.length : 0;
  25074. var polygonHoles = [];
  25075. var i;
  25076. var j;
  25077. for (i = 0; i < numChildren; i++) {
  25078. var hole = holes[i];
  25079. var holePositions = arrayRemoveDuplicates(hole.positions, Cartesian3.equalsEpsilon, true);
  25080. if (holePositions.length < 3) {
  25081. continue;
  25082. }
  25083. var holePositions2D = tangentPlane.projectPointsOntoPlane(holePositions);
  25084. originalWindingOrder = PolygonPipeline.computeWindingOrder2D(holePositions2D);
  25085. if (originalWindingOrder === WindingOrder.CLOCKWISE) {
  25086. holePositions2D.reverse();
  25087. holePositions = holePositions.slice().reverse();
  25088. }
  25089. polygonHoles.push(holePositions);
  25090. holeIndices.push(positions.length);
  25091. positions = positions.concat(holePositions);
  25092. positions2D = positions2D.concat(holePositions2D);
  25093. var numGrandchildren = 0;
  25094. if (defined(hole.holes)) {
  25095. numGrandchildren = hole.holes.length;
  25096. }
  25097. for (j = 0; j < numGrandchildren; j++) {
  25098. queue.enqueue(hole.holes[j]);
  25099. }
  25100. }
  25101. if (!perPositionHeight) {
  25102. for (i = 0; i < outerRing.length; i++) {
  25103. ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
  25104. }
  25105. for (i = 0; i < polygonHoles.length; i++) {
  25106. var polygonHole = polygonHoles[i];
  25107. for (j = 0; j < polygonHole.length; ++j) {
  25108. ellipsoid.scaleToGeodeticSurface(polygonHole[j], polygonHole[j]);
  25109. }
  25110. }
  25111. }
  25112. hierarchy.push({
  25113. outerRing : outerRing,
  25114. holes : polygonHoles
  25115. });
  25116. polygons.push({
  25117. positions : positions,
  25118. positions2D : positions2D,
  25119. holes : holeIndices
  25120. });
  25121. }
  25122. return {
  25123. hierarchy : hierarchy,
  25124. polygons : polygons
  25125. };
  25126. };
  25127. PolygonGeometryLibrary.createGeometryFromPositions = function(ellipsoid, polygon, granularity, perPositionHeight, vertexFormat) {
  25128. var indices = PolygonPipeline.triangulate(polygon.positions2D, polygon.holes);
  25129. /* If polygon is completely unrenderable, just use the first three vertices */
  25130. if (indices.length < 3) {
  25131. indices = [0, 1, 2];
  25132. }
  25133. var positions = polygon.positions;
  25134. if (perPositionHeight) {
  25135. var length = positions.length;
  25136. var flattenedPositions = new Array(length * 3);
  25137. var index = 0;
  25138. for ( var i = 0; i < length; i++) {
  25139. var p = positions[i];
  25140. flattenedPositions[index++] = p.x;
  25141. flattenedPositions[index++] = p.y;
  25142. flattenedPositions[index++] = p.z;
  25143. }
  25144. var geometry = new Geometry({
  25145. attributes : {
  25146. position : new GeometryAttribute({
  25147. componentDatatype : ComponentDatatype.DOUBLE,
  25148. componentsPerAttribute : 3,
  25149. values : flattenedPositions
  25150. })
  25151. },
  25152. indices : indices,
  25153. primitiveType : PrimitiveType.TRIANGLES
  25154. });
  25155. if (vertexFormat.normal) {
  25156. return GeometryPipeline.computeNormal(geometry);
  25157. }
  25158. return geometry;
  25159. }
  25160. return PolygonPipeline.computeSubdivision(ellipsoid, positions, indices, granularity);
  25161. };
  25162. var computeWallIndicesSubdivided = [];
  25163. var p1Scratch = new Cartesian3();
  25164. var p2Scratch = new Cartesian3();
  25165. PolygonGeometryLibrary.computeWallGeometry = function(positions, ellipsoid, granularity, perPositionHeight) {
  25166. var edgePositions;
  25167. var topEdgeLength;
  25168. var i;
  25169. var p1;
  25170. var p2;
  25171. var length = positions.length;
  25172. var index = 0;
  25173. if (!perPositionHeight) {
  25174. var minDistance = CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
  25175. var numVertices = 0;
  25176. for (i = 0; i < length; i++) {
  25177. numVertices += PolygonGeometryLibrary.subdivideLineCount(positions[i], positions[(i + 1) % length], minDistance);
  25178. }
  25179. topEdgeLength = (numVertices + length) * 3;
  25180. edgePositions = new Array(topEdgeLength * 2);
  25181. for (i = 0; i < length; i++) {
  25182. p1 = positions[i];
  25183. p2 = positions[(i + 1) % length];
  25184. var tempPositions = PolygonGeometryLibrary.subdivideLine(p1, p2, minDistance, computeWallIndicesSubdivided);
  25185. var tempPositionsLength = tempPositions.length;
  25186. for (var j = 0; j < tempPositionsLength; ++j, ++index) {
  25187. edgePositions[index] = tempPositions[j];
  25188. edgePositions[index + topEdgeLength] = tempPositions[j];
  25189. }
  25190. edgePositions[index] = p2.x;
  25191. edgePositions[index + topEdgeLength] = p2.x;
  25192. ++index;
  25193. edgePositions[index] = p2.y;
  25194. edgePositions[index + topEdgeLength] = p2.y;
  25195. ++index;
  25196. edgePositions[index] = p2.z;
  25197. edgePositions[index + topEdgeLength] = p2.z;
  25198. ++index;
  25199. }
  25200. } else {
  25201. topEdgeLength = length * 3 * 2;
  25202. edgePositions = new Array(topEdgeLength * 2);
  25203. for (i = 0; i < length; i++) {
  25204. p1 = positions[i];
  25205. p2 = positions[(i + 1) % length];
  25206. edgePositions[index] = edgePositions[index + topEdgeLength] = p1.x;
  25207. ++index;
  25208. edgePositions[index] = edgePositions[index + topEdgeLength] = p1.y;
  25209. ++index;
  25210. edgePositions[index] = edgePositions[index + topEdgeLength] = p1.z;
  25211. ++index;
  25212. edgePositions[index] = edgePositions[index + topEdgeLength] = p2.x;
  25213. ++index;
  25214. edgePositions[index] = edgePositions[index + topEdgeLength] = p2.y;
  25215. ++index;
  25216. edgePositions[index] = edgePositions[index + topEdgeLength] = p2.z;
  25217. ++index;
  25218. }
  25219. }
  25220. length = edgePositions.length;
  25221. var indices = IndexDatatype.createTypedArray(length / 3, length - positions.length * 6);
  25222. var edgeIndex = 0;
  25223. length /= 6;
  25224. for (i = 0; i < length; i++) {
  25225. var UL = i;
  25226. var UR = UL + 1;
  25227. var LL = UL + length;
  25228. var LR = LL + 1;
  25229. p1 = Cartesian3.fromArray(edgePositions, UL * 3, p1Scratch);
  25230. p2 = Cartesian3.fromArray(edgePositions, UR * 3, p2Scratch);
  25231. if (Cartesian3.equalsEpsilon(p1, p2, CesiumMath.EPSILON14)) {
  25232. continue;
  25233. }
  25234. indices[edgeIndex++] = UL;
  25235. indices[edgeIndex++] = LL;
  25236. indices[edgeIndex++] = UR;
  25237. indices[edgeIndex++] = UR;
  25238. indices[edgeIndex++] = LL;
  25239. indices[edgeIndex++] = LR;
  25240. }
  25241. return new Geometry({
  25242. attributes : new GeometryAttributes({
  25243. position : new GeometryAttribute({
  25244. componentDatatype : ComponentDatatype.DOUBLE,
  25245. componentsPerAttribute : 3,
  25246. values : edgePositions
  25247. })
  25248. }),
  25249. indices : indices,
  25250. primitiveType : PrimitiveType.TRIANGLES
  25251. });
  25252. };
  25253. return PolygonGeometryLibrary;
  25254. });
  25255. /*global define*/
  25256. define('Core/VertexFormat',[
  25257. './defaultValue',
  25258. './defined',
  25259. './DeveloperError',
  25260. './freezeObject'
  25261. ], function(
  25262. defaultValue,
  25263. defined,
  25264. DeveloperError,
  25265. freezeObject) {
  25266. 'use strict';
  25267. /**
  25268. * A vertex format defines what attributes make up a vertex. A VertexFormat can be provided
  25269. * to a {@link Geometry} to request that certain properties be computed, e.g., just position,
  25270. * position and normal, etc.
  25271. *
  25272. * @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example.
  25273. *
  25274. * @alias VertexFormat
  25275. * @constructor
  25276. *
  25277. * @example
  25278. * // Create a vertex format with position and 2D texture coordinate attributes.
  25279. * var format = new Cesium.VertexFormat({
  25280. * position : true,
  25281. * st : true
  25282. * });
  25283. *
  25284. * @see Geometry#attributes
  25285. * @see Packable
  25286. */
  25287. function VertexFormat(options) {
  25288. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  25289. /**
  25290. * When <code>true</code>, the vertex has a 3D position attribute.
  25291. * <p>
  25292. * 64-bit floating-point (for precision). 3 components per attribute.
  25293. * </p>
  25294. *
  25295. * @type Boolean
  25296. *
  25297. * @default false
  25298. */
  25299. this.position = defaultValue(options.position, false);
  25300. /**
  25301. * When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting.
  25302. * <p>
  25303. * 32-bit floating-point. 3 components per attribute.
  25304. * </p>
  25305. *
  25306. * @type Boolean
  25307. *
  25308. * @default false
  25309. */
  25310. this.normal = defaultValue(options.normal, false);
  25311. /**
  25312. * When <code>true</code>, the vertex has a 2D texture coordinate attribute.
  25313. * <p>
  25314. * 32-bit floating-point. 2 components per attribute
  25315. * </p>
  25316. *
  25317. * @type Boolean
  25318. *
  25319. * @default false
  25320. */
  25321. this.st = defaultValue(options.st, false);
  25322. /**
  25323. * When <code>true</code>, the vertex has a binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  25324. * <p>
  25325. * 32-bit floating-point. 3 components per attribute.
  25326. * </p>
  25327. *
  25328. * @type Boolean
  25329. *
  25330. * @default false
  25331. */
  25332. this.binormal = defaultValue(options.binormal, false);
  25333. /**
  25334. * When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  25335. * <p>
  25336. * 32-bit floating-point. 3 components per attribute.
  25337. * </p>
  25338. *
  25339. * @type Boolean
  25340. *
  25341. * @default false
  25342. */
  25343. this.tangent = defaultValue(options.tangent, false);
  25344. /**
  25345. * When <code>true</code>, the vertex has an RGB color attribute.
  25346. * <p>
  25347. * 8-bit unsigned byte. 3 components per attribute.
  25348. * </p>
  25349. *
  25350. * @type Boolean
  25351. *
  25352. * @default false
  25353. */
  25354. this.color = defaultValue(options.color, false);
  25355. }
  25356. /**
  25357. * An immutable vertex format with only a position attribute.
  25358. *
  25359. * @type {VertexFormat}
  25360. * @constant
  25361. *
  25362. * @see VertexFormat#position
  25363. */
  25364. VertexFormat.POSITION_ONLY = freezeObject(new VertexFormat({
  25365. position : true
  25366. }));
  25367. /**
  25368. * An immutable vertex format with position and normal attributes.
  25369. * This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}.
  25370. *
  25371. * @type {VertexFormat}
  25372. * @constant
  25373. *
  25374. * @see VertexFormat#position
  25375. * @see VertexFormat#normal
  25376. */
  25377. VertexFormat.POSITION_AND_NORMAL = freezeObject(new VertexFormat({
  25378. position : true,
  25379. normal : true
  25380. }));
  25381. /**
  25382. * An immutable vertex format with position, normal, and st attributes.
  25383. * This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport}
  25384. * is <code>TEXTURED/code>.
  25385. *
  25386. * @type {VertexFormat}
  25387. * @constant
  25388. *
  25389. * @see VertexFormat#position
  25390. * @see VertexFormat#normal
  25391. * @see VertexFormat#st
  25392. */
  25393. VertexFormat.POSITION_NORMAL_AND_ST = freezeObject(new VertexFormat({
  25394. position : true,
  25395. normal : true,
  25396. st : true
  25397. }));
  25398. /**
  25399. * An immutable vertex format with position and st attributes.
  25400. * This is compatible with {@link EllipsoidSurfaceAppearance}.
  25401. *
  25402. * @type {VertexFormat}
  25403. * @constant
  25404. *
  25405. * @see VertexFormat#position
  25406. * @see VertexFormat#st
  25407. */
  25408. VertexFormat.POSITION_AND_ST = freezeObject(new VertexFormat({
  25409. position : true,
  25410. st : true
  25411. }));
  25412. /**
  25413. * An immutable vertex format with position and color attributes.
  25414. *
  25415. * @type {VertexFormat}
  25416. * @constant
  25417. *
  25418. * @see VertexFormat#position
  25419. * @see VertexFormat#color
  25420. */
  25421. VertexFormat.POSITION_AND_COLOR = freezeObject(new VertexFormat({
  25422. position : true,
  25423. color : true
  25424. }));
  25425. /**
  25426. * An immutable vertex format with well-known attributes: position, normal, st, binormal, and tangent.
  25427. *
  25428. * @type {VertexFormat}
  25429. * @constant
  25430. *
  25431. * @see VertexFormat#position
  25432. * @see VertexFormat#normal
  25433. * @see VertexFormat#st
  25434. * @see VertexFormat#binormal
  25435. * @see VertexFormat#tangent
  25436. */
  25437. VertexFormat.ALL = freezeObject(new VertexFormat({
  25438. position : true,
  25439. normal : true,
  25440. st : true,
  25441. binormal : true,
  25442. tangent : true
  25443. }));
  25444. /**
  25445. * An immutable vertex format with position, normal, and st attributes.
  25446. * This is compatible with most appearances and materials; however
  25447. * normal and st attributes are not always required. When this is
  25448. * known in advance, another <code>VertexFormat</code> should be used.
  25449. *
  25450. * @type {VertexFormat}
  25451. * @constant
  25452. *
  25453. * @see VertexFormat#position
  25454. * @see VertexFormat#normal
  25455. */
  25456. VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
  25457. /**
  25458. * The number of elements used to pack the object into an array.
  25459. * @type {Number}
  25460. */
  25461. VertexFormat.packedLength = 6;
  25462. /**
  25463. * Stores the provided instance into the provided array.
  25464. *
  25465. * @param {VertexFormat} value The value to pack.
  25466. * @param {Number[]} array The array to pack into.
  25467. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  25468. *
  25469. * @returns {Number[]} The array that was packed into
  25470. */
  25471. VertexFormat.pack = function(value, array, startingIndex) {
  25472. if (!defined(value)) {
  25473. throw new DeveloperError('value is required');
  25474. }
  25475. if (!defined(array)) {
  25476. throw new DeveloperError('array is required');
  25477. }
  25478. startingIndex = defaultValue(startingIndex, 0);
  25479. array[startingIndex++] = value.position ? 1.0 : 0.0;
  25480. array[startingIndex++] = value.normal ? 1.0 : 0.0;
  25481. array[startingIndex++] = value.st ? 1.0 : 0.0;
  25482. array[startingIndex++] = value.binormal ? 1.0 : 0.0;
  25483. array[startingIndex++] = value.tangent ? 1.0 : 0.0;
  25484. array[startingIndex++] = value.color ? 1.0 : 0.0;
  25485. return array;
  25486. };
  25487. /**
  25488. * Retrieves an instance from a packed array.
  25489. *
  25490. * @param {Number[]} array The packed array.
  25491. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  25492. * @param {VertexFormat} [result] The object into which to store the result.
  25493. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided.
  25494. */
  25495. VertexFormat.unpack = function(array, startingIndex, result) {
  25496. if (!defined(array)) {
  25497. throw new DeveloperError('array is required');
  25498. }
  25499. startingIndex = defaultValue(startingIndex, 0);
  25500. if (!defined(result)) {
  25501. result = new VertexFormat();
  25502. }
  25503. result.position = array[startingIndex++] === 1.0;
  25504. result.normal = array[startingIndex++] === 1.0;
  25505. result.st = array[startingIndex++] === 1.0;
  25506. result.binormal = array[startingIndex++] === 1.0;
  25507. result.tangent = array[startingIndex++] === 1.0;
  25508. result.color = array[startingIndex++] === 1.0;
  25509. return result;
  25510. };
  25511. /**
  25512. * Duplicates a VertexFormat instance.
  25513. *
  25514. * @param {VertexFormat} cartesian The vertex format to duplicate.
  25515. * @param {VertexFormat} [result] The object onto which to store the result.
  25516. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined)
  25517. */
  25518. VertexFormat.clone = function(vertexFormat, result) {
  25519. if (!defined(vertexFormat)) {
  25520. return undefined;
  25521. }
  25522. if (!defined(result)) {
  25523. result = new VertexFormat();
  25524. }
  25525. result.position = vertexFormat.position;
  25526. result.normal = vertexFormat.normal;
  25527. result.st = vertexFormat.st;
  25528. result.binormal = vertexFormat.binormal;
  25529. result.tangent = vertexFormat.tangent;
  25530. result.color = vertexFormat.color;
  25531. return result;
  25532. };
  25533. return VertexFormat;
  25534. });
  25535. /*global define*/
  25536. define('Core/PolygonGeometry',[
  25537. './BoundingRectangle',
  25538. './BoundingSphere',
  25539. './Cartesian2',
  25540. './Cartesian3',
  25541. './Cartographic',
  25542. './ComponentDatatype',
  25543. './defaultValue',
  25544. './defined',
  25545. './defineProperties',
  25546. './DeveloperError',
  25547. './Ellipsoid',
  25548. './EllipsoidTangentPlane',
  25549. './Geometry',
  25550. './GeometryAttribute',
  25551. './GeometryInstance',
  25552. './GeometryPipeline',
  25553. './IndexDatatype',
  25554. './Math',
  25555. './Matrix3',
  25556. './PolygonGeometryLibrary',
  25557. './PolygonPipeline',
  25558. './Quaternion',
  25559. './Rectangle',
  25560. './VertexFormat',
  25561. './WindingOrder'
  25562. ], function(
  25563. BoundingRectangle,
  25564. BoundingSphere,
  25565. Cartesian2,
  25566. Cartesian3,
  25567. Cartographic,
  25568. ComponentDatatype,
  25569. defaultValue,
  25570. defined,
  25571. defineProperties,
  25572. DeveloperError,
  25573. Ellipsoid,
  25574. EllipsoidTangentPlane,
  25575. Geometry,
  25576. GeometryAttribute,
  25577. GeometryInstance,
  25578. GeometryPipeline,
  25579. IndexDatatype,
  25580. CesiumMath,
  25581. Matrix3,
  25582. PolygonGeometryLibrary,
  25583. PolygonPipeline,
  25584. Quaternion,
  25585. Rectangle,
  25586. VertexFormat,
  25587. WindingOrder) {
  25588. 'use strict';
  25589. var computeBoundingRectangleCartesian2 = new Cartesian2();
  25590. var computeBoundingRectangleCartesian3 = new Cartesian3();
  25591. var computeBoundingRectangleQuaternion = new Quaternion();
  25592. var computeBoundingRectangleMatrix3 = new Matrix3();
  25593. function computeBoundingRectangle(tangentPlane, positions, angle, result) {
  25594. var rotation = Quaternion.fromAxisAngle(tangentPlane._plane.normal, angle, computeBoundingRectangleQuaternion);
  25595. var textureMatrix = Matrix3.fromQuaternion(rotation, computeBoundingRectangleMatrix3);
  25596. var minX = Number.POSITIVE_INFINITY;
  25597. var maxX = Number.NEGATIVE_INFINITY;
  25598. var minY = Number.POSITIVE_INFINITY;
  25599. var maxY = Number.NEGATIVE_INFINITY;
  25600. var length = positions.length;
  25601. for ( var i = 0; i < length; ++i) {
  25602. var p = Cartesian3.clone(positions[i], computeBoundingRectangleCartesian3);
  25603. Matrix3.multiplyByVector(textureMatrix, p, p);
  25604. var st = tangentPlane.projectPointOntoPlane(p, computeBoundingRectangleCartesian2);
  25605. if (defined(st)) {
  25606. minX = Math.min(minX, st.x);
  25607. maxX = Math.max(maxX, st.x);
  25608. minY = Math.min(minY, st.y);
  25609. maxY = Math.max(maxY, st.y);
  25610. }
  25611. }
  25612. result.x = minX;
  25613. result.y = minY;
  25614. result.width = maxX - minX;
  25615. result.height = maxY - minY;
  25616. return result;
  25617. }
  25618. var scratchCarto1 = new Cartographic();
  25619. var scratchCarto2 = new Cartographic();
  25620. function adjustPosHeightsForNormal(position, p1, p2, ellipsoid) {
  25621. var carto1 = ellipsoid.cartesianToCartographic(position, scratchCarto1);
  25622. var height = carto1.height;
  25623. var p1Carto = ellipsoid.cartesianToCartographic(p1, scratchCarto2);
  25624. p1Carto.height = height;
  25625. ellipsoid.cartographicToCartesian(p1Carto, p1);
  25626. var p2Carto = ellipsoid.cartesianToCartographic(p2, scratchCarto2);
  25627. p2Carto.height = height - 100;
  25628. ellipsoid.cartographicToCartesian(p2Carto, p2);
  25629. }
  25630. var scratchBoundingRectangle = new BoundingRectangle();
  25631. var scratchPosition = new Cartesian3();
  25632. var scratchNormal = new Cartesian3();
  25633. var scratchTangent = new Cartesian3();
  25634. var scratchBinormal = new Cartesian3();
  25635. var p1Scratch = new Cartesian3();
  25636. var p2Scratch = new Cartesian3();
  25637. var scratchPerPosNormal = new Cartesian3();
  25638. var scratchPerPosTangent = new Cartesian3();
  25639. var scratchPerPosBinormal = new Cartesian3();
  25640. var appendTextureCoordinatesOrigin = new Cartesian2();
  25641. var appendTextureCoordinatesCartesian2 = new Cartesian2();
  25642. var appendTextureCoordinatesCartesian3 = new Cartesian3();
  25643. var appendTextureCoordinatesQuaternion = new Quaternion();
  25644. var appendTextureCoordinatesMatrix3 = new Matrix3();
  25645. function computeAttributes(options) {
  25646. var vertexFormat = options.vertexFormat;
  25647. var geometry = options.geometry;
  25648. if (vertexFormat.st || vertexFormat.normal || vertexFormat.tangent || vertexFormat.binormal) {
  25649. // PERFORMANCE_IDEA: Compute before subdivision, then just interpolate during subdivision.
  25650. // PERFORMANCE_IDEA: Compute with createGeometryFromPositions() for fast path when there's no holes.
  25651. var boundingRectangle = options.boundingRectangle;
  25652. var tangentPlane = options.tangentPlane;
  25653. var ellipsoid = options.ellipsoid;
  25654. var stRotation = options.stRotation;
  25655. var wall = options.wall;
  25656. var top = options.top || wall;
  25657. var bottom = options.bottom || wall;
  25658. var perPositionHeight = options.perPositionHeight;
  25659. var origin = appendTextureCoordinatesOrigin;
  25660. origin.x = boundingRectangle.x;
  25661. origin.y = boundingRectangle.y;
  25662. var flatPositions = geometry.attributes.position.values;
  25663. var length = flatPositions.length;
  25664. var textureCoordinates = vertexFormat.st ? new Float32Array(2 * (length / 3)) : undefined;
  25665. var normals;
  25666. if (vertexFormat.normal) {
  25667. if (perPositionHeight && top && !wall) {
  25668. normals = geometry.attributes.normal.values;
  25669. } else {
  25670. normals = new Float32Array(length);
  25671. }
  25672. }
  25673. var tangents = vertexFormat.tangent ? new Float32Array(length) : undefined;
  25674. var binormals = vertexFormat.binormal ? new Float32Array(length) : undefined;
  25675. var textureCoordIndex = 0;
  25676. var attrIndex = 0;
  25677. var normal = scratchNormal;
  25678. var tangent = scratchTangent;
  25679. var binormal = scratchBinormal;
  25680. var recomputeNormal = true;
  25681. var rotation = Quaternion.fromAxisAngle(tangentPlane._plane.normal, stRotation, appendTextureCoordinatesQuaternion);
  25682. var textureMatrix = Matrix3.fromQuaternion(rotation, appendTextureCoordinatesMatrix3);
  25683. var bottomOffset = 0;
  25684. var bottomOffset2 = 0;
  25685. if (top && bottom) {
  25686. bottomOffset = length / 2;
  25687. bottomOffset2 = length / 3;
  25688. length /= 2;
  25689. }
  25690. for ( var i = 0; i < length; i += 3) {
  25691. var position = Cartesian3.fromArray(flatPositions, i, appendTextureCoordinatesCartesian3);
  25692. if (vertexFormat.st) {
  25693. var p = Matrix3.multiplyByVector(textureMatrix, position, scratchPosition);
  25694. p = ellipsoid.scaleToGeodeticSurface(p,p);
  25695. var st = tangentPlane.projectPointOntoPlane(p, appendTextureCoordinatesCartesian2);
  25696. Cartesian2.subtract(st, origin, st);
  25697. var stx = CesiumMath.clamp(st.x / boundingRectangle.width, 0, 1);
  25698. var sty = CesiumMath.clamp(st.y / boundingRectangle.height, 0, 1);
  25699. if (bottom) {
  25700. textureCoordinates[textureCoordIndex + bottomOffset2] = stx;
  25701. textureCoordinates[textureCoordIndex + 1 + bottomOffset2] = sty;
  25702. }
  25703. if (top) {
  25704. textureCoordinates[textureCoordIndex] = stx;
  25705. textureCoordinates[textureCoordIndex + 1] = sty;
  25706. }
  25707. textureCoordIndex += 2;
  25708. }
  25709. if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.binormal) {
  25710. var attrIndex1 = attrIndex + 1;
  25711. var attrIndex2 = attrIndex + 2;
  25712. if (wall) {
  25713. if (i + 3 < length) {
  25714. var p1 = Cartesian3.fromArray(flatPositions, i + 3, p1Scratch);
  25715. if (recomputeNormal) {
  25716. var p2 = Cartesian3.fromArray(flatPositions, i + length, p2Scratch);
  25717. if (perPositionHeight) {
  25718. adjustPosHeightsForNormal(position, p1, p2, ellipsoid);
  25719. }
  25720. Cartesian3.subtract(p1, position, p1);
  25721. Cartesian3.subtract(p2, position, p2);
  25722. normal = Cartesian3.normalize(Cartesian3.cross(p2, p1, normal), normal);
  25723. recomputeNormal = false;
  25724. }
  25725. if (Cartesian3.equalsEpsilon(p1, position, CesiumMath.EPSILON10)) { // if we've reached a corner
  25726. recomputeNormal = true;
  25727. }
  25728. }
  25729. if (vertexFormat.tangent || vertexFormat.binormal) {
  25730. binormal = ellipsoid.geodeticSurfaceNormal(position, binormal);
  25731. if (vertexFormat.tangent) {
  25732. tangent = Cartesian3.normalize(Cartesian3.cross(binormal, normal, tangent), tangent);
  25733. }
  25734. }
  25735. } else {
  25736. normal = ellipsoid.geodeticSurfaceNormal(position, normal);
  25737. if (vertexFormat.tangent || vertexFormat.binormal) {
  25738. if (perPositionHeight) {
  25739. scratchPerPosNormal = Cartesian3.fromArray(normals, attrIndex, scratchPerPosNormal);
  25740. scratchPerPosTangent = Cartesian3.cross(Cartesian3.UNIT_Z, scratchPerPosNormal, scratchPerPosTangent);
  25741. scratchPerPosTangent = Cartesian3.normalize(Matrix3.multiplyByVector(textureMatrix, scratchPerPosTangent, scratchPerPosTangent), scratchPerPosTangent);
  25742. if (vertexFormat.binormal) {
  25743. scratchPerPosBinormal = Cartesian3.normalize(Cartesian3.cross(scratchPerPosNormal, scratchPerPosTangent, scratchPerPosBinormal), scratchPerPosBinormal);
  25744. }
  25745. }
  25746. tangent = Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent);
  25747. tangent = Cartesian3.normalize(Matrix3.multiplyByVector(textureMatrix, tangent, tangent), tangent);
  25748. if (vertexFormat.binormal) {
  25749. binormal = Cartesian3.normalize(Cartesian3.cross(normal, tangent, binormal), binormal);
  25750. }
  25751. }
  25752. }
  25753. if (vertexFormat.normal) {
  25754. if (options.wall) {
  25755. normals[attrIndex + bottomOffset] = normal.x;
  25756. normals[attrIndex1 + bottomOffset] = normal.y;
  25757. normals[attrIndex2 + bottomOffset] = normal.z;
  25758. } else if (bottom){
  25759. normals[attrIndex + bottomOffset] = -normal.x;
  25760. normals[attrIndex1 + bottomOffset] = -normal.y;
  25761. normals[attrIndex2 + bottomOffset] = -normal.z;
  25762. }
  25763. if ((top && !perPositionHeight) || wall) {
  25764. normals[attrIndex] = normal.x;
  25765. normals[attrIndex1] = normal.y;
  25766. normals[attrIndex2] = normal.z;
  25767. }
  25768. }
  25769. if (vertexFormat.tangent) {
  25770. if (options.wall) {
  25771. tangents[attrIndex + bottomOffset] = tangent.x;
  25772. tangents[attrIndex1 + bottomOffset] = tangent.y;
  25773. tangents[attrIndex2 + bottomOffset] = tangent.z;
  25774. } else if (bottom) {
  25775. tangents[attrIndex + bottomOffset] = -tangent.x;
  25776. tangents[attrIndex1 + bottomOffset] = -tangent.y;
  25777. tangents[attrIndex2 + bottomOffset] = -tangent.z;
  25778. }
  25779. if(top) {
  25780. if (perPositionHeight) {
  25781. tangents[attrIndex] = scratchPerPosTangent.x;
  25782. tangents[attrIndex1] = scratchPerPosTangent.y;
  25783. tangents[attrIndex2] = scratchPerPosTangent.z;
  25784. } else {
  25785. tangents[attrIndex] = tangent.x;
  25786. tangents[attrIndex1] = tangent.y;
  25787. tangents[attrIndex2] = tangent.z;
  25788. }
  25789. }
  25790. }
  25791. if (vertexFormat.binormal) {
  25792. if (bottom) {
  25793. binormals[attrIndex + bottomOffset] = binormal.x;
  25794. binormals[attrIndex1 + bottomOffset] = binormal.y;
  25795. binormals[attrIndex2 + bottomOffset] = binormal.z;
  25796. }
  25797. if (top) {
  25798. if (perPositionHeight) {
  25799. binormals[attrIndex] = scratchPerPosBinormal.x;
  25800. binormals[attrIndex1] = scratchPerPosBinormal.y;
  25801. binormals[attrIndex2] = scratchPerPosBinormal.z;
  25802. } else {
  25803. binormals[attrIndex] = binormal.x;
  25804. binormals[attrIndex1] = binormal.y;
  25805. binormals[attrIndex2] = binormal.z;
  25806. }
  25807. }
  25808. }
  25809. attrIndex += 3;
  25810. }
  25811. }
  25812. if (vertexFormat.st) {
  25813. geometry.attributes.st = new GeometryAttribute({
  25814. componentDatatype : ComponentDatatype.FLOAT,
  25815. componentsPerAttribute : 2,
  25816. values : textureCoordinates
  25817. });
  25818. }
  25819. if (vertexFormat.normal) {
  25820. geometry.attributes.normal = new GeometryAttribute({
  25821. componentDatatype : ComponentDatatype.FLOAT,
  25822. componentsPerAttribute : 3,
  25823. values : normals
  25824. });
  25825. }
  25826. if (vertexFormat.tangent) {
  25827. geometry.attributes.tangent = new GeometryAttribute({
  25828. componentDatatype : ComponentDatatype.FLOAT,
  25829. componentsPerAttribute : 3,
  25830. values : tangents
  25831. });
  25832. }
  25833. if (vertexFormat.binormal) {
  25834. geometry.attributes.binormal = new GeometryAttribute({
  25835. componentDatatype : ComponentDatatype.FLOAT,
  25836. componentsPerAttribute : 3,
  25837. values : binormals
  25838. });
  25839. }
  25840. }
  25841. return geometry;
  25842. }
  25843. var createGeometryFromPositionsExtrudedPositions = [];
  25844. function createGeometryFromPositionsExtruded(ellipsoid, polygon, granularity, hierarchy, perPositionHeight, closeTop, closeBottom, vertexFormat) {
  25845. var geos = {
  25846. walls : []
  25847. };
  25848. var i;
  25849. if (closeTop || closeBottom) {
  25850. var topGeo = PolygonGeometryLibrary.createGeometryFromPositions(ellipsoid, polygon, granularity, perPositionHeight, vertexFormat);
  25851. var edgePoints = topGeo.attributes.position.values;
  25852. var indices = topGeo.indices;
  25853. var numPositions;
  25854. var newIndices;
  25855. if (closeTop && closeBottom) {
  25856. var topBottomPositions = edgePoints.concat(edgePoints);
  25857. numPositions = topBottomPositions.length / 3;
  25858. newIndices = IndexDatatype.createTypedArray(numPositions, indices.length * 2);
  25859. newIndices.set(indices);
  25860. var ilength = indices.length;
  25861. var length = numPositions / 2;
  25862. for (i = 0; i < ilength; i += 3) {
  25863. var i0 = newIndices[i] + length;
  25864. var i1 = newIndices[i + 1] + length;
  25865. var i2 = newIndices[i + 2] + length;
  25866. newIndices[i + ilength] = i2;
  25867. newIndices[i + 1 + ilength] = i1;
  25868. newIndices[i + 2 + ilength] = i0;
  25869. }
  25870. topGeo.attributes.position.values = topBottomPositions;
  25871. if (perPositionHeight) {
  25872. var normals = topGeo.attributes.normal.values;
  25873. topGeo.attributes.normal.values = new Float32Array(topBottomPositions.length);
  25874. topGeo.attributes.normal.values.set(normals);
  25875. }
  25876. topGeo.indices = newIndices;
  25877. } else if (closeBottom) {
  25878. numPositions = edgePoints.length / 3;
  25879. newIndices = IndexDatatype.createTypedArray(numPositions, indices.length);
  25880. for (i = 0; i < indices.length; i += 3) {
  25881. newIndices[i] = indices[i + 2];
  25882. newIndices[i + 1] = indices[i + 1];
  25883. newIndices[i + 2] = indices[i];
  25884. }
  25885. topGeo.indices = newIndices;
  25886. }
  25887. geos.topAndBottom = new GeometryInstance({
  25888. geometry : topGeo
  25889. });
  25890. }
  25891. var outerRing = hierarchy.outerRing;
  25892. var tangentPlane = EllipsoidTangentPlane.fromPoints(outerRing, ellipsoid);
  25893. var positions2D = tangentPlane.projectPointsOntoPlane(outerRing, createGeometryFromPositionsExtrudedPositions);
  25894. var windingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  25895. if (windingOrder === WindingOrder.CLOCKWISE) {
  25896. outerRing = outerRing.slice().reverse();
  25897. }
  25898. var wallGeo = PolygonGeometryLibrary.computeWallGeometry(outerRing, ellipsoid, granularity, perPositionHeight);
  25899. geos.walls.push(new GeometryInstance({
  25900. geometry : wallGeo
  25901. }));
  25902. var holes = hierarchy.holes;
  25903. for (i = 0; i < holes.length; i++) {
  25904. var hole = holes[i];
  25905. tangentPlane = EllipsoidTangentPlane.fromPoints(hole, ellipsoid);
  25906. positions2D = tangentPlane.projectPointsOntoPlane(hole, createGeometryFromPositionsExtrudedPositions);
  25907. windingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  25908. if (windingOrder === WindingOrder.COUNTER_CLOCKWISE) {
  25909. hole = hole.slice().reverse();
  25910. }
  25911. wallGeo = PolygonGeometryLibrary.computeWallGeometry(hole, ellipsoid, granularity);
  25912. geos.walls.push(new GeometryInstance({
  25913. geometry : wallGeo
  25914. }));
  25915. }
  25916. return geos;
  25917. }
  25918. /**
  25919. * A description of a polygon on the ellipsoid. The polygon is defined by a polygon hierarchy. Polygon geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
  25920. *
  25921. * @alias PolygonGeometry
  25922. * @constructor
  25923. *
  25924. * @param {Object} options Object with the following properties:
  25925. * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
  25926. * @param {Number} [options.height=0.0] The distance in meters between the polygon and the ellipsoid surface.
  25927. * @param {Number} [options.extrudedHeight] The distance in meters between the polygon's extruded face and the ellipsoid surface.
  25928. * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
  25929. * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
  25930. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  25931. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  25932. * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
  25933. * @param {Boolean} [options.closeTop=true] When false, leaves off the top of an extruded polygon open.
  25934. * @param {Boolean} [options.closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
  25935. *
  25936. * @see PolygonGeometry#createGeometry
  25937. * @see PolygonGeometry#fromPositions
  25938. *
  25939. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Polygon.html|Cesium Sandcastle Polygon Demo}
  25940. *
  25941. * @example
  25942. * // 1. create a polygon from points
  25943. * var polygon = new Cesium.PolygonGeometry({
  25944. * polygonHierarchy : new Cesium.PolygonHierarchy(
  25945. * Cesium.Cartesian3.fromDegreesArray([
  25946. * -72.0, 40.0,
  25947. * -70.0, 35.0,
  25948. * -75.0, 30.0,
  25949. * -70.0, 30.0,
  25950. * -68.0, 40.0
  25951. * ])
  25952. * )
  25953. * });
  25954. * var geometry = Cesium.PolygonGeometry.createGeometry(polygon);
  25955. *
  25956. * // 2. create a nested polygon with holes
  25957. * var polygonWithHole = new Cesium.PolygonGeometry({
  25958. * polygonHierarchy : new Cesium.PolygonHierarchy(
  25959. * Cesium.Cartesian3.fromDegreesArray([
  25960. * -109.0, 30.0,
  25961. * -95.0, 30.0,
  25962. * -95.0, 40.0,
  25963. * -109.0, 40.0
  25964. * ]),
  25965. * [new Cesium.PolygonHierarchy(
  25966. * Cesium.Cartesian3.fromDegreesArray([
  25967. * -107.0, 31.0,
  25968. * -107.0, 39.0,
  25969. * -97.0, 39.0,
  25970. * -97.0, 31.0
  25971. * ]),
  25972. * [new Cesium.PolygonHierarchy(
  25973. * Cesium.Cartesian3.fromDegreesArray([
  25974. * -105.0, 33.0,
  25975. * -99.0, 33.0,
  25976. * -99.0, 37.0,
  25977. * -105.0, 37.0
  25978. * ]),
  25979. * [new Cesium.PolygonHierarchy(
  25980. * Cesium.Cartesian3.fromDegreesArray([
  25981. * -103.0, 34.0,
  25982. * -101.0, 34.0,
  25983. * -101.0, 36.0,
  25984. * -103.0, 36.0
  25985. * ])
  25986. * )]
  25987. * )]
  25988. * )]
  25989. * )
  25990. * });
  25991. * var geometry = Cesium.PolygonGeometry.createGeometry(polygonWithHole);
  25992. *
  25993. * // 3. create extruded polygon
  25994. * var extrudedPolygon = new Cesium.PolygonGeometry({
  25995. * polygonHierarchy : new Cesium.PolygonHierarchy(
  25996. * Cesium.Cartesian3.fromDegreesArray([
  25997. * -72.0, 40.0,
  25998. * -70.0, 35.0,
  25999. * -75.0, 30.0,
  26000. * -70.0, 30.0,
  26001. * -68.0, 40.0
  26002. * ])
  26003. * ),
  26004. * extrudedHeight: 300000
  26005. * });
  26006. * var geometry = Cesium.PolygonGeometry.createGeometry(extrudedPolygon);
  26007. */
  26008. function PolygonGeometry(options) {
  26009. if (!defined(options) || !defined(options.polygonHierarchy)) {
  26010. throw new DeveloperError('options.polygonHierarchy is required.');
  26011. }
  26012. if (defined(options.perPositionHeight) && options.perPositionHeight && defined(options.height)) {
  26013. throw new DeveloperError('Cannot use both options.perPositionHeight and options.height');
  26014. }
  26015. var polygonHierarchy = options.polygonHierarchy;
  26016. var vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
  26017. var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  26018. var granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  26019. var stRotation = defaultValue(options.stRotation, 0.0);
  26020. var height = defaultValue(options.height, 0.0);
  26021. var perPositionHeight = defaultValue(options.perPositionHeight, false);
  26022. var extrudedHeight = options.extrudedHeight;
  26023. var extrude = defined(extrudedHeight);
  26024. if (!perPositionHeight && extrude) {
  26025. //Ignore extrudedHeight if it matches height
  26026. if (CesiumMath.equalsEpsilon(height, extrudedHeight, CesiumMath.EPSILON10)) {
  26027. extrudedHeight = undefined;
  26028. extrude = false;
  26029. } else {
  26030. var h = extrudedHeight;
  26031. extrudedHeight = Math.min(h, height);
  26032. height = Math.max(h, height);
  26033. }
  26034. }
  26035. this._vertexFormat = VertexFormat.clone(vertexFormat);
  26036. this._ellipsoid = Ellipsoid.clone(ellipsoid);
  26037. this._granularity = granularity;
  26038. this._stRotation = stRotation;
  26039. this._height = height;
  26040. this._extrudedHeight = defaultValue(extrudedHeight, 0.0);
  26041. this._extrude = extrude;
  26042. this._closeTop = defaultValue(options.closeTop, true);
  26043. this._closeBottom = defaultValue(options.closeBottom, true);
  26044. this._polygonHierarchy = polygonHierarchy;
  26045. this._perPositionHeight = perPositionHeight;
  26046. this._workerName = 'createPolygonGeometry';
  26047. var positions = polygonHierarchy.positions;
  26048. if (!defined(positions) || positions.length < 3) {
  26049. this._rectangle = new Rectangle();
  26050. } else {
  26051. this._rectangle = Rectangle.fromCartesianArray(positions, ellipsoid);
  26052. }
  26053. /**
  26054. * The number of elements used to pack the object into an array.
  26055. * @type {Number}
  26056. */
  26057. this.packedLength = PolygonGeometryLibrary.computeHierarchyPackedLength(polygonHierarchy) + Ellipsoid.packedLength + VertexFormat.packedLength + Rectangle.packedLength + 9;
  26058. }
  26059. /**
  26060. * A description of a polygon from an array of positions. Polygon geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
  26061. *
  26062. * @param {Object} options Object with the following properties:
  26063. * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
  26064. * @param {Number} [options.height=0.0] The height of the polygon.
  26065. * @param {Number} [options.extrudedHeight] The height of the polygon extrusion.
  26066. * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
  26067. * @param {Number} [options.stRotation=0.0] The rotation of the texture coordiantes, in radians. A positive rotation is counter-clockwise.
  26068. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  26069. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  26070. * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
  26071. * @param {Boolean} [options.closeTop=true] When false, leaves off the top of an extruded polygon open.
  26072. * @param {Boolean} [options.closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
  26073. * @returns {PolygonGeometry}
  26074. *
  26075. *
  26076. * @example
  26077. * // create a polygon from points
  26078. * var polygon = Cesium.PolygonGeometry.fromPositions({
  26079. * positions : Cesium.Cartesian3.fromDegreesArray([
  26080. * -72.0, 40.0,
  26081. * -70.0, 35.0,
  26082. * -75.0, 30.0,
  26083. * -70.0, 30.0,
  26084. * -68.0, 40.0
  26085. * ])
  26086. * });
  26087. * var geometry = Cesium.PolygonGeometry.createGeometry(polygon);
  26088. *
  26089. * @see PolygonGeometry#createGeometry
  26090. */
  26091. PolygonGeometry.fromPositions = function(options) {
  26092. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  26093. if (!defined(options.positions)) {
  26094. throw new DeveloperError('options.positions is required.');
  26095. }
  26096. var newOptions = {
  26097. polygonHierarchy : {
  26098. positions : options.positions
  26099. },
  26100. height : options.height,
  26101. extrudedHeight : options.extrudedHeight,
  26102. vertexFormat : options.vertexFormat,
  26103. stRotation : options.stRotation,
  26104. ellipsoid : options.ellipsoid,
  26105. granularity : options.granularity,
  26106. perPositionHeight : options.perPositionHeight,
  26107. closeTop : options.closeTop,
  26108. closeBottom: options.closeBottom
  26109. };
  26110. return new PolygonGeometry(newOptions);
  26111. };
  26112. /**
  26113. * Stores the provided instance into the provided array.
  26114. *
  26115. * @param {PolygonGeometry} value The value to pack.
  26116. * @param {Number[]} array The array to pack into.
  26117. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  26118. *
  26119. * @returns {Number[]} The array that was packed into
  26120. */
  26121. PolygonGeometry.pack = function(value, array, startingIndex) {
  26122. if (!defined(value)) {
  26123. throw new DeveloperError('value is required');
  26124. }
  26125. if (!defined(array)) {
  26126. throw new DeveloperError('array is required');
  26127. }
  26128. startingIndex = defaultValue(startingIndex, 0);
  26129. startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(value._polygonHierarchy, array, startingIndex);
  26130. Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  26131. startingIndex += Ellipsoid.packedLength;
  26132. VertexFormat.pack(value._vertexFormat, array, startingIndex);
  26133. startingIndex += VertexFormat.packedLength;
  26134. Rectangle.pack(value._rectangle, array, startingIndex);
  26135. startingIndex += Rectangle.packedLength;
  26136. array[startingIndex++] = value._height;
  26137. array[startingIndex++] = value._extrudedHeight;
  26138. array[startingIndex++] = value._granularity;
  26139. array[startingIndex++] = value._stRotation;
  26140. array[startingIndex++] = value._extrude ? 1.0 : 0.0;
  26141. array[startingIndex++] = value._perPositionHeight ? 1.0 : 0.0;
  26142. array[startingIndex++] = value._closeTop ? 1.0 : 0.0;
  26143. array[startingIndex++] = value._closeBottom ? 1.0 : 0.0;
  26144. array[startingIndex] = value.packedLength;
  26145. return array;
  26146. };
  26147. var scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  26148. var scratchVertexFormat = new VertexFormat();
  26149. var scratchRectangle = new Rectangle();
  26150. //Only used to avoid inaability to default construct.
  26151. var dummyOptions = {
  26152. polygonHierarchy : {}
  26153. };
  26154. /**
  26155. * Retrieves an instance from a packed array.
  26156. *
  26157. * @param {Number[]} array The packed array.
  26158. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  26159. * @param {PolygonGeometry} [result] The object into which to store the result.
  26160. */
  26161. PolygonGeometry.unpack = function(array, startingIndex, result) {
  26162. if (!defined(array)) {
  26163. throw new DeveloperError('array is required');
  26164. }
  26165. startingIndex = defaultValue(startingIndex, 0);
  26166. var polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(array, startingIndex);
  26167. startingIndex = polygonHierarchy.startingIndex;
  26168. delete polygonHierarchy.startingIndex;
  26169. var ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  26170. startingIndex += Ellipsoid.packedLength;
  26171. var vertexFormat = VertexFormat.unpack(array, startingIndex, scratchVertexFormat);
  26172. startingIndex += VertexFormat.packedLength;
  26173. var rectangle = Rectangle.unpack(array, startingIndex, scratchRectangle);
  26174. startingIndex += Rectangle.packedLength;
  26175. var height = array[startingIndex++];
  26176. var extrudedHeight = array[startingIndex++];
  26177. var granularity = array[startingIndex++];
  26178. var stRotation = array[startingIndex++];
  26179. var extrude = array[startingIndex++] === 1.0;
  26180. var perPositionHeight = array[startingIndex++] === 1.0;
  26181. var closeTop = array[startingIndex++] === 1.0;
  26182. var closeBottom = array[startingIndex++] === 1.0;
  26183. var packedLength = array[startingIndex];
  26184. if (!defined(result)) {
  26185. result = new PolygonGeometry(dummyOptions);
  26186. }
  26187. result._polygonHierarchy = polygonHierarchy;
  26188. result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  26189. result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
  26190. result._height = height;
  26191. result._extrudedHeight = extrudedHeight;
  26192. result._granularity = granularity;
  26193. result._stRotation = stRotation;
  26194. result._extrude = extrude;
  26195. result._perPositionHeight = perPositionHeight;
  26196. result._closeTop = closeTop;
  26197. result._closeBottom = closeBottom;
  26198. result._rectangle = Rectangle.clone(rectangle);
  26199. result.packedLength = packedLength;
  26200. return result;
  26201. };
  26202. /**
  26203. * Computes the geometric representation of a polygon, including its vertices, indices, and a bounding sphere.
  26204. *
  26205. * @param {PolygonGeometry} polygonGeometry A description of the polygon.
  26206. * @returns {Geometry|undefined} The computed vertices and indices.
  26207. */
  26208. PolygonGeometry.createGeometry = function(polygonGeometry) {
  26209. var vertexFormat = polygonGeometry._vertexFormat;
  26210. var ellipsoid = polygonGeometry._ellipsoid;
  26211. var granularity = polygonGeometry._granularity;
  26212. var stRotation = polygonGeometry._stRotation;
  26213. var height = polygonGeometry._height;
  26214. var extrudedHeight = polygonGeometry._extrudedHeight;
  26215. var extrude = polygonGeometry._extrude;
  26216. var polygonHierarchy = polygonGeometry._polygonHierarchy;
  26217. var perPositionHeight = polygonGeometry._perPositionHeight;
  26218. var closeTop = polygonGeometry._closeTop;
  26219. var closeBottom = polygonGeometry._closeBottom;
  26220. var outerPositions = polygonHierarchy.positions;
  26221. if (outerPositions.length < 3) {
  26222. return;
  26223. }
  26224. var tangentPlane = EllipsoidTangentPlane.fromPoints(outerPositions, ellipsoid);
  26225. var results = PolygonGeometryLibrary.polygonsFromHierarchy(polygonHierarchy, perPositionHeight, tangentPlane, ellipsoid);
  26226. var hierarchy = results.hierarchy;
  26227. var polygons = results.polygons;
  26228. if (hierarchy.length === 0) {
  26229. return;
  26230. }
  26231. outerPositions = hierarchy[0].outerRing;
  26232. var boundingRectangle = computeBoundingRectangle(tangentPlane, outerPositions, stRotation, scratchBoundingRectangle);
  26233. var geometry;
  26234. var geometries = [];
  26235. var options = {
  26236. perPositionHeight: perPositionHeight,
  26237. vertexFormat: vertexFormat,
  26238. geometry: undefined,
  26239. tangentPlane: tangentPlane,
  26240. boundingRectangle: boundingRectangle,
  26241. ellipsoid: ellipsoid,
  26242. stRotation: stRotation,
  26243. bottom: false,
  26244. top: true,
  26245. wall: false
  26246. };
  26247. var i;
  26248. if (extrude) {
  26249. options.top = closeTop;
  26250. options.bottom = closeBottom;
  26251. for (i = 0; i < polygons.length; i++) {
  26252. geometry = createGeometryFromPositionsExtruded(ellipsoid, polygons[i], granularity, hierarchy[i], perPositionHeight, closeTop, closeBottom, vertexFormat);
  26253. var topAndBottom;
  26254. if (closeTop && closeBottom) {
  26255. topAndBottom = geometry.topAndBottom;
  26256. options.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(topAndBottom.geometry, height, extrudedHeight, ellipsoid, perPositionHeight);
  26257. } else if (closeTop) {
  26258. topAndBottom = geometry.topAndBottom;
  26259. topAndBottom.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(topAndBottom.geometry.attributes.position.values, height, ellipsoid, !perPositionHeight);
  26260. options.geometry = topAndBottom.geometry;
  26261. } else if (closeBottom) {
  26262. topAndBottom = geometry.topAndBottom;
  26263. topAndBottom.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(topAndBottom.geometry.attributes.position.values, extrudedHeight, ellipsoid, true);
  26264. options.geometry = topAndBottom.geometry;
  26265. }
  26266. if (closeTop || closeBottom) {
  26267. options.wall = false;
  26268. topAndBottom.geometry = computeAttributes(options);
  26269. geometries.push(topAndBottom);
  26270. }
  26271. var walls = geometry.walls;
  26272. options.wall = true;
  26273. for ( var k = 0; k < walls.length; k++) {
  26274. var wall = walls[k];
  26275. options.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(wall.geometry, height, extrudedHeight, ellipsoid, perPositionHeight);
  26276. wall.geometry = computeAttributes(options);
  26277. geometries.push(wall);
  26278. }
  26279. }
  26280. } else {
  26281. for (i = 0; i < polygons.length; i++) {
  26282. geometry = new GeometryInstance({
  26283. geometry : PolygonGeometryLibrary.createGeometryFromPositions(ellipsoid, polygons[i], granularity, perPositionHeight, vertexFormat)
  26284. });
  26285. geometry.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(geometry.geometry.attributes.position.values, height, ellipsoid, !perPositionHeight);
  26286. options.geometry = geometry.geometry;
  26287. geometry.geometry = computeAttributes(options);
  26288. geometries.push(geometry);
  26289. }
  26290. }
  26291. geometry = GeometryPipeline.combineInstances(geometries)[0];
  26292. geometry.attributes.position.values = new Float64Array(geometry.attributes.position.values);
  26293. geometry.indices = IndexDatatype.createTypedArray(geometry.attributes.position.values.length / 3, geometry.indices);
  26294. var attributes = geometry.attributes;
  26295. var boundingSphere = BoundingSphere.fromVertices(attributes.position.values);
  26296. if (!vertexFormat.position) {
  26297. delete attributes.position;
  26298. }
  26299. return new Geometry({
  26300. attributes : attributes,
  26301. indices : geometry.indices,
  26302. primitiveType : geometry.primitiveType,
  26303. boundingSphere : boundingSphere
  26304. });
  26305. };
  26306. /**
  26307. * @private
  26308. */
  26309. PolygonGeometry.createShadowVolume = function(polygonGeometry, minHeightFunc, maxHeightFunc) {
  26310. var granularity = polygonGeometry._granularity;
  26311. var ellipsoid = polygonGeometry._ellipsoid;
  26312. var minHeight = minHeightFunc(granularity, ellipsoid);
  26313. var maxHeight = maxHeightFunc(granularity, ellipsoid);
  26314. return new PolygonGeometry({
  26315. polygonHierarchy : polygonGeometry._polygonHierarchy,
  26316. ellipsoid : ellipsoid,
  26317. stRotation : polygonGeometry._stRotation,
  26318. granularity : granularity,
  26319. perPositionHeight : false,
  26320. extrudedHeight : minHeight,
  26321. height : maxHeight,
  26322. vertexFormat : VertexFormat.POSITION_ONLY
  26323. });
  26324. };
  26325. defineProperties(PolygonGeometry.prototype, {
  26326. /**
  26327. * @private
  26328. */
  26329. rectangle : {
  26330. get : function() {
  26331. return this._rectangle;
  26332. }
  26333. }
  26334. });
  26335. return PolygonGeometry;
  26336. });
  26337. /*global define*/
  26338. define('Workers/createPolygonGeometry',[
  26339. '../Core/defined',
  26340. '../Core/Ellipsoid',
  26341. '../Core/PolygonGeometry'
  26342. ], function(
  26343. defined,
  26344. Ellipsoid,
  26345. PolygonGeometry) {
  26346. 'use strict';
  26347. function createPolygonGeometry(polygonGeometry, offset) {
  26348. if (defined(offset)) {
  26349. polygonGeometry = PolygonGeometry.unpack(polygonGeometry, offset);
  26350. }
  26351. polygonGeometry._ellipsoid = Ellipsoid.clone(polygonGeometry._ellipsoid);
  26352. return PolygonGeometry.createGeometry(polygonGeometry);
  26353. }
  26354. return createPolygonGeometry;
  26355. });
  26356. }());