babylon.1.14-beta-debug.js 1012 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.multiplyInPlace = function (otherVector) {
  238. this.x *= otherVector.x;
  239. this.y *= otherVector.y;
  240. };
  241. Vector2.prototype.multiply = function (otherVector) {
  242. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  243. };
  244. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  245. result.x = this.x * otherVector.x;
  246. result.y = this.y * otherVector.y;
  247. };
  248. Vector2.prototype.multiplyByFloats = function (x, y) {
  249. return new Vector2(this.x * x, this.y * y);
  250. };
  251. Vector2.prototype.divide = function (otherVector) {
  252. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  253. };
  254. Vector2.prototype.divideToRef = function (otherVector, result) {
  255. result.x = this.x / otherVector.x;
  256. result.y = this.y / otherVector.y;
  257. };
  258. Vector2.prototype.negate = function () {
  259. return new Vector2(-this.x, -this.y);
  260. };
  261. Vector2.prototype.scaleInPlace = function (scale) {
  262. this.x *= scale;
  263. this.y *= scale;
  264. };
  265. Vector2.prototype.scale = function (scale) {
  266. return new Vector2(this.x * scale, this.y * scale);
  267. };
  268. Vector2.prototype.equals = function (otherVector) {
  269. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  270. };
  271. Vector2.prototype.length = function () {
  272. return Math.sqrt(this.x * this.x + this.y * this.y);
  273. };
  274. Vector2.prototype.lengthSquared = function () {
  275. return (this.x * this.x + this.y * this.y);
  276. };
  277. Vector2.prototype.normalize = function () {
  278. var len = this.length();
  279. if (len === 0)
  280. return;
  281. var num = 1.0 / len;
  282. this.x *= num;
  283. this.y *= num;
  284. };
  285. Vector2.prototype.clone = function () {
  286. return new Vector2(this.x, this.y);
  287. };
  288. Vector2.Zero = function () {
  289. return new Vector2(0, 0);
  290. };
  291. Vector2.FromArray = function (array, offset) {
  292. if (!offset) {
  293. offset = 0;
  294. }
  295. return new Vector2(array[offset], array[offset + 1]);
  296. };
  297. Vector2.FromArrayToRef = function (array, offset, result) {
  298. result.x = array[offset];
  299. result.y = array[offset + 1];
  300. };
  301. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  302. var squared = amount * amount;
  303. var cubed = amount * squared;
  304. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  305. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  306. return new Vector2(x, y);
  307. };
  308. Vector2.Clamp = function (value, min, max) {
  309. var x = value.x;
  310. x = (x > max.x) ? max.x : x;
  311. x = (x < min.x) ? min.x : x;
  312. var y = value.y;
  313. y = (y > max.y) ? max.y : y;
  314. y = (y < min.y) ? min.y : y;
  315. return new Vector2(x, y);
  316. };
  317. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  318. var squared = amount * amount;
  319. var cubed = amount * squared;
  320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  322. var part3 = (cubed - (2.0 * squared)) + amount;
  323. var part4 = cubed - squared;
  324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  326. return new Vector2(x, y);
  327. };
  328. Vector2.Lerp = function (start, end, amount) {
  329. var x = start.x + ((end.x - start.x) * amount);
  330. var y = start.y + ((end.y - start.y) * amount);
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Dot = function (left, right) {
  334. return left.x * right.x + left.y * right.y;
  335. };
  336. Vector2.Normalize = function (vector) {
  337. var newVector = vector.clone();
  338. newVector.normalize();
  339. return newVector;
  340. };
  341. Vector2.Minimize = function (left, right) {
  342. var x = (left.x < right.x) ? left.x : right.x;
  343. var y = (left.y < right.y) ? left.y : right.y;
  344. return new Vector2(x, y);
  345. };
  346. Vector2.Maximize = function (left, right) {
  347. var x = (left.x > right.x) ? left.x : right.x;
  348. var y = (left.y > right.y) ? left.y : right.y;
  349. return new Vector2(x, y);
  350. };
  351. Vector2.Transform = function (vector, transformation) {
  352. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  353. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Distance = function (value1, value2) {
  357. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  358. };
  359. Vector2.DistanceSquared = function (value1, value2) {
  360. var x = value1.x - value2.x;
  361. var y = value1.y - value2.y;
  362. return (x * x) + (y * y);
  363. };
  364. return Vector2;
  365. })();
  366. BABYLON.Vector2 = Vector2;
  367. var Vector3 = (function () {
  368. function Vector3(x, y, z) {
  369. this.x = x;
  370. this.y = y;
  371. this.z = z;
  372. }
  373. Vector3.prototype.toString = function () {
  374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  375. };
  376. Vector3.prototype.asArray = function () {
  377. var result = [];
  378. this.toArray(result, 0);
  379. return result;
  380. };
  381. Vector3.prototype.toArray = function (array, index) {
  382. if (index === undefined) {
  383. index = 0;
  384. }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. array[index + 2] = this.z;
  388. };
  389. Vector3.prototype.addInPlace = function (otherVector) {
  390. this.x += otherVector.x;
  391. this.y += otherVector.y;
  392. this.z += otherVector.z;
  393. };
  394. Vector3.prototype.add = function (otherVector) {
  395. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  396. };
  397. Vector3.prototype.addToRef = function (otherVector, result) {
  398. result.x = this.x + otherVector.x;
  399. result.y = this.y + otherVector.y;
  400. result.z = this.z + otherVector.z;
  401. };
  402. Vector3.prototype.subtractInPlace = function (otherVector) {
  403. this.x -= otherVector.x;
  404. this.y -= otherVector.y;
  405. this.z -= otherVector.z;
  406. };
  407. Vector3.prototype.subtract = function (otherVector) {
  408. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  409. };
  410. Vector3.prototype.subtractToRef = function (otherVector, result) {
  411. result.x = this.x - otherVector.x;
  412. result.y = this.y - otherVector.y;
  413. result.z = this.z - otherVector.z;
  414. };
  415. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  416. return new Vector3(this.x - x, this.y - y, this.z - z);
  417. };
  418. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  419. result.x = this.x - x;
  420. result.y = this.y - y;
  421. result.z = this.z - z;
  422. };
  423. Vector3.prototype.negate = function () {
  424. return new Vector3(-this.x, -this.y, -this.z);
  425. };
  426. Vector3.prototype.scaleInPlace = function (scale) {
  427. this.x *= scale;
  428. this.y *= scale;
  429. this.z *= scale;
  430. };
  431. Vector3.prototype.scale = function (scale) {
  432. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  433. };
  434. Vector3.prototype.scaleToRef = function (scale, result) {
  435. result.x = this.x * scale;
  436. result.y = this.y * scale;
  437. result.z = this.z * scale;
  438. };
  439. Vector3.prototype.equals = function (otherVector) {
  440. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  441. };
  442. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  443. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  444. };
  445. Vector3.prototype.equalsToFloats = function (x, y, z) {
  446. return this.x === x && this.y === y && this.z === z;
  447. };
  448. Vector3.prototype.multiplyInPlace = function (otherVector) {
  449. this.x *= otherVector.x;
  450. this.y *= otherVector.y;
  451. this.z *= otherVector.z;
  452. };
  453. Vector3.prototype.multiply = function (otherVector) {
  454. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  455. };
  456. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  457. result.x = this.x * otherVector.x;
  458. result.y = this.y * otherVector.y;
  459. result.z = this.z * otherVector.z;
  460. };
  461. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  462. return new Vector3(this.x * x, this.y * y, this.z * z);
  463. };
  464. Vector3.prototype.divide = function (otherVector) {
  465. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  466. };
  467. Vector3.prototype.divideToRef = function (otherVector, result) {
  468. result.x = this.x / otherVector.x;
  469. result.y = this.y / otherVector.y;
  470. result.z = this.z / otherVector.z;
  471. };
  472. Vector3.prototype.MinimizeInPlace = function (other) {
  473. if (other.x < this.x)
  474. this.x = other.x;
  475. if (other.y < this.y)
  476. this.y = other.y;
  477. if (other.z < this.z)
  478. this.z = other.z;
  479. };
  480. Vector3.prototype.MaximizeInPlace = function (other) {
  481. if (other.x > this.x)
  482. this.x = other.x;
  483. if (other.y > this.y)
  484. this.y = other.y;
  485. if (other.z > this.z)
  486. this.z = other.z;
  487. };
  488. Vector3.prototype.length = function () {
  489. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  490. };
  491. Vector3.prototype.lengthSquared = function () {
  492. return (this.x * this.x + this.y * this.y + this.z * this.z);
  493. };
  494. Vector3.prototype.normalize = function () {
  495. var len = this.length();
  496. if (len === 0)
  497. return;
  498. var num = 1.0 / len;
  499. this.x *= num;
  500. this.y *= num;
  501. this.z *= num;
  502. };
  503. Vector3.prototype.clone = function () {
  504. return new Vector3(this.x, this.y, this.z);
  505. };
  506. Vector3.prototype.copyFrom = function (source) {
  507. this.x = source.x;
  508. this.y = source.y;
  509. this.z = source.z;
  510. };
  511. Vector3.prototype.copyFromFloats = function (x, y, z) {
  512. this.x = x;
  513. this.y = y;
  514. this.z = z;
  515. };
  516. Vector3.FromArray = function (array, offset) {
  517. if (!offset) {
  518. offset = 0;
  519. }
  520. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  521. };
  522. Vector3.FromArrayToRef = function (array, offset, result) {
  523. result.x = array[offset];
  524. result.y = array[offset + 1];
  525. result.z = array[offset + 2];
  526. };
  527. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  528. result.x = array[offset];
  529. result.y = array[offset + 1];
  530. result.z = array[offset + 2];
  531. };
  532. Vector3.FromFloatsToRef = function (x, y, z, result) {
  533. result.x = x;
  534. result.y = y;
  535. result.z = z;
  536. };
  537. Vector3.Zero = function () {
  538. return new Vector3(0, 0, 0);
  539. };
  540. Vector3.Up = function () {
  541. return new Vector3(0, 1.0, 0);
  542. };
  543. Vector3.TransformCoordinates = function (vector, transformation) {
  544. var result = Vector3.Zero();
  545. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  546. return result;
  547. };
  548. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  552. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  553. result.x = x / w;
  554. result.y = y / w;
  555. result.z = z / w;
  556. };
  557. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  558. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  559. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  560. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  561. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  562. result.x = rx / rw;
  563. result.y = ry / rw;
  564. result.z = rz / rw;
  565. };
  566. Vector3.TransformNormal = function (vector, transformation) {
  567. var result = Vector3.Zero();
  568. Vector3.TransformNormalToRef(vector, transformation, result);
  569. return result;
  570. };
  571. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  572. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  573. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  574. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  575. };
  576. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  577. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  578. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  579. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  580. };
  581. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  582. var squared = amount * amount;
  583. var cubed = amount * squared;
  584. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  586. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  587. return new Vector3(x, y, z);
  588. };
  589. Vector3.Clamp = function (value, min, max) {
  590. var x = value.x;
  591. x = (x > max.x) ? max.x : x;
  592. x = (x < min.x) ? min.x : x;
  593. var y = value.y;
  594. y = (y > max.y) ? max.y : y;
  595. y = (y < min.y) ? min.y : y;
  596. var z = value.z;
  597. z = (z > max.z) ? max.z : z;
  598. z = (z < min.z) ? min.z : z;
  599. return new Vector3(x, y, z);
  600. };
  601. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  602. var squared = amount * amount;
  603. var cubed = amount * squared;
  604. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  605. var part2 = (-2.0 * cubed) + (3.0 * squared);
  606. var part3 = (cubed - (2.0 * squared)) + amount;
  607. var part4 = cubed - squared;
  608. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  609. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  610. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  611. return new Vector3(x, y, z);
  612. };
  613. Vector3.Lerp = function (start, end, amount) {
  614. var x = start.x + ((end.x - start.x) * amount);
  615. var y = start.y + ((end.y - start.y) * amount);
  616. var z = start.z + ((end.z - start.z) * amount);
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Dot = function (left, right) {
  620. return (left.x * right.x + left.y * right.y + left.z * right.z);
  621. };
  622. Vector3.Cross = function (left, right) {
  623. var result = Vector3.Zero();
  624. Vector3.CrossToRef(left, right, result);
  625. return result;
  626. };
  627. Vector3.CrossToRef = function (left, right, result) {
  628. result.x = left.y * right.z - left.z * right.y;
  629. result.y = left.z * right.x - left.x * right.z;
  630. result.z = left.x * right.y - left.y * right.x;
  631. };
  632. Vector3.Normalize = function (vector) {
  633. var result = Vector3.Zero();
  634. Vector3.NormalizeToRef(vector, result);
  635. return result;
  636. };
  637. Vector3.NormalizeToRef = function (vector, result) {
  638. result.copyFrom(vector);
  639. result.normalize();
  640. };
  641. Vector3.Project = function (vector, world, transform, viewport) {
  642. var cw = viewport.width;
  643. var ch = viewport.height;
  644. var cx = viewport.x;
  645. var cy = viewport.y;
  646. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  647. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  648. return Vector3.TransformCoordinates(vector, finalMatrix);
  649. };
  650. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  651. var matrix = world.multiply(view).multiply(projection);
  652. matrix.invert();
  653. source.x = source.x / viewportWidth * 2 - 1;
  654. source.y = -(source.y / viewportHeight * 2 - 1);
  655. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  656. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  657. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  658. vector = vector.scale(1.0 / num);
  659. }
  660. return vector;
  661. };
  662. Vector3.Minimize = function (left, right) {
  663. var min = left.clone();
  664. min.MinimizeInPlace(right);
  665. return min;
  666. };
  667. Vector3.Maximize = function (left, right) {
  668. var max = left.clone();
  669. max.MaximizeInPlace(right);
  670. return max;
  671. };
  672. Vector3.Distance = function (value1, value2) {
  673. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  674. };
  675. Vector3.DistanceSquared = function (value1, value2) {
  676. var x = value1.x - value2.x;
  677. var y = value1.y - value2.y;
  678. var z = value1.z - value2.z;
  679. return (x * x) + (y * y) + (z * z);
  680. };
  681. Vector3.Center = function (value1, value2) {
  682. var center = value1.add(value2);
  683. center.scaleInPlace(0.5);
  684. return center;
  685. };
  686. return Vector3;
  687. })();
  688. BABYLON.Vector3 = Vector3;
  689. var Quaternion = (function () {
  690. function Quaternion(x, y, z, w) {
  691. if (typeof x === "undefined") { x = 0; }
  692. if (typeof y === "undefined") { y = 0; }
  693. if (typeof z === "undefined") { z = 0; }
  694. if (typeof w === "undefined") { w = 1; }
  695. this.x = x;
  696. this.y = y;
  697. this.z = z;
  698. this.w = w;
  699. }
  700. Quaternion.prototype.toString = function () {
  701. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  702. };
  703. Quaternion.prototype.asArray = function () {
  704. return [this.x, this.y, this.z, this.w];
  705. };
  706. Quaternion.prototype.equals = function (otherQuaternion) {
  707. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  708. };
  709. Quaternion.prototype.clone = function () {
  710. return new Quaternion(this.x, this.y, this.z, this.w);
  711. };
  712. Quaternion.prototype.copyFrom = function (other) {
  713. this.x = other.x;
  714. this.y = other.y;
  715. this.z = other.z;
  716. this.w = other.w;
  717. };
  718. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  719. this.x = x;
  720. this.y = y;
  721. this.z = z;
  722. this.w = w;
  723. };
  724. Quaternion.prototype.add = function (other) {
  725. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  726. };
  727. Quaternion.prototype.subtract = function (other) {
  728. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  729. };
  730. Quaternion.prototype.scale = function (value) {
  731. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  732. };
  733. Quaternion.prototype.multiply = function (q1) {
  734. var result = new Quaternion(0, 0, 0, 1.0);
  735. this.multiplyToRef(q1, result);
  736. return result;
  737. };
  738. Quaternion.prototype.multiplyToRef = function (q1, result) {
  739. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  740. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  741. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  742. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  743. };
  744. Quaternion.prototype.length = function () {
  745. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  746. };
  747. Quaternion.prototype.normalize = function () {
  748. var length = 1.0 / this.length();
  749. this.x *= length;
  750. this.y *= length;
  751. this.z *= length;
  752. this.w *= length;
  753. };
  754. Quaternion.prototype.toEulerAngles = function () {
  755. var result = Vector3.Zero();
  756. this.toEulerAnglesToRef(result);
  757. return result;
  758. };
  759. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  760. var qx = this.x;
  761. var qy = this.y;
  762. var qz = this.z;
  763. var qw = this.w;
  764. var sqx = qx * qx;
  765. var sqy = qy * qy;
  766. var sqz = qz * qz;
  767. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  768. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  769. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  770. var gimbaLockTest = qx * qy + qz * qw;
  771. if (gimbaLockTest > 0.499) {
  772. yaw = 2.0 * Math.atan2(qx, qw);
  773. roll = 0;
  774. } else if (gimbaLockTest < -0.499) {
  775. yaw = -2.0 * Math.atan2(qx, qw);
  776. roll = 0;
  777. }
  778. result.x = pitch;
  779. result.y = yaw;
  780. result.z = roll;
  781. };
  782. Quaternion.prototype.toRotationMatrix = function (result) {
  783. var xx = this.x * this.x;
  784. var yy = this.y * this.y;
  785. var zz = this.z * this.z;
  786. var xy = this.x * this.y;
  787. var zw = this.z * this.w;
  788. var zx = this.z * this.x;
  789. var yw = this.y * this.w;
  790. var yz = this.y * this.z;
  791. var xw = this.x * this.w;
  792. result.m[0] = 1.0 - (2.0 * (yy + zz));
  793. result.m[1] = 2.0 * (xy + zw);
  794. result.m[2] = 2.0 * (zx - yw);
  795. result.m[3] = 0;
  796. result.m[4] = 2.0 * (xy - zw);
  797. result.m[5] = 1.0 - (2.0 * (zz + xx));
  798. result.m[6] = 2.0 * (yz + xw);
  799. result.m[7] = 0;
  800. result.m[8] = 2.0 * (zx + yw);
  801. result.m[9] = 2.0 * (yz - xw);
  802. result.m[10] = 1.0 - (2.0 * (yy + xx));
  803. result.m[11] = 0;
  804. result.m[12] = 0;
  805. result.m[13] = 0;
  806. result.m[14] = 0;
  807. result.m[15] = 1.0;
  808. };
  809. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  810. var data = matrix.m;
  811. var m11 = data[0], m12 = data[4], m13 = data[8];
  812. var m21 = data[1], m22 = data[5], m23 = data[9];
  813. var m31 = data[2], m32 = data[6], m33 = data[10];
  814. var trace = m11 + m22 + m33;
  815. var s;
  816. if (trace > 0) {
  817. s = 0.5 / Math.sqrt(trace + 1.0);
  818. this.w = 0.25 / s;
  819. this.x = (m32 - m23) * s;
  820. this.y = (m13 - m31) * s;
  821. this.z = (m21 - m12) * s;
  822. return;
  823. }
  824. if (m11 > m22 && m11 > m33) {
  825. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  826. this.w = (m32 - m23) / s;
  827. this.x = 0.25 * s;
  828. this.y = (m12 + m21) / s;
  829. this.z = (m13 + m31) / s;
  830. return;
  831. }
  832. if (m22 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  834. this.w = (m13 - m31) / s;
  835. this.x = (m12 + m21) / s;
  836. this.y = 0.25 * s;
  837. this.z = (m23 + m32) / s;
  838. return;
  839. }
  840. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  841. this.w = (m21 - m12) / s;
  842. this.x = (m13 + m31) / s;
  843. this.y = (m23 + m32) / s;
  844. this.z = 0.25 * s;
  845. };
  846. Quaternion.Inverse = function (q) {
  847. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  848. };
  849. Quaternion.RotationAxis = function (axis, angle) {
  850. var result = new Quaternion();
  851. var sin = Math.sin(angle / 2);
  852. result.w = Math.cos(angle / 2);
  853. result.x = axis.x * sin;
  854. result.y = axis.y * sin;
  855. result.z = axis.z * sin;
  856. return result;
  857. };
  858. Quaternion.FromArray = function (array, offset) {
  859. if (!offset) {
  860. offset = 0;
  861. }
  862. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  863. };
  864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  865. var result = new Quaternion();
  866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  867. return result;
  868. };
  869. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  870. var halfRoll = roll * 0.5;
  871. var halfPitch = pitch * 0.5;
  872. var halfYaw = yaw * 0.5;
  873. var sinRoll = Math.sin(halfRoll);
  874. var cosRoll = Math.cos(halfRoll);
  875. var sinPitch = Math.sin(halfPitch);
  876. var cosPitch = Math.cos(halfPitch);
  877. var sinYaw = Math.sin(halfYaw);
  878. var cosYaw = Math.cos(halfYaw);
  879. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  880. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  881. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  882. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  883. };
  884. Quaternion.Slerp = function (left, right, amount) {
  885. var num2;
  886. var num3;
  887. var num = amount;
  888. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  889. var flag = false;
  890. if (num4 < 0) {
  891. flag = true;
  892. num4 = -num4;
  893. }
  894. if (num4 > 0.999999) {
  895. num3 = 1 - num;
  896. num2 = flag ? -num : num;
  897. } else {
  898. var num5 = Math.acos(num4);
  899. var num6 = (1.0 / Math.sin(num5));
  900. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  901. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  902. }
  903. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  904. };
  905. return Quaternion;
  906. })();
  907. BABYLON.Quaternion = Quaternion;
  908. var Matrix = (function () {
  909. function Matrix() {
  910. this.m = new Float32Array(16);
  911. }
  912. Matrix.prototype.isIdentity = function () {
  913. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  914. return false;
  915. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  916. return false;
  917. return true;
  918. };
  919. Matrix.prototype.determinant = function () {
  920. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  921. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  922. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  923. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  924. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  925. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  926. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  927. };
  928. Matrix.prototype.toArray = function () {
  929. return this.m;
  930. };
  931. Matrix.prototype.asArray = function () {
  932. return this.toArray();
  933. };
  934. Matrix.prototype.invert = function () {
  935. this.invertToRef(this);
  936. };
  937. Matrix.prototype.invertToRef = function (other) {
  938. var l1 = this.m[0];
  939. var l2 = this.m[1];
  940. var l3 = this.m[2];
  941. var l4 = this.m[3];
  942. var l5 = this.m[4];
  943. var l6 = this.m[5];
  944. var l7 = this.m[6];
  945. var l8 = this.m[7];
  946. var l9 = this.m[8];
  947. var l10 = this.m[9];
  948. var l11 = this.m[10];
  949. var l12 = this.m[11];
  950. var l13 = this.m[12];
  951. var l14 = this.m[13];
  952. var l15 = this.m[14];
  953. var l16 = this.m[15];
  954. var l17 = (l11 * l16) - (l12 * l15);
  955. var l18 = (l10 * l16) - (l12 * l14);
  956. var l19 = (l10 * l15) - (l11 * l14);
  957. var l20 = (l9 * l16) - (l12 * l13);
  958. var l21 = (l9 * l15) - (l11 * l13);
  959. var l22 = (l9 * l14) - (l10 * l13);
  960. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  961. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  962. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  963. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  964. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  965. var l28 = (l7 * l16) - (l8 * l15);
  966. var l29 = (l6 * l16) - (l8 * l14);
  967. var l30 = (l6 * l15) - (l7 * l14);
  968. var l31 = (l5 * l16) - (l8 * l13);
  969. var l32 = (l5 * l15) - (l7 * l13);
  970. var l33 = (l5 * l14) - (l6 * l13);
  971. var l34 = (l7 * l12) - (l8 * l11);
  972. var l35 = (l6 * l12) - (l8 * l10);
  973. var l36 = (l6 * l11) - (l7 * l10);
  974. var l37 = (l5 * l12) - (l8 * l9);
  975. var l38 = (l5 * l11) - (l7 * l9);
  976. var l39 = (l5 * l10) - (l6 * l9);
  977. other.m[0] = l23 * l27;
  978. other.m[4] = l24 * l27;
  979. other.m[8] = l25 * l27;
  980. other.m[12] = l26 * l27;
  981. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  982. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  983. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  984. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  985. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  986. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  987. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  988. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  989. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  990. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  991. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  992. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  993. };
  994. Matrix.prototype.setTranslation = function (vector3) {
  995. this.m[12] = vector3.x;
  996. this.m[13] = vector3.y;
  997. this.m[14] = vector3.z;
  998. };
  999. Matrix.prototype.multiply = function (other) {
  1000. var result = new Matrix();
  1001. this.multiplyToRef(other, result);
  1002. return result;
  1003. };
  1004. Matrix.prototype.copyFrom = function (other) {
  1005. for (var index = 0; index < 16; index++) {
  1006. this.m[index] = other.m[index];
  1007. }
  1008. };
  1009. Matrix.prototype.copyToArray = function (array, offset) {
  1010. if (typeof offset === "undefined") { offset = 0; }
  1011. for (var index = 0; index < 16; index++) {
  1012. array[offset + index] = this.m[index];
  1013. }
  1014. };
  1015. Matrix.prototype.multiplyToRef = function (other, result) {
  1016. this.multiplyToArray(other, result.m, 0);
  1017. };
  1018. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1019. var tm0 = this.m[0];
  1020. var tm1 = this.m[1];
  1021. var tm2 = this.m[2];
  1022. var tm3 = this.m[3];
  1023. var tm4 = this.m[4];
  1024. var tm5 = this.m[5];
  1025. var tm6 = this.m[6];
  1026. var tm7 = this.m[7];
  1027. var tm8 = this.m[8];
  1028. var tm9 = this.m[9];
  1029. var tm10 = this.m[10];
  1030. var tm11 = this.m[11];
  1031. var tm12 = this.m[12];
  1032. var tm13 = this.m[13];
  1033. var tm14 = this.m[14];
  1034. var tm15 = this.m[15];
  1035. var om0 = other.m[0];
  1036. var om1 = other.m[1];
  1037. var om2 = other.m[2];
  1038. var om3 = other.m[3];
  1039. var om4 = other.m[4];
  1040. var om5 = other.m[5];
  1041. var om6 = other.m[6];
  1042. var om7 = other.m[7];
  1043. var om8 = other.m[8];
  1044. var om9 = other.m[9];
  1045. var om10 = other.m[10];
  1046. var om11 = other.m[11];
  1047. var om12 = other.m[12];
  1048. var om13 = other.m[13];
  1049. var om14 = other.m[14];
  1050. var om15 = other.m[15];
  1051. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1052. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1053. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1054. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1055. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1056. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1057. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1058. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1059. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1060. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1061. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1062. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1063. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1064. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1065. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1066. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1067. };
  1068. Matrix.prototype.equals = function (value) {
  1069. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1070. };
  1071. Matrix.prototype.clone = function () {
  1072. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1073. };
  1074. Matrix.FromArray = function (array, offset) {
  1075. var result = new Matrix();
  1076. if (!offset) {
  1077. offset = 0;
  1078. }
  1079. Matrix.FromArrayToRef(array, offset, result);
  1080. return result;
  1081. };
  1082. Matrix.FromArrayToRef = function (array, offset, result) {
  1083. for (var index = 0; index < 16; index++) {
  1084. result.m[index] = array[index + offset];
  1085. }
  1086. };
  1087. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1088. result.m[0] = initialM11;
  1089. result.m[1] = initialM12;
  1090. result.m[2] = initialM13;
  1091. result.m[3] = initialM14;
  1092. result.m[4] = initialM21;
  1093. result.m[5] = initialM22;
  1094. result.m[6] = initialM23;
  1095. result.m[7] = initialM24;
  1096. result.m[8] = initialM31;
  1097. result.m[9] = initialM32;
  1098. result.m[10] = initialM33;
  1099. result.m[11] = initialM34;
  1100. result.m[12] = initialM41;
  1101. result.m[13] = initialM42;
  1102. result.m[14] = initialM43;
  1103. result.m[15] = initialM44;
  1104. };
  1105. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1106. var result = new Matrix();
  1107. result.m[0] = initialM11;
  1108. result.m[1] = initialM12;
  1109. result.m[2] = initialM13;
  1110. result.m[3] = initialM14;
  1111. result.m[4] = initialM21;
  1112. result.m[5] = initialM22;
  1113. result.m[6] = initialM23;
  1114. result.m[7] = initialM24;
  1115. result.m[8] = initialM31;
  1116. result.m[9] = initialM32;
  1117. result.m[10] = initialM33;
  1118. result.m[11] = initialM34;
  1119. result.m[12] = initialM41;
  1120. result.m[13] = initialM42;
  1121. result.m[14] = initialM43;
  1122. result.m[15] = initialM44;
  1123. return result;
  1124. };
  1125. Matrix.Identity = function () {
  1126. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1127. };
  1128. Matrix.IdentityToRef = function (result) {
  1129. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1130. };
  1131. Matrix.Zero = function () {
  1132. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1133. };
  1134. Matrix.RotationX = function (angle) {
  1135. var result = new Matrix();
  1136. Matrix.RotationXToRef(angle, result);
  1137. return result;
  1138. };
  1139. Matrix.RotationXToRef = function (angle, result) {
  1140. var s = Math.sin(angle);
  1141. var c = Math.cos(angle);
  1142. result.m[0] = 1.0;
  1143. result.m[15] = 1.0;
  1144. result.m[5] = c;
  1145. result.m[10] = c;
  1146. result.m[9] = -s;
  1147. result.m[6] = s;
  1148. result.m[1] = 0;
  1149. result.m[2] = 0;
  1150. result.m[3] = 0;
  1151. result.m[4] = 0;
  1152. result.m[7] = 0;
  1153. result.m[8] = 0;
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. };
  1159. Matrix.RotationY = function (angle) {
  1160. var result = new Matrix();
  1161. Matrix.RotationYToRef(angle, result);
  1162. return result;
  1163. };
  1164. Matrix.RotationYToRef = function (angle, result) {
  1165. var s = Math.sin(angle);
  1166. var c = Math.cos(angle);
  1167. result.m[5] = 1.0;
  1168. result.m[15] = 1.0;
  1169. result.m[0] = c;
  1170. result.m[2] = -s;
  1171. result.m[8] = s;
  1172. result.m[10] = c;
  1173. result.m[1] = 0;
  1174. result.m[3] = 0;
  1175. result.m[4] = 0;
  1176. result.m[6] = 0;
  1177. result.m[7] = 0;
  1178. result.m[9] = 0;
  1179. result.m[11] = 0;
  1180. result.m[12] = 0;
  1181. result.m[13] = 0;
  1182. result.m[14] = 0;
  1183. };
  1184. Matrix.RotationZ = function (angle) {
  1185. var result = new Matrix();
  1186. Matrix.RotationZToRef(angle, result);
  1187. return result;
  1188. };
  1189. Matrix.RotationZToRef = function (angle, result) {
  1190. var s = Math.sin(angle);
  1191. var c = Math.cos(angle);
  1192. result.m[10] = 1.0;
  1193. result.m[15] = 1.0;
  1194. result.m[0] = c;
  1195. result.m[1] = s;
  1196. result.m[4] = -s;
  1197. result.m[5] = c;
  1198. result.m[2] = 0;
  1199. result.m[3] = 0;
  1200. result.m[6] = 0;
  1201. result.m[7] = 0;
  1202. result.m[8] = 0;
  1203. result.m[9] = 0;
  1204. result.m[11] = 0;
  1205. result.m[12] = 0;
  1206. result.m[13] = 0;
  1207. result.m[14] = 0;
  1208. };
  1209. Matrix.RotationAxis = function (axis, angle) {
  1210. var s = Math.sin(-angle);
  1211. var c = Math.cos(-angle);
  1212. var c1 = 1 - c;
  1213. axis.normalize();
  1214. var result = Matrix.Zero();
  1215. result.m[0] = (axis.x * axis.x) * c1 + c;
  1216. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1217. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1218. result.m[3] = 0.0;
  1219. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1220. result.m[5] = (axis.y * axis.y) * c1 + c;
  1221. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1222. result.m[7] = 0.0;
  1223. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1224. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1225. result.m[10] = (axis.z * axis.z) * c1 + c;
  1226. result.m[11] = 0.0;
  1227. result.m[15] = 1.0;
  1228. return result;
  1229. };
  1230. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1231. var result = new Matrix();
  1232. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1233. return result;
  1234. };
  1235. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1236. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1237. this._tempQuaternion.toRotationMatrix(result);
  1238. };
  1239. Matrix.Scaling = function (x, y, z) {
  1240. var result = Matrix.Zero();
  1241. Matrix.ScalingToRef(x, y, z, result);
  1242. return result;
  1243. };
  1244. Matrix.ScalingToRef = function (x, y, z, result) {
  1245. result.m[0] = x;
  1246. result.m[1] = 0;
  1247. result.m[2] = 0;
  1248. result.m[3] = 0;
  1249. result.m[4] = 0;
  1250. result.m[5] = y;
  1251. result.m[6] = 0;
  1252. result.m[7] = 0;
  1253. result.m[8] = 0;
  1254. result.m[9] = 0;
  1255. result.m[10] = z;
  1256. result.m[11] = 0;
  1257. result.m[12] = 0;
  1258. result.m[13] = 0;
  1259. result.m[14] = 0;
  1260. result.m[15] = 1.0;
  1261. };
  1262. Matrix.Translation = function (x, y, z) {
  1263. var result = Matrix.Identity();
  1264. Matrix.TranslationToRef(x, y, z, result);
  1265. return result;
  1266. };
  1267. Matrix.TranslationToRef = function (x, y, z, result) {
  1268. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1269. };
  1270. Matrix.LookAtLH = function (eye, target, up) {
  1271. var result = Matrix.Zero();
  1272. Matrix.LookAtLHToRef(eye, target, up, result);
  1273. return result;
  1274. };
  1275. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1276. target.subtractToRef(eye, this._zAxis);
  1277. this._zAxis.normalize();
  1278. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1279. this._xAxis.normalize();
  1280. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1281. this._yAxis.normalize();
  1282. var ex = -Vector3.Dot(this._xAxis, eye);
  1283. var ey = -Vector3.Dot(this._yAxis, eye);
  1284. var ez = -Vector3.Dot(this._zAxis, eye);
  1285. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1286. };
  1287. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1288. var hw = 2.0 / width;
  1289. var hh = 2.0 / height;
  1290. var id = 1.0 / (zfar - znear);
  1291. var nid = znear / (znear - zfar);
  1292. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1293. };
  1294. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1295. var matrix = Matrix.Zero();
  1296. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1297. return matrix;
  1298. };
  1299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1300. result.m[0] = 2.0 / (right - left);
  1301. result.m[1] = result.m[2] = result.m[3] = 0;
  1302. result.m[5] = 2.0 / (top - bottom);
  1303. result.m[4] = result.m[6] = result.m[7] = 0;
  1304. result.m[10] = -1.0 / (znear - zfar);
  1305. result.m[8] = result.m[9] = result.m[11] = 0;
  1306. result.m[12] = (left + right) / (left - right);
  1307. result.m[13] = (top + bottom) / (bottom - top);
  1308. result.m[14] = znear / (znear - zfar);
  1309. result.m[15] = 1.0;
  1310. };
  1311. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1312. var matrix = Matrix.Zero();
  1313. matrix.m[0] = (2.0 * znear) / width;
  1314. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1315. matrix.m[5] = (2.0 * znear) / height;
  1316. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1317. matrix.m[10] = -zfar / (znear - zfar);
  1318. matrix.m[8] = matrix.m[9] = 0.0;
  1319. matrix.m[11] = 1.0;
  1320. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1321. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1322. return matrix;
  1323. };
  1324. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1325. var matrix = Matrix.Zero();
  1326. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1327. return matrix;
  1328. };
  1329. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1330. var tan = 1.0 / (Math.tan(fov * 0.5));
  1331. result.m[0] = tan / aspect;
  1332. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1333. result.m[5] = tan;
  1334. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1335. result.m[8] = result.m[9] = 0.0;
  1336. result.m[10] = -zfar / (znear - zfar);
  1337. result.m[11] = 1.0;
  1338. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1339. result.m[14] = (znear * zfar) / (znear - zfar);
  1340. };
  1341. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1342. var cw = viewport.width;
  1343. var ch = viewport.height;
  1344. var cx = viewport.x;
  1345. var cy = viewport.y;
  1346. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1347. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1348. };
  1349. Matrix.Transpose = function (matrix) {
  1350. var result = new Matrix();
  1351. result.m[0] = matrix.m[0];
  1352. result.m[1] = matrix.m[4];
  1353. result.m[2] = matrix.m[8];
  1354. result.m[3] = matrix.m[12];
  1355. result.m[4] = matrix.m[1];
  1356. result.m[5] = matrix.m[5];
  1357. result.m[6] = matrix.m[9];
  1358. result.m[7] = matrix.m[13];
  1359. result.m[8] = matrix.m[2];
  1360. result.m[9] = matrix.m[6];
  1361. result.m[10] = matrix.m[10];
  1362. result.m[11] = matrix.m[14];
  1363. result.m[12] = matrix.m[3];
  1364. result.m[13] = matrix.m[7];
  1365. result.m[14] = matrix.m[11];
  1366. result.m[15] = matrix.m[15];
  1367. return result;
  1368. };
  1369. Matrix.Reflection = function (plane) {
  1370. var matrix = new Matrix();
  1371. Matrix.ReflectionToRef(plane, matrix);
  1372. return matrix;
  1373. };
  1374. Matrix.ReflectionToRef = function (plane, result) {
  1375. plane.normalize();
  1376. var x = plane.normal.x;
  1377. var y = plane.normal.y;
  1378. var z = plane.normal.z;
  1379. var temp = -2 * x;
  1380. var temp2 = -2 * y;
  1381. var temp3 = -2 * z;
  1382. result.m[0] = (temp * x) + 1;
  1383. result.m[1] = temp2 * x;
  1384. result.m[2] = temp3 * x;
  1385. result.m[3] = 0.0;
  1386. result.m[4] = temp * y;
  1387. result.m[5] = (temp2 * y) + 1;
  1388. result.m[6] = temp3 * y;
  1389. result.m[7] = 0.0;
  1390. result.m[8] = temp * z;
  1391. result.m[9] = temp2 * z;
  1392. result.m[10] = (temp3 * z) + 1;
  1393. result.m[11] = 0.0;
  1394. result.m[12] = temp * plane.d;
  1395. result.m[13] = temp2 * plane.d;
  1396. result.m[14] = temp3 * plane.d;
  1397. result.m[15] = 1.0;
  1398. };
  1399. Matrix._tempQuaternion = new Quaternion();
  1400. Matrix._xAxis = Vector3.Zero();
  1401. Matrix._yAxis = Vector3.Zero();
  1402. Matrix._zAxis = Vector3.Zero();
  1403. return Matrix;
  1404. })();
  1405. BABYLON.Matrix = Matrix;
  1406. var Plane = (function () {
  1407. function Plane(a, b, c, d) {
  1408. this.normal = new Vector3(a, b, c);
  1409. this.d = d;
  1410. }
  1411. Plane.prototype.asArray = function () {
  1412. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1413. };
  1414. Plane.prototype.clone = function () {
  1415. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1416. };
  1417. Plane.prototype.normalize = function () {
  1418. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1419. var magnitude = 0;
  1420. if (norm != 0) {
  1421. magnitude = 1.0 / norm;
  1422. }
  1423. this.normal.x *= magnitude;
  1424. this.normal.y *= magnitude;
  1425. this.normal.z *= magnitude;
  1426. this.d *= magnitude;
  1427. };
  1428. Plane.prototype.transform = function (transformation) {
  1429. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1430. var x = this.normal.x;
  1431. var y = this.normal.y;
  1432. var z = this.normal.z;
  1433. var d = this.d;
  1434. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1435. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1436. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1437. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1438. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1439. };
  1440. Plane.prototype.dotCoordinate = function (point) {
  1441. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1442. };
  1443. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1444. var x1 = point2.x - point1.x;
  1445. var y1 = point2.y - point1.y;
  1446. var z1 = point2.z - point1.z;
  1447. var x2 = point3.x - point1.x;
  1448. var y2 = point3.y - point1.y;
  1449. var z2 = point3.z - point1.z;
  1450. var yz = (y1 * z2) - (z1 * y2);
  1451. var xz = (z1 * x2) - (x1 * z2);
  1452. var xy = (x1 * y2) - (y1 * x2);
  1453. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1454. var invPyth;
  1455. if (pyth != 0) {
  1456. invPyth = 1.0 / pyth;
  1457. } else {
  1458. invPyth = 0;
  1459. }
  1460. this.normal.x = yz * invPyth;
  1461. this.normal.y = xz * invPyth;
  1462. this.normal.z = xy * invPyth;
  1463. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1464. };
  1465. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1466. var dot = Vector3.Dot(this.normal, direction);
  1467. return (dot <= epsilon);
  1468. };
  1469. Plane.prototype.signedDistanceTo = function (point) {
  1470. return Vector3.Dot(point, this.normal) + this.d;
  1471. };
  1472. Plane.FromArray = function (array) {
  1473. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1474. };
  1475. Plane.FromPoints = function (point1, point2, point3) {
  1476. var result = new BABYLON.Plane(0, 0, 0, 0);
  1477. result.copyFromPoints(point1, point2, point3);
  1478. return result;
  1479. };
  1480. Plane.FromPositionAndNormal = function (origin, normal) {
  1481. var result = new BABYLON.Plane(0, 0, 0, 0);
  1482. normal.normalize();
  1483. result.normal = normal;
  1484. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1485. return result;
  1486. };
  1487. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1488. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1489. return Vector3.Dot(point, normal) + d;
  1490. };
  1491. return Plane;
  1492. })();
  1493. BABYLON.Plane = Plane;
  1494. var Viewport = (function () {
  1495. function Viewport(x, y, width, height) {
  1496. this.x = x;
  1497. this.y = y;
  1498. this.width = width;
  1499. this.height = height;
  1500. }
  1501. Viewport.prototype.toGlobal = function (engine) {
  1502. var width = engine.getRenderWidth();
  1503. var height = engine.getRenderHeight();
  1504. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1505. };
  1506. return Viewport;
  1507. })();
  1508. BABYLON.Viewport = Viewport;
  1509. var Frustum = (function () {
  1510. function Frustum() {
  1511. }
  1512. Frustum.GetPlanes = function (transform) {
  1513. var frustumPlanes = [];
  1514. for (var index = 0; index < 6; index++) {
  1515. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1516. }
  1517. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1518. return frustumPlanes;
  1519. };
  1520. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1521. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1522. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1523. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1524. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1525. frustumPlanes[0].normalize();
  1526. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1527. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1528. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1529. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1530. frustumPlanes[1].normalize();
  1531. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1532. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1533. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1534. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1535. frustumPlanes[2].normalize();
  1536. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1537. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1538. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1539. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1540. frustumPlanes[3].normalize();
  1541. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1542. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1543. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1544. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1545. frustumPlanes[4].normalize();
  1546. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1547. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1548. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1549. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1550. frustumPlanes[5].normalize();
  1551. };
  1552. return Frustum;
  1553. })();
  1554. BABYLON.Frustum = Frustum;
  1555. var Ray = (function () {
  1556. function Ray(origin, direction) {
  1557. this.origin = origin;
  1558. this.direction = direction;
  1559. }
  1560. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1561. var d = 0.0;
  1562. var maxValue = Number.MAX_VALUE;
  1563. if (Math.abs(this.direction.x) < 0.0000001) {
  1564. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1565. return false;
  1566. }
  1567. } else {
  1568. var inv = 1.0 / this.direction.x;
  1569. var min = (minimum.x - this.origin.x) * inv;
  1570. var max = (maximum.x - this.origin.x) * inv;
  1571. if (min > max) {
  1572. var temp = min;
  1573. min = max;
  1574. max = temp;
  1575. }
  1576. d = Math.max(min, d);
  1577. maxValue = Math.min(max, maxValue);
  1578. if (d > maxValue) {
  1579. return false;
  1580. }
  1581. }
  1582. if (Math.abs(this.direction.y) < 0.0000001) {
  1583. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1584. return false;
  1585. }
  1586. } else {
  1587. inv = 1.0 / this.direction.y;
  1588. min = (minimum.y - this.origin.y) * inv;
  1589. max = (maximum.y - this.origin.y) * inv;
  1590. if (min > max) {
  1591. temp = min;
  1592. min = max;
  1593. max = temp;
  1594. }
  1595. d = Math.max(min, d);
  1596. maxValue = Math.min(max, maxValue);
  1597. if (d > maxValue) {
  1598. return false;
  1599. }
  1600. }
  1601. if (Math.abs(this.direction.z) < 0.0000001) {
  1602. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1603. return false;
  1604. }
  1605. } else {
  1606. inv = 1.0 / this.direction.z;
  1607. min = (minimum.z - this.origin.z) * inv;
  1608. max = (maximum.z - this.origin.z) * inv;
  1609. if (min > max) {
  1610. temp = min;
  1611. min = max;
  1612. max = temp;
  1613. }
  1614. d = Math.max(min, d);
  1615. maxValue = Math.min(max, maxValue);
  1616. if (d > maxValue) {
  1617. return false;
  1618. }
  1619. }
  1620. return true;
  1621. };
  1622. Ray.prototype.intersectsBox = function (box) {
  1623. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1624. };
  1625. Ray.prototype.intersectsSphere = function (sphere) {
  1626. var x = sphere.center.x - this.origin.x;
  1627. var y = sphere.center.y - this.origin.y;
  1628. var z = sphere.center.z - this.origin.z;
  1629. var pyth = (x * x) + (y * y) + (z * z);
  1630. var rr = sphere.radius * sphere.radius;
  1631. if (pyth <= rr) {
  1632. return true;
  1633. }
  1634. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1635. if (dot < 0.0) {
  1636. return false;
  1637. }
  1638. var temp = pyth - (dot * dot);
  1639. return temp <= rr;
  1640. };
  1641. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1642. if (!this._edge1) {
  1643. this._edge1 = BABYLON.Vector3.Zero();
  1644. this._edge2 = BABYLON.Vector3.Zero();
  1645. this._pvec = BABYLON.Vector3.Zero();
  1646. this._tvec = BABYLON.Vector3.Zero();
  1647. this._qvec = BABYLON.Vector3.Zero();
  1648. }
  1649. vertex1.subtractToRef(vertex0, this._edge1);
  1650. vertex2.subtractToRef(vertex0, this._edge2);
  1651. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1652. var det = Vector3.Dot(this._edge1, this._pvec);
  1653. if (det === 0) {
  1654. return null;
  1655. }
  1656. var invdet = 1 / det;
  1657. this.origin.subtractToRef(vertex0, this._tvec);
  1658. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1659. if (bu < 0 || bu > 1.0) {
  1660. return null;
  1661. }
  1662. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1663. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1664. if (bv < 0 || bu + bv > 1.0) {
  1665. return null;
  1666. }
  1667. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1668. };
  1669. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1670. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1671. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1672. var direction = end.subtract(start);
  1673. direction.normalize();
  1674. return new Ray(start, direction);
  1675. };
  1676. Ray.Transform = function (ray, matrix) {
  1677. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1678. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1679. return new Ray(newOrigin, newDirection);
  1680. };
  1681. return Ray;
  1682. })();
  1683. BABYLON.Ray = Ray;
  1684. (function (Space) {
  1685. Space[Space["LOCAL"] = 0] = "LOCAL";
  1686. Space[Space["WORLD"] = 1] = "WORLD";
  1687. })(BABYLON.Space || (BABYLON.Space = {}));
  1688. var Space = BABYLON.Space;
  1689. var Axis = (function () {
  1690. function Axis() {
  1691. }
  1692. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1693. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1694. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1695. return Axis;
  1696. })();
  1697. BABYLON.Axis = Axis;
  1698. ;
  1699. })(BABYLON || (BABYLON = {}));
  1700. var BABYLON;
  1701. (function (BABYLON) {
  1702. var screenshotCanvas;
  1703. var fpsRange = 60;
  1704. var previousFramesDuration = [];
  1705. var fps = 60;
  1706. var deltaTime = 0;
  1707. var cloneValue = function (source, destinationObject) {
  1708. if (!source)
  1709. return null;
  1710. if (source instanceof BABYLON.Mesh) {
  1711. return null;
  1712. }
  1713. if (source instanceof BABYLON.SubMesh) {
  1714. return source.clone(destinationObject);
  1715. } else if (source.clone) {
  1716. return source.clone();
  1717. }
  1718. return null;
  1719. };
  1720. var Tools = (function () {
  1721. function Tools() {
  1722. }
  1723. Tools.GetFilename = function (path) {
  1724. var index = path.lastIndexOf("/");
  1725. if (index < 0)
  1726. return path;
  1727. return path.substring(index + 1);
  1728. };
  1729. Tools.GetDOMTextContent = function (element) {
  1730. var result = "";
  1731. var child = element.firstChild;
  1732. while (child) {
  1733. if (child.nodeType == 3) {
  1734. result += child.textContent;
  1735. }
  1736. child = child.nextSibling;
  1737. }
  1738. return result;
  1739. };
  1740. Tools.ToDegrees = function (angle) {
  1741. return angle * 180 / Math.PI;
  1742. };
  1743. Tools.ToRadians = function (angle) {
  1744. return angle * Math.PI / 180;
  1745. };
  1746. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1747. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1748. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1749. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1750. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1751. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1752. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1753. }
  1754. return {
  1755. minimum: minimum,
  1756. maximum: maximum
  1757. };
  1758. };
  1759. Tools.ExtractMinAndMax = function (positions, start, count) {
  1760. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1761. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1762. for (var index = start; index < start + count; index++) {
  1763. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1764. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1765. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1766. }
  1767. return {
  1768. minimum: minimum,
  1769. maximum: maximum
  1770. };
  1771. };
  1772. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1773. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1774. return undefined;
  1775. return Array.isArray(obj) ? obj : [obj];
  1776. };
  1777. Tools.GetPointerPrefix = function () {
  1778. var eventPrefix = "pointer";
  1779. if (!navigator.pointerEnabled) {
  1780. eventPrefix = "mouse";
  1781. }
  1782. return eventPrefix;
  1783. };
  1784. Tools.QueueNewFrame = function (func) {
  1785. if (window.requestAnimationFrame)
  1786. window.requestAnimationFrame(func);
  1787. else if (window.msRequestAnimationFrame)
  1788. window.msRequestAnimationFrame(func);
  1789. else if (window.webkitRequestAnimationFrame)
  1790. window.webkitRequestAnimationFrame(func);
  1791. else if (window.mozRequestAnimationFrame)
  1792. window.mozRequestAnimationFrame(func);
  1793. else if (window.oRequestAnimationFrame)
  1794. window.oRequestAnimationFrame(func);
  1795. else {
  1796. window.setTimeout(func, 16);
  1797. }
  1798. };
  1799. Tools.RequestFullscreen = function (element) {
  1800. if (element.requestFullscreen)
  1801. element.requestFullscreen();
  1802. else if (element.msRequestFullscreen)
  1803. element.msRequestFullscreen();
  1804. else if (element.webkitRequestFullscreen)
  1805. element.webkitRequestFullscreen();
  1806. else if (element.mozRequestFullScreen)
  1807. element.mozRequestFullScreen();
  1808. };
  1809. Tools.ExitFullscreen = function () {
  1810. if (document.exitFullscreen) {
  1811. document.exitFullscreen();
  1812. } else if (document.mozCancelFullScreen) {
  1813. document.mozCancelFullScreen();
  1814. } else if (document.webkitCancelFullScreen) {
  1815. document.webkitCancelFullScreen();
  1816. } else if (document.msCancelFullScreen) {
  1817. document.msCancelFullScreen();
  1818. }
  1819. };
  1820. Tools.CleanUrl = function (url) {
  1821. url = url.replace(/#/mg, "%23");
  1822. return url;
  1823. };
  1824. Tools.LoadImage = function (url, onload, onerror, database) {
  1825. url = Tools.CleanUrl(url);
  1826. var img = new Image();
  1827. img.crossOrigin = 'anonymous';
  1828. img.onload = function () {
  1829. onload(img);
  1830. };
  1831. img.onerror = function (err) {
  1832. onerror(img, err);
  1833. };
  1834. var noIndexedDB = function () {
  1835. img.src = url;
  1836. };
  1837. var loadFromIndexedDB = function () {
  1838. database.loadImageFromDB(url, img);
  1839. };
  1840. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1841. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1842. } else {
  1843. if (url.indexOf("file:") === -1) {
  1844. noIndexedDB();
  1845. } else {
  1846. try {
  1847. var textureName = url.substring(5);
  1848. var blobURL;
  1849. try {
  1850. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1851. } catch (ex) {
  1852. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1853. }
  1854. img.src = blobURL;
  1855. } catch (e) {
  1856. Tools.Log("Error while trying to load texture: " + textureName);
  1857. img.src = null;
  1858. }
  1859. }
  1860. }
  1861. return img;
  1862. };
  1863. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1864. url = Tools.CleanUrl(url);
  1865. var noIndexedDB = function () {
  1866. var request = new XMLHttpRequest();
  1867. var loadUrl = Tools.BaseUrl + url;
  1868. request.open('GET', loadUrl, true);
  1869. if (useArrayBuffer) {
  1870. request.responseType = "arraybuffer";
  1871. }
  1872. request.onprogress = progressCallBack;
  1873. request.onreadystatechange = function () {
  1874. if (request.readyState == 4) {
  1875. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1876. callback(!useArrayBuffer ? request.responseText : request.response);
  1877. } else {
  1878. if (onError) {
  1879. onError();
  1880. } else {
  1881. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1882. }
  1883. }
  1884. }
  1885. };
  1886. request.send(null);
  1887. };
  1888. var loadFromIndexedDB = function () {
  1889. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1890. };
  1891. if (url.indexOf("file:") !== -1) {
  1892. var fileName = url.substring(5);
  1893. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1894. } else {
  1895. if (database && database.enableSceneOffline) {
  1896. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1897. } else {
  1898. noIndexedDB();
  1899. }
  1900. }
  1901. };
  1902. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1903. var reader = new FileReader();
  1904. reader.onload = function (e) {
  1905. callback(e.target.result);
  1906. };
  1907. reader.onprogress = progressCallBack;
  1908. if (!useArrayBuffer) {
  1909. reader.readAsText(fileToLoad);
  1910. } else {
  1911. reader.readAsArrayBuffer(fileToLoad);
  1912. }
  1913. };
  1914. Tools.CheckExtends = function (v, min, max) {
  1915. if (v.x < min.x)
  1916. min.x = v.x;
  1917. if (v.y < min.y)
  1918. min.y = v.y;
  1919. if (v.z < min.z)
  1920. min.z = v.z;
  1921. if (v.x > max.x)
  1922. max.x = v.x;
  1923. if (v.y > max.y)
  1924. max.y = v.y;
  1925. if (v.z > max.z)
  1926. max.z = v.z;
  1927. };
  1928. Tools.WithinEpsilon = function (a, b) {
  1929. var num = a - b;
  1930. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1931. };
  1932. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1933. for (var prop in source) {
  1934. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1935. continue;
  1936. }
  1937. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1938. continue;
  1939. }
  1940. var sourceValue = source[prop];
  1941. var typeOfSourceValue = typeof sourceValue;
  1942. if (typeOfSourceValue == "function") {
  1943. continue;
  1944. }
  1945. if (typeOfSourceValue == "object") {
  1946. if (sourceValue instanceof Array) {
  1947. destination[prop] = [];
  1948. if (sourceValue.length > 0) {
  1949. if (typeof sourceValue[0] == "object") {
  1950. for (var index = 0; index < sourceValue.length; index++) {
  1951. var clonedValue = cloneValue(sourceValue[index], destination);
  1952. if (destination[prop].indexOf(clonedValue) === -1) {
  1953. destination[prop].push(clonedValue);
  1954. }
  1955. }
  1956. } else {
  1957. destination[prop] = sourceValue.slice(0);
  1958. }
  1959. }
  1960. } else {
  1961. destination[prop] = cloneValue(sourceValue, destination);
  1962. }
  1963. } else {
  1964. destination[prop] = sourceValue;
  1965. }
  1966. }
  1967. };
  1968. Tools.IsEmpty = function (obj) {
  1969. for (var i in obj) {
  1970. return false;
  1971. }
  1972. return true;
  1973. };
  1974. Tools.RegisterTopRootEvents = function (events) {
  1975. for (var index = 0; index < events.length; index++) {
  1976. var event = events[index];
  1977. window.addEventListener(event.name, event.handler, false);
  1978. try {
  1979. if (window.parent) {
  1980. window.parent.addEventListener(event.name, event.handler, false);
  1981. }
  1982. } catch (e) {
  1983. }
  1984. }
  1985. };
  1986. Tools.UnregisterTopRootEvents = function (events) {
  1987. for (var index = 0; index < events.length; index++) {
  1988. var event = events[index];
  1989. window.removeEventListener(event.name, event.handler);
  1990. try {
  1991. if (window.parent) {
  1992. window.parent.removeEventListener(event.name, event.handler);
  1993. }
  1994. } catch (e) {
  1995. }
  1996. }
  1997. };
  1998. Tools.GetFps = function () {
  1999. return fps;
  2000. };
  2001. Tools.GetDeltaTime = function () {
  2002. return deltaTime;
  2003. };
  2004. Tools._MeasureFps = function () {
  2005. previousFramesDuration.push((new Date).getTime());
  2006. var length = previousFramesDuration.length;
  2007. if (length >= 2) {
  2008. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2009. }
  2010. if (length >= fpsRange) {
  2011. if (length > fpsRange) {
  2012. previousFramesDuration.splice(0, 1);
  2013. length = previousFramesDuration.length;
  2014. }
  2015. var sum = 0;
  2016. for (var id = 0; id < length - 1; id++) {
  2017. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2018. }
  2019. fps = 1000.0 / (sum / (length - 1));
  2020. }
  2021. };
  2022. Tools.CreateScreenshot = function (engine, camera, size) {
  2023. var width;
  2024. var height;
  2025. var scene = camera.getScene();
  2026. var previousCamera = null;
  2027. if (scene.activeCamera !== camera) {
  2028. previousCamera = scene.activeCamera;
  2029. scene.activeCamera = camera;
  2030. }
  2031. if (size.precision) {
  2032. width = Math.round(engine.getRenderWidth() * size.precision);
  2033. height = Math.round(width / engine.getAspectRatio(camera));
  2034. size = { width: width, height: height };
  2035. } else if (size.width && size.height) {
  2036. width = size.width;
  2037. height = size.height;
  2038. } else if (size.width && !size.height) {
  2039. width = size.width;
  2040. height = Math.round(width / engine.getAspectRatio(camera));
  2041. size = { width: width, height: height };
  2042. } else if (size.height && !size.width) {
  2043. height = size.height;
  2044. width = Math.round(height * engine.getAspectRatio(camera));
  2045. size = { width: width, height: height };
  2046. } else if (!isNaN(size)) {
  2047. height = size;
  2048. width = size;
  2049. } else {
  2050. Tools.Error("Invalid 'size' parameter !");
  2051. return;
  2052. }
  2053. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2054. texture.renderList = engine.scenes[0].meshes;
  2055. texture.onAfterRender = function () {
  2056. var numberOfChannelsByLine = width * 4;
  2057. var halfHeight = height / 2;
  2058. var data = engine.readPixels(0, 0, width, height);
  2059. for (var i = 0; i < halfHeight; i++) {
  2060. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2061. var currentCell = j + i * numberOfChannelsByLine;
  2062. var targetLine = height - i - 1;
  2063. var targetCell = j + targetLine * numberOfChannelsByLine;
  2064. var temp = data[currentCell];
  2065. data[currentCell] = data[targetCell];
  2066. data[targetCell] = temp;
  2067. }
  2068. }
  2069. if (!screenshotCanvas) {
  2070. screenshotCanvas = document.createElement('canvas');
  2071. }
  2072. screenshotCanvas.width = width;
  2073. screenshotCanvas.height = height;
  2074. var context = screenshotCanvas.getContext('2d');
  2075. var imageData = context.createImageData(width, height);
  2076. imageData.data.set(data);
  2077. context.putImageData(imageData, 0, 0);
  2078. var base64Image = screenshotCanvas.toDataURL();
  2079. if (("download" in document.createElement("a"))) {
  2080. var a = window.document.createElement("a");
  2081. a.href = base64Image;
  2082. var date = new Date();
  2083. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2084. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2085. window.document.body.appendChild(a);
  2086. a.addEventListener("click", function () {
  2087. a.parentElement.removeChild(a);
  2088. });
  2089. a.click();
  2090. } else {
  2091. var newWindow = window.open("");
  2092. var img = newWindow.document.createElement("img");
  2093. img.src = base64Image;
  2094. newWindow.document.body.appendChild(img);
  2095. }
  2096. };
  2097. texture.render(true);
  2098. texture.dispose();
  2099. if (previousCamera) {
  2100. scene.activeCamera = previousCamera;
  2101. }
  2102. };
  2103. Tools.ValidateXHRData = function (xhr, dataType) {
  2104. if (typeof dataType === "undefined") { dataType = 7; }
  2105. try {
  2106. if (dataType & 1) {
  2107. if (xhr.responseText && xhr.responseText.length > 0) {
  2108. return true;
  2109. } else if (dataType === 1) {
  2110. return false;
  2111. }
  2112. }
  2113. if (dataType & 2) {
  2114. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2115. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2116. return true;
  2117. } else if (dataType === 2) {
  2118. return false;
  2119. }
  2120. }
  2121. if (dataType & 4) {
  2122. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2123. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2124. return true;
  2125. } else {
  2126. return false;
  2127. }
  2128. }
  2129. } catch (e) {
  2130. }
  2131. return false;
  2132. };
  2133. Object.defineProperty(Tools, "NoneLogLevel", {
  2134. get: function () {
  2135. return Tools._NoneLogLevel;
  2136. },
  2137. enumerable: true,
  2138. configurable: true
  2139. });
  2140. Object.defineProperty(Tools, "MessageLogLevel", {
  2141. get: function () {
  2142. return Tools._MessageLogLevel;
  2143. },
  2144. enumerable: true,
  2145. configurable: true
  2146. });
  2147. Object.defineProperty(Tools, "WarningLogLevel", {
  2148. get: function () {
  2149. return Tools._WarningLogLevel;
  2150. },
  2151. enumerable: true,
  2152. configurable: true
  2153. });
  2154. Object.defineProperty(Tools, "ErrorLogLevel", {
  2155. get: function () {
  2156. return Tools._ErrorLogLevel;
  2157. },
  2158. enumerable: true,
  2159. configurable: true
  2160. });
  2161. Object.defineProperty(Tools, "AllLogLevel", {
  2162. get: function () {
  2163. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2164. },
  2165. enumerable: true,
  2166. configurable: true
  2167. });
  2168. Tools._FormatMessage = function (message) {
  2169. var padStr = function (i) {
  2170. return (i < 10) ? "0" + i : "" + i;
  2171. };
  2172. var date = new Date();
  2173. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2174. };
  2175. Tools._LogDisabled = function (message) {
  2176. };
  2177. Tools._LogEnabled = function (message) {
  2178. console.log(Tools._FormatMessage(message));
  2179. };
  2180. Tools._WarnDisabled = function (message) {
  2181. };
  2182. Tools._WarnEnabled = function (message) {
  2183. console.warn(Tools._FormatMessage(message));
  2184. };
  2185. Tools._ErrorDisabled = function (message) {
  2186. };
  2187. Tools._ErrorEnabled = function (message) {
  2188. console.error(Tools._FormatMessage(message));
  2189. };
  2190. Object.defineProperty(Tools, "LogLevels", {
  2191. set: function (level) {
  2192. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2193. Tools.Log = Tools._LogEnabled;
  2194. } else {
  2195. Tools.Log = Tools._LogDisabled;
  2196. }
  2197. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2198. Tools.Warn = Tools._WarnEnabled;
  2199. } else {
  2200. Tools.Warn = Tools._WarnDisabled;
  2201. }
  2202. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2203. Tools.Error = Tools._ErrorEnabled;
  2204. } else {
  2205. Tools.Error = Tools._ErrorDisabled;
  2206. }
  2207. },
  2208. enumerable: true,
  2209. configurable: true
  2210. });
  2211. Tools.BaseUrl = "";
  2212. Tools._NoneLogLevel = 0;
  2213. Tools._MessageLogLevel = 1;
  2214. Tools._WarningLogLevel = 2;
  2215. Tools._ErrorLogLevel = 4;
  2216. Tools.Log = Tools._LogEnabled;
  2217. Tools.Warn = Tools._WarnEnabled;
  2218. Tools.Error = Tools._ErrorEnabled;
  2219. return Tools;
  2220. })();
  2221. BABYLON.Tools = Tools;
  2222. })(BABYLON || (BABYLON = {}));
  2223. var BABYLON;
  2224. (function (BABYLON) {
  2225. var _DepthCullingState = (function () {
  2226. function _DepthCullingState() {
  2227. this._isDepthTestDirty = false;
  2228. this._isDepthMaskDirty = false;
  2229. this._isDepthFuncDirty = false;
  2230. this._isCullFaceDirty = false;
  2231. this._isCullDirty = false;
  2232. }
  2233. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2234. get: function () {
  2235. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2236. },
  2237. enumerable: true,
  2238. configurable: true
  2239. });
  2240. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2241. get: function () {
  2242. return this._cullFace;
  2243. },
  2244. set: function (value) {
  2245. if (this._cullFace === value) {
  2246. return;
  2247. }
  2248. this._cullFace = value;
  2249. this._isCullFaceDirty = true;
  2250. },
  2251. enumerable: true,
  2252. configurable: true
  2253. });
  2254. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2255. get: function () {
  2256. return this._cull;
  2257. },
  2258. set: function (value) {
  2259. if (this._cull === value) {
  2260. return;
  2261. }
  2262. this._cull = value;
  2263. this._isCullDirty = true;
  2264. },
  2265. enumerable: true,
  2266. configurable: true
  2267. });
  2268. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2269. get: function () {
  2270. return this._depthFunc;
  2271. },
  2272. set: function (value) {
  2273. if (this._depthFunc === value) {
  2274. return;
  2275. }
  2276. this._depthFunc = value;
  2277. this._isDepthFuncDirty = true;
  2278. },
  2279. enumerable: true,
  2280. configurable: true
  2281. });
  2282. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2283. get: function () {
  2284. return this._depthMask;
  2285. },
  2286. set: function (value) {
  2287. if (this._depthMask === value) {
  2288. return;
  2289. }
  2290. this._depthMask = value;
  2291. this._isDepthMaskDirty = true;
  2292. },
  2293. enumerable: true,
  2294. configurable: true
  2295. });
  2296. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2297. get: function () {
  2298. return this._depthTest;
  2299. },
  2300. set: function (value) {
  2301. if (this._depthTest === value) {
  2302. return;
  2303. }
  2304. this._depthTest = value;
  2305. this._isDepthTestDirty = true;
  2306. },
  2307. enumerable: true,
  2308. configurable: true
  2309. });
  2310. _DepthCullingState.prototype.reset = function () {
  2311. this._depthMask = true;
  2312. this._depthTest = true;
  2313. this._depthFunc = null;
  2314. this._cull = null;
  2315. this._cullFace = null;
  2316. this._isDepthTestDirty = true;
  2317. this._isDepthMaskDirty = true;
  2318. this._isDepthFuncDirty = false;
  2319. this._isCullFaceDirty = false;
  2320. this._isCullDirty = false;
  2321. };
  2322. _DepthCullingState.prototype.apply = function (gl) {
  2323. if (!this.isDirty) {
  2324. return;
  2325. }
  2326. if (this._isCullDirty) {
  2327. if (this.cull === true) {
  2328. gl.enable(gl.CULL_FACE);
  2329. } else if (this.cull === false) {
  2330. gl.disable(gl.CULL_FACE);
  2331. }
  2332. this._isCullDirty = false;
  2333. }
  2334. if (this._isCullFaceDirty) {
  2335. gl.cullFace(this.cullFace);
  2336. this._isCullFaceDirty = false;
  2337. }
  2338. if (this._isDepthMaskDirty) {
  2339. gl.depthMask(this.depthMask);
  2340. this._isDepthMaskDirty = false;
  2341. }
  2342. if (this._isDepthTestDirty) {
  2343. if (this.depthTest === true) {
  2344. gl.enable(gl.DEPTH_TEST);
  2345. } else if (this.depthTest === false) {
  2346. gl.disable(gl.DEPTH_TEST);
  2347. }
  2348. this._isDepthTestDirty = false;
  2349. }
  2350. if (this._isDepthFuncDirty) {
  2351. gl.depthFunc(this.depthFunc);
  2352. this._isDepthFuncDirty = false;
  2353. }
  2354. };
  2355. return _DepthCullingState;
  2356. })();
  2357. BABYLON._DepthCullingState = _DepthCullingState;
  2358. var _AlphaState = (function () {
  2359. function _AlphaState() {
  2360. this._isAlphaBlendDirty = false;
  2361. this._isBlendFunctionParametersDirty = false;
  2362. this._alphaBlend = false;
  2363. this._blendFunctionParameters = new Array(4);
  2364. }
  2365. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2366. get: function () {
  2367. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2368. },
  2369. enumerable: true,
  2370. configurable: true
  2371. });
  2372. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2373. get: function () {
  2374. return this._alphaBlend;
  2375. },
  2376. set: function (value) {
  2377. if (this._alphaBlend === value) {
  2378. return;
  2379. }
  2380. this._alphaBlend = value;
  2381. this._isAlphaBlendDirty = true;
  2382. },
  2383. enumerable: true,
  2384. configurable: true
  2385. });
  2386. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2387. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2388. return;
  2389. }
  2390. this._blendFunctionParameters[0] = value0;
  2391. this._blendFunctionParameters[1] = value1;
  2392. this._blendFunctionParameters[2] = value2;
  2393. this._blendFunctionParameters[3] = value3;
  2394. this._isBlendFunctionParametersDirty = true;
  2395. };
  2396. _AlphaState.prototype.reset = function () {
  2397. this._alphaBlend = false;
  2398. this._blendFunctionParameters[0] = null;
  2399. this._blendFunctionParameters[1] = null;
  2400. this._blendFunctionParameters[2] = null;
  2401. this._blendFunctionParameters[3] = null;
  2402. this._isAlphaBlendDirty = true;
  2403. this._isBlendFunctionParametersDirty = false;
  2404. };
  2405. _AlphaState.prototype.apply = function (gl) {
  2406. if (!this.isDirty) {
  2407. return;
  2408. }
  2409. if (this._isAlphaBlendDirty) {
  2410. if (this._alphaBlend === true) {
  2411. gl.enable(gl.BLEND);
  2412. } else if (this._alphaBlend === false) {
  2413. gl.disable(gl.BLEND);
  2414. }
  2415. this._isAlphaBlendDirty = false;
  2416. }
  2417. if (this._isBlendFunctionParametersDirty) {
  2418. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2419. this._isBlendFunctionParametersDirty = false;
  2420. }
  2421. };
  2422. return _AlphaState;
  2423. })();
  2424. BABYLON._AlphaState = _AlphaState;
  2425. var compileShader = function (gl, source, type, defines) {
  2426. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2427. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2428. gl.compileShader(shader);
  2429. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2430. throw new Error(gl.getShaderInfoLog(shader));
  2431. }
  2432. return shader;
  2433. };
  2434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2435. var magFilter = gl.NEAREST;
  2436. var minFilter = gl.NEAREST;
  2437. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2438. magFilter = gl.LINEAR;
  2439. if (generateMipMaps) {
  2440. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2441. } else {
  2442. minFilter = gl.LINEAR;
  2443. }
  2444. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2445. magFilter = gl.LINEAR;
  2446. if (generateMipMaps) {
  2447. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2448. } else {
  2449. minFilter = gl.LINEAR;
  2450. }
  2451. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2452. magFilter = gl.NEAREST;
  2453. if (generateMipMaps) {
  2454. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2455. } else {
  2456. minFilter = gl.NEAREST;
  2457. }
  2458. }
  2459. return {
  2460. min: minFilter,
  2461. mag: magFilter
  2462. };
  2463. };
  2464. var getExponantOfTwo = function (value, max) {
  2465. var count = 1;
  2466. do {
  2467. count *= 2;
  2468. } while(count < value);
  2469. if (count > max)
  2470. count = max;
  2471. return count;
  2472. };
  2473. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2474. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2475. var engine = scene.getEngine();
  2476. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2477. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2478. gl.bindTexture(gl.TEXTURE_2D, texture);
  2479. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2480. processFunction(potWidth, potHeight);
  2481. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2484. if (!noMipmap && !isCompressed) {
  2485. gl.generateMipmap(gl.TEXTURE_2D);
  2486. }
  2487. gl.bindTexture(gl.TEXTURE_2D, null);
  2488. engine._activeTexturesCache = [];
  2489. texture._baseWidth = width;
  2490. texture._baseHeight = height;
  2491. texture._width = potWidth;
  2492. texture._height = potHeight;
  2493. texture.isReady = true;
  2494. scene._removePendingData(texture);
  2495. };
  2496. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2497. var img;
  2498. var onload = function () {
  2499. loadedImages.push(img);
  2500. scene._removePendingData(img);
  2501. if (index != extensions.length - 1) {
  2502. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2503. } else {
  2504. onfinish(loadedImages);
  2505. }
  2506. };
  2507. var onerror = function () {
  2508. scene._removePendingData(img);
  2509. };
  2510. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2511. scene._addPendingData(img);
  2512. };
  2513. var EngineCapabilities = (function () {
  2514. function EngineCapabilities() {
  2515. }
  2516. return EngineCapabilities;
  2517. })();
  2518. BABYLON.EngineCapabilities = EngineCapabilities;
  2519. var Engine = (function () {
  2520. function Engine(canvas, antialias, options) {
  2521. var _this = this;
  2522. this.isFullscreen = false;
  2523. this.isPointerLock = false;
  2524. this.forceWireframe = false;
  2525. this.cullBackFaces = true;
  2526. this.renderEvenInBackground = true;
  2527. this.scenes = new Array();
  2528. this._windowIsBackground = false;
  2529. this._runningLoop = false;
  2530. this._loadingDivBackgroundColor = "black";
  2531. this._depthCullingState = new _DepthCullingState();
  2532. this._alphaState = new _AlphaState();
  2533. this._loadedTexturesCache = new Array();
  2534. this._activeTexturesCache = new Array();
  2535. this._compiledEffects = {};
  2536. this._renderingCanvas = canvas;
  2537. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2538. options = options || {};
  2539. options.antialias = antialias;
  2540. try {
  2541. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2542. } catch (e) {
  2543. throw new Error("WebGL not supported");
  2544. }
  2545. if (!this._gl) {
  2546. throw new Error("WebGL not supported");
  2547. }
  2548. this._onBlur = function () {
  2549. _this._windowIsBackground = true;
  2550. };
  2551. this._onFocus = function () {
  2552. _this._windowIsBackground = false;
  2553. };
  2554. window.addEventListener("blur", this._onBlur);
  2555. window.addEventListener("focus", this._onFocus);
  2556. this._workingCanvas = document.createElement("canvas");
  2557. this._workingContext = this._workingCanvas.getContext("2d");
  2558. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2559. this.resize();
  2560. this._caps = new EngineCapabilities();
  2561. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2562. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2563. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2564. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2565. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2566. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2567. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2568. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  2569. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2570. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2571. this.setDepthBuffer(true);
  2572. this.setDepthFunctionToLessOrEqual();
  2573. this.setDepthWrite(true);
  2574. this._onFullscreenChange = function () {
  2575. if (document.fullscreen !== undefined) {
  2576. _this.isFullscreen = document.fullscreen;
  2577. } else if (document.mozFullScreen !== undefined) {
  2578. _this.isFullscreen = document.mozFullScreen;
  2579. } else if (document.webkitIsFullScreen !== undefined) {
  2580. _this.isFullscreen = document.webkitIsFullScreen;
  2581. } else if (document.msIsFullScreen !== undefined) {
  2582. _this.isFullscreen = document.msIsFullScreen;
  2583. }
  2584. if (_this.isFullscreen && _this._pointerLockRequested) {
  2585. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2586. if (canvas.requestPointerLock) {
  2587. canvas.requestPointerLock();
  2588. }
  2589. }
  2590. };
  2591. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2592. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2593. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2594. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2595. this._onPointerLockChange = function () {
  2596. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2597. };
  2598. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2599. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2600. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2601. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2602. }
  2603. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2604. get: function () {
  2605. return Engine._ALPHA_DISABLE;
  2606. },
  2607. enumerable: true,
  2608. configurable: true
  2609. });
  2610. Object.defineProperty(Engine, "ALPHA_ADD", {
  2611. get: function () {
  2612. return Engine._ALPHA_ADD;
  2613. },
  2614. enumerable: true,
  2615. configurable: true
  2616. });
  2617. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2618. get: function () {
  2619. return Engine._ALPHA_COMBINE;
  2620. },
  2621. enumerable: true,
  2622. configurable: true
  2623. });
  2624. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2625. get: function () {
  2626. return Engine._DELAYLOADSTATE_NONE;
  2627. },
  2628. enumerable: true,
  2629. configurable: true
  2630. });
  2631. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2632. get: function () {
  2633. return Engine._DELAYLOADSTATE_LOADED;
  2634. },
  2635. enumerable: true,
  2636. configurable: true
  2637. });
  2638. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2639. get: function () {
  2640. return Engine._DELAYLOADSTATE_LOADING;
  2641. },
  2642. enumerable: true,
  2643. configurable: true
  2644. });
  2645. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2646. get: function () {
  2647. return Engine._DELAYLOADSTATE_NOTLOADED;
  2648. },
  2649. enumerable: true,
  2650. configurable: true
  2651. });
  2652. Object.defineProperty(Engine, "Version", {
  2653. get: function () {
  2654. return "1.14.0";
  2655. },
  2656. enumerable: true,
  2657. configurable: true
  2658. });
  2659. Engine.prototype.getAspectRatio = function (camera) {
  2660. var viewport = camera.viewport;
  2661. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2662. };
  2663. Engine.prototype.getRenderWidth = function () {
  2664. if (this._currentRenderTarget) {
  2665. return this._currentRenderTarget._width;
  2666. }
  2667. return this._renderingCanvas.width;
  2668. };
  2669. Engine.prototype.getRenderHeight = function () {
  2670. if (this._currentRenderTarget) {
  2671. return this._currentRenderTarget._height;
  2672. }
  2673. return this._renderingCanvas.height;
  2674. };
  2675. Engine.prototype.getRenderingCanvas = function () {
  2676. return this._renderingCanvas;
  2677. };
  2678. Engine.prototype.getRenderingCanvasClientRect = function () {
  2679. return this._renderingCanvas.getBoundingClientRect();
  2680. };
  2681. Engine.prototype.setHardwareScalingLevel = function (level) {
  2682. this._hardwareScalingLevel = level;
  2683. this.resize();
  2684. };
  2685. Engine.prototype.getHardwareScalingLevel = function () {
  2686. return this._hardwareScalingLevel;
  2687. };
  2688. Engine.prototype.getLoadedTexturesCache = function () {
  2689. return this._loadedTexturesCache;
  2690. };
  2691. Engine.prototype.getCaps = function () {
  2692. return this._caps;
  2693. };
  2694. Engine.prototype.setDepthFunctionToGreater = function () {
  2695. this._depthCullingState.depthFunc = this._gl.GREATER;
  2696. };
  2697. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2698. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2699. };
  2700. Engine.prototype.setDepthFunctionToLess = function () {
  2701. this._depthCullingState.depthFunc = this._gl.LESS;
  2702. };
  2703. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2704. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2705. };
  2706. Engine.prototype.stopRenderLoop = function () {
  2707. this._renderFunction = null;
  2708. this._runningLoop = false;
  2709. };
  2710. Engine.prototype._renderLoop = function () {
  2711. var _this = this;
  2712. var shouldRender = true;
  2713. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2714. shouldRender = false;
  2715. }
  2716. if (shouldRender) {
  2717. this.beginFrame();
  2718. if (this._renderFunction) {
  2719. this._renderFunction();
  2720. }
  2721. this.endFrame();
  2722. }
  2723. if (this._runningLoop) {
  2724. BABYLON.Tools.QueueNewFrame(function () {
  2725. _this._renderLoop();
  2726. });
  2727. }
  2728. };
  2729. Engine.prototype.runRenderLoop = function (renderFunction) {
  2730. var _this = this;
  2731. this._runningLoop = true;
  2732. this._renderFunction = renderFunction;
  2733. BABYLON.Tools.QueueNewFrame(function () {
  2734. _this._renderLoop();
  2735. });
  2736. };
  2737. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2738. if (this.isFullscreen) {
  2739. BABYLON.Tools.ExitFullscreen();
  2740. } else {
  2741. this._pointerLockRequested = requestPointerLock;
  2742. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2743. }
  2744. };
  2745. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2746. this.applyStates();
  2747. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2748. if (this._depthCullingState.depthMask) {
  2749. this._gl.clearDepth(1.0);
  2750. }
  2751. var mode = 0;
  2752. if (backBuffer)
  2753. mode |= this._gl.COLOR_BUFFER_BIT;
  2754. if (depthStencil && this._depthCullingState.depthMask)
  2755. mode |= this._gl.DEPTH_BUFFER_BIT;
  2756. this._gl.clear(mode);
  2757. };
  2758. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2759. var width = requiredWidth || this._renderingCanvas.width;
  2760. var height = requiredHeight || this._renderingCanvas.height;
  2761. var x = viewport.x || 0;
  2762. var y = viewport.y || 0;
  2763. this._cachedViewport = viewport;
  2764. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2765. };
  2766. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2767. this._cachedViewport = null;
  2768. this._gl.viewport(x, y, width, height);
  2769. };
  2770. Engine.prototype.beginFrame = function () {
  2771. BABYLON.Tools._MeasureFps();
  2772. };
  2773. Engine.prototype.endFrame = function () {
  2774. this.flushFramebuffer();
  2775. };
  2776. Engine.prototype.resize = function () {
  2777. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2778. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2779. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2780. };
  2781. Engine.prototype.bindFramebuffer = function (texture) {
  2782. this._currentRenderTarget = texture;
  2783. var gl = this._gl;
  2784. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2785. this._gl.viewport(0, 0, texture._width, texture._height);
  2786. this.wipeCaches();
  2787. };
  2788. Engine.prototype.unBindFramebuffer = function (texture) {
  2789. this._currentRenderTarget = null;
  2790. if (texture.generateMipMaps) {
  2791. var gl = this._gl;
  2792. gl.bindTexture(gl.TEXTURE_2D, texture);
  2793. gl.generateMipmap(gl.TEXTURE_2D);
  2794. gl.bindTexture(gl.TEXTURE_2D, null);
  2795. }
  2796. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2797. };
  2798. Engine.prototype.flushFramebuffer = function () {
  2799. this._gl.flush();
  2800. };
  2801. Engine.prototype.restoreDefaultFramebuffer = function () {
  2802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2803. this.setViewport(this._cachedViewport);
  2804. this.wipeCaches();
  2805. };
  2806. Engine.prototype._resetVertexBufferBinding = function () {
  2807. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2808. this._cachedVertexBuffers = null;
  2809. };
  2810. Engine.prototype.createVertexBuffer = function (vertices) {
  2811. var vbo = this._gl.createBuffer();
  2812. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2813. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2814. this._resetVertexBufferBinding();
  2815. vbo.references = 1;
  2816. return vbo;
  2817. };
  2818. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2819. var vbo = this._gl.createBuffer();
  2820. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2821. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2822. this._resetVertexBufferBinding();
  2823. vbo.references = 1;
  2824. return vbo;
  2825. };
  2826. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2827. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2828. if (vertices instanceof Float32Array) {
  2829. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2830. } else {
  2831. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2832. }
  2833. this._resetVertexBufferBinding();
  2834. };
  2835. Engine.prototype._resetIndexBufferBinding = function () {
  2836. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2837. this._cachedIndexBuffer = null;
  2838. };
  2839. Engine.prototype.createIndexBuffer = function (indices) {
  2840. var vbo = this._gl.createBuffer();
  2841. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2842. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2843. this._resetIndexBufferBinding();
  2844. vbo.references = 1;
  2845. return vbo;
  2846. };
  2847. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2848. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2849. this._cachedVertexBuffers = vertexBuffer;
  2850. this._cachedEffectForVertexBuffers = effect;
  2851. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2852. var offset = 0;
  2853. for (var index = 0; index < vertexDeclaration.length; index++) {
  2854. var order = effect.getAttributeLocation(index);
  2855. if (order >= 0) {
  2856. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2857. }
  2858. offset += vertexDeclaration[index] * 4;
  2859. }
  2860. }
  2861. if (this._cachedIndexBuffer !== indexBuffer) {
  2862. this._cachedIndexBuffer = indexBuffer;
  2863. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2864. }
  2865. };
  2866. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2867. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2868. this._cachedVertexBuffers = vertexBuffers;
  2869. this._cachedEffectForVertexBuffers = effect;
  2870. var attributes = effect.getAttributesNames();
  2871. for (var index = 0; index < attributes.length; index++) {
  2872. var order = effect.getAttributeLocation(index);
  2873. if (order >= 0) {
  2874. var vertexBuffer = vertexBuffers[attributes[index]];
  2875. if (!vertexBuffer) {
  2876. continue;
  2877. }
  2878. var stride = vertexBuffer.getStrideSize();
  2879. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2880. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2881. }
  2882. }
  2883. }
  2884. if (this._cachedIndexBuffer !== indexBuffer) {
  2885. this._cachedIndexBuffer = indexBuffer;
  2886. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2887. }
  2888. };
  2889. Engine.prototype._releaseBuffer = function (buffer) {
  2890. buffer.references--;
  2891. if (buffer.references === 0) {
  2892. this._gl.deleteBuffer(buffer);
  2893. return true;
  2894. }
  2895. return false;
  2896. };
  2897. Engine.prototype.createInstancesBuffer = function (capacity) {
  2898. var buffer = this._gl.createBuffer();
  2899. buffer.capacity = capacity;
  2900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2901. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2902. return buffer;
  2903. };
  2904. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2905. this._gl.deleteBuffer(buffer);
  2906. };
  2907. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2909. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2910. for (var index = 0; index < 4; index++) {
  2911. var offsetLocation = offsetLocations[index];
  2912. this._gl.enableVertexAttribArray(offsetLocation);
  2913. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2914. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2915. }
  2916. };
  2917. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2919. for (var index = 0; index < 4; index++) {
  2920. var offsetLocation = offsetLocations[index];
  2921. this._gl.disableVertexAttribArray(offsetLocation);
  2922. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2923. }
  2924. };
  2925. Engine.prototype.applyStates = function () {
  2926. this._depthCullingState.apply(this._gl);
  2927. this._alphaState.apply(this._gl);
  2928. };
  2929. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2930. this.applyStates();
  2931. if (instancesCount) {
  2932. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2933. return;
  2934. }
  2935. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2936. };
  2937. Engine.prototype._releaseEffect = function (effect) {
  2938. if (this._compiledEffects[effect._key]) {
  2939. delete this._compiledEffects[effect._key];
  2940. if (effect.getProgram()) {
  2941. this._gl.deleteProgram(effect.getProgram());
  2942. }
  2943. }
  2944. };
  2945. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2946. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2947. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2948. var name = vertex + "+" + fragment + "@" + defines;
  2949. if (this._compiledEffects[name]) {
  2950. return this._compiledEffects[name];
  2951. }
  2952. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2953. effect._key = name;
  2954. this._compiledEffects[name] = effect;
  2955. return effect;
  2956. };
  2957. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2958. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2959. if (typeof samplers === "undefined") { samplers = []; }
  2960. if (typeof defines === "undefined") { defines = ""; }
  2961. return this.createEffect({
  2962. vertex: "particles",
  2963. fragmentElement: fragmentName
  2964. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2965. };
  2966. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2967. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2968. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2969. var shaderProgram = this._gl.createProgram();
  2970. this._gl.attachShader(shaderProgram, vertexShader);
  2971. this._gl.attachShader(shaderProgram, fragmentShader);
  2972. this._gl.linkProgram(shaderProgram);
  2973. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2974. if (!linked) {
  2975. var error = this._gl.getProgramInfoLog(shaderProgram);
  2976. if (error) {
  2977. throw new Error(error);
  2978. }
  2979. }
  2980. this._gl.deleteShader(vertexShader);
  2981. this._gl.deleteShader(fragmentShader);
  2982. return shaderProgram;
  2983. };
  2984. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2985. var results = [];
  2986. for (var index = 0; index < uniformsNames.length; index++) {
  2987. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2988. }
  2989. return results;
  2990. };
  2991. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2992. var results = [];
  2993. for (var index = 0; index < attributesNames.length; index++) {
  2994. try {
  2995. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2996. } catch (e) {
  2997. results.push(-1);
  2998. }
  2999. }
  3000. return results;
  3001. };
  3002. Engine.prototype.enableEffect = function (effect) {
  3003. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3004. return;
  3005. }
  3006. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3007. this._gl.useProgram(effect.getProgram());
  3008. for (var i in this._vertexAttribArrays) {
  3009. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3010. continue;
  3011. }
  3012. this._vertexAttribArrays[i] = false;
  3013. this._gl.disableVertexAttribArray(i);
  3014. }
  3015. var attributesCount = effect.getAttributesCount();
  3016. for (var index = 0; index < attributesCount; index++) {
  3017. var order = effect.getAttributeLocation(index);
  3018. if (order >= 0) {
  3019. this._vertexAttribArrays[order] = true;
  3020. this._gl.enableVertexAttribArray(order);
  3021. }
  3022. }
  3023. this._currentEffect = effect;
  3024. };
  3025. Engine.prototype.setArray = function (uniform, array) {
  3026. if (!uniform)
  3027. return;
  3028. this._gl.uniform1fv(uniform, array);
  3029. };
  3030. Engine.prototype.setMatrices = function (uniform, matrices) {
  3031. if (!uniform)
  3032. return;
  3033. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3034. };
  3035. Engine.prototype.setMatrix = function (uniform, matrix) {
  3036. if (!uniform)
  3037. return;
  3038. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3039. };
  3040. Engine.prototype.setFloat = function (uniform, value) {
  3041. if (!uniform)
  3042. return;
  3043. this._gl.uniform1f(uniform, value);
  3044. };
  3045. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3046. if (!uniform)
  3047. return;
  3048. this._gl.uniform2f(uniform, x, y);
  3049. };
  3050. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3051. if (!uniform)
  3052. return;
  3053. this._gl.uniform3f(uniform, x, y, z);
  3054. };
  3055. Engine.prototype.setBool = function (uniform, bool) {
  3056. if (!uniform)
  3057. return;
  3058. this._gl.uniform1i(uniform, bool);
  3059. };
  3060. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3061. if (!uniform)
  3062. return;
  3063. this._gl.uniform4f(uniform, x, y, z, w);
  3064. };
  3065. Engine.prototype.setColor3 = function (uniform, color3) {
  3066. if (!uniform)
  3067. return;
  3068. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3069. };
  3070. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3071. if (!uniform)
  3072. return;
  3073. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3074. };
  3075. Engine.prototype.setState = function (culling, force) {
  3076. if (this._depthCullingState.cull !== culling || force) {
  3077. if (culling) {
  3078. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3079. this._depthCullingState.cull = true;
  3080. } else {
  3081. this._depthCullingState.cull = false;
  3082. }
  3083. }
  3084. };
  3085. Engine.prototype.setDepthBuffer = function (enable) {
  3086. this._depthCullingState.depthTest = enable;
  3087. };
  3088. Engine.prototype.getDepthWrite = function () {
  3089. return this._depthCullingState.depthMask;
  3090. };
  3091. Engine.prototype.setDepthWrite = function (enable) {
  3092. this._depthCullingState.depthMask = enable;
  3093. };
  3094. Engine.prototype.setColorWrite = function (enable) {
  3095. this._gl.colorMask(enable, enable, enable, enable);
  3096. };
  3097. Engine.prototype.setAlphaMode = function (mode) {
  3098. switch (mode) {
  3099. case BABYLON.Engine.ALPHA_DISABLE:
  3100. this.setDepthWrite(true);
  3101. this._alphaState.alphaBlend = false;
  3102. break;
  3103. case BABYLON.Engine.ALPHA_COMBINE:
  3104. this.setDepthWrite(false);
  3105. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3106. this._alphaState.alphaBlend = true;
  3107. break;
  3108. case BABYLON.Engine.ALPHA_ADD:
  3109. this.setDepthWrite(false);
  3110. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3111. this._alphaState.alphaBlend = true;
  3112. break;
  3113. }
  3114. };
  3115. Engine.prototype.setAlphaTesting = function (enable) {
  3116. this._alphaTest = enable;
  3117. };
  3118. Engine.prototype.getAlphaTesting = function () {
  3119. return this._alphaTest;
  3120. };
  3121. Engine.prototype.wipeCaches = function () {
  3122. this._activeTexturesCache = [];
  3123. this._currentEffect = null;
  3124. this._depthCullingState.reset();
  3125. this._alphaState.reset();
  3126. this._cachedVertexBuffers = null;
  3127. this._cachedIndexBuffer = null;
  3128. this._cachedEffectForVertexBuffers = null;
  3129. };
  3130. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3131. var gl = this._gl;
  3132. gl.bindTexture(gl.TEXTURE_2D, texture);
  3133. var magFilter = gl.NEAREST;
  3134. var minFilter = gl.NEAREST;
  3135. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3136. magFilter = gl.LINEAR;
  3137. minFilter = gl.LINEAR;
  3138. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3139. magFilter = gl.LINEAR;
  3140. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3141. }
  3142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3144. gl.bindTexture(gl.TEXTURE_2D, null);
  3145. };
  3146. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3147. var _this = this;
  3148. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3149. var texture = this._gl.createTexture();
  3150. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3151. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3152. var isTGA = (extension === ".tga");
  3153. scene._addPendingData(texture);
  3154. texture.url = url;
  3155. texture.noMipmap = noMipmap;
  3156. texture.references = 1;
  3157. this._loadedTexturesCache.push(texture);
  3158. if (isTGA) {
  3159. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3160. var data = new Uint8Array(arrayBuffer);
  3161. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3162. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3163. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3164. }, samplingMode);
  3165. }, null, scene.database, true);
  3166. } else if (isDDS) {
  3167. BABYLON.Tools.LoadFile(url, function (data) {
  3168. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3169. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3170. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3171. console.log("loading " + url);
  3172. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3173. }, samplingMode);
  3174. }, null, scene.database, true);
  3175. } else {
  3176. var onload = function (img) {
  3177. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3178. var isPot = (img.width == potWidth && img.height == potHeight);
  3179. if (!isPot) {
  3180. _this._workingCanvas.width = potWidth;
  3181. _this._workingCanvas.height = potHeight;
  3182. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3183. }
  3184. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3185. }, samplingMode);
  3186. };
  3187. var onerror = function () {
  3188. scene._removePendingData(texture);
  3189. };
  3190. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3191. }
  3192. return texture;
  3193. };
  3194. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3195. var texture = this._gl.createTexture();
  3196. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3197. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3198. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3199. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3201. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3202. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3203. this._activeTexturesCache = [];
  3204. texture._baseWidth = width;
  3205. texture._baseHeight = height;
  3206. texture._width = width;
  3207. texture._height = height;
  3208. texture.isReady = false;
  3209. texture.generateMipMaps = generateMipMaps;
  3210. texture.references = 1;
  3211. this._loadedTexturesCache.push(texture);
  3212. return texture;
  3213. };
  3214. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3215. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3216. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3217. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3218. if (texture.generateMipMaps) {
  3219. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3220. }
  3221. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3222. this._activeTexturesCache = [];
  3223. texture.isReady = true;
  3224. };
  3225. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3226. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3227. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3228. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3229. if (!texture._workingCanvas) {
  3230. texture._workingCanvas = document.createElement("canvas");
  3231. texture._workingContext = texture._workingCanvas.getContext("2d");
  3232. texture._workingCanvas.width = texture._width;
  3233. texture._workingCanvas.height = texture._height;
  3234. }
  3235. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3236. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3237. } else {
  3238. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3239. }
  3240. if (texture.generateMipMaps) {
  3241. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3242. }
  3243. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3244. this._activeTexturesCache = [];
  3245. texture.isReady = true;
  3246. };
  3247. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3248. var generateMipMaps = false;
  3249. var generateDepthBuffer = true;
  3250. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3251. if (options !== undefined) {
  3252. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3253. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3254. if (options.samplingMode !== undefined) {
  3255. samplingMode = options.samplingMode;
  3256. }
  3257. }
  3258. var gl = this._gl;
  3259. var texture = gl.createTexture();
  3260. gl.bindTexture(gl.TEXTURE_2D, texture);
  3261. var width = size.width || size;
  3262. var height = size.height || size;
  3263. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3264. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3268. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3269. var depthBuffer;
  3270. if (generateDepthBuffer) {
  3271. depthBuffer = gl.createRenderbuffer();
  3272. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3273. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3274. }
  3275. var framebuffer = gl.createFramebuffer();
  3276. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3277. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3278. if (generateDepthBuffer) {
  3279. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3280. }
  3281. gl.bindTexture(gl.TEXTURE_2D, null);
  3282. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3283. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3284. texture._framebuffer = framebuffer;
  3285. if (generateDepthBuffer) {
  3286. texture._depthBuffer = depthBuffer;
  3287. }
  3288. texture._width = width;
  3289. texture._height = height;
  3290. texture.isReady = true;
  3291. texture.generateMipMaps = generateMipMaps;
  3292. texture.references = 1;
  3293. this._activeTexturesCache = [];
  3294. this._loadedTexturesCache.push(texture);
  3295. return texture;
  3296. };
  3297. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3298. var _this = this;
  3299. var gl = this._gl;
  3300. var texture = gl.createTexture();
  3301. texture.isCube = true;
  3302. texture.url = rootUrl;
  3303. texture.references = 1;
  3304. this._loadedTexturesCache.push(texture);
  3305. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3306. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3307. if (isDDS) {
  3308. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3309. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3310. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3311. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3312. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3313. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3314. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3315. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3316. }
  3317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3320. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3321. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3322. _this._activeTexturesCache = [];
  3323. texture._width = info.width;
  3324. texture._height = info.height;
  3325. texture.isReady = true;
  3326. }, null, null, true);
  3327. } else {
  3328. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3329. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3330. var height = width;
  3331. _this._workingCanvas.width = width;
  3332. _this._workingCanvas.height = height;
  3333. var faces = [
  3334. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3335. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3336. ];
  3337. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3338. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3339. for (var index = 0; index < faces.length; index++) {
  3340. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3341. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3342. }
  3343. if (!noMipmap) {
  3344. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3345. }
  3346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3348. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3349. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3350. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3351. _this._activeTexturesCache = [];
  3352. texture._width = width;
  3353. texture._height = height;
  3354. texture.isReady = true;
  3355. }, extensions);
  3356. }
  3357. return texture;
  3358. };
  3359. Engine.prototype._releaseTexture = function (texture) {
  3360. var gl = this._gl;
  3361. if (texture._framebuffer) {
  3362. gl.deleteFramebuffer(texture._framebuffer);
  3363. }
  3364. if (texture._depthBuffer) {
  3365. gl.deleteRenderbuffer(texture._depthBuffer);
  3366. }
  3367. gl.deleteTexture(texture);
  3368. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3369. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3370. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3371. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3372. this._activeTexturesCache[channel] = null;
  3373. }
  3374. var index = this._loadedTexturesCache.indexOf(texture);
  3375. if (index !== -1) {
  3376. this._loadedTexturesCache.splice(index, 1);
  3377. }
  3378. };
  3379. Engine.prototype.bindSamplers = function (effect) {
  3380. this._gl.useProgram(effect.getProgram());
  3381. var samplers = effect.getSamplers();
  3382. for (var index = 0; index < samplers.length; index++) {
  3383. var uniform = effect.getUniform(samplers[index]);
  3384. this._gl.uniform1i(uniform, index);
  3385. }
  3386. this._currentEffect = null;
  3387. };
  3388. Engine.prototype._bindTexture = function (channel, texture) {
  3389. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3390. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3391. this._activeTexturesCache[channel] = null;
  3392. };
  3393. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3394. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3395. };
  3396. Engine.prototype.setTexture = function (channel, texture) {
  3397. if (channel < 0) {
  3398. return;
  3399. }
  3400. if (!texture || !texture.isReady()) {
  3401. if (this._activeTexturesCache[channel] != null) {
  3402. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3403. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3404. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3405. this._activeTexturesCache[channel] = null;
  3406. }
  3407. return;
  3408. }
  3409. if (texture instanceof BABYLON.VideoTexture) {
  3410. if (texture.update()) {
  3411. this._activeTexturesCache[channel] = null;
  3412. }
  3413. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3414. texture.delayLoad();
  3415. return;
  3416. }
  3417. if (this._activeTexturesCache[channel] == texture) {
  3418. return;
  3419. }
  3420. this._activeTexturesCache[channel] = texture;
  3421. var internalTexture = texture.getInternalTexture();
  3422. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3423. if (internalTexture.isCube) {
  3424. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3425. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3426. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3427. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3428. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3429. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3430. }
  3431. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3432. } else {
  3433. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3434. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3435. internalTexture._cachedWrapU = texture.wrapU;
  3436. switch (texture.wrapU) {
  3437. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3438. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3439. break;
  3440. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3441. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3442. break;
  3443. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3444. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3445. break;
  3446. }
  3447. }
  3448. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3449. internalTexture._cachedWrapV = texture.wrapV;
  3450. switch (texture.wrapV) {
  3451. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3452. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3453. break;
  3454. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3455. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3456. break;
  3457. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3458. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3459. break;
  3460. }
  3461. }
  3462. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3463. }
  3464. };
  3465. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3466. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3467. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3468. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3469. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3470. }
  3471. };
  3472. Engine.prototype.readPixels = function (x, y, width, height) {
  3473. var data = new Uint8Array(height * width * 4);
  3474. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3475. return data;
  3476. };
  3477. Engine.prototype.dispose = function () {
  3478. this.hideLoadingUI();
  3479. this.stopRenderLoop();
  3480. while (this.scenes.length) {
  3481. this.scenes[0].dispose();
  3482. }
  3483. for (var name in this._compiledEffects) {
  3484. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3485. }
  3486. for (var i in this._vertexAttribArrays) {
  3487. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3488. continue;
  3489. }
  3490. this._gl.disableVertexAttribArray(i);
  3491. }
  3492. window.removeEventListener("blur", this._onBlur);
  3493. window.removeEventListener("focus", this._onFocus);
  3494. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3495. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3496. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3497. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3498. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3499. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3500. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3501. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3502. };
  3503. Engine.prototype.displayLoadingUI = function () {
  3504. var _this = this;
  3505. this._loadingDiv = document.createElement("div");
  3506. this._loadingDiv.style.opacity = "0";
  3507. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3508. this._loadingTextDiv = document.createElement("div");
  3509. this._loadingTextDiv.style.position = "absolute";
  3510. this._loadingTextDiv.style.left = "0";
  3511. this._loadingTextDiv.style.top = "50%";
  3512. this._loadingTextDiv.style.marginTop = "80px";
  3513. this._loadingTextDiv.style.width = "100%";
  3514. this._loadingTextDiv.style.height = "20px";
  3515. this._loadingTextDiv.style.fontFamily = "Arial";
  3516. this._loadingTextDiv.style.fontSize = "14px";
  3517. this._loadingTextDiv.style.color = "white";
  3518. this._loadingTextDiv.style.textAlign = "center";
  3519. this._loadingTextDiv.innerHTML = "Loading";
  3520. this._loadingDiv.appendChild(this._loadingTextDiv);
  3521. var imgBack = new Image();
  3522. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  3523. imgBack.style.position = "absolute";
  3524. imgBack.style.left = "50%";
  3525. imgBack.style.top = "50%";
  3526. imgBack.style.marginLeft = "-50px";
  3527. imgBack.style.marginTop = "-50px";
  3528. imgBack.style.transition = "transform 1.0s ease";
  3529. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3530. var deg = 360;
  3531. var onTransitionEnd = function () {
  3532. deg += 360;
  3533. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3534. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3535. };
  3536. imgBack.addEventListener("transitionend", onTransitionEnd);
  3537. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3538. this._loadingDiv.appendChild(imgBack);
  3539. var imgFront = new Image();
  3540. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  3541. imgFront.style.position = "absolute";
  3542. imgFront.style.left = "50%";
  3543. imgFront.style.top = "50%";
  3544. imgFront.style.marginLeft = "-50px";
  3545. imgFront.style.marginTop = "-50px";
  3546. this._loadingDiv.appendChild(imgFront);
  3547. this._resizeLoadingUI = function () {
  3548. var canvasRect = _this.getRenderingCanvasClientRect();
  3549. _this._loadingDiv.style.position = "absolute";
  3550. _this._loadingDiv.style.left = canvasRect.left + "px";
  3551. _this._loadingDiv.style.top = canvasRect.top + "px";
  3552. _this._loadingDiv.style.width = canvasRect.width + "px";
  3553. _this._loadingDiv.style.height = canvasRect.height + "px";
  3554. };
  3555. this._resizeLoadingUI();
  3556. window.addEventListener("resize", this._resizeLoadingUI);
  3557. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3558. document.body.appendChild(this._loadingDiv);
  3559. setTimeout(function () {
  3560. _this._loadingDiv.style.opacity = "1";
  3561. imgBack.style.transform = "rotateZ(360deg)";
  3562. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3563. }, 0);
  3564. };
  3565. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3566. set: function (text) {
  3567. if (!this._loadingDiv) {
  3568. return;
  3569. }
  3570. this._loadingTextDiv.innerHTML = text;
  3571. },
  3572. enumerable: true,
  3573. configurable: true
  3574. });
  3575. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3576. get: function () {
  3577. return this._loadingDivBackgroundColor;
  3578. },
  3579. set: function (color) {
  3580. this._loadingDivBackgroundColor = color;
  3581. if (!this._loadingDiv) {
  3582. return;
  3583. }
  3584. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3585. },
  3586. enumerable: true,
  3587. configurable: true
  3588. });
  3589. Engine.prototype.hideLoadingUI = function () {
  3590. var _this = this;
  3591. if (!this._loadingDiv) {
  3592. return;
  3593. }
  3594. var onTransitionEnd = function () {
  3595. if (!_this._loadingDiv) {
  3596. return;
  3597. }
  3598. document.body.removeChild(_this._loadingDiv);
  3599. window.removeEventListener("resize", _this._resizeLoadingUI);
  3600. _this._loadingDiv = null;
  3601. };
  3602. this._loadingDiv.style.opacity = "0";
  3603. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3604. };
  3605. Engine.isSupported = function () {
  3606. try {
  3607. var tempcanvas = document.createElement("canvas");
  3608. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3609. return gl != null && !!window.WebGLRenderingContext;
  3610. } catch (e) {
  3611. return false;
  3612. }
  3613. };
  3614. Engine._ALPHA_DISABLE = 0;
  3615. Engine._ALPHA_ADD = 1;
  3616. Engine._ALPHA_COMBINE = 2;
  3617. Engine._DELAYLOADSTATE_NONE = 0;
  3618. Engine._DELAYLOADSTATE_LOADED = 1;
  3619. Engine._DELAYLOADSTATE_LOADING = 2;
  3620. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3621. Engine.Epsilon = 0.001;
  3622. Engine.CollisionsEpsilon = 0.001;
  3623. Engine.ShadersRepository = "Babylon/Shaders/";
  3624. return Engine;
  3625. })();
  3626. BABYLON.Engine = Engine;
  3627. })(BABYLON || (BABYLON = {}));
  3628. var BABYLON;
  3629. (function (BABYLON) {
  3630. var Node = (function () {
  3631. function Node(name, scene) {
  3632. this.state = "";
  3633. this.animations = new Array();
  3634. this._childrenFlag = -1;
  3635. this._isEnabled = true;
  3636. this._isReady = true;
  3637. this._currentRenderId = -1;
  3638. this.name = name;
  3639. this.id = name;
  3640. this._scene = scene;
  3641. this._initCache();
  3642. }
  3643. Node.prototype.getScene = function () {
  3644. return this._scene;
  3645. };
  3646. Node.prototype.getEngine = function () {
  3647. return this._scene.getEngine();
  3648. };
  3649. Node.prototype.getWorldMatrix = function () {
  3650. return BABYLON.Matrix.Identity();
  3651. };
  3652. Node.prototype._initCache = function () {
  3653. this._cache = {};
  3654. this._cache.parent = undefined;
  3655. };
  3656. Node.prototype.updateCache = function (force) {
  3657. if (!force && this.isSynchronized())
  3658. return;
  3659. this._cache.parent = this.parent;
  3660. this._updateCache();
  3661. };
  3662. Node.prototype._updateCache = function (ignoreParentClass) {
  3663. };
  3664. Node.prototype._isSynchronized = function () {
  3665. return true;
  3666. };
  3667. Node.prototype.isSynchronizedWithParent = function () {
  3668. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3669. };
  3670. Node.prototype.isSynchronized = function (updateCache) {
  3671. var check = this.hasNewParent();
  3672. check = check || !this.isSynchronizedWithParent();
  3673. check = check || !this._isSynchronized();
  3674. if (updateCache)
  3675. this.updateCache(true);
  3676. return !check;
  3677. };
  3678. Node.prototype.hasNewParent = function (update) {
  3679. if (this._cache.parent === this.parent)
  3680. return false;
  3681. if (update)
  3682. this._cache.parent = this.parent;
  3683. return true;
  3684. };
  3685. Node.prototype.isReady = function () {
  3686. return this._isReady;
  3687. };
  3688. Node.prototype.isEnabled = function () {
  3689. if (!this._isEnabled) {
  3690. return false;
  3691. }
  3692. if (this.parent) {
  3693. return this.parent.isEnabled();
  3694. }
  3695. return true;
  3696. };
  3697. Node.prototype.setEnabled = function (value) {
  3698. this._isEnabled = value;
  3699. };
  3700. Node.prototype.isDescendantOf = function (ancestor) {
  3701. if (this.parent) {
  3702. if (this.parent === ancestor) {
  3703. return true;
  3704. }
  3705. return this.parent.isDescendantOf(ancestor);
  3706. }
  3707. return false;
  3708. };
  3709. Node.prototype._getDescendants = function (list, results) {
  3710. for (var index = 0; index < list.length; index++) {
  3711. var item = list[index];
  3712. if (item.isDescendantOf(this)) {
  3713. results.push(item);
  3714. }
  3715. }
  3716. };
  3717. Node.prototype.getDescendants = function () {
  3718. var results = [];
  3719. this._getDescendants(this._scene.meshes, results);
  3720. this._getDescendants(this._scene.lights, results);
  3721. this._getDescendants(this._scene.cameras, results);
  3722. return results;
  3723. };
  3724. Node.prototype._setReady = function (state) {
  3725. if (state == this._isReady) {
  3726. return;
  3727. }
  3728. if (!state) {
  3729. this._isReady = false;
  3730. return;
  3731. }
  3732. this._isReady = true;
  3733. if (this.onReady) {
  3734. this.onReady(this);
  3735. }
  3736. };
  3737. return Node;
  3738. })();
  3739. BABYLON.Node = Node;
  3740. })(BABYLON || (BABYLON = {}));
  3741. var BABYLON;
  3742. (function (BABYLON) {
  3743. var BoundingSphere = (function () {
  3744. function BoundingSphere(minimum, maximum) {
  3745. this.minimum = minimum;
  3746. this.maximum = maximum;
  3747. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3748. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3749. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3750. this.radius = distance * 0.5;
  3751. this.centerWorld = BABYLON.Vector3.Zero();
  3752. this._update(BABYLON.Matrix.Identity());
  3753. }
  3754. BoundingSphere.prototype._update = function (world) {
  3755. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3756. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3757. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3758. };
  3759. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3760. for (var i = 0; i < 6; i++) {
  3761. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3762. return false;
  3763. }
  3764. return true;
  3765. };
  3766. BoundingSphere.prototype.intersectsPoint = function (point) {
  3767. var x = this.centerWorld.x - point.x;
  3768. var y = this.centerWorld.y - point.y;
  3769. var z = this.centerWorld.z - point.z;
  3770. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3771. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3772. return false;
  3773. return true;
  3774. };
  3775. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3776. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3777. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3778. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3779. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3780. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3781. return false;
  3782. return true;
  3783. };
  3784. return BoundingSphere;
  3785. })();
  3786. BABYLON.BoundingSphere = BoundingSphere;
  3787. })(BABYLON || (BABYLON = {}));
  3788. var BABYLON;
  3789. (function (BABYLON) {
  3790. var BoundingBox = (function () {
  3791. function BoundingBox(minimum, maximum) {
  3792. this.minimum = minimum;
  3793. this.maximum = maximum;
  3794. this.vectors = new Array();
  3795. this.vectorsWorld = new Array();
  3796. this.vectors.push(this.minimum.clone());
  3797. this.vectors.push(this.maximum.clone());
  3798. this.vectors.push(this.minimum.clone());
  3799. this.vectors[2].x = this.maximum.x;
  3800. this.vectors.push(this.minimum.clone());
  3801. this.vectors[3].y = this.maximum.y;
  3802. this.vectors.push(this.minimum.clone());
  3803. this.vectors[4].z = this.maximum.z;
  3804. this.vectors.push(this.maximum.clone());
  3805. this.vectors[5].z = this.minimum.z;
  3806. this.vectors.push(this.maximum.clone());
  3807. this.vectors[6].x = this.minimum.x;
  3808. this.vectors.push(this.maximum.clone());
  3809. this.vectors[7].y = this.minimum.y;
  3810. this.center = this.maximum.add(this.minimum).scale(0.5);
  3811. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3812. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3813. for (var index = 0; index < this.vectors.length; index++) {
  3814. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3815. }
  3816. this.minimumWorld = BABYLON.Vector3.Zero();
  3817. this.maximumWorld = BABYLON.Vector3.Zero();
  3818. this._update(BABYLON.Matrix.Identity());
  3819. }
  3820. BoundingBox.prototype.getWorldMatrix = function () {
  3821. return this._worldMatrix;
  3822. };
  3823. BoundingBox.prototype._update = function (world) {
  3824. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3825. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3826. for (var index = 0; index < this.vectors.length; index++) {
  3827. var v = this.vectorsWorld[index];
  3828. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3829. if (v.x < this.minimumWorld.x)
  3830. this.minimumWorld.x = v.x;
  3831. if (v.y < this.minimumWorld.y)
  3832. this.minimumWorld.y = v.y;
  3833. if (v.z < this.minimumWorld.z)
  3834. this.minimumWorld.z = v.z;
  3835. if (v.x > this.maximumWorld.x)
  3836. this.maximumWorld.x = v.x;
  3837. if (v.y > this.maximumWorld.y)
  3838. this.maximumWorld.y = v.y;
  3839. if (v.z > this.maximumWorld.z)
  3840. this.maximumWorld.z = v.z;
  3841. }
  3842. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3843. this.center.scaleInPlace(0.5);
  3844. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3845. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3846. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3847. this._worldMatrix = world;
  3848. };
  3849. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3850. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3851. };
  3852. BoundingBox.prototype.intersectsPoint = function (point) {
  3853. var delta = BABYLON.Engine.Epsilon;
  3854. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3855. return false;
  3856. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3857. return false;
  3858. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3859. return false;
  3860. return true;
  3861. };
  3862. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3863. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3864. };
  3865. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3866. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3867. return false;
  3868. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3869. return false;
  3870. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3871. return false;
  3872. return true;
  3873. };
  3874. BoundingBox.Intersects = function (box0, box1) {
  3875. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3876. return false;
  3877. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3878. return false;
  3879. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3880. return false;
  3881. return true;
  3882. };
  3883. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3884. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3885. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3886. return (num <= (sphereRadius * sphereRadius));
  3887. };
  3888. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3889. for (var p = 0; p < 6; p++) {
  3890. var inCount = 8;
  3891. for (var i = 0; i < 8; i++) {
  3892. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3893. --inCount;
  3894. } else {
  3895. break;
  3896. }
  3897. }
  3898. if (inCount == 0)
  3899. return false;
  3900. }
  3901. return true;
  3902. };
  3903. return BoundingBox;
  3904. })();
  3905. BABYLON.BoundingBox = BoundingBox;
  3906. })(BABYLON || (BABYLON = {}));
  3907. var BABYLON;
  3908. (function (BABYLON) {
  3909. var computeBoxExtents = function (axis, box) {
  3910. var p = BABYLON.Vector3.Dot(box.center, axis);
  3911. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3912. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3913. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3914. var r = r0 + r1 + r2;
  3915. return {
  3916. min: p - r,
  3917. max: p + r
  3918. };
  3919. };
  3920. var extentsOverlap = function (min0, max0, min1, max1) {
  3921. return !(min0 > max1 || min1 > max0);
  3922. };
  3923. var axisOverlap = function (axis, box0, box1) {
  3924. var result0 = computeBoxExtents(axis, box0);
  3925. var result1 = computeBoxExtents(axis, box1);
  3926. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3927. };
  3928. var BoundingInfo = (function () {
  3929. function BoundingInfo(minimum, maximum) {
  3930. this.minimum = minimum;
  3931. this.maximum = maximum;
  3932. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3933. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3934. }
  3935. BoundingInfo.prototype._update = function (world) {
  3936. this.boundingBox._update(world);
  3937. this.boundingSphere._update(world);
  3938. };
  3939. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3940. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3941. return false;
  3942. return this.boundingBox.isInFrustum(frustumPlanes);
  3943. };
  3944. BoundingInfo.prototype._checkCollision = function (collider) {
  3945. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3946. };
  3947. BoundingInfo.prototype.intersectsPoint = function (point) {
  3948. if (!this.boundingSphere.centerWorld) {
  3949. return false;
  3950. }
  3951. if (!this.boundingSphere.intersectsPoint(point)) {
  3952. return false;
  3953. }
  3954. if (!this.boundingBox.intersectsPoint(point)) {
  3955. return false;
  3956. }
  3957. return true;
  3958. };
  3959. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3960. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3961. return false;
  3962. }
  3963. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3964. return false;
  3965. }
  3966. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3967. return false;
  3968. }
  3969. if (!precise) {
  3970. return true;
  3971. }
  3972. var box0 = this.boundingBox;
  3973. var box1 = boundingInfo.boundingBox;
  3974. if (!axisOverlap(box0.directions[0], box0, box1))
  3975. return false;
  3976. if (!axisOverlap(box0.directions[1], box0, box1))
  3977. return false;
  3978. if (!axisOverlap(box0.directions[2], box0, box1))
  3979. return false;
  3980. if (!axisOverlap(box1.directions[0], box0, box1))
  3981. return false;
  3982. if (!axisOverlap(box1.directions[1], box0, box1))
  3983. return false;
  3984. if (!axisOverlap(box1.directions[2], box0, box1))
  3985. return false;
  3986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3987. return false;
  3988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3989. return false;
  3990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3991. return false;
  3992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3993. return false;
  3994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3995. return false;
  3996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3997. return false;
  3998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3999. return false;
  4000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4001. return false;
  4002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4003. return false;
  4004. return true;
  4005. };
  4006. return BoundingInfo;
  4007. })();
  4008. BABYLON.BoundingInfo = BoundingInfo;
  4009. })(BABYLON || (BABYLON = {}));
  4010. var __extends = this.__extends || function (d, b) {
  4011. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4012. function __() { this.constructor = d; }
  4013. __.prototype = b.prototype;
  4014. d.prototype = new __();
  4015. };
  4016. var BABYLON;
  4017. (function (BABYLON) {
  4018. var Light = (function (_super) {
  4019. __extends(Light, _super);
  4020. function Light(name, scene) {
  4021. _super.call(this, name, scene);
  4022. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4023. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4024. this.intensity = 1.0;
  4025. this.range = Number.MAX_VALUE;
  4026. this.includedOnlyMeshes = new Array();
  4027. this.excludedMeshes = new Array();
  4028. this._excludedMeshesIds = new Array();
  4029. this._includedOnlyMeshesIds = new Array();
  4030. scene.lights.push(this);
  4031. }
  4032. Light.prototype.getShadowGenerator = function () {
  4033. return this._shadowGenerator;
  4034. };
  4035. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4036. };
  4037. Light.prototype._getWorldMatrix = function () {
  4038. return BABYLON.Matrix.Identity();
  4039. };
  4040. Light.prototype.canAffectMesh = function (mesh) {
  4041. if (!mesh) {
  4042. return true;
  4043. }
  4044. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4045. return false;
  4046. }
  4047. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4048. return false;
  4049. }
  4050. return true;
  4051. };
  4052. Light.prototype.getWorldMatrix = function () {
  4053. this._currentRenderId = this.getScene().getRenderId();
  4054. var worldMatrix = this._getWorldMatrix();
  4055. if (this.parent && this.parent.getWorldMatrix) {
  4056. if (!this._parentedWorldMatrix) {
  4057. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4058. }
  4059. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4060. return this._parentedWorldMatrix;
  4061. }
  4062. return worldMatrix;
  4063. };
  4064. Light.prototype.dispose = function () {
  4065. if (this._shadowGenerator) {
  4066. this._shadowGenerator.dispose();
  4067. this._shadowGenerator = null;
  4068. }
  4069. var index = this.getScene().lights.indexOf(this);
  4070. this.getScene().lights.splice(index, 1);
  4071. };
  4072. return Light;
  4073. })(BABYLON.Node);
  4074. BABYLON.Light = Light;
  4075. })(BABYLON || (BABYLON = {}));
  4076. var __extends = this.__extends || function (d, b) {
  4077. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4078. function __() { this.constructor = d; }
  4079. __.prototype = b.prototype;
  4080. d.prototype = new __();
  4081. };
  4082. var BABYLON;
  4083. (function (BABYLON) {
  4084. var PointLight = (function (_super) {
  4085. __extends(PointLight, _super);
  4086. function PointLight(name, position, scene) {
  4087. _super.call(this, name, scene);
  4088. this.position = position;
  4089. }
  4090. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4091. if (this.parent && this.parent.getWorldMatrix) {
  4092. if (!this._transformedPosition) {
  4093. this._transformedPosition = BABYLON.Vector3.Zero();
  4094. }
  4095. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4096. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4097. return;
  4098. }
  4099. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4100. };
  4101. PointLight.prototype.getShadowGenerator = function () {
  4102. return null;
  4103. };
  4104. PointLight.prototype._getWorldMatrix = function () {
  4105. if (!this._worldMatrix) {
  4106. this._worldMatrix = BABYLON.Matrix.Identity();
  4107. }
  4108. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4109. return this._worldMatrix;
  4110. };
  4111. return PointLight;
  4112. })(BABYLON.Light);
  4113. BABYLON.PointLight = PointLight;
  4114. })(BABYLON || (BABYLON = {}));
  4115. var __extends = this.__extends || function (d, b) {
  4116. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4117. function __() { this.constructor = d; }
  4118. __.prototype = b.prototype;
  4119. d.prototype = new __();
  4120. };
  4121. var BABYLON;
  4122. (function (BABYLON) {
  4123. var SpotLight = (function (_super) {
  4124. __extends(SpotLight, _super);
  4125. function SpotLight(name, position, direction, angle, exponent, scene) {
  4126. _super.call(this, name, scene);
  4127. this.position = position;
  4128. this.direction = direction;
  4129. this.angle = angle;
  4130. this.exponent = exponent;
  4131. }
  4132. SpotLight.prototype.setDirectionToTarget = function (target) {
  4133. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4134. return this.direction;
  4135. };
  4136. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4137. var normalizeDirection;
  4138. if (this.parent && this.parent.getWorldMatrix) {
  4139. if (!this._transformedDirection) {
  4140. this._transformedDirection = BABYLON.Vector3.Zero();
  4141. }
  4142. if (!this._transformedPosition) {
  4143. this._transformedPosition = BABYLON.Vector3.Zero();
  4144. }
  4145. var parentWorldMatrix = this.parent.getWorldMatrix();
  4146. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4147. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4148. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4149. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4150. } else {
  4151. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4152. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4153. }
  4154. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4155. };
  4156. SpotLight.prototype._getWorldMatrix = function () {
  4157. if (!this._worldMatrix) {
  4158. this._worldMatrix = BABYLON.Matrix.Identity();
  4159. }
  4160. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4161. return this._worldMatrix;
  4162. };
  4163. return SpotLight;
  4164. })(BABYLON.Light);
  4165. BABYLON.SpotLight = SpotLight;
  4166. })(BABYLON || (BABYLON = {}));
  4167. var __extends = this.__extends || function (d, b) {
  4168. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4169. function __() { this.constructor = d; }
  4170. __.prototype = b.prototype;
  4171. d.prototype = new __();
  4172. };
  4173. var BABYLON;
  4174. (function (BABYLON) {
  4175. var DirectionalLight = (function (_super) {
  4176. __extends(DirectionalLight, _super);
  4177. function DirectionalLight(name, direction, scene) {
  4178. _super.call(this, name, scene);
  4179. this.direction = direction;
  4180. this.position = direction.scale(-1);
  4181. }
  4182. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4183. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4184. return this.direction;
  4185. };
  4186. DirectionalLight.prototype._computeTransformedPosition = function () {
  4187. if (this.parent && this.parent.getWorldMatrix) {
  4188. if (!this._transformedPosition) {
  4189. this._transformedPosition = BABYLON.Vector3.Zero();
  4190. }
  4191. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4192. return true;
  4193. }
  4194. return false;
  4195. };
  4196. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4197. if (this.parent && this.parent.getWorldMatrix) {
  4198. if (!this._transformedDirection) {
  4199. this._transformedDirection = BABYLON.Vector3.Zero();
  4200. }
  4201. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4202. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4203. return;
  4204. }
  4205. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4206. };
  4207. DirectionalLight.prototype._getWorldMatrix = function () {
  4208. if (!this._worldMatrix) {
  4209. this._worldMatrix = BABYLON.Matrix.Identity();
  4210. }
  4211. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4212. return this._worldMatrix;
  4213. };
  4214. return DirectionalLight;
  4215. })(BABYLON.Light);
  4216. BABYLON.DirectionalLight = DirectionalLight;
  4217. })(BABYLON || (BABYLON = {}));
  4218. var BABYLON;
  4219. (function (BABYLON) {
  4220. var ShadowGenerator = (function () {
  4221. function ShadowGenerator(mapSize, light) {
  4222. var _this = this;
  4223. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4224. this._darkness = 0;
  4225. this._transparencyShadow = false;
  4226. this._viewMatrix = BABYLON.Matrix.Zero();
  4227. this._projectionMatrix = BABYLON.Matrix.Zero();
  4228. this._transformMatrix = BABYLON.Matrix.Zero();
  4229. this._worldViewProjection = BABYLON.Matrix.Zero();
  4230. this._light = light;
  4231. this._scene = light.getScene();
  4232. light._shadowGenerator = this;
  4233. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4234. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4235. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4236. this._shadowMap.renderParticles = false;
  4237. var renderSubMesh = function (subMesh) {
  4238. var mesh = subMesh.getRenderingMesh();
  4239. var scene = _this._scene;
  4240. var engine = scene.getEngine();
  4241. engine.setState(subMesh.getMaterial().backFaceCulling);
  4242. var batch = mesh._getInstancesRenderList(subMesh._id);
  4243. if (batch.mustReturn) {
  4244. return;
  4245. }
  4246. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4247. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4248. engine.enableEffect(_this._effect);
  4249. mesh._bind(subMesh, _this._effect, false);
  4250. var material = subMesh.getMaterial();
  4251. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4252. if (material && material.needAlphaTesting()) {
  4253. var alphaTexture = material.getAlphaTestTexture();
  4254. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4255. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4256. }
  4257. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4258. if (useBones) {
  4259. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4260. }
  4261. if (hardwareInstancedRendering) {
  4262. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4263. } else {
  4264. if (batch.renderSelf[subMesh._id]) {
  4265. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4266. mesh._draw(subMesh, true);
  4267. }
  4268. if (batch.visibleInstances[subMesh._id]) {
  4269. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4270. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4271. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4272. mesh._draw(subMesh, true);
  4273. }
  4274. }
  4275. }
  4276. } else {
  4277. _this._shadowMap.resetRefreshCounter();
  4278. }
  4279. };
  4280. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4281. var index;
  4282. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4283. renderSubMesh(opaqueSubMeshes.data[index]);
  4284. }
  4285. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4286. renderSubMesh(alphaTestSubMeshes.data[index]);
  4287. }
  4288. if (_this._transparencyShadow) {
  4289. for (index = 0; index < transparentSubMeshes.length; index++) {
  4290. renderSubMesh(transparentSubMeshes.data[index]);
  4291. }
  4292. }
  4293. };
  4294. }
  4295. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4296. get: function () {
  4297. return ShadowGenerator._FILTER_NONE;
  4298. },
  4299. enumerable: true,
  4300. configurable: true
  4301. });
  4302. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4303. get: function () {
  4304. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4305. },
  4306. enumerable: true,
  4307. configurable: true
  4308. });
  4309. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4310. get: function () {
  4311. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4312. },
  4313. enumerable: true,
  4314. configurable: true
  4315. });
  4316. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4317. get: function () {
  4318. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4319. },
  4320. set: function (value) {
  4321. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4322. },
  4323. enumerable: true,
  4324. configurable: true
  4325. });
  4326. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4327. get: function () {
  4328. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4329. },
  4330. set: function (value) {
  4331. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4332. },
  4333. enumerable: true,
  4334. configurable: true
  4335. });
  4336. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4337. var defines = [];
  4338. if (this.useVarianceShadowMap) {
  4339. defines.push("#define VSM");
  4340. }
  4341. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4342. var mesh = subMesh.getMesh();
  4343. var material = subMesh.getMaterial();
  4344. if (material && material.needAlphaTesting()) {
  4345. defines.push("#define ALPHATEST");
  4346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4347. attribs.push(BABYLON.VertexBuffer.UVKind);
  4348. defines.push("#define UV1");
  4349. }
  4350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4352. defines.push("#define UV2");
  4353. }
  4354. }
  4355. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4358. defines.push("#define BONES");
  4359. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4360. }
  4361. if (useInstances) {
  4362. defines.push("#define INSTANCES");
  4363. attribs.push("world0");
  4364. attribs.push("world1");
  4365. attribs.push("world2");
  4366. attribs.push("world3");
  4367. }
  4368. var join = defines.join("\n");
  4369. if (this._cachedDefines != join) {
  4370. this._cachedDefines = join;
  4371. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4372. }
  4373. return this._effect.isReady();
  4374. };
  4375. ShadowGenerator.prototype.getShadowMap = function () {
  4376. return this._shadowMap;
  4377. };
  4378. ShadowGenerator.prototype.getLight = function () {
  4379. return this._light;
  4380. };
  4381. ShadowGenerator.prototype.getTransformMatrix = function () {
  4382. var lightPosition = this._light.position;
  4383. var lightDirection = this._light.direction;
  4384. if (this._light._computeTransformedPosition()) {
  4385. lightPosition = this._light._transformedPosition;
  4386. }
  4387. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4388. this._cachedPosition = lightPosition.clone();
  4389. this._cachedDirection = lightDirection.clone();
  4390. var activeCamera = this._scene.activeCamera;
  4391. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4392. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4393. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4394. }
  4395. return this._transformMatrix;
  4396. };
  4397. ShadowGenerator.prototype.getDarkness = function () {
  4398. return this._darkness;
  4399. };
  4400. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4401. if (darkness >= 1.0)
  4402. this._darkness = 1.0;
  4403. else if (darkness <= 0.0)
  4404. this._darkness = 0.0;
  4405. else
  4406. this._darkness = darkness;
  4407. };
  4408. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4409. this._transparencyShadow = hasShadow;
  4410. };
  4411. ShadowGenerator.prototype.dispose = function () {
  4412. this._shadowMap.dispose();
  4413. };
  4414. ShadowGenerator._FILTER_NONE = 0;
  4415. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4416. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4417. return ShadowGenerator;
  4418. })();
  4419. BABYLON.ShadowGenerator = ShadowGenerator;
  4420. })(BABYLON || (BABYLON = {}));
  4421. var __extends = this.__extends || function (d, b) {
  4422. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4423. function __() { this.constructor = d; }
  4424. __.prototype = b.prototype;
  4425. d.prototype = new __();
  4426. };
  4427. var BABYLON;
  4428. (function (BABYLON) {
  4429. var HemisphericLight = (function (_super) {
  4430. __extends(HemisphericLight, _super);
  4431. function HemisphericLight(name, direction, scene) {
  4432. _super.call(this, name, scene);
  4433. this.direction = direction;
  4434. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4435. }
  4436. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4437. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4438. return this.direction;
  4439. };
  4440. HemisphericLight.prototype.getShadowGenerator = function () {
  4441. return null;
  4442. };
  4443. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4444. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4445. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4446. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4447. };
  4448. HemisphericLight.prototype._getWorldMatrix = function () {
  4449. if (!this._worldMatrix) {
  4450. this._worldMatrix = BABYLON.Matrix.Identity();
  4451. }
  4452. return this._worldMatrix;
  4453. };
  4454. return HemisphericLight;
  4455. })(BABYLON.Light);
  4456. BABYLON.HemisphericLight = HemisphericLight;
  4457. })(BABYLON || (BABYLON = {}));
  4458. var BABYLON;
  4459. (function (BABYLON) {
  4460. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4461. if (boxMin.x > sphereCenter.x + sphereRadius)
  4462. return false;
  4463. if (sphereCenter.x - sphereRadius > boxMax.x)
  4464. return false;
  4465. if (boxMin.y > sphereCenter.y + sphereRadius)
  4466. return false;
  4467. if (sphereCenter.y - sphereRadius > boxMax.y)
  4468. return false;
  4469. if (boxMin.z > sphereCenter.z + sphereRadius)
  4470. return false;
  4471. if (sphereCenter.z - sphereRadius > boxMax.z)
  4472. return false;
  4473. return true;
  4474. };
  4475. var getLowestRoot = function (a, b, c, maxR) {
  4476. var determinant = b * b - 4.0 * a * c;
  4477. var result = { root: 0, found: false };
  4478. if (determinant < 0)
  4479. return result;
  4480. var sqrtD = Math.sqrt(determinant);
  4481. var r1 = (-b - sqrtD) / (2.0 * a);
  4482. var r2 = (-b + sqrtD) / (2.0 * a);
  4483. if (r1 > r2) {
  4484. var temp = r2;
  4485. r2 = r1;
  4486. r1 = temp;
  4487. }
  4488. if (r1 > 0 && r1 < maxR) {
  4489. result.root = r1;
  4490. result.found = true;
  4491. return result;
  4492. }
  4493. if (r2 > 0 && r2 < maxR) {
  4494. result.root = r2;
  4495. result.found = true;
  4496. return result;
  4497. }
  4498. return result;
  4499. };
  4500. var Collider = (function () {
  4501. function Collider() {
  4502. this.radius = new BABYLON.Vector3(1, 1, 1);
  4503. this.retry = 0;
  4504. this.basePointWorld = BABYLON.Vector3.Zero();
  4505. this.velocityWorld = BABYLON.Vector3.Zero();
  4506. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4507. this._collisionPoint = BABYLON.Vector3.Zero();
  4508. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4509. this._tempVector = BABYLON.Vector3.Zero();
  4510. this._tempVector2 = BABYLON.Vector3.Zero();
  4511. this._tempVector3 = BABYLON.Vector3.Zero();
  4512. this._tempVector4 = BABYLON.Vector3.Zero();
  4513. this._edge = BABYLON.Vector3.Zero();
  4514. this._baseToVertex = BABYLON.Vector3.Zero();
  4515. this._destinationPoint = BABYLON.Vector3.Zero();
  4516. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4517. this._displacementVector = BABYLON.Vector3.Zero();
  4518. }
  4519. Collider.prototype._initialize = function (source, dir, e) {
  4520. this.velocity = dir;
  4521. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4522. this.basePoint = source;
  4523. source.multiplyToRef(this.radius, this.basePointWorld);
  4524. dir.multiplyToRef(this.radius, this.velocityWorld);
  4525. this.velocityWorldLength = this.velocityWorld.length();
  4526. this.epsilon = e;
  4527. this.collisionFound = false;
  4528. };
  4529. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4530. pa.subtractToRef(point, this._tempVector);
  4531. pb.subtractToRef(point, this._tempVector2);
  4532. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4533. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4534. if (d < 0)
  4535. return false;
  4536. pc.subtractToRef(point, this._tempVector3);
  4537. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4538. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4539. if (d < 0)
  4540. return false;
  4541. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4542. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4543. return d >= 0;
  4544. };
  4545. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4546. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4547. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4548. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4549. return false;
  4550. }
  4551. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4552. return false;
  4553. return true;
  4554. };
  4555. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4556. var t0;
  4557. var embeddedInPlane = false;
  4558. if (!subMesh._trianglePlanes) {
  4559. subMesh._trianglePlanes = [];
  4560. }
  4561. if (!subMesh._trianglePlanes[faceIndex]) {
  4562. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4563. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4564. }
  4565. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4566. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4567. return;
  4568. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4569. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4570. if (normalDotVelocity == 0) {
  4571. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4572. return;
  4573. embeddedInPlane = true;
  4574. t0 = 0;
  4575. } else {
  4576. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4577. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4578. if (t0 > t1) {
  4579. var temp = t1;
  4580. t1 = t0;
  4581. t0 = temp;
  4582. }
  4583. if (t0 > 1.0 || t1 < 0.0)
  4584. return;
  4585. if (t0 < 0)
  4586. t0 = 0;
  4587. if (t0 > 1.0)
  4588. t0 = 1.0;
  4589. }
  4590. this._collisionPoint.copyFromFloats(0, 0, 0);
  4591. var found = false;
  4592. var t = 1.0;
  4593. if (!embeddedInPlane) {
  4594. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4595. this.velocity.scaleToRef(t0, this._tempVector);
  4596. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4597. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4598. found = true;
  4599. t = t0;
  4600. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4601. }
  4602. }
  4603. if (!found) {
  4604. var velocitySquaredLength = this.velocity.lengthSquared();
  4605. var a = velocitySquaredLength;
  4606. this.basePoint.subtractToRef(p1, this._tempVector);
  4607. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4608. var c = this._tempVector.lengthSquared() - 1.0;
  4609. var lowestRoot = getLowestRoot(a, b, c, t);
  4610. if (lowestRoot.found) {
  4611. t = lowestRoot.root;
  4612. found = true;
  4613. this._collisionPoint.copyFrom(p1);
  4614. }
  4615. this.basePoint.subtractToRef(p2, this._tempVector);
  4616. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4617. c = this._tempVector.lengthSquared() - 1.0;
  4618. lowestRoot = getLowestRoot(a, b, c, t);
  4619. if (lowestRoot.found) {
  4620. t = lowestRoot.root;
  4621. found = true;
  4622. this._collisionPoint.copyFrom(p2);
  4623. }
  4624. this.basePoint.subtractToRef(p3, this._tempVector);
  4625. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4626. c = this._tempVector.lengthSquared() - 1.0;
  4627. lowestRoot = getLowestRoot(a, b, c, t);
  4628. if (lowestRoot.found) {
  4629. t = lowestRoot.root;
  4630. found = true;
  4631. this._collisionPoint.copyFrom(p3);
  4632. }
  4633. p2.subtractToRef(p1, this._edge);
  4634. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4635. var edgeSquaredLength = this._edge.lengthSquared();
  4636. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4637. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4638. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4639. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4640. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4641. lowestRoot = getLowestRoot(a, b, c, t);
  4642. if (lowestRoot.found) {
  4643. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4644. if (f >= 0.0 && f <= 1.0) {
  4645. t = lowestRoot.root;
  4646. found = true;
  4647. this._edge.scaleInPlace(f);
  4648. p1.addToRef(this._edge, this._collisionPoint);
  4649. }
  4650. }
  4651. p3.subtractToRef(p2, this._edge);
  4652. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4653. edgeSquaredLength = this._edge.lengthSquared();
  4654. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4655. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4656. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4657. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4658. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4659. lowestRoot = getLowestRoot(a, b, c, t);
  4660. if (lowestRoot.found) {
  4661. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4662. if (f >= 0.0 && f <= 1.0) {
  4663. t = lowestRoot.root;
  4664. found = true;
  4665. this._edge.scaleInPlace(f);
  4666. p2.addToRef(this._edge, this._collisionPoint);
  4667. }
  4668. }
  4669. p1.subtractToRef(p3, this._edge);
  4670. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4671. edgeSquaredLength = this._edge.lengthSquared();
  4672. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4673. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4674. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4675. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4676. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4677. lowestRoot = getLowestRoot(a, b, c, t);
  4678. if (lowestRoot.found) {
  4679. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4680. if (f >= 0.0 && f <= 1.0) {
  4681. t = lowestRoot.root;
  4682. found = true;
  4683. this._edge.scaleInPlace(f);
  4684. p3.addToRef(this._edge, this._collisionPoint);
  4685. }
  4686. }
  4687. }
  4688. if (found) {
  4689. var distToCollision = t * this.velocity.length();
  4690. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4691. if (!this.intersectionPoint) {
  4692. this.intersectionPoint = this._collisionPoint.clone();
  4693. } else {
  4694. this.intersectionPoint.copyFrom(this._collisionPoint);
  4695. }
  4696. this.nearestDistance = distToCollision;
  4697. this.collisionFound = true;
  4698. this.collidedMesh = subMesh.getMesh();
  4699. }
  4700. }
  4701. };
  4702. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4703. for (var i = indexStart; i < indexEnd; i += 3) {
  4704. var p1 = pts[indices[i] - decal];
  4705. var p2 = pts[indices[i + 1] - decal];
  4706. var p3 = pts[indices[i + 2] - decal];
  4707. this._testTriangle(i, subMesh, p3, p2, p1);
  4708. }
  4709. };
  4710. Collider.prototype._getResponse = function (pos, vel) {
  4711. pos.addToRef(vel, this._destinationPoint);
  4712. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4713. this.basePoint.addToRef(vel, pos);
  4714. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4715. this._slidePlaneNormal.normalize();
  4716. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4717. pos.addInPlace(this._displacementVector);
  4718. this.intersectionPoint.addInPlace(this._displacementVector);
  4719. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4720. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4721. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4722. };
  4723. return Collider;
  4724. })();
  4725. BABYLON.Collider = Collider;
  4726. })(BABYLON || (BABYLON = {}));
  4727. var __extends = this.__extends || function (d, b) {
  4728. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4729. function __() { this.constructor = d; }
  4730. __.prototype = b.prototype;
  4731. d.prototype = new __();
  4732. };
  4733. var BABYLON;
  4734. (function (BABYLON) {
  4735. var Camera = (function (_super) {
  4736. __extends(Camera, _super);
  4737. function Camera(name, position, scene) {
  4738. _super.call(this, name, scene);
  4739. this.position = position;
  4740. this.upVector = BABYLON.Vector3.Up();
  4741. this.orthoLeft = null;
  4742. this.orthoRight = null;
  4743. this.orthoBottom = null;
  4744. this.orthoTop = null;
  4745. this.fov = 0.8;
  4746. this.minZ = 1.0;
  4747. this.maxZ = 10000.0;
  4748. this.inertia = 0.9;
  4749. this.mode = Camera.PERSPECTIVE_CAMERA;
  4750. this.isIntermediate = false;
  4751. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4752. this.subCameras = [];
  4753. this.layerMask = 0xFFFFFFFF;
  4754. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4755. this._projectionMatrix = new BABYLON.Matrix();
  4756. this._postProcesses = new Array();
  4757. this._postProcessesTakenIndices = [];
  4758. scene.cameras.push(this);
  4759. if (!scene.activeCamera) {
  4760. scene.activeCamera = this;
  4761. }
  4762. }
  4763. Camera.prototype._initCache = function () {
  4764. _super.prototype._initCache.call(this);
  4765. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4766. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4767. this._cache.mode = undefined;
  4768. this._cache.minZ = undefined;
  4769. this._cache.maxZ = undefined;
  4770. this._cache.fov = undefined;
  4771. this._cache.aspectRatio = undefined;
  4772. this._cache.orthoLeft = undefined;
  4773. this._cache.orthoRight = undefined;
  4774. this._cache.orthoBottom = undefined;
  4775. this._cache.orthoTop = undefined;
  4776. this._cache.renderWidth = undefined;
  4777. this._cache.renderHeight = undefined;
  4778. };
  4779. Camera.prototype._updateCache = function (ignoreParentClass) {
  4780. if (!ignoreParentClass) {
  4781. _super.prototype._updateCache.call(this);
  4782. }
  4783. var engine = this.getEngine();
  4784. this._cache.position.copyFrom(this.position);
  4785. this._cache.upVector.copyFrom(this.upVector);
  4786. this._cache.mode = this.mode;
  4787. this._cache.minZ = this.minZ;
  4788. this._cache.maxZ = this.maxZ;
  4789. this._cache.fov = this.fov;
  4790. this._cache.aspectRatio = engine.getAspectRatio(this);
  4791. this._cache.orthoLeft = this.orthoLeft;
  4792. this._cache.orthoRight = this.orthoRight;
  4793. this._cache.orthoBottom = this.orthoBottom;
  4794. this._cache.orthoTop = this.orthoTop;
  4795. this._cache.renderWidth = engine.getRenderWidth();
  4796. this._cache.renderHeight = engine.getRenderHeight();
  4797. };
  4798. Camera.prototype._updateFromScene = function () {
  4799. this.updateCache();
  4800. this._update();
  4801. };
  4802. Camera.prototype._isSynchronized = function () {
  4803. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4804. };
  4805. Camera.prototype._isSynchronizedViewMatrix = function () {
  4806. if (!_super.prototype._isSynchronized.call(this))
  4807. return false;
  4808. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4809. };
  4810. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4811. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4812. if (!check) {
  4813. return false;
  4814. }
  4815. var engine = this.getEngine();
  4816. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4817. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4818. } else {
  4819. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  4820. }
  4821. return check;
  4822. };
  4823. Camera.prototype.attachControl = function (element) {
  4824. };
  4825. Camera.prototype.detachControl = function (element) {
  4826. };
  4827. Camera.prototype._update = function () {
  4828. };
  4829. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4830. if (typeof insertAt === "undefined") { insertAt = null; }
  4831. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4832. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4833. return 0;
  4834. }
  4835. if (insertAt == null || insertAt < 0) {
  4836. this._postProcesses.push(postProcess);
  4837. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4838. return this._postProcesses.length - 1;
  4839. }
  4840. var add = 0;
  4841. if (this._postProcesses[insertAt]) {
  4842. var start = this._postProcesses.length - 1;
  4843. for (var i = start; i >= insertAt + 1; --i) {
  4844. this._postProcesses[i + 1] = this._postProcesses[i];
  4845. }
  4846. add = 1;
  4847. }
  4848. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4849. if (this._postProcessesTakenIndices[i] < insertAt) {
  4850. continue;
  4851. }
  4852. start = this._postProcessesTakenIndices.length - 1;
  4853. for (var j = start; j >= i; --j) {
  4854. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4855. }
  4856. this._postProcessesTakenIndices[i] = insertAt;
  4857. break;
  4858. }
  4859. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4860. this._postProcessesTakenIndices.push(insertAt);
  4861. }
  4862. var result = insertAt + add;
  4863. this._postProcesses[result] = postProcess;
  4864. return result;
  4865. };
  4866. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4867. if (typeof atIndices === "undefined") { atIndices = null; }
  4868. var result = [];
  4869. if (!atIndices) {
  4870. var length = this._postProcesses.length;
  4871. for (var i = 0; i < length; i++) {
  4872. if (this._postProcesses[i] !== postProcess) {
  4873. continue;
  4874. }
  4875. delete this._postProcesses[i];
  4876. var index = this._postProcessesTakenIndices.indexOf(i);
  4877. this._postProcessesTakenIndices.splice(index, 1);
  4878. }
  4879. } else {
  4880. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4881. for (i = 0; i < atIndices.length; i++) {
  4882. var foundPostProcess = this._postProcesses[atIndices[i]];
  4883. if (foundPostProcess !== postProcess) {
  4884. result.push(i);
  4885. continue;
  4886. }
  4887. delete this._postProcesses[atIndices[i]];
  4888. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4889. this._postProcessesTakenIndices.splice(index, 1);
  4890. }
  4891. }
  4892. return result;
  4893. };
  4894. Camera.prototype.getWorldMatrix = function () {
  4895. if (!this._worldMatrix) {
  4896. this._worldMatrix = BABYLON.Matrix.Identity();
  4897. }
  4898. var viewMatrix = this.getViewMatrix();
  4899. viewMatrix.invertToRef(this._worldMatrix);
  4900. return this._worldMatrix;
  4901. };
  4902. Camera.prototype._getViewMatrix = function () {
  4903. return BABYLON.Matrix.Identity();
  4904. };
  4905. Camera.prototype.getViewMatrix = function () {
  4906. this._computedViewMatrix = this._computeViewMatrix();
  4907. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4908. return this._computedViewMatrix;
  4909. }
  4910. if (!this._worldMatrix) {
  4911. this._worldMatrix = BABYLON.Matrix.Identity();
  4912. }
  4913. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4914. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4915. this._computedViewMatrix.invert();
  4916. this._currentRenderId = this.getScene().getRenderId();
  4917. return this._computedViewMatrix;
  4918. };
  4919. Camera.prototype._computeViewMatrix = function (force) {
  4920. if (!force && this._isSynchronizedViewMatrix()) {
  4921. return this._computedViewMatrix;
  4922. }
  4923. this._computedViewMatrix = this._getViewMatrix();
  4924. if (!this.parent || !this.parent.getWorldMatrix) {
  4925. this._currentRenderId = this.getScene().getRenderId();
  4926. }
  4927. return this._computedViewMatrix;
  4928. };
  4929. Camera.prototype.getProjectionMatrix = function (force) {
  4930. if (!force && this._isSynchronizedProjectionMatrix()) {
  4931. return this._projectionMatrix;
  4932. }
  4933. var engine = this.getEngine();
  4934. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4935. if (this.minZ <= 0) {
  4936. this.minZ = 0.1;
  4937. }
  4938. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4939. return this._projectionMatrix;
  4940. }
  4941. var halfWidth = engine.getRenderWidth() / 2.0;
  4942. var halfHeight = engine.getRenderHeight() / 2.0;
  4943. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4944. return this._projectionMatrix;
  4945. };
  4946. Camera.prototype.dispose = function () {
  4947. var index = this.getScene().cameras.indexOf(this);
  4948. this.getScene().cameras.splice(index, 1);
  4949. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4950. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4951. }
  4952. };
  4953. Camera.PERSPECTIVE_CAMERA = 0;
  4954. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4955. return Camera;
  4956. })(BABYLON.Node);
  4957. BABYLON.Camera = Camera;
  4958. })(BABYLON || (BABYLON = {}));
  4959. var __extends = this.__extends || function (d, b) {
  4960. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4961. function __() { this.constructor = d; }
  4962. __.prototype = b.prototype;
  4963. d.prototype = new __();
  4964. };
  4965. var BABYLON;
  4966. (function (BABYLON) {
  4967. var TargetCamera = (function (_super) {
  4968. __extends(TargetCamera, _super);
  4969. function TargetCamera(name, position, scene) {
  4970. _super.call(this, name, position, scene);
  4971. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4972. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4973. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4974. this.speed = 2.0;
  4975. this.noRotationConstraint = false;
  4976. this.lockedTarget = null;
  4977. this._currentTarget = BABYLON.Vector3.Zero();
  4978. this._viewMatrix = BABYLON.Matrix.Zero();
  4979. this._camMatrix = BABYLON.Matrix.Zero();
  4980. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4981. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4982. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4983. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4984. this._lookAtTemp = BABYLON.Matrix.Zero();
  4985. this._tempMatrix = BABYLON.Matrix.Zero();
  4986. }
  4987. TargetCamera.prototype._getLockedTargetPosition = function () {
  4988. if (!this.lockedTarget) {
  4989. return null;
  4990. }
  4991. return this.lockedTarget.position || this.lockedTarget;
  4992. };
  4993. TargetCamera.prototype._initCache = function () {
  4994. _super.prototype._initCache.call(this);
  4995. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4996. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4997. };
  4998. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4999. if (!ignoreParentClass) {
  5000. _super.prototype._updateCache.call(this);
  5001. }
  5002. var lockedTargetPosition = this._getLockedTargetPosition();
  5003. if (!lockedTargetPosition) {
  5004. this._cache.lockedTarget = null;
  5005. } else {
  5006. if (!this._cache.lockedTarget) {
  5007. this._cache.lockedTarget = lockedTargetPosition.clone();
  5008. } else {
  5009. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5010. }
  5011. }
  5012. this._cache.rotation.copyFrom(this.rotation);
  5013. };
  5014. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5015. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5016. return false;
  5017. }
  5018. var lockedTargetPosition = this._getLockedTargetPosition();
  5019. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5020. };
  5021. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5022. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5023. };
  5024. TargetCamera.prototype.setTarget = function (target) {
  5025. this.upVector.normalize();
  5026. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5027. this._camMatrix.invert();
  5028. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5029. var vDir = target.subtract(this.position);
  5030. if (vDir.x >= 0.0) {
  5031. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5032. } else {
  5033. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5034. }
  5035. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5036. if (isNaN(this.rotation.x)) {
  5037. this.rotation.x = 0;
  5038. }
  5039. if (isNaN(this.rotation.y)) {
  5040. this.rotation.y = 0;
  5041. }
  5042. if (isNaN(this.rotation.z)) {
  5043. this.rotation.z = 0;
  5044. }
  5045. };
  5046. TargetCamera.prototype.getTarget = function () {
  5047. return this._currentTarget;
  5048. };
  5049. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5050. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5051. };
  5052. TargetCamera.prototype._updatePosition = function () {
  5053. this.position.addInPlace(this.cameraDirection);
  5054. };
  5055. TargetCamera.prototype._update = function () {
  5056. var needToMove = this._decideIfNeedsToMove();
  5057. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5058. if (needToMove) {
  5059. this._updatePosition();
  5060. }
  5061. if (needToRotate) {
  5062. this.rotation.x += this.cameraRotation.x;
  5063. this.rotation.y += this.cameraRotation.y;
  5064. if (!this.noRotationConstraint) {
  5065. var limit = (Math.PI / 2) * 0.95;
  5066. if (this.rotation.x > limit)
  5067. this.rotation.x = limit;
  5068. if (this.rotation.x < -limit)
  5069. this.rotation.x = -limit;
  5070. }
  5071. }
  5072. if (needToMove) {
  5073. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5074. this.cameraDirection.x = 0;
  5075. }
  5076. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5077. this.cameraDirection.y = 0;
  5078. }
  5079. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5080. this.cameraDirection.z = 0;
  5081. }
  5082. this.cameraDirection.scaleInPlace(this.inertia);
  5083. }
  5084. if (needToRotate) {
  5085. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5086. this.cameraRotation.x = 0;
  5087. }
  5088. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5089. this.cameraRotation.y = 0;
  5090. }
  5091. this.cameraRotation.scaleInPlace(this.inertia);
  5092. }
  5093. };
  5094. TargetCamera.prototype._getViewMatrix = function () {
  5095. if (!this.lockedTarget) {
  5096. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5097. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5098. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5099. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5100. this._lookAtTemp.invert();
  5101. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5102. } else {
  5103. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5104. }
  5105. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5106. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5107. } else {
  5108. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5109. }
  5110. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5111. return this._viewMatrix;
  5112. };
  5113. return TargetCamera;
  5114. })(BABYLON.Camera);
  5115. BABYLON.TargetCamera = TargetCamera;
  5116. })(BABYLON || (BABYLON = {}));
  5117. var __extends = this.__extends || function (d, b) {
  5118. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5119. function __() { this.constructor = d; }
  5120. __.prototype = b.prototype;
  5121. d.prototype = new __();
  5122. };
  5123. var BABYLON;
  5124. (function (BABYLON) {
  5125. var FollowCamera = (function (_super) {
  5126. __extends(FollowCamera, _super);
  5127. function FollowCamera(name, position, scene) {
  5128. _super.call(this, name, position, scene);
  5129. this.radius = 12;
  5130. this.rotationOffset = 0;
  5131. this.heightOffset = 4;
  5132. this.cameraAcceleration = 0.05;
  5133. this.maxCameraSpeed = 20;
  5134. }
  5135. FollowCamera.prototype.getRadians = function (degrees) {
  5136. return degrees * Math.PI / 180;
  5137. };
  5138. FollowCamera.prototype.follow = function (cameraTarget) {
  5139. if (!cameraTarget)
  5140. return;
  5141. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5142. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5143. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5144. var dx = targetX - this.position.x;
  5145. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5146. var dz = (targetZ) - this.position.z;
  5147. var vx = dx * this.cameraAcceleration * 2;
  5148. var vy = dy * this.cameraAcceleration;
  5149. var vz = dz * this.cameraAcceleration * 2;
  5150. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5151. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5152. }
  5153. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5154. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5155. }
  5156. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5157. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5158. }
  5159. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5160. this.setTarget(cameraTarget.position);
  5161. };
  5162. FollowCamera.prototype._update = function () {
  5163. _super.prototype._update.call(this);
  5164. this.follow(this.target);
  5165. };
  5166. return FollowCamera;
  5167. })(BABYLON.TargetCamera);
  5168. BABYLON.FollowCamera = FollowCamera;
  5169. })(BABYLON || (BABYLON = {}));
  5170. var __extends = this.__extends || function (d, b) {
  5171. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5172. function __() { this.constructor = d; }
  5173. __.prototype = b.prototype;
  5174. d.prototype = new __();
  5175. };
  5176. var BABYLON;
  5177. (function (BABYLON) {
  5178. var FreeCamera = (function (_super) {
  5179. __extends(FreeCamera, _super);
  5180. function FreeCamera(name, position, scene) {
  5181. _super.call(this, name, position, scene);
  5182. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5183. this.keysUp = [38];
  5184. this.keysDown = [40];
  5185. this.keysLeft = [37];
  5186. this.keysRight = [39];
  5187. this.checkCollisions = false;
  5188. this.applyGravity = false;
  5189. this.angularSensibility = 2000.0;
  5190. this._keys = [];
  5191. this._collider = new BABYLON.Collider();
  5192. this._needMoveForGravity = true;
  5193. this._oldPosition = BABYLON.Vector3.Zero();
  5194. this._diffPosition = BABYLON.Vector3.Zero();
  5195. this._newPosition = BABYLON.Vector3.Zero();
  5196. }
  5197. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5198. var _this = this;
  5199. var previousPosition;
  5200. var engine = this.getEngine();
  5201. if (this._attachedElement) {
  5202. return;
  5203. }
  5204. this._attachedElement = element;
  5205. if (this._onMouseDown === undefined) {
  5206. this._onMouseDown = function (evt) {
  5207. previousPosition = {
  5208. x: evt.clientX,
  5209. y: evt.clientY
  5210. };
  5211. if (!noPreventDefault) {
  5212. evt.preventDefault();
  5213. }
  5214. };
  5215. this._onMouseUp = function (evt) {
  5216. previousPosition = null;
  5217. if (!noPreventDefault) {
  5218. evt.preventDefault();
  5219. }
  5220. };
  5221. this._onMouseOut = function (evt) {
  5222. previousPosition = null;
  5223. _this._keys = [];
  5224. if (!noPreventDefault) {
  5225. evt.preventDefault();
  5226. }
  5227. };
  5228. this._onMouseMove = function (evt) {
  5229. if (!previousPosition && !engine.isPointerLock) {
  5230. return;
  5231. }
  5232. var offsetX;
  5233. var offsetY;
  5234. if (!engine.isPointerLock) {
  5235. offsetX = evt.clientX - previousPosition.x;
  5236. offsetY = evt.clientY - previousPosition.y;
  5237. } else {
  5238. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5239. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5240. }
  5241. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5242. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5243. previousPosition = {
  5244. x: evt.clientX,
  5245. y: evt.clientY
  5246. };
  5247. if (!noPreventDefault) {
  5248. evt.preventDefault();
  5249. }
  5250. };
  5251. this._onKeyDown = function (evt) {
  5252. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5253. var index = _this._keys.indexOf(evt.keyCode);
  5254. if (index === -1) {
  5255. _this._keys.push(evt.keyCode);
  5256. }
  5257. if (!noPreventDefault) {
  5258. evt.preventDefault();
  5259. }
  5260. }
  5261. };
  5262. this._onKeyUp = function (evt) {
  5263. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5264. var index = _this._keys.indexOf(evt.keyCode);
  5265. if (index >= 0) {
  5266. _this._keys.splice(index, 1);
  5267. }
  5268. if (!noPreventDefault) {
  5269. evt.preventDefault();
  5270. }
  5271. }
  5272. };
  5273. this._onLostFocus = function () {
  5274. _this._keys = [];
  5275. };
  5276. this._reset = function () {
  5277. _this._keys = [];
  5278. previousPosition = null;
  5279. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5280. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5281. };
  5282. }
  5283. element.addEventListener("mousedown", this._onMouseDown, false);
  5284. element.addEventListener("mouseup", this._onMouseUp, false);
  5285. element.addEventListener("mouseout", this._onMouseOut, false);
  5286. element.addEventListener("mousemove", this._onMouseMove, false);
  5287. BABYLON.Tools.RegisterTopRootEvents([
  5288. { name: "keydown", handler: this._onKeyDown },
  5289. { name: "keyup", handler: this._onKeyUp },
  5290. { name: "blur", handler: this._onLostFocus }
  5291. ]);
  5292. };
  5293. FreeCamera.prototype.detachControl = function (element) {
  5294. if (this._attachedElement != element) {
  5295. return;
  5296. }
  5297. element.removeEventListener("mousedown", this._onMouseDown);
  5298. element.removeEventListener("mouseup", this._onMouseUp);
  5299. element.removeEventListener("mouseout", this._onMouseOut);
  5300. element.removeEventListener("mousemove", this._onMouseMove);
  5301. BABYLON.Tools.UnregisterTopRootEvents([
  5302. { name: "keydown", handler: this._onKeyDown },
  5303. { name: "keyup", handler: this._onKeyUp },
  5304. { name: "blur", handler: this._onLostFocus }
  5305. ]);
  5306. this._attachedElement = null;
  5307. if (this._reset) {
  5308. this._reset();
  5309. }
  5310. };
  5311. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5312. var globalPosition;
  5313. if (this.parent) {
  5314. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5315. } else {
  5316. globalPosition = this.position;
  5317. }
  5318. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5319. this._collider.radius = this.ellipsoid;
  5320. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5321. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5322. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5323. this.position.addInPlace(this._diffPosition);
  5324. if (this.onCollide) {
  5325. this.onCollide(this._collider.collidedMesh);
  5326. }
  5327. }
  5328. };
  5329. FreeCamera.prototype._checkInputs = function () {
  5330. if (!this._localDirection) {
  5331. this._localDirection = BABYLON.Vector3.Zero();
  5332. this._transformedDirection = BABYLON.Vector3.Zero();
  5333. }
  5334. for (var index = 0; index < this._keys.length; index++) {
  5335. var keyCode = this._keys[index];
  5336. var speed = this._computeLocalCameraSpeed();
  5337. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5338. this._localDirection.copyFromFloats(-speed, 0, 0);
  5339. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5340. this._localDirection.copyFromFloats(0, 0, speed);
  5341. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5342. this._localDirection.copyFromFloats(speed, 0, 0);
  5343. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5344. this._localDirection.copyFromFloats(0, 0, -speed);
  5345. }
  5346. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5347. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5348. this.cameraDirection.addInPlace(this._transformedDirection);
  5349. }
  5350. };
  5351. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5352. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5353. };
  5354. FreeCamera.prototype._updatePosition = function () {
  5355. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5356. this._collideWithWorld(this.cameraDirection);
  5357. if (this.applyGravity) {
  5358. var oldPosition = this.position;
  5359. this._collideWithWorld(this.getScene().gravity);
  5360. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5361. }
  5362. } else {
  5363. this.position.addInPlace(this.cameraDirection);
  5364. }
  5365. };
  5366. FreeCamera.prototype._update = function () {
  5367. this._checkInputs();
  5368. _super.prototype._update.call(this);
  5369. };
  5370. return FreeCamera;
  5371. })(BABYLON.TargetCamera);
  5372. BABYLON.FreeCamera = FreeCamera;
  5373. })(BABYLON || (BABYLON = {}));
  5374. var __extends = this.__extends || function (d, b) {
  5375. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5376. function __() { this.constructor = d; }
  5377. __.prototype = b.prototype;
  5378. d.prototype = new __();
  5379. };
  5380. var BABYLON;
  5381. (function (BABYLON) {
  5382. var TouchCamera = (function (_super) {
  5383. __extends(TouchCamera, _super);
  5384. function TouchCamera(name, position, scene) {
  5385. _super.call(this, name, position, scene);
  5386. this._offsetX = null;
  5387. this._offsetY = null;
  5388. this._pointerCount = 0;
  5389. this._pointerPressed = [];
  5390. this.angularSensibility = 200000.0;
  5391. this.moveSensibility = 500.0;
  5392. }
  5393. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5394. var _this = this;
  5395. var previousPosition;
  5396. if (this._attachedCanvas) {
  5397. return;
  5398. }
  5399. this._attachedCanvas = canvas;
  5400. if (this._onPointerDown === undefined) {
  5401. this._onPointerDown = function (evt) {
  5402. if (!noPreventDefault) {
  5403. evt.preventDefault();
  5404. }
  5405. _this._pointerPressed.push(evt.pointerId);
  5406. if (_this._pointerPressed.length !== 1) {
  5407. return;
  5408. }
  5409. previousPosition = {
  5410. x: evt.clientX,
  5411. y: evt.clientY
  5412. };
  5413. };
  5414. this._onPointerUp = function (evt) {
  5415. if (!noPreventDefault) {
  5416. evt.preventDefault();
  5417. }
  5418. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5419. if (index === -1) {
  5420. return;
  5421. }
  5422. _this._pointerPressed.splice(index, 1);
  5423. if (index != 0) {
  5424. return;
  5425. }
  5426. previousPosition = null;
  5427. _this._offsetX = null;
  5428. _this._offsetY = null;
  5429. };
  5430. this._onPointerMove = function (evt) {
  5431. if (!noPreventDefault) {
  5432. evt.preventDefault();
  5433. }
  5434. if (!previousPosition) {
  5435. return;
  5436. }
  5437. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5438. if (index != 0) {
  5439. return;
  5440. }
  5441. _this._offsetX = evt.clientX - previousPosition.x;
  5442. _this._offsetY = -(evt.clientY - previousPosition.y);
  5443. };
  5444. this._onLostFocus = function () {
  5445. _this._offsetX = null;
  5446. _this._offsetY = null;
  5447. };
  5448. }
  5449. canvas.addEventListener("pointerdown", this._onPointerDown);
  5450. canvas.addEventListener("pointerup", this._onPointerUp);
  5451. canvas.addEventListener("pointerout", this._onPointerUp);
  5452. canvas.addEventListener("pointermove", this._onPointerMove);
  5453. BABYLON.Tools.RegisterTopRootEvents([
  5454. { name: "blur", handler: this._onLostFocus }
  5455. ]);
  5456. };
  5457. TouchCamera.prototype.detachControl = function (canvas) {
  5458. if (this._attachedCanvas != canvas) {
  5459. return;
  5460. }
  5461. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5462. canvas.removeEventListener("pointerup", this._onPointerUp);
  5463. canvas.removeEventListener("pointerout", this._onPointerUp);
  5464. canvas.removeEventListener("pointermove", this._onPointerMove);
  5465. BABYLON.Tools.UnregisterTopRootEvents([
  5466. { name: "blur", handler: this._onLostFocus }
  5467. ]);
  5468. this._attachedCanvas = null;
  5469. };
  5470. TouchCamera.prototype._checkInputs = function () {
  5471. if (!this._offsetX) {
  5472. return;
  5473. }
  5474. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5475. if (this._pointerPressed.length > 1) {
  5476. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5477. } else {
  5478. var speed = this._computeLocalCameraSpeed();
  5479. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5480. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5481. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5482. }
  5483. };
  5484. return TouchCamera;
  5485. })(BABYLON.FreeCamera);
  5486. BABYLON.TouchCamera = TouchCamera;
  5487. })(BABYLON || (BABYLON = {}));
  5488. var __extends = this.__extends || function (d, b) {
  5489. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5490. function __() { this.constructor = d; }
  5491. __.prototype = b.prototype;
  5492. d.prototype = new __();
  5493. };
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var DeviceOrientationCamera = (function (_super) {
  5497. __extends(DeviceOrientationCamera, _super);
  5498. function DeviceOrientationCamera(name, position, scene) {
  5499. var _this = this;
  5500. _super.call(this, name, position, scene);
  5501. this._offsetX = null;
  5502. this._offsetY = null;
  5503. this._orientationGamma = 0;
  5504. this._orientationBeta = 0;
  5505. this._initialOrientationGamma = 0;
  5506. this._initialOrientationBeta = 0;
  5507. this.angularSensibility = 10000.0;
  5508. this.moveSensibility = 50.0;
  5509. window.addEventListener("resize", function () {
  5510. _this._initialOrientationGamma = null;
  5511. }, false);
  5512. }
  5513. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5514. var _this = this;
  5515. if (this._attachedCanvas) {
  5516. return;
  5517. }
  5518. this._attachedCanvas = canvas;
  5519. if (!this._orientationChanged) {
  5520. this._orientationChanged = function (evt) {
  5521. if (!_this._initialOrientationGamma) {
  5522. _this._initialOrientationGamma = evt.gamma;
  5523. _this._initialOrientationBeta = evt.beta;
  5524. }
  5525. _this._orientationGamma = evt.gamma;
  5526. _this._orientationBeta = evt.beta;
  5527. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5528. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5529. };
  5530. }
  5531. window.addEventListener("deviceorientation", this._orientationChanged);
  5532. };
  5533. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5534. if (this._attachedCanvas != canvas) {
  5535. return;
  5536. }
  5537. window.removeEventListener("deviceorientation", this._orientationChanged);
  5538. this._attachedCanvas = null;
  5539. this._orientationGamma = 0;
  5540. this._orientationBeta = 0;
  5541. this._initialOrientationGamma = 0;
  5542. this._initialOrientationBeta = 0;
  5543. };
  5544. DeviceOrientationCamera.prototype._checkInputs = function () {
  5545. if (!this._offsetX) {
  5546. return;
  5547. }
  5548. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5549. var speed = this._computeLocalCameraSpeed();
  5550. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5551. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5552. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5553. };
  5554. return DeviceOrientationCamera;
  5555. })(BABYLON.FreeCamera);
  5556. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5557. })(BABYLON || (BABYLON = {}));
  5558. var __extends = this.__extends || function (d, b) {
  5559. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5560. function __() { this.constructor = d; }
  5561. __.prototype = b.prototype;
  5562. d.prototype = new __();
  5563. };
  5564. var BABYLON;
  5565. (function (BABYLON) {
  5566. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5567. var ArcRotateCamera = (function (_super) {
  5568. __extends(ArcRotateCamera, _super);
  5569. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5570. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5571. this.alpha = alpha;
  5572. this.beta = beta;
  5573. this.radius = radius;
  5574. this.target = target;
  5575. this.inertialAlphaOffset = 0;
  5576. this.inertialBetaOffset = 0;
  5577. this.inertialRadiusOffset = 0;
  5578. this.lowerAlphaLimit = null;
  5579. this.upperAlphaLimit = null;
  5580. this.lowerBetaLimit = 0.01;
  5581. this.upperBetaLimit = Math.PI;
  5582. this.lowerRadiusLimit = null;
  5583. this.upperRadiusLimit = null;
  5584. this.angularSensibility = 1000.0;
  5585. this.wheelPrecision = 3.0;
  5586. this.keysUp = [38];
  5587. this.keysDown = [40];
  5588. this.keysLeft = [37];
  5589. this.keysRight = [39];
  5590. this.zoomOnFactor = 1;
  5591. this._keys = [];
  5592. this._viewMatrix = new BABYLON.Matrix();
  5593. this.checkCollisions = false;
  5594. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5595. this._collider = new BABYLON.Collider();
  5596. this._previousPosition = BABYLON.Vector3.Zero();
  5597. this._collisionVelocity = BABYLON.Vector3.Zero();
  5598. this._newPosition = BABYLON.Vector3.Zero();
  5599. this.getViewMatrix();
  5600. }
  5601. ArcRotateCamera.prototype._getTargetPosition = function () {
  5602. return this.target.position || this.target;
  5603. };
  5604. ArcRotateCamera.prototype._initCache = function () {
  5605. _super.prototype._initCache.call(this);
  5606. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5607. this._cache.alpha = undefined;
  5608. this._cache.beta = undefined;
  5609. this._cache.radius = undefined;
  5610. };
  5611. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5612. if (!ignoreParentClass) {
  5613. _super.prototype._updateCache.call(this);
  5614. }
  5615. this._cache.target.copyFrom(this._getTargetPosition());
  5616. this._cache.alpha = this.alpha;
  5617. this._cache.beta = this.beta;
  5618. this._cache.radius = this.radius;
  5619. };
  5620. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5621. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5622. return false;
  5623. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5624. };
  5625. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5626. var _this = this;
  5627. var previousPosition;
  5628. var pointerId;
  5629. if (this._attachedElement) {
  5630. return;
  5631. }
  5632. this._attachedElement = element;
  5633. var engine = this.getEngine();
  5634. if (this._onPointerDown === undefined) {
  5635. this._onPointerDown = function (evt) {
  5636. if (pointerId) {
  5637. return;
  5638. }
  5639. pointerId = evt.pointerId;
  5640. previousPosition = {
  5641. x: evt.clientX,
  5642. y: evt.clientY
  5643. };
  5644. if (!noPreventDefault) {
  5645. evt.preventDefault();
  5646. }
  5647. };
  5648. this._onPointerUp = function (evt) {
  5649. previousPosition = null;
  5650. pointerId = null;
  5651. if (!noPreventDefault) {
  5652. evt.preventDefault();
  5653. }
  5654. };
  5655. this._onPointerMove = function (evt) {
  5656. if (!previousPosition) {
  5657. return;
  5658. }
  5659. if (pointerId !== evt.pointerId) {
  5660. return;
  5661. }
  5662. var offsetX = evt.clientX - previousPosition.x;
  5663. var offsetY = evt.clientY - previousPosition.y;
  5664. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5665. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5666. previousPosition = {
  5667. x: evt.clientX,
  5668. y: evt.clientY
  5669. };
  5670. if (!noPreventDefault) {
  5671. evt.preventDefault();
  5672. }
  5673. };
  5674. this._onMouseMove = function (evt) {
  5675. if (!engine.isPointerLock) {
  5676. return;
  5677. }
  5678. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5679. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5680. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5681. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5682. if (!noPreventDefault) {
  5683. evt.preventDefault();
  5684. }
  5685. };
  5686. this._wheel = function (event) {
  5687. var delta = 0;
  5688. if (event.wheelDelta) {
  5689. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5690. } else if (event.detail) {
  5691. delta = -event.detail / _this.wheelPrecision;
  5692. }
  5693. if (delta)
  5694. _this.inertialRadiusOffset += delta;
  5695. if (event.preventDefault) {
  5696. if (!noPreventDefault) {
  5697. event.preventDefault();
  5698. }
  5699. }
  5700. };
  5701. this._onKeyDown = function (evt) {
  5702. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5703. var index = _this._keys.indexOf(evt.keyCode);
  5704. if (index === -1) {
  5705. _this._keys.push(evt.keyCode);
  5706. }
  5707. if (evt.preventDefault) {
  5708. if (!noPreventDefault) {
  5709. evt.preventDefault();
  5710. }
  5711. }
  5712. }
  5713. };
  5714. this._onKeyUp = function (evt) {
  5715. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5716. var index = _this._keys.indexOf(evt.keyCode);
  5717. if (index >= 0) {
  5718. _this._keys.splice(index, 1);
  5719. }
  5720. if (evt.preventDefault) {
  5721. if (!noPreventDefault) {
  5722. evt.preventDefault();
  5723. }
  5724. }
  5725. }
  5726. };
  5727. this._onLostFocus = function () {
  5728. _this._keys = [];
  5729. pointerId = null;
  5730. };
  5731. this._onGestureStart = function (e) {
  5732. if (window.MSGesture === undefined) {
  5733. return;
  5734. }
  5735. if (!_this._MSGestureHandler) {
  5736. _this._MSGestureHandler = new MSGesture();
  5737. _this._MSGestureHandler.target = element;
  5738. }
  5739. _this._MSGestureHandler.addPointer(e.pointerId);
  5740. };
  5741. this._onGesture = function (e) {
  5742. _this.radius *= e.scale;
  5743. if (e.preventDefault) {
  5744. if (!noPreventDefault) {
  5745. e.stopPropagation();
  5746. e.preventDefault();
  5747. }
  5748. }
  5749. };
  5750. this._reset = function () {
  5751. _this._keys = [];
  5752. _this.inertialAlphaOffset = 0;
  5753. _this.inertialBetaOffset = 0;
  5754. _this.inertialRadiusOffset = 0;
  5755. previousPosition = null;
  5756. pointerId = null;
  5757. };
  5758. }
  5759. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5760. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5761. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5762. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5763. element.addEventListener("mousemove", this._onMouseMove, false);
  5764. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5765. element.addEventListener("MSGestureChange", this._onGesture, false);
  5766. element.addEventListener('mousewheel', this._wheel, false);
  5767. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5768. BABYLON.Tools.RegisterTopRootEvents([
  5769. { name: "keydown", handler: this._onKeyDown },
  5770. { name: "keyup", handler: this._onKeyUp },
  5771. { name: "blur", handler: this._onLostFocus }
  5772. ]);
  5773. };
  5774. ArcRotateCamera.prototype.detachControl = function (element) {
  5775. if (this._attachedElement != element) {
  5776. return;
  5777. }
  5778. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5779. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5780. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5781. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5782. element.removeEventListener("mousemove", this._onMouseMove);
  5783. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5784. element.removeEventListener("MSGestureChange", this._onGesture);
  5785. element.removeEventListener('mousewheel', this._wheel);
  5786. element.removeEventListener('DOMMouseScroll', this._wheel);
  5787. BABYLON.Tools.UnregisterTopRootEvents([
  5788. { name: "keydown", handler: this._onKeyDown },
  5789. { name: "keyup", handler: this._onKeyUp },
  5790. { name: "blur", handler: this._onLostFocus }
  5791. ]);
  5792. this._MSGestureHandler = null;
  5793. this._attachedElement = null;
  5794. if (this._reset) {
  5795. this._reset();
  5796. }
  5797. };
  5798. ArcRotateCamera.prototype._update = function () {
  5799. for (var index = 0; index < this._keys.length; index++) {
  5800. var keyCode = this._keys[index];
  5801. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5802. this.inertialAlphaOffset -= 0.01;
  5803. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5804. this.inertialBetaOffset -= 0.01;
  5805. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5806. this.inertialAlphaOffset += 0.01;
  5807. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5808. this.inertialBetaOffset += 0.01;
  5809. }
  5810. }
  5811. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5812. this.alpha += this.inertialAlphaOffset;
  5813. this.beta += this.inertialBetaOffset;
  5814. this.radius -= this.inertialRadiusOffset;
  5815. this.inertialAlphaOffset *= this.inertia;
  5816. this.inertialBetaOffset *= this.inertia;
  5817. this.inertialRadiusOffset *= this.inertia;
  5818. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5819. this.inertialAlphaOffset = 0;
  5820. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5821. this.inertialBetaOffset = 0;
  5822. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5823. this.inertialRadiusOffset = 0;
  5824. }
  5825. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5826. this.alpha = this.lowerAlphaLimit;
  5827. }
  5828. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5829. this.alpha = this.upperAlphaLimit;
  5830. }
  5831. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5832. this.beta = this.lowerBetaLimit;
  5833. }
  5834. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5835. this.beta = this.upperBetaLimit;
  5836. }
  5837. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5838. this.radius = this.lowerRadiusLimit;
  5839. }
  5840. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5841. this.radius = this.upperRadiusLimit;
  5842. }
  5843. };
  5844. ArcRotateCamera.prototype.setPosition = function (position) {
  5845. var radiusv3 = position.subtract(this._getTargetPosition());
  5846. this.radius = radiusv3.length();
  5847. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5848. if (radiusv3.z < 0) {
  5849. this.alpha = 2 * Math.PI - this.alpha;
  5850. }
  5851. this.beta = Math.acos(radiusv3.y / this.radius);
  5852. };
  5853. ArcRotateCamera.prototype._getViewMatrix = function () {
  5854. var cosa = Math.cos(this.alpha);
  5855. var sina = Math.sin(this.alpha);
  5856. var cosb = Math.cos(this.beta);
  5857. var sinb = Math.sin(this.beta);
  5858. var target = this._getTargetPosition();
  5859. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5860. if (this.checkCollisions) {
  5861. this._collider.radius = this.collisionRadius;
  5862. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5863. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5864. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5865. this.position.copyFrom(this._previousPosition);
  5866. this.alpha = this._previousAlpha;
  5867. this.beta = this._previousBeta;
  5868. this.radius = this._previousRadius;
  5869. if (this.onCollide) {
  5870. this.onCollide(this._collider.collidedMesh);
  5871. }
  5872. }
  5873. }
  5874. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5875. this._previousAlpha = this.alpha;
  5876. this._previousBeta = this.beta;
  5877. this._previousRadius = this.radius;
  5878. this._previousPosition.copyFrom(this.position);
  5879. return this._viewMatrix;
  5880. };
  5881. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5882. meshes = meshes || this.getScene().meshes;
  5883. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5884. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5885. this.radius = distance * this.zoomOnFactor;
  5886. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5887. };
  5888. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5889. var meshesOrMinMaxVector;
  5890. var distance;
  5891. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5892. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5893. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5894. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5895. } else {
  5896. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5897. distance = meshesOrMinMaxVectorAndDistance.distance;
  5898. }
  5899. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5900. this.maxZ = distance * 2;
  5901. };
  5902. return ArcRotateCamera;
  5903. })(BABYLON.Camera);
  5904. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5905. })(BABYLON || (BABYLON = {}));
  5906. var BABYLON;
  5907. (function (BABYLON) {
  5908. var Scene = (function () {
  5909. function Scene(engine) {
  5910. this.autoClear = true;
  5911. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5912. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5913. this.forceWireframe = false;
  5914. this.cameraToUseForPointers = null;
  5915. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5916. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5917. this.fogDensity = 0.1;
  5918. this.fogStart = 0;
  5919. this.fogEnd = 1000.0;
  5920. this.lightsEnabled = true;
  5921. this.lights = new Array();
  5922. this.cameras = new Array();
  5923. this.activeCameras = new Array();
  5924. this.meshes = new Array();
  5925. this._geometries = new Array();
  5926. this.materials = new Array();
  5927. this.multiMaterials = new Array();
  5928. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5929. this.texturesEnabled = true;
  5930. this.textures = new Array();
  5931. this.particlesEnabled = true;
  5932. this.particleSystems = new Array();
  5933. this.spriteManagers = new Array();
  5934. this.layers = new Array();
  5935. this.skeletons = new Array();
  5936. this.lensFlareSystems = new Array();
  5937. this.collisionsEnabled = true;
  5938. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5939. this.postProcessesEnabled = true;
  5940. this.renderTargetsEnabled = true;
  5941. this.customRenderTargets = new Array();
  5942. this.importedMeshesFiles = new Array();
  5943. this._actionManagers = new Array();
  5944. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5945. this._totalVertices = 0;
  5946. this._activeVertices = 0;
  5947. this._activeParticles = 0;
  5948. this._lastFrameDuration = 0;
  5949. this._evaluateActiveMeshesDuration = 0;
  5950. this._renderTargetsDuration = 0;
  5951. this._particlesDuration = 0;
  5952. this._renderDuration = 0;
  5953. this._spritesDuration = 0;
  5954. this._animationRatio = 0;
  5955. this._renderId = 0;
  5956. this._executeWhenReadyTimeoutId = -1;
  5957. this._toBeDisposed = new BABYLON.SmartArray(256);
  5958. this._onReadyCallbacks = new Array();
  5959. this._pendingData = [];
  5960. this._onBeforeRenderCallbacks = new Array();
  5961. this._activeMeshes = new BABYLON.SmartArray(256);
  5962. this._processedMaterials = new BABYLON.SmartArray(256);
  5963. this._renderTargets = new BABYLON.SmartArray(256);
  5964. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5965. this._activeSkeletons = new BABYLON.SmartArray(32);
  5966. this._activeAnimatables = new Array();
  5967. this._transformMatrix = BABYLON.Matrix.Zero();
  5968. this._scaledPosition = BABYLON.Vector3.Zero();
  5969. this._scaledVelocity = BABYLON.Vector3.Zero();
  5970. this._engine = engine;
  5971. engine.scenes.push(this);
  5972. this._renderingManager = new BABYLON.RenderingManager(this);
  5973. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5974. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5975. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5976. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5977. this.attachControl();
  5978. }
  5979. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5980. get: function () {
  5981. return this._meshUnderPointer;
  5982. },
  5983. enumerable: true,
  5984. configurable: true
  5985. });
  5986. Object.defineProperty(Scene.prototype, "pointerX", {
  5987. get: function () {
  5988. return this._pointerX;
  5989. },
  5990. enumerable: true,
  5991. configurable: true
  5992. });
  5993. Object.defineProperty(Scene.prototype, "pointerY", {
  5994. get: function () {
  5995. return this._pointerY;
  5996. },
  5997. enumerable: true,
  5998. configurable: true
  5999. });
  6000. Scene.prototype.getBoundingBoxRenderer = function () {
  6001. return this._boundingBoxRenderer;
  6002. };
  6003. Scene.prototype.getOutlineRenderer = function () {
  6004. return this._outlineRenderer;
  6005. };
  6006. Scene.prototype.getEngine = function () {
  6007. return this._engine;
  6008. };
  6009. Scene.prototype.getTotalVertices = function () {
  6010. return this._totalVertices;
  6011. };
  6012. Scene.prototype.getActiveVertices = function () {
  6013. return this._activeVertices;
  6014. };
  6015. Scene.prototype.getActiveParticles = function () {
  6016. return this._activeParticles;
  6017. };
  6018. Scene.prototype.getLastFrameDuration = function () {
  6019. return this._lastFrameDuration;
  6020. };
  6021. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6022. return this._evaluateActiveMeshesDuration;
  6023. };
  6024. Scene.prototype.getActiveMeshes = function () {
  6025. return this._activeMeshes;
  6026. };
  6027. Scene.prototype.getRenderTargetsDuration = function () {
  6028. return this._renderTargetsDuration;
  6029. };
  6030. Scene.prototype.getRenderDuration = function () {
  6031. return this._renderDuration;
  6032. };
  6033. Scene.prototype.getParticlesDuration = function () {
  6034. return this._particlesDuration;
  6035. };
  6036. Scene.prototype.getSpritesDuration = function () {
  6037. return this._spritesDuration;
  6038. };
  6039. Scene.prototype.getAnimationRatio = function () {
  6040. return this._animationRatio;
  6041. };
  6042. Scene.prototype.getRenderId = function () {
  6043. return this._renderId;
  6044. };
  6045. Scene.prototype._updatePointerPosition = function (evt) {
  6046. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6047. this._pointerX = evt.clientX - canvasRect.left;
  6048. this._pointerY = evt.clientY - canvasRect.top;
  6049. if (this.cameraToUseForPointers) {
  6050. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6051. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6052. }
  6053. };
  6054. Scene.prototype.attachControl = function () {
  6055. var _this = this;
  6056. this._onPointerMove = function (evt) {
  6057. var canvas = _this._engine.getRenderingCanvas();
  6058. _this._updatePointerPosition(evt);
  6059. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6060. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6061. }, false, _this.cameraToUseForPointers);
  6062. if (pickResult.hit) {
  6063. _this._meshUnderPointer = pickResult.pickedMesh;
  6064. _this.setPointerOverMesh(pickResult.pickedMesh);
  6065. canvas.style.cursor = "pointer";
  6066. } else {
  6067. _this.setPointerOverMesh(null);
  6068. canvas.style.cursor = "";
  6069. _this._meshUnderPointer = null;
  6070. }
  6071. };
  6072. this._onPointerDown = function (evt) {
  6073. var predicate = null;
  6074. if (!_this.onPointerDown) {
  6075. predicate = function (mesh) {
  6076. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6077. };
  6078. }
  6079. _this._updatePointerPosition(evt);
  6080. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6081. if (pickResult.hit) {
  6082. if (pickResult.pickedMesh.actionManager) {
  6083. switch (evt.button) {
  6084. case 0:
  6085. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6086. break;
  6087. case 1:
  6088. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6089. break;
  6090. case 2:
  6091. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6092. break;
  6093. }
  6094. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6095. }
  6096. }
  6097. if (_this.onPointerDown) {
  6098. _this.onPointerDown(evt, pickResult);
  6099. }
  6100. };
  6101. this._onKeyDown = function (evt) {
  6102. if (_this.actionManager) {
  6103. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6104. }
  6105. };
  6106. this._onKeyUp = function (evt) {
  6107. if (_this.actionManager) {
  6108. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6109. }
  6110. };
  6111. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6112. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6113. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6114. window.addEventListener("keydown", this._onKeyDown, false);
  6115. window.addEventListener("keyup", this._onKeyUp, false);
  6116. };
  6117. Scene.prototype.detachControl = function () {
  6118. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6119. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6120. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6121. window.removeEventListener("keydown", this._onKeyDown);
  6122. window.removeEventListener("keyup", this._onKeyUp);
  6123. };
  6124. Scene.prototype.isReady = function () {
  6125. if (this._pendingData.length > 0) {
  6126. return false;
  6127. }
  6128. for (var index = 0; index < this._geometries.length; index++) {
  6129. var geometry = this._geometries[index];
  6130. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6131. return false;
  6132. }
  6133. }
  6134. for (index = 0; index < this.meshes.length; index++) {
  6135. var mesh = this.meshes[index];
  6136. if (!mesh.isReady()) {
  6137. return false;
  6138. }
  6139. var mat = mesh.material;
  6140. if (mat) {
  6141. if (!mat.isReady(mesh)) {
  6142. return false;
  6143. }
  6144. }
  6145. }
  6146. return true;
  6147. };
  6148. Scene.prototype.registerBeforeRender = function (func) {
  6149. this._onBeforeRenderCallbacks.push(func);
  6150. };
  6151. Scene.prototype.unregisterBeforeRender = function (func) {
  6152. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6153. if (index > -1) {
  6154. this._onBeforeRenderCallbacks.splice(index, 1);
  6155. }
  6156. };
  6157. Scene.prototype._addPendingData = function (data) {
  6158. this._pendingData.push(data);
  6159. };
  6160. Scene.prototype._removePendingData = function (data) {
  6161. var index = this._pendingData.indexOf(data);
  6162. if (index !== -1) {
  6163. this._pendingData.splice(index, 1);
  6164. }
  6165. };
  6166. Scene.prototype.getWaitingItemsCount = function () {
  6167. return this._pendingData.length;
  6168. };
  6169. Scene.prototype.executeWhenReady = function (func) {
  6170. var _this = this;
  6171. this._onReadyCallbacks.push(func);
  6172. if (this._executeWhenReadyTimeoutId !== -1) {
  6173. return;
  6174. }
  6175. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6176. _this._checkIsReady();
  6177. }, 150);
  6178. };
  6179. Scene.prototype._checkIsReady = function () {
  6180. var _this = this;
  6181. if (this.isReady()) {
  6182. this._onReadyCallbacks.forEach(function (func) {
  6183. func();
  6184. });
  6185. this._onReadyCallbacks = [];
  6186. this._executeWhenReadyTimeoutId = -1;
  6187. return;
  6188. }
  6189. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6190. _this._checkIsReady();
  6191. }, 150);
  6192. };
  6193. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6194. if (speedRatio === undefined) {
  6195. speedRatio = 1.0;
  6196. }
  6197. this.stopAnimation(target);
  6198. if (!animatable) {
  6199. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6200. }
  6201. if (target.animations) {
  6202. animatable.appendAnimations(target, target.animations);
  6203. }
  6204. if (target.getAnimatables) {
  6205. var animatables = target.getAnimatables();
  6206. for (var index = 0; index < animatables.length; index++) {
  6207. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6208. }
  6209. }
  6210. return animatable;
  6211. };
  6212. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6213. if (speedRatio === undefined) {
  6214. speedRatio = 1.0;
  6215. }
  6216. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6217. return animatable;
  6218. };
  6219. Scene.prototype.getAnimatableByTarget = function (target) {
  6220. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6221. if (this._activeAnimatables[index].target === target) {
  6222. return this._activeAnimatables[index];
  6223. }
  6224. }
  6225. return null;
  6226. };
  6227. Scene.prototype.stopAnimation = function (target) {
  6228. var animatable = this.getAnimatableByTarget(target);
  6229. if (animatable) {
  6230. animatable.stop();
  6231. }
  6232. };
  6233. Scene.prototype._animate = function () {
  6234. if (!this._animationStartDate) {
  6235. this._animationStartDate = new Date().getTime();
  6236. }
  6237. var now = new Date().getTime();
  6238. var delay = now - this._animationStartDate;
  6239. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6240. if (!this._activeAnimatables[index]._animate(delay)) {
  6241. this._activeAnimatables.splice(index, 1);
  6242. index--;
  6243. }
  6244. }
  6245. };
  6246. Scene.prototype.getViewMatrix = function () {
  6247. return this._viewMatrix;
  6248. };
  6249. Scene.prototype.getProjectionMatrix = function () {
  6250. return this._projectionMatrix;
  6251. };
  6252. Scene.prototype.getTransformMatrix = function () {
  6253. return this._transformMatrix;
  6254. };
  6255. Scene.prototype.setTransformMatrix = function (view, projection) {
  6256. this._viewMatrix = view;
  6257. this._projectionMatrix = projection;
  6258. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6259. };
  6260. Scene.prototype.setActiveCameraByID = function (id) {
  6261. var camera = this.getCameraByID(id);
  6262. if (camera) {
  6263. this.activeCamera = camera;
  6264. return camera;
  6265. }
  6266. return null;
  6267. };
  6268. Scene.prototype.setActiveCameraByName = function (name) {
  6269. var camera = this.getCameraByName(name);
  6270. if (camera) {
  6271. this.activeCamera = camera;
  6272. return camera;
  6273. }
  6274. return null;
  6275. };
  6276. Scene.prototype.getMaterialByID = function (id) {
  6277. for (var index = 0; index < this.materials.length; index++) {
  6278. if (this.materials[index].id === id) {
  6279. return this.materials[index];
  6280. }
  6281. }
  6282. return null;
  6283. };
  6284. Scene.prototype.getMaterialByName = function (name) {
  6285. for (var index = 0; index < this.materials.length; index++) {
  6286. if (this.materials[index].name === name) {
  6287. return this.materials[index];
  6288. }
  6289. }
  6290. return null;
  6291. };
  6292. Scene.prototype.getCameraByID = function (id) {
  6293. for (var index = 0; index < this.cameras.length; index++) {
  6294. if (this.cameras[index].id === id) {
  6295. return this.cameras[index];
  6296. }
  6297. }
  6298. return null;
  6299. };
  6300. Scene.prototype.getCameraByName = function (name) {
  6301. for (var index = 0; index < this.cameras.length; index++) {
  6302. if (this.cameras[index].name === name) {
  6303. return this.cameras[index];
  6304. }
  6305. }
  6306. return null;
  6307. };
  6308. Scene.prototype.getLightByName = function (name) {
  6309. for (var index = 0; index < this.lights.length; index++) {
  6310. if (this.lights[index].name === name) {
  6311. return this.lights[index];
  6312. }
  6313. }
  6314. return null;
  6315. };
  6316. Scene.prototype.getLightByID = function (id) {
  6317. for (var index = 0; index < this.lights.length; index++) {
  6318. if (this.lights[index].id === id) {
  6319. return this.lights[index];
  6320. }
  6321. }
  6322. return null;
  6323. };
  6324. Scene.prototype.getGeometryByID = function (id) {
  6325. for (var index = 0; index < this._geometries.length; index++) {
  6326. if (this._geometries[index].id === id) {
  6327. return this._geometries[index];
  6328. }
  6329. }
  6330. return null;
  6331. };
  6332. Scene.prototype.pushGeometry = function (geometry, force) {
  6333. if (!force && this.getGeometryByID(geometry.id)) {
  6334. return false;
  6335. }
  6336. this._geometries.push(geometry);
  6337. return true;
  6338. };
  6339. Scene.prototype.getGeometries = function () {
  6340. return this._geometries;
  6341. };
  6342. Scene.prototype.getMeshByID = function (id) {
  6343. for (var index = 0; index < this.meshes.length; index++) {
  6344. if (this.meshes[index].id === id) {
  6345. return this.meshes[index];
  6346. }
  6347. }
  6348. return null;
  6349. };
  6350. Scene.prototype.getLastMeshByID = function (id) {
  6351. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6352. if (this.meshes[index].id === id) {
  6353. return this.meshes[index];
  6354. }
  6355. }
  6356. return null;
  6357. };
  6358. Scene.prototype.getLastEntryByID = function (id) {
  6359. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6360. if (this.meshes[index].id === id) {
  6361. return this.meshes[index];
  6362. }
  6363. }
  6364. for (index = this.cameras.length - 1; index >= 0; index--) {
  6365. if (this.cameras[index].id === id) {
  6366. return this.cameras[index];
  6367. }
  6368. }
  6369. for (index = this.lights.length - 1; index >= 0; index--) {
  6370. if (this.lights[index].id === id) {
  6371. return this.lights[index];
  6372. }
  6373. }
  6374. return null;
  6375. };
  6376. Scene.prototype.getMeshByName = function (name) {
  6377. for (var index = 0; index < this.meshes.length; index++) {
  6378. if (this.meshes[index].name === name) {
  6379. return this.meshes[index];
  6380. }
  6381. }
  6382. return null;
  6383. };
  6384. Scene.prototype.getLastSkeletonByID = function (id) {
  6385. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6386. if (this.skeletons[index].id === id) {
  6387. return this.skeletons[index];
  6388. }
  6389. }
  6390. return null;
  6391. };
  6392. Scene.prototype.getSkeletonById = function (id) {
  6393. for (var index = 0; index < this.skeletons.length; index++) {
  6394. if (this.skeletons[index].id === id) {
  6395. return this.skeletons[index];
  6396. }
  6397. }
  6398. return null;
  6399. };
  6400. Scene.prototype.getSkeletonByName = function (name) {
  6401. for (var index = 0; index < this.skeletons.length; index++) {
  6402. if (this.skeletons[index].name === name) {
  6403. return this.skeletons[index];
  6404. }
  6405. }
  6406. return null;
  6407. };
  6408. Scene.prototype.isActiveMesh = function (mesh) {
  6409. return (this._activeMeshes.indexOf(mesh) !== -1);
  6410. };
  6411. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6412. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6413. var material = subMesh.getMaterial();
  6414. if (mesh.showSubMeshesBoundingBox) {
  6415. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6416. }
  6417. if (material) {
  6418. if (material.getRenderTargetTextures) {
  6419. if (this._processedMaterials.indexOf(material) === -1) {
  6420. this._processedMaterials.push(material);
  6421. this._renderTargets.concat(material.getRenderTargetTextures());
  6422. }
  6423. }
  6424. this._activeVertices += subMesh.verticesCount;
  6425. this._renderingManager.dispatch(subMesh);
  6426. }
  6427. }
  6428. };
  6429. Scene.prototype._evaluateActiveMeshes = function () {
  6430. this._activeMeshes.reset();
  6431. this._renderingManager.reset();
  6432. this._processedMaterials.reset();
  6433. this._activeParticleSystems.reset();
  6434. this._activeSkeletons.reset();
  6435. this._boundingBoxRenderer.reset();
  6436. if (!this._frustumPlanes) {
  6437. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6438. } else {
  6439. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6440. }
  6441. var meshes;
  6442. var len;
  6443. if (this._selectionOctree) {
  6444. var selection = this._selectionOctree.select(this._frustumPlanes);
  6445. meshes = selection.data;
  6446. len = selection.length;
  6447. } else {
  6448. len = this.meshes.length;
  6449. meshes = this.meshes;
  6450. }
  6451. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6452. var mesh = meshes[meshIndex];
  6453. this._totalVertices += mesh.getTotalVertices();
  6454. if (!mesh.isReady()) {
  6455. continue;
  6456. }
  6457. mesh.computeWorldMatrix();
  6458. mesh._preActivate();
  6459. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6460. this._meshesForIntersections.pushNoDuplicate(mesh);
  6461. }
  6462. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6463. this._activeMeshes.push(mesh);
  6464. mesh._activate(this._renderId);
  6465. this._activeMesh(mesh);
  6466. }
  6467. }
  6468. var beforeParticlesDate = new Date().getTime();
  6469. if (this.particlesEnabled) {
  6470. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6471. var particleSystem = this.particleSystems[particleIndex];
  6472. if (!particleSystem.isStarted()) {
  6473. continue;
  6474. }
  6475. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6476. this._activeParticleSystems.push(particleSystem);
  6477. particleSystem.animate();
  6478. }
  6479. }
  6480. }
  6481. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6482. };
  6483. Scene.prototype._activeMesh = function (mesh) {
  6484. if (mesh.skeleton) {
  6485. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6486. }
  6487. if (mesh.showBoundingBox) {
  6488. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6489. }
  6490. if (mesh.subMeshes) {
  6491. var len;
  6492. var subMeshes;
  6493. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6494. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6495. len = intersections.length;
  6496. subMeshes = intersections.data;
  6497. } else {
  6498. subMeshes = mesh.subMeshes;
  6499. len = subMeshes.length;
  6500. }
  6501. for (var subIndex = 0; subIndex < len; subIndex++) {
  6502. var subMesh = subMeshes[subIndex];
  6503. this._evaluateSubMesh(subMesh, mesh);
  6504. }
  6505. }
  6506. };
  6507. Scene.prototype.updateTransformMatrix = function (force) {
  6508. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6509. };
  6510. Scene.prototype._renderForCamera = function (camera) {
  6511. var engine = this._engine;
  6512. this.activeCamera = camera;
  6513. if (!this.activeCamera)
  6514. throw new Error("Active camera not set");
  6515. engine.setViewport(this.activeCamera.viewport);
  6516. this._renderId++;
  6517. this.updateTransformMatrix();
  6518. if (this.beforeCameraRender) {
  6519. this.beforeCameraRender(this.activeCamera);
  6520. }
  6521. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6522. this._evaluateActiveMeshes();
  6523. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6524. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6525. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6526. skeleton.prepare();
  6527. }
  6528. var beforeRenderTargetDate = new Date().getTime();
  6529. if (this.renderTargetsEnabled) {
  6530. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6531. var renderTarget = this._renderTargets.data[renderIndex];
  6532. if (renderTarget._shouldRender()) {
  6533. this._renderId++;
  6534. renderTarget.render();
  6535. }
  6536. }
  6537. this._renderId++;
  6538. }
  6539. if (this._renderTargets.length > 0) {
  6540. engine.restoreDefaultFramebuffer();
  6541. }
  6542. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6543. this.postProcessManager._prepareFrame();
  6544. var beforeRenderDate = new Date().getTime();
  6545. if (this.layers.length) {
  6546. engine.setDepthBuffer(false);
  6547. var layerIndex;
  6548. var layer;
  6549. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6550. layer = this.layers[layerIndex];
  6551. if (layer.isBackground) {
  6552. layer.render();
  6553. }
  6554. }
  6555. engine.setDepthBuffer(true);
  6556. }
  6557. this._renderingManager.render(null, null, true, true);
  6558. this._boundingBoxRenderer.render();
  6559. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6560. this.lensFlareSystems[lensFlareSystemIndex].render();
  6561. }
  6562. if (this.layers.length) {
  6563. engine.setDepthBuffer(false);
  6564. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6565. layer = this.layers[layerIndex];
  6566. if (!layer.isBackground) {
  6567. layer.render();
  6568. }
  6569. }
  6570. engine.setDepthBuffer(true);
  6571. }
  6572. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6573. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6574. this.activeCamera._updateFromScene();
  6575. this._renderTargets.reset();
  6576. if (this.afterCameraRender) {
  6577. this.afterCameraRender(this.activeCamera);
  6578. }
  6579. };
  6580. Scene.prototype._processSubCameras = function (camera) {
  6581. if (camera.subCameras.length == 0) {
  6582. this._renderForCamera(camera);
  6583. return;
  6584. }
  6585. for (var index = 0; index < camera.subCameras.length; index++) {
  6586. this._renderForCamera(camera.subCameras[index]);
  6587. }
  6588. this.activeCamera = camera;
  6589. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6590. this.activeCamera._updateFromScene();
  6591. };
  6592. Scene.prototype._checkIntersections = function () {
  6593. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6594. var sourceMesh = this._meshesForIntersections.data[index];
  6595. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6596. var action = sourceMesh.actionManager.actions[actionIndex];
  6597. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6598. var otherMesh = action.getTriggerParameter();
  6599. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6600. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6601. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6602. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6603. sourceMesh._intersectionsInProgress.push(otherMesh);
  6604. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6605. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6606. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6607. if (indexOfOther > -1) {
  6608. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6609. }
  6610. }
  6611. }
  6612. }
  6613. }
  6614. };
  6615. Scene.prototype.render = function () {
  6616. var startDate = new Date().getTime();
  6617. this._particlesDuration = 0;
  6618. this._spritesDuration = 0;
  6619. this._activeParticles = 0;
  6620. this._renderDuration = 0;
  6621. this._evaluateActiveMeshesDuration = 0;
  6622. this._totalVertices = 0;
  6623. this._activeVertices = 0;
  6624. this._meshesForIntersections.reset();
  6625. if (this.actionManager) {
  6626. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6627. }
  6628. if (this.beforeRender) {
  6629. this.beforeRender();
  6630. }
  6631. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6632. this._onBeforeRenderCallbacks[callbackIndex]();
  6633. }
  6634. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6635. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6636. this._animate();
  6637. if (this._physicsEngine) {
  6638. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6639. }
  6640. var beforeRenderTargetDate = new Date().getTime();
  6641. var engine = this.getEngine();
  6642. if (this.renderTargetsEnabled) {
  6643. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6644. var renderTarget = this.customRenderTargets[customIndex];
  6645. if (renderTarget._shouldRender()) {
  6646. this._renderId++;
  6647. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6648. if (!this.activeCamera)
  6649. throw new Error("Active camera not set");
  6650. engine.setViewport(this.activeCamera.viewport);
  6651. this.updateTransformMatrix();
  6652. renderTarget.render();
  6653. }
  6654. }
  6655. this._renderId++;
  6656. }
  6657. if (this.customRenderTargets.length > 0) {
  6658. engine.restoreDefaultFramebuffer();
  6659. }
  6660. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6661. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6662. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6663. var light = this.lights[lightIndex];
  6664. var shadowGenerator = light.getShadowGenerator();
  6665. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6666. this._renderTargets.push(shadowGenerator.getShadowMap());
  6667. }
  6668. }
  6669. this.postProcessRenderPipelineManager.update();
  6670. if (this.activeCameras.length > 0) {
  6671. var currentRenderId = this._renderId;
  6672. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6673. this._renderId = currentRenderId;
  6674. this._processSubCameras(this.activeCameras[cameraIndex]);
  6675. }
  6676. } else {
  6677. if (!this.activeCamera) {
  6678. throw new Error("No camera defined");
  6679. }
  6680. this._processSubCameras(this.activeCamera);
  6681. }
  6682. this._checkIntersections();
  6683. if (this.afterRender) {
  6684. this.afterRender();
  6685. }
  6686. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6687. this._toBeDisposed.data[index].dispose();
  6688. this._toBeDisposed[index] = null;
  6689. }
  6690. this._toBeDisposed.reset();
  6691. this._lastFrameDuration = new Date().getTime() - startDate;
  6692. };
  6693. Scene.prototype.dispose = function () {
  6694. this.beforeRender = null;
  6695. this.afterRender = null;
  6696. this.skeletons = [];
  6697. this._boundingBoxRenderer.dispose();
  6698. if (this.onDispose) {
  6699. this.onDispose();
  6700. }
  6701. this.detachControl();
  6702. var canvas = this._engine.getRenderingCanvas();
  6703. var index;
  6704. for (index = 0; index < this.cameras.length; index++) {
  6705. this.cameras[index].detachControl(canvas);
  6706. }
  6707. while (this.lights.length) {
  6708. this.lights[0].dispose();
  6709. }
  6710. while (this.meshes.length) {
  6711. this.meshes[0].dispose(true);
  6712. }
  6713. while (this.cameras.length) {
  6714. this.cameras[0].dispose();
  6715. }
  6716. while (this.materials.length) {
  6717. this.materials[0].dispose();
  6718. }
  6719. while (this.particleSystems.length) {
  6720. this.particleSystems[0].dispose();
  6721. }
  6722. while (this.spriteManagers.length) {
  6723. this.spriteManagers[0].dispose();
  6724. }
  6725. while (this.layers.length) {
  6726. this.layers[0].dispose();
  6727. }
  6728. while (this.textures.length) {
  6729. this.textures[0].dispose();
  6730. }
  6731. this.postProcessManager.dispose();
  6732. if (this._physicsEngine) {
  6733. this.disablePhysicsEngine();
  6734. }
  6735. index = this._engine.scenes.indexOf(this);
  6736. if (index > -1) {
  6737. this._engine.scenes.splice(index, 1);
  6738. }
  6739. this._engine.wipeCaches();
  6740. };
  6741. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6742. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6743. position.divideToRef(collider.radius, this._scaledPosition);
  6744. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6745. collider.retry = 0;
  6746. collider.initialVelocity = this._scaledVelocity;
  6747. collider.initialPosition = this._scaledPosition;
  6748. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6749. finalPosition.multiplyInPlace(collider.radius);
  6750. };
  6751. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6752. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6753. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6754. if (collider.retry >= maximumRetry) {
  6755. finalPosition.copyFrom(position);
  6756. return;
  6757. }
  6758. collider._initialize(position, velocity, closeDistance);
  6759. for (var index = 0; index < this.meshes.length; index++) {
  6760. var mesh = this.meshes[index];
  6761. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6762. mesh._checkCollision(collider);
  6763. }
  6764. }
  6765. if (!collider.collisionFound) {
  6766. position.addToRef(velocity, finalPosition);
  6767. return;
  6768. }
  6769. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6770. collider._getResponse(position, velocity);
  6771. }
  6772. if (velocity.length() <= closeDistance) {
  6773. finalPosition.copyFrom(position);
  6774. return;
  6775. }
  6776. collider.retry++;
  6777. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6778. };
  6779. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6780. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6781. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6782. if (!this._selectionOctree) {
  6783. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6784. }
  6785. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6786. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6787. for (var index = 0; index < this.meshes.length; index++) {
  6788. var mesh = this.meshes[index];
  6789. mesh.computeWorldMatrix(true);
  6790. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6791. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6792. BABYLON.Tools.CheckExtends(minBox, min, max);
  6793. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6794. }
  6795. this._selectionOctree.update(min, max, this.meshes);
  6796. return this._selectionOctree;
  6797. };
  6798. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6799. var engine = this._engine;
  6800. if (!camera) {
  6801. if (!this.activeCamera)
  6802. throw new Error("Active camera not set");
  6803. camera = this.activeCamera;
  6804. }
  6805. var cameraViewport = camera.viewport;
  6806. var viewport = cameraViewport.toGlobal(engine);
  6807. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6808. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6809. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6810. };
  6811. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6812. var pickingInfo = null;
  6813. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6814. var mesh = this.meshes[meshIndex];
  6815. if (predicate) {
  6816. if (!predicate(mesh)) {
  6817. continue;
  6818. }
  6819. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6820. continue;
  6821. }
  6822. var world = mesh.getWorldMatrix();
  6823. var ray = rayFunction(world);
  6824. var result = mesh.intersects(ray, fastCheck);
  6825. if (!result || !result.hit)
  6826. continue;
  6827. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6828. continue;
  6829. pickingInfo = result;
  6830. if (fastCheck) {
  6831. break;
  6832. }
  6833. }
  6834. return pickingInfo || new BABYLON.PickingInfo();
  6835. };
  6836. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6837. var _this = this;
  6838. return this._internalPick(function (world) {
  6839. return _this.createPickingRay(x, y, world, camera);
  6840. }, predicate, fastCheck);
  6841. };
  6842. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6843. var _this = this;
  6844. return this._internalPick(function (world) {
  6845. if (!_this._pickWithRayInverseMatrix) {
  6846. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6847. }
  6848. world.invertToRef(_this._pickWithRayInverseMatrix);
  6849. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6850. }, predicate, fastCheck);
  6851. };
  6852. Scene.prototype.setPointerOverMesh = function (mesh) {
  6853. if (this._pointerOverMesh === mesh) {
  6854. return;
  6855. }
  6856. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6857. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6858. }
  6859. this._pointerOverMesh = mesh;
  6860. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6861. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6862. }
  6863. };
  6864. Scene.prototype.getPointerOverMesh = function () {
  6865. return this._pointerOverMesh;
  6866. };
  6867. Scene.prototype.getPhysicsEngine = function () {
  6868. return this._physicsEngine;
  6869. };
  6870. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6871. if (this._physicsEngine) {
  6872. return true;
  6873. }
  6874. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6875. if (!this._physicsEngine.isSupported()) {
  6876. this._physicsEngine = null;
  6877. return false;
  6878. }
  6879. this._physicsEngine._initialize(gravity);
  6880. return true;
  6881. };
  6882. Scene.prototype.disablePhysicsEngine = function () {
  6883. if (!this._physicsEngine) {
  6884. return;
  6885. }
  6886. this._physicsEngine.dispose();
  6887. this._physicsEngine = undefined;
  6888. };
  6889. Scene.prototype.isPhysicsEnabled = function () {
  6890. return this._physicsEngine !== undefined;
  6891. };
  6892. Scene.prototype.setGravity = function (gravity) {
  6893. if (!this._physicsEngine) {
  6894. return;
  6895. }
  6896. this._physicsEngine._setGravity(gravity);
  6897. };
  6898. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6899. if (parts.parts) {
  6900. options = parts;
  6901. parts = parts.parts;
  6902. }
  6903. if (!this._physicsEngine) {
  6904. return null;
  6905. }
  6906. for (var index = 0; index < parts.length; index++) {
  6907. var mesh = parts[index].mesh;
  6908. mesh._physicImpostor = parts[index].impostor;
  6909. mesh._physicsMass = options.mass / parts.length;
  6910. mesh._physicsFriction = options.friction;
  6911. mesh._physicRestitution = options.restitution;
  6912. }
  6913. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6914. };
  6915. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6916. for (var index = 0; index < compound.parts.length; index++) {
  6917. var mesh = compound.parts[index].mesh;
  6918. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6919. this._physicsEngine._unregisterMesh(mesh);
  6920. }
  6921. };
  6922. Scene.prototype._getByTags = function (list, tagsQuery) {
  6923. if (tagsQuery === undefined) {
  6924. return list;
  6925. }
  6926. var listByTags = [];
  6927. for (var i in list) {
  6928. var item = list[i];
  6929. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6930. listByTags.push(item);
  6931. }
  6932. }
  6933. return listByTags;
  6934. };
  6935. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6936. return this._getByTags(this.meshes, tagsQuery);
  6937. };
  6938. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6939. return this._getByTags(this.cameras, tagsQuery);
  6940. };
  6941. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6942. return this._getByTags(this.lights, tagsQuery);
  6943. };
  6944. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6945. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6946. };
  6947. Scene.FOGMODE_NONE = 0;
  6948. Scene.FOGMODE_EXP = 1;
  6949. Scene.FOGMODE_EXP2 = 2;
  6950. Scene.FOGMODE_LINEAR = 3;
  6951. Scene.MinDeltaTime = 1.0;
  6952. Scene.MaxDeltaTime = 1000.0;
  6953. return Scene;
  6954. })();
  6955. BABYLON.Scene = Scene;
  6956. })(BABYLON || (BABYLON = {}));
  6957. var BABYLON;
  6958. (function (BABYLON) {
  6959. var VertexBuffer = (function () {
  6960. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6961. if (engine instanceof BABYLON.Mesh) {
  6962. this._engine = engine.getScene().getEngine();
  6963. } else {
  6964. this._engine = engine;
  6965. }
  6966. this._updatable = updatable;
  6967. this._data = data;
  6968. if (!postponeInternalCreation) {
  6969. this.create();
  6970. }
  6971. this._kind = kind;
  6972. switch (kind) {
  6973. case VertexBuffer.PositionKind:
  6974. this._strideSize = 3;
  6975. break;
  6976. case VertexBuffer.NormalKind:
  6977. this._strideSize = 3;
  6978. break;
  6979. case VertexBuffer.UVKind:
  6980. this._strideSize = 2;
  6981. break;
  6982. case VertexBuffer.UV2Kind:
  6983. this._strideSize = 2;
  6984. break;
  6985. case VertexBuffer.ColorKind:
  6986. this._strideSize = 3;
  6987. break;
  6988. case VertexBuffer.MatricesIndicesKind:
  6989. this._strideSize = 4;
  6990. break;
  6991. case VertexBuffer.MatricesWeightsKind:
  6992. this._strideSize = 4;
  6993. break;
  6994. }
  6995. }
  6996. VertexBuffer.prototype.isUpdatable = function () {
  6997. return this._updatable;
  6998. };
  6999. VertexBuffer.prototype.getData = function () {
  7000. return this._data;
  7001. };
  7002. VertexBuffer.prototype.getBuffer = function () {
  7003. return this._buffer;
  7004. };
  7005. VertexBuffer.prototype.getStrideSize = function () {
  7006. return this._strideSize;
  7007. };
  7008. VertexBuffer.prototype.create = function (data) {
  7009. if (!data && this._buffer) {
  7010. return;
  7011. }
  7012. data = data || this._data;
  7013. if (!this._buffer) {
  7014. if (this._updatable) {
  7015. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7016. } else {
  7017. this._buffer = this._engine.createVertexBuffer(data);
  7018. }
  7019. }
  7020. if (this._updatable) {
  7021. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7022. this._data = data;
  7023. }
  7024. };
  7025. VertexBuffer.prototype.update = function (data) {
  7026. this.create(data);
  7027. };
  7028. VertexBuffer.prototype.dispose = function () {
  7029. if (!this._buffer) {
  7030. return;
  7031. }
  7032. if (this._engine._releaseBuffer(this._buffer)) {
  7033. this._buffer = null;
  7034. }
  7035. };
  7036. Object.defineProperty(VertexBuffer, "PositionKind", {
  7037. get: function () {
  7038. return VertexBuffer._PositionKind;
  7039. },
  7040. enumerable: true,
  7041. configurable: true
  7042. });
  7043. Object.defineProperty(VertexBuffer, "NormalKind", {
  7044. get: function () {
  7045. return VertexBuffer._NormalKind;
  7046. },
  7047. enumerable: true,
  7048. configurable: true
  7049. });
  7050. Object.defineProperty(VertexBuffer, "UVKind", {
  7051. get: function () {
  7052. return VertexBuffer._UVKind;
  7053. },
  7054. enumerable: true,
  7055. configurable: true
  7056. });
  7057. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7058. get: function () {
  7059. return VertexBuffer._UV2Kind;
  7060. },
  7061. enumerable: true,
  7062. configurable: true
  7063. });
  7064. Object.defineProperty(VertexBuffer, "ColorKind", {
  7065. get: function () {
  7066. return VertexBuffer._ColorKind;
  7067. },
  7068. enumerable: true,
  7069. configurable: true
  7070. });
  7071. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7072. get: function () {
  7073. return VertexBuffer._MatricesIndicesKind;
  7074. },
  7075. enumerable: true,
  7076. configurable: true
  7077. });
  7078. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7079. get: function () {
  7080. return VertexBuffer._MatricesWeightsKind;
  7081. },
  7082. enumerable: true,
  7083. configurable: true
  7084. });
  7085. VertexBuffer._PositionKind = "position";
  7086. VertexBuffer._NormalKind = "normal";
  7087. VertexBuffer._UVKind = "uv";
  7088. VertexBuffer._UV2Kind = "uv2";
  7089. VertexBuffer._ColorKind = "color";
  7090. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7091. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7092. return VertexBuffer;
  7093. })();
  7094. BABYLON.VertexBuffer = VertexBuffer;
  7095. })(BABYLON || (BABYLON = {}));
  7096. var __extends = this.__extends || function (d, b) {
  7097. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7098. function __() { this.constructor = d; }
  7099. __.prototype = b.prototype;
  7100. d.prototype = new __();
  7101. };
  7102. var BABYLON;
  7103. (function (BABYLON) {
  7104. var AbstractMesh = (function (_super) {
  7105. __extends(AbstractMesh, _super);
  7106. function AbstractMesh(name, scene) {
  7107. _super.call(this, name, scene);
  7108. this.position = new BABYLON.Vector3(0, 0, 0);
  7109. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7110. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7111. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7112. this.visibility = 1.0;
  7113. this.infiniteDistance = false;
  7114. this.isVisible = true;
  7115. this.isPickable = true;
  7116. this.showBoundingBox = false;
  7117. this.showSubMeshesBoundingBox = false;
  7118. this.onDispose = null;
  7119. this.checkCollisions = false;
  7120. this.isBlocker = false;
  7121. this.renderingGroupId = 0;
  7122. this.receiveShadows = false;
  7123. this.renderOutline = false;
  7124. this.outlineColor = BABYLON.Color3.Red();
  7125. this.outlineWidth = 0.02;
  7126. this.useOctreeForRenderingSelection = true;
  7127. this.useOctreeForPicking = true;
  7128. this.useOctreeForCollisions = true;
  7129. this.layerMask = 0xFFFFFFFF;
  7130. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7131. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7132. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7133. this._collider = new BABYLON.Collider();
  7134. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7135. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7136. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7137. this._localScaling = BABYLON.Matrix.Zero();
  7138. this._localRotation = BABYLON.Matrix.Zero();
  7139. this._localTranslation = BABYLON.Matrix.Zero();
  7140. this._localBillboard = BABYLON.Matrix.Zero();
  7141. this._localPivotScaling = BABYLON.Matrix.Zero();
  7142. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7143. this._localWorld = BABYLON.Matrix.Zero();
  7144. this._worldMatrix = BABYLON.Matrix.Zero();
  7145. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7146. this._absolutePosition = BABYLON.Vector3.Zero();
  7147. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7148. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7149. this._isDirty = false;
  7150. this._pivotMatrix = BABYLON.Matrix.Identity();
  7151. this._isDisposed = false;
  7152. this._renderId = 0;
  7153. this._intersectionsInProgress = new Array();
  7154. scene.meshes.push(this);
  7155. }
  7156. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7157. get: function () {
  7158. return AbstractMesh._BILLBOARDMODE_NONE;
  7159. },
  7160. enumerable: true,
  7161. configurable: true
  7162. });
  7163. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7164. get: function () {
  7165. return AbstractMesh._BILLBOARDMODE_X;
  7166. },
  7167. enumerable: true,
  7168. configurable: true
  7169. });
  7170. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7171. get: function () {
  7172. return AbstractMesh._BILLBOARDMODE_Y;
  7173. },
  7174. enumerable: true,
  7175. configurable: true
  7176. });
  7177. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7178. get: function () {
  7179. return AbstractMesh._BILLBOARDMODE_Z;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7185. get: function () {
  7186. return AbstractMesh._BILLBOARDMODE_ALL;
  7187. },
  7188. enumerable: true,
  7189. configurable: true
  7190. });
  7191. AbstractMesh.prototype.getTotalVertices = function () {
  7192. return 0;
  7193. };
  7194. AbstractMesh.prototype.getIndices = function () {
  7195. return null;
  7196. };
  7197. AbstractMesh.prototype.getVerticesData = function (kind) {
  7198. return null;
  7199. };
  7200. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7201. return false;
  7202. };
  7203. AbstractMesh.prototype.getBoundingInfo = function () {
  7204. if (!this._boundingInfo) {
  7205. this._updateBoundingInfo();
  7206. }
  7207. return this._boundingInfo;
  7208. };
  7209. AbstractMesh.prototype._preActivate = function () {
  7210. };
  7211. AbstractMesh.prototype._activate = function (renderId) {
  7212. this._renderId = renderId;
  7213. };
  7214. AbstractMesh.prototype.getWorldMatrix = function () {
  7215. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7216. this.computeWorldMatrix();
  7217. }
  7218. return this._worldMatrix;
  7219. };
  7220. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7221. get: function () {
  7222. return this._worldMatrix;
  7223. },
  7224. enumerable: true,
  7225. configurable: true
  7226. });
  7227. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7228. get: function () {
  7229. return this._absolutePosition;
  7230. },
  7231. enumerable: true,
  7232. configurable: true
  7233. });
  7234. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7235. if (!this.rotationQuaternion) {
  7236. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7237. this.rotation = BABYLON.Vector3.Zero();
  7238. }
  7239. if (!space || space == 0 /* LOCAL */) {
  7240. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7241. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7242. } else {
  7243. if (this.parent) {
  7244. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7245. invertParentWorldMatrix.invert();
  7246. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7247. }
  7248. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7249. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7250. }
  7251. };
  7252. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7253. var displacementVector = axis.scale(distance);
  7254. if (!space || space == 0 /* LOCAL */) {
  7255. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7256. this.setPositionWithLocalVector(tempV3);
  7257. } else {
  7258. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7259. }
  7260. };
  7261. AbstractMesh.prototype.getAbsolutePosition = function () {
  7262. this.computeWorldMatrix();
  7263. return this._absolutePosition;
  7264. };
  7265. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7266. if (!absolutePosition) {
  7267. return;
  7268. }
  7269. var absolutePositionX;
  7270. var absolutePositionY;
  7271. var absolutePositionZ;
  7272. if (absolutePosition.x === undefined) {
  7273. if (arguments.length < 3) {
  7274. return;
  7275. }
  7276. absolutePositionX = arguments[0];
  7277. absolutePositionY = arguments[1];
  7278. absolutePositionZ = arguments[2];
  7279. } else {
  7280. absolutePositionX = absolutePosition.x;
  7281. absolutePositionY = absolutePosition.y;
  7282. absolutePositionZ = absolutePosition.z;
  7283. }
  7284. if (this.parent) {
  7285. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7286. invertParentWorldMatrix.invert();
  7287. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7288. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7289. } else {
  7290. this.position.x = absolutePositionX;
  7291. this.position.y = absolutePositionY;
  7292. this.position.z = absolutePositionZ;
  7293. }
  7294. };
  7295. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7296. this._pivotMatrix = matrix;
  7297. this._cache.pivotMatrixUpdated = true;
  7298. };
  7299. AbstractMesh.prototype.getPivotMatrix = function () {
  7300. return this._pivotMatrix;
  7301. };
  7302. AbstractMesh.prototype._isSynchronized = function () {
  7303. if (this._isDirty) {
  7304. return false;
  7305. }
  7306. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7307. return false;
  7308. if (this._cache.pivotMatrixUpdated) {
  7309. return false;
  7310. }
  7311. if (this.infiniteDistance) {
  7312. return false;
  7313. }
  7314. if (!this._cache.position.equals(this.position))
  7315. return false;
  7316. if (this.rotationQuaternion) {
  7317. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7318. return false;
  7319. } else {
  7320. if (!this._cache.rotation.equals(this.rotation))
  7321. return false;
  7322. }
  7323. if (!this._cache.scaling.equals(this.scaling))
  7324. return false;
  7325. return true;
  7326. };
  7327. AbstractMesh.prototype._initCache = function () {
  7328. _super.prototype._initCache.call(this);
  7329. this._cache.localMatrixUpdated = false;
  7330. this._cache.position = BABYLON.Vector3.Zero();
  7331. this._cache.scaling = BABYLON.Vector3.Zero();
  7332. this._cache.rotation = BABYLON.Vector3.Zero();
  7333. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7334. };
  7335. AbstractMesh.prototype.markAsDirty = function (property) {
  7336. if (property === "rotation") {
  7337. this.rotationQuaternion = null;
  7338. }
  7339. this._currentRenderId = Number.MAX_VALUE;
  7340. this._isDirty = true;
  7341. };
  7342. AbstractMesh.prototype._updateBoundingInfo = function () {
  7343. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7344. this._boundingInfo._update(this.worldMatrixFromCache);
  7345. if (!this.subMeshes) {
  7346. return;
  7347. }
  7348. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7349. var subMesh = this.subMeshes[subIndex];
  7350. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7351. }
  7352. };
  7353. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7354. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7355. return this._worldMatrix;
  7356. }
  7357. this._cache.position.copyFrom(this.position);
  7358. this._cache.scaling.copyFrom(this.scaling);
  7359. this._cache.pivotMatrixUpdated = false;
  7360. this._currentRenderId = this.getScene().getRenderId();
  7361. this._isDirty = false;
  7362. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7363. if (this.rotationQuaternion) {
  7364. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7365. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7366. } else {
  7367. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7368. this._cache.rotation.copyFrom(this.rotation);
  7369. }
  7370. if (this.infiniteDistance && !this.parent) {
  7371. var camera = this.getScene().activeCamera;
  7372. var cameraWorldMatrix = camera.getWorldMatrix();
  7373. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7374. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7375. } else {
  7376. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7377. }
  7378. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7379. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7380. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7381. var localPosition = this.position.clone();
  7382. var zero = this.getScene().activeCamera.position.clone();
  7383. if (this.parent && this.parent.position) {
  7384. localPosition.addInPlace(this.parent.position);
  7385. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7386. }
  7387. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7388. zero = this.getScene().activeCamera.position;
  7389. } else {
  7390. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7391. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7392. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7393. zero.y = localPosition.y + 0.001;
  7394. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7395. zero.z = localPosition.z + 0.001;
  7396. }
  7397. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7398. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7399. this._localBillboard.invert();
  7400. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7401. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7402. }
  7403. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7404. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7405. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7406. } else {
  7407. this._worldMatrix.copyFrom(this._localWorld);
  7408. }
  7409. this._updateBoundingInfo();
  7410. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7411. return this._worldMatrix;
  7412. };
  7413. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7414. this.computeWorldMatrix();
  7415. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7416. };
  7417. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7418. this.computeWorldMatrix();
  7419. var invLocalWorldMatrix = this._localWorld.clone();
  7420. invLocalWorldMatrix.invert();
  7421. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7422. };
  7423. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7424. this.computeWorldMatrix();
  7425. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7426. };
  7427. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7428. yawCor = yawCor || 0;
  7429. pitchCor = pitchCor || 0;
  7430. rollCor = rollCor || 0;
  7431. var dv = targetPoint.subtract(this.position);
  7432. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7433. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7434. var pitch = Math.atan2(dv.y, len);
  7435. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7436. };
  7437. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7438. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7439. return false;
  7440. }
  7441. return true;
  7442. };
  7443. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7444. if (!this._boundingInfo || !mesh._boundingInfo) {
  7445. return false;
  7446. }
  7447. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7448. };
  7449. AbstractMesh.prototype.intersectsPoint = function (point) {
  7450. if (!this._boundingInfo) {
  7451. return false;
  7452. }
  7453. return this._boundingInfo.intersectsPoint(point);
  7454. };
  7455. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7456. var physicsEngine = this.getScene().getPhysicsEngine();
  7457. if (!physicsEngine) {
  7458. return;
  7459. }
  7460. if (impostor.impostor) {
  7461. options = impostor;
  7462. impostor = impostor.impostor;
  7463. }
  7464. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7465. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7466. physicsEngine._unregisterMesh(this);
  7467. return;
  7468. }
  7469. options.mass = options.mass || 0;
  7470. options.friction = options.friction || 0.2;
  7471. options.restitution = options.restitution || 0.9;
  7472. this._physicImpostor = impostor;
  7473. this._physicsMass = options.mass;
  7474. this._physicsFriction = options.friction;
  7475. this._physicRestitution = options.restitution;
  7476. physicsEngine._registerMesh(this, impostor, options);
  7477. };
  7478. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7479. if (!this._physicImpostor) {
  7480. return BABYLON.PhysicsEngine.NoImpostor;
  7481. }
  7482. return this._physicImpostor;
  7483. };
  7484. AbstractMesh.prototype.getPhysicsMass = function () {
  7485. if (!this._physicsMass) {
  7486. return 0;
  7487. }
  7488. return this._physicsMass;
  7489. };
  7490. AbstractMesh.prototype.getPhysicsFriction = function () {
  7491. if (!this._physicsFriction) {
  7492. return 0;
  7493. }
  7494. return this._physicsFriction;
  7495. };
  7496. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7497. if (!this._physicRestitution) {
  7498. return 0;
  7499. }
  7500. return this._physicRestitution;
  7501. };
  7502. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7503. if (!this._physicImpostor) {
  7504. return;
  7505. }
  7506. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7507. };
  7508. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7509. if (!this._physicImpostor) {
  7510. return;
  7511. }
  7512. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7513. };
  7514. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7515. if (!this._physicImpostor) {
  7516. return;
  7517. }
  7518. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7519. };
  7520. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7521. var globalPosition = this.getAbsolutePosition();
  7522. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7523. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7524. this._collider.radius = this.ellipsoid;
  7525. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7526. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7527. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7528. this.position.addInPlace(this._diffPositionForCollisions);
  7529. }
  7530. };
  7531. /**
  7532. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7533. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7534. */
  7535. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7536. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7537. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7538. if (!this._submeshesOctree) {
  7539. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7540. }
  7541. this.computeWorldMatrix(true);
  7542. var bbox = this.getBoundingInfo().boundingBox;
  7543. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7544. return this._submeshesOctree;
  7545. };
  7546. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7547. this._generatePointsArray();
  7548. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7549. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7550. subMesh._lastColliderWorldVertices = [];
  7551. subMesh._trianglePlanes = [];
  7552. var start = subMesh.verticesStart;
  7553. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7554. for (var i = start; i < end; i++) {
  7555. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7556. }
  7557. }
  7558. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7559. };
  7560. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7561. var subMeshes;
  7562. var len;
  7563. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7564. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7565. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7566. len = intersections.length;
  7567. subMeshes = intersections.data;
  7568. } else {
  7569. subMeshes = this.subMeshes;
  7570. len = subMeshes.length;
  7571. }
  7572. for (var index = 0; index < len; index++) {
  7573. var subMesh = subMeshes[index];
  7574. if (len > 1 && !subMesh._checkCollision(collider))
  7575. continue;
  7576. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7577. }
  7578. };
  7579. AbstractMesh.prototype._checkCollision = function (collider) {
  7580. if (!this._boundingInfo._checkCollision(collider))
  7581. return;
  7582. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7583. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7584. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7585. };
  7586. AbstractMesh.prototype._generatePointsArray = function () {
  7587. return false;
  7588. };
  7589. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7590. var pickingInfo = new BABYLON.PickingInfo();
  7591. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7592. return pickingInfo;
  7593. }
  7594. if (!this._generatePointsArray()) {
  7595. return pickingInfo;
  7596. }
  7597. var intersectInfo = null;
  7598. var subMeshes;
  7599. var len;
  7600. if (this._submeshesOctree && this.useOctreeForPicking) {
  7601. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7602. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7603. len = intersections.length;
  7604. subMeshes = intersections.data;
  7605. } else {
  7606. subMeshes = this.subMeshes;
  7607. len = subMeshes.length;
  7608. }
  7609. for (var index = 0; index < len; index++) {
  7610. var subMesh = subMeshes[index];
  7611. if (len > 1 && !subMesh.canIntersects(ray))
  7612. continue;
  7613. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7614. if (currentIntersectInfo) {
  7615. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7616. intersectInfo = currentIntersectInfo;
  7617. if (fastCheck) {
  7618. break;
  7619. }
  7620. }
  7621. }
  7622. }
  7623. if (intersectInfo) {
  7624. var world = this.getWorldMatrix();
  7625. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7626. var direction = ray.direction.clone();
  7627. direction.normalize();
  7628. direction = direction.scale(intersectInfo.distance);
  7629. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7630. var pickedPoint = worldOrigin.add(worldDirection);
  7631. pickingInfo.hit = true;
  7632. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7633. pickingInfo.pickedPoint = pickedPoint;
  7634. pickingInfo.pickedMesh = this;
  7635. pickingInfo.bu = intersectInfo.bu;
  7636. pickingInfo.bv = intersectInfo.bv;
  7637. pickingInfo.faceId = intersectInfo.faceId;
  7638. return pickingInfo;
  7639. }
  7640. return pickingInfo;
  7641. };
  7642. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7643. return null;
  7644. };
  7645. AbstractMesh.prototype.releaseSubMeshes = function () {
  7646. if (this.subMeshes) {
  7647. while (this.subMeshes.length) {
  7648. this.subMeshes[0].dispose();
  7649. }
  7650. } else {
  7651. this.subMeshes = new Array();
  7652. }
  7653. };
  7654. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7655. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7656. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7657. }
  7658. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7659. var other = this._intersectionsInProgress[index];
  7660. var pos = other._intersectionsInProgress.indexOf(this);
  7661. other._intersectionsInProgress.splice(pos, 1);
  7662. }
  7663. this._intersectionsInProgress = [];
  7664. this.releaseSubMeshes();
  7665. var index = this.getScene().meshes.indexOf(this);
  7666. if (index != -1) {
  7667. this.getScene().meshes.splice(index, 1);
  7668. }
  7669. if (!doNotRecurse) {
  7670. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7671. if (this.getScene().particleSystems[index].emitter == this) {
  7672. this.getScene().particleSystems[index].dispose();
  7673. index--;
  7674. }
  7675. }
  7676. var objects = this.getScene().meshes.slice(0);
  7677. for (index = 0; index < objects.length; index++) {
  7678. if (objects[index].parent == this) {
  7679. objects[index].dispose();
  7680. }
  7681. }
  7682. } else {
  7683. for (index = 0; index < this.getScene().meshes.length; index++) {
  7684. var obj = this.getScene().meshes[index];
  7685. if (obj.parent === this) {
  7686. obj.parent = null;
  7687. obj.computeWorldMatrix(true);
  7688. }
  7689. }
  7690. }
  7691. this._isDisposed = true;
  7692. if (this.onDispose) {
  7693. this.onDispose();
  7694. }
  7695. };
  7696. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7697. AbstractMesh._BILLBOARDMODE_X = 1;
  7698. AbstractMesh._BILLBOARDMODE_Y = 2;
  7699. AbstractMesh._BILLBOARDMODE_Z = 4;
  7700. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7701. return AbstractMesh;
  7702. })(BABYLON.Node);
  7703. BABYLON.AbstractMesh = AbstractMesh;
  7704. })(BABYLON || (BABYLON = {}));
  7705. var __extends = this.__extends || function (d, b) {
  7706. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7707. function __() { this.constructor = d; }
  7708. __.prototype = b.prototype;
  7709. d.prototype = new __();
  7710. };
  7711. var BABYLON;
  7712. (function (BABYLON) {
  7713. var _InstancesBatch = (function () {
  7714. function _InstancesBatch() {
  7715. this.mustReturn = false;
  7716. this.visibleInstances = new Array();
  7717. this.renderSelf = new Array();
  7718. }
  7719. return _InstancesBatch;
  7720. })();
  7721. BABYLON._InstancesBatch = _InstancesBatch;
  7722. var Mesh = (function (_super) {
  7723. __extends(Mesh, _super);
  7724. function Mesh(name, scene) {
  7725. _super.call(this, name, scene);
  7726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7727. this.instances = new Array();
  7728. this._onBeforeRenderCallbacks = new Array();
  7729. this._onAfterRenderCallbacks = new Array();
  7730. this._visibleInstances = {};
  7731. this._renderIdForInstances = new Array();
  7732. this._batchCache = new _InstancesBatch();
  7733. this._instancesBufferSize = 32 * 16 * 4;
  7734. }
  7735. Mesh.prototype.getTotalVertices = function () {
  7736. if (!this._geometry) {
  7737. return 0;
  7738. }
  7739. return this._geometry.getTotalVertices();
  7740. };
  7741. Mesh.prototype.getVerticesData = function (kind) {
  7742. if (!this._geometry) {
  7743. return null;
  7744. }
  7745. return this._geometry.getVerticesData(kind);
  7746. };
  7747. Mesh.prototype.getVertexBuffer = function (kind) {
  7748. if (!this._geometry) {
  7749. return undefined;
  7750. }
  7751. return this._geometry.getVertexBuffer(kind);
  7752. };
  7753. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7754. if (!this._geometry) {
  7755. if (this._delayInfo) {
  7756. return this._delayInfo.indexOf(kind) !== -1;
  7757. }
  7758. return false;
  7759. }
  7760. return this._geometry.isVerticesDataPresent(kind);
  7761. };
  7762. Mesh.prototype.getVerticesDataKinds = function () {
  7763. if (!this._geometry) {
  7764. var result = [];
  7765. if (this._delayInfo) {
  7766. for (var kind in this._delayInfo) {
  7767. result.push(kind);
  7768. }
  7769. }
  7770. return result;
  7771. }
  7772. return this._geometry.getVerticesDataKinds();
  7773. };
  7774. Mesh.prototype.getTotalIndices = function () {
  7775. if (!this._geometry) {
  7776. return 0;
  7777. }
  7778. return this._geometry.getTotalIndices();
  7779. };
  7780. Mesh.prototype.getIndices = function () {
  7781. if (!this._geometry) {
  7782. return [];
  7783. }
  7784. return this._geometry.getIndices();
  7785. };
  7786. Mesh.prototype.isReady = function () {
  7787. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7788. return false;
  7789. }
  7790. return _super.prototype.isReady.call(this);
  7791. };
  7792. Mesh.prototype.isDisposed = function () {
  7793. return this._isDisposed;
  7794. };
  7795. Mesh.prototype._preActivate = function () {
  7796. var sceneRenderId = this.getScene().getRenderId();
  7797. if (this._preActivateId == sceneRenderId) {
  7798. return;
  7799. }
  7800. this._preActivateId = sceneRenderId;
  7801. this._visibleInstances = null;
  7802. };
  7803. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7804. if (!this._visibleInstances) {
  7805. this._visibleInstances = {};
  7806. this._visibleInstances.defaultRenderId = renderId;
  7807. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7808. }
  7809. if (!this._visibleInstances[renderId]) {
  7810. this._visibleInstances[renderId] = new Array();
  7811. }
  7812. this._visibleInstances[renderId].push(instance);
  7813. };
  7814. Mesh.prototype.refreshBoundingInfo = function () {
  7815. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7816. if (data) {
  7817. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7818. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7819. }
  7820. if (this.subMeshes) {
  7821. for (var index = 0; index < this.subMeshes.length; index++) {
  7822. this.subMeshes[index].refreshBoundingInfo();
  7823. }
  7824. }
  7825. this._updateBoundingInfo();
  7826. };
  7827. Mesh.prototype._createGlobalSubMesh = function () {
  7828. var totalVertices = this.getTotalVertices();
  7829. if (!totalVertices || !this.getIndices()) {
  7830. return null;
  7831. }
  7832. this.releaseSubMeshes();
  7833. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7834. };
  7835. Mesh.prototype.subdivide = function (count) {
  7836. if (count < 1) {
  7837. return;
  7838. }
  7839. var totalIndices = this.getTotalIndices();
  7840. var subdivisionSize = (totalIndices / count) | 0;
  7841. var offset = 0;
  7842. while (subdivisionSize % 3 != 0) {
  7843. subdivisionSize++;
  7844. }
  7845. this.releaseSubMeshes();
  7846. for (var index = 0; index < count; index++) {
  7847. if (offset >= totalIndices) {
  7848. break;
  7849. }
  7850. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7851. offset += subdivisionSize;
  7852. }
  7853. this.synchronizeInstances();
  7854. };
  7855. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7856. if (kind instanceof Array) {
  7857. var temp = data;
  7858. data = kind;
  7859. kind = temp;
  7860. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7861. }
  7862. if (!this._geometry) {
  7863. var vertexData = new BABYLON.VertexData();
  7864. vertexData.set(data, kind);
  7865. var scene = this.getScene();
  7866. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7867. } else {
  7868. this._geometry.setVerticesData(kind, data, updatable);
  7869. }
  7870. };
  7871. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7872. if (!this._geometry) {
  7873. return;
  7874. }
  7875. if (!makeItUnique) {
  7876. this._geometry.updateVerticesData(kind, data, updateExtends);
  7877. } else {
  7878. this.makeGeometryUnique();
  7879. this.updateVerticesData(kind, data, updateExtends, false);
  7880. }
  7881. };
  7882. Mesh.prototype.makeGeometryUnique = function () {
  7883. if (!this._geometry) {
  7884. return;
  7885. }
  7886. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7887. geometry.applyToMesh(this);
  7888. };
  7889. Mesh.prototype.setIndices = function (indices) {
  7890. if (!this._geometry) {
  7891. var vertexData = new BABYLON.VertexData();
  7892. vertexData.indices = indices;
  7893. var scene = this.getScene();
  7894. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7895. } else {
  7896. this._geometry.setIndices(indices);
  7897. }
  7898. };
  7899. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7900. var engine = this.getScene().getEngine();
  7901. var indexToBind = this._geometry.getIndexBuffer();
  7902. if (wireframe) {
  7903. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7904. }
  7905. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7906. };
  7907. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7908. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7909. return;
  7910. }
  7911. var engine = this.getScene().getEngine();
  7912. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7913. };
  7914. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7915. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7916. return;
  7917. }
  7918. var engine = this.getScene().getEngine();
  7919. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7920. };
  7921. Mesh.prototype.registerBeforeRender = function (func) {
  7922. this._onBeforeRenderCallbacks.push(func);
  7923. };
  7924. Mesh.prototype.unregisterBeforeRender = function (func) {
  7925. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7926. if (index > -1) {
  7927. this._onBeforeRenderCallbacks.splice(index, 1);
  7928. }
  7929. };
  7930. Mesh.prototype.registerAfterRender = function (func) {
  7931. this._onAfterRenderCallbacks.push(func);
  7932. };
  7933. Mesh.prototype.unregisterAfterRender = function (func) {
  7934. var index = this._onAfterRenderCallbacks.indexOf(func);
  7935. if (index > -1) {
  7936. this._onAfterRenderCallbacks.splice(index, 1);
  7937. }
  7938. };
  7939. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7940. var scene = this.getScene();
  7941. this._batchCache.mustReturn = false;
  7942. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7943. this._batchCache.visibleInstances[subMeshId] = null;
  7944. if (this._visibleInstances) {
  7945. var currentRenderId = scene.getRenderId();
  7946. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7947. var selfRenderId = this._renderId;
  7948. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7949. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7950. currentRenderId = this._visibleInstances.defaultRenderId;
  7951. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7952. }
  7953. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7954. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7955. this._batchCache.mustReturn = true;
  7956. return this._batchCache;
  7957. }
  7958. if (currentRenderId !== selfRenderId) {
  7959. this._batchCache.renderSelf[subMeshId] = false;
  7960. }
  7961. }
  7962. this._renderIdForInstances[subMeshId] = currentRenderId;
  7963. }
  7964. return this._batchCache;
  7965. };
  7966. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7967. var matricesCount = this.instances.length + 1;
  7968. var bufferSize = matricesCount * 16 * 4;
  7969. while (this._instancesBufferSize < bufferSize) {
  7970. this._instancesBufferSize *= 2;
  7971. }
  7972. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7973. if (this._worldMatricesInstancesBuffer) {
  7974. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7975. }
  7976. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7977. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7978. }
  7979. var offset = 0;
  7980. var instancesCount = 0;
  7981. var world = this.getWorldMatrix();
  7982. if (batch.renderSelf[subMesh._id]) {
  7983. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7984. offset += 16;
  7985. instancesCount++;
  7986. }
  7987. var visibleInstances = batch.visibleInstances[subMesh._id];
  7988. if (visibleInstances) {
  7989. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7990. var instance = visibleInstances[instanceIndex];
  7991. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7992. offset += 16;
  7993. instancesCount++;
  7994. }
  7995. }
  7996. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7997. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7998. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7999. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8000. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8001. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8002. this._draw(subMesh, !wireFrame, instancesCount);
  8003. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8004. };
  8005. Mesh.prototype.render = function (subMesh) {
  8006. var scene = this.getScene();
  8007. var batch = this._getInstancesRenderList(subMesh._id);
  8008. if (batch.mustReturn) {
  8009. return;
  8010. }
  8011. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8012. return;
  8013. }
  8014. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8015. this._onBeforeRenderCallbacks[callbackIndex]();
  8016. }
  8017. var engine = scene.getEngine();
  8018. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8019. var effectiveMaterial = subMesh.getMaterial();
  8020. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8021. return;
  8022. }
  8023. var savedDepthWrite = engine.getDepthWrite();
  8024. if (this.renderOutline) {
  8025. engine.setDepthWrite(false);
  8026. scene.getOutlineRenderer().render(subMesh, batch);
  8027. }
  8028. effectiveMaterial._preBind();
  8029. var effect = effectiveMaterial.getEffect();
  8030. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8031. this._bind(subMesh, effect, wireFrame);
  8032. var world = this.getWorldMatrix();
  8033. effectiveMaterial.bind(world, this);
  8034. if (hardwareInstancedRendering) {
  8035. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8036. } else {
  8037. if (batch.renderSelf[subMesh._id]) {
  8038. this._draw(subMesh, !wireFrame);
  8039. }
  8040. if (batch.visibleInstances[subMesh._id]) {
  8041. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8042. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8043. world = instance.getWorldMatrix();
  8044. effectiveMaterial.bindOnlyWorldMatrix(world);
  8045. this._draw(subMesh, !wireFrame);
  8046. }
  8047. }
  8048. }
  8049. effectiveMaterial.unbind();
  8050. if (this.renderOutline && savedDepthWrite) {
  8051. engine.setDepthWrite(true);
  8052. engine.setColorWrite(false);
  8053. scene.getOutlineRenderer().render(subMesh, batch);
  8054. engine.setColorWrite(true);
  8055. }
  8056. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8057. this._onAfterRenderCallbacks[callbackIndex]();
  8058. }
  8059. };
  8060. Mesh.prototype.getEmittedParticleSystems = function () {
  8061. var results = new Array();
  8062. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8063. var particleSystem = this.getScene().particleSystems[index];
  8064. if (particleSystem.emitter === this) {
  8065. results.push(particleSystem);
  8066. }
  8067. }
  8068. return results;
  8069. };
  8070. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8071. var results = new Array();
  8072. var descendants = this.getDescendants();
  8073. descendants.push(this);
  8074. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8075. var particleSystem = this.getScene().particleSystems[index];
  8076. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8077. results.push(particleSystem);
  8078. }
  8079. }
  8080. return results;
  8081. };
  8082. Mesh.prototype.getChildren = function () {
  8083. var results = [];
  8084. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8085. var mesh = this.getScene().meshes[index];
  8086. if (mesh.parent == this) {
  8087. results.push(mesh);
  8088. }
  8089. }
  8090. return results;
  8091. };
  8092. Mesh.prototype._checkDelayState = function () {
  8093. var _this = this;
  8094. var that = this;
  8095. var scene = this.getScene();
  8096. if (this._geometry) {
  8097. this._geometry.load(scene);
  8098. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8099. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8100. scene._addPendingData(that);
  8101. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8102. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8103. if (data instanceof ArrayBuffer) {
  8104. _this._delayLoadingFunction(data, _this);
  8105. } else {
  8106. _this._delayLoadingFunction(JSON.parse(data), _this);
  8107. }
  8108. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8109. scene._removePendingData(_this);
  8110. }, function () {
  8111. }, scene.database, getBinaryData);
  8112. }
  8113. };
  8114. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8115. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8116. return false;
  8117. }
  8118. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8119. return false;
  8120. }
  8121. this._checkDelayState();
  8122. return true;
  8123. };
  8124. Mesh.prototype.setMaterialByID = function (id) {
  8125. var materials = this.getScene().materials;
  8126. for (var index = 0; index < materials.length; index++) {
  8127. if (materials[index].id == id) {
  8128. this.material = materials[index];
  8129. return;
  8130. }
  8131. }
  8132. var multiMaterials = this.getScene().multiMaterials;
  8133. for (index = 0; index < multiMaterials.length; index++) {
  8134. if (multiMaterials[index].id == id) {
  8135. this.material = multiMaterials[index];
  8136. return;
  8137. }
  8138. }
  8139. };
  8140. Mesh.prototype.getAnimatables = function () {
  8141. var results = [];
  8142. if (this.material) {
  8143. results.push(this.material);
  8144. }
  8145. return results;
  8146. };
  8147. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8148. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8149. return;
  8150. }
  8151. this._resetPointsArrayCache();
  8152. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8153. var temp = [];
  8154. for (var index = 0; index < data.length; index += 3) {
  8155. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8156. }
  8157. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8158. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8159. return;
  8160. }
  8161. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8162. for (index = 0; index < data.length; index += 3) {
  8163. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8164. }
  8165. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8166. };
  8167. Mesh.prototype._resetPointsArrayCache = function () {
  8168. this._positions = null;
  8169. };
  8170. Mesh.prototype._generatePointsArray = function () {
  8171. if (this._positions)
  8172. return true;
  8173. this._positions = [];
  8174. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8175. if (!data) {
  8176. return false;
  8177. }
  8178. for (var index = 0; index < data.length; index += 3) {
  8179. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8180. }
  8181. return true;
  8182. };
  8183. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8184. var result = new BABYLON.Mesh(name, this.getScene());
  8185. this._geometry.applyToMesh(result);
  8186. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8187. result.material = this.material;
  8188. if (newParent) {
  8189. result.parent = newParent;
  8190. }
  8191. if (!doNotCloneChildren) {
  8192. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8193. var mesh = this.getScene().meshes[index];
  8194. if (mesh.parent == this) {
  8195. mesh.clone(mesh.name, result);
  8196. }
  8197. }
  8198. }
  8199. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8200. var system = this.getScene().particleSystems[index];
  8201. if (system.emitter == this) {
  8202. system.clone(system.name, result);
  8203. }
  8204. }
  8205. result.computeWorldMatrix(true);
  8206. return result;
  8207. };
  8208. Mesh.prototype.dispose = function (doNotRecurse) {
  8209. if (this._geometry) {
  8210. this._geometry.releaseForMesh(this, true);
  8211. }
  8212. if (this._worldMatricesInstancesBuffer) {
  8213. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8214. this._worldMatricesInstancesBuffer = null;
  8215. }
  8216. while (this.instances.length) {
  8217. this.instances[0].dispose();
  8218. }
  8219. _super.prototype.dispose.call(this, doNotRecurse);
  8220. };
  8221. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8222. var _this = this;
  8223. var scene = this.getScene();
  8224. var onload = function (img) {
  8225. var canvas = document.createElement("canvas");
  8226. var context = canvas.getContext("2d");
  8227. var heightMapWidth = img.width;
  8228. var heightMapHeight = img.height;
  8229. canvas.width = heightMapWidth;
  8230. canvas.height = heightMapHeight;
  8231. context.drawImage(img, 0, 0);
  8232. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8233. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8234. };
  8235. BABYLON.Tools.LoadImage(url, onload, function () {
  8236. }, scene.database);
  8237. };
  8238. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8239. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8240. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8241. return;
  8242. }
  8243. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8244. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8245. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8246. var position = BABYLON.Vector3.Zero();
  8247. var normal = BABYLON.Vector3.Zero();
  8248. var uv = BABYLON.Vector2.Zero();
  8249. for (var index = 0; index < positions.length; index += 3) {
  8250. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8251. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8252. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8253. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8254. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8255. var pos = (u + v * heightMapWidth) * 4;
  8256. var r = buffer[pos] / 255.0;
  8257. var g = buffer[pos + 1] / 255.0;
  8258. var b = buffer[pos + 2] / 255.0;
  8259. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8260. normal.normalize();
  8261. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8262. position = position.add(normal);
  8263. position.toArray(positions, index);
  8264. }
  8265. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8266. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8267. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8268. };
  8269. Mesh.prototype.convertToFlatShadedMesh = function () {
  8270. var kinds = this.getVerticesDataKinds();
  8271. var vbs = [];
  8272. var data = [];
  8273. var newdata = [];
  8274. var updatableNormals = false;
  8275. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8276. var kind = kinds[kindIndex];
  8277. var vertexBuffer = this.getVertexBuffer(kind);
  8278. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8279. updatableNormals = vertexBuffer.isUpdatable();
  8280. kinds.splice(kindIndex, 1);
  8281. kindIndex--;
  8282. continue;
  8283. }
  8284. vbs[kind] = vertexBuffer;
  8285. data[kind] = vbs[kind].getData();
  8286. newdata[kind] = [];
  8287. }
  8288. var previousSubmeshes = this.subMeshes.slice(0);
  8289. var indices = this.getIndices();
  8290. var totalIndices = this.getTotalIndices();
  8291. for (index = 0; index < totalIndices; index++) {
  8292. var vertexIndex = indices[index];
  8293. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8294. kind = kinds[kindIndex];
  8295. var stride = vbs[kind].getStrideSize();
  8296. for (var offset = 0; offset < stride; offset++) {
  8297. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8298. }
  8299. }
  8300. }
  8301. var normals = [];
  8302. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8303. for (var index = 0; index < totalIndices; index += 3) {
  8304. indices[index] = index;
  8305. indices[index + 1] = index + 1;
  8306. indices[index + 2] = index + 2;
  8307. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8308. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8309. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8310. var p1p2 = p1.subtract(p2);
  8311. var p3p2 = p3.subtract(p2);
  8312. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8313. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8314. normals.push(normal.x);
  8315. normals.push(normal.y);
  8316. normals.push(normal.z);
  8317. }
  8318. }
  8319. this.setIndices(indices);
  8320. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8321. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8322. kind = kinds[kindIndex];
  8323. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8324. }
  8325. this.releaseSubMeshes();
  8326. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8327. var previousOne = previousSubmeshes[submeshIndex];
  8328. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8329. }
  8330. this.synchronizeInstances();
  8331. };
  8332. Mesh.prototype.createInstance = function (name) {
  8333. return new BABYLON.InstancedMesh(name, this);
  8334. };
  8335. Mesh.prototype.synchronizeInstances = function () {
  8336. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8337. var instance = this.instances[instanceIndex];
  8338. instance._syncSubMeshes();
  8339. }
  8340. };
  8341. Mesh.CreateBox = function (name, size, scene, updatable) {
  8342. var box = new BABYLON.Mesh(name, scene);
  8343. var vertexData = BABYLON.VertexData.CreateBox(size);
  8344. vertexData.applyToMesh(box, updatable);
  8345. return box;
  8346. };
  8347. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8348. var sphere = new BABYLON.Mesh(name, scene);
  8349. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8350. vertexData.applyToMesh(sphere, updatable);
  8351. return sphere;
  8352. };
  8353. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8354. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8355. if (scene !== undefined) {
  8356. updatable = scene;
  8357. }
  8358. scene = subdivisions;
  8359. subdivisions = 1;
  8360. }
  8361. var cylinder = new BABYLON.Mesh(name, scene);
  8362. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8363. vertexData.applyToMesh(cylinder, updatable);
  8364. return cylinder;
  8365. };
  8366. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8367. var torus = new BABYLON.Mesh(name, scene);
  8368. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8369. vertexData.applyToMesh(torus, updatable);
  8370. return torus;
  8371. };
  8372. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8373. var torusKnot = new BABYLON.Mesh(name, scene);
  8374. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8375. vertexData.applyToMesh(torusKnot, updatable);
  8376. return torusKnot;
  8377. };
  8378. Mesh.CreateLines = function (name, points, scene, updatable) {
  8379. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8380. var vertexData = BABYLON.VertexData.CreateLines(points);
  8381. vertexData.applyToMesh(lines, updatable);
  8382. return lines;
  8383. };
  8384. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8385. var plane = new BABYLON.Mesh(name, scene);
  8386. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8387. vertexData.applyToMesh(plane, updatable);
  8388. return plane;
  8389. };
  8390. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8391. var ground = new BABYLON.GroundMesh(name, scene);
  8392. ground._setReady(false);
  8393. ground._subdivisions = subdivisions;
  8394. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8395. vertexData.applyToMesh(ground, updatable);
  8396. ground._setReady(true);
  8397. return ground;
  8398. };
  8399. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8400. var tiledGround = new BABYLON.Mesh(name, scene);
  8401. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8402. vertexData.applyToMesh(tiledGround, updatable);
  8403. return tiledGround;
  8404. };
  8405. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8406. var ground = new BABYLON.GroundMesh(name, scene);
  8407. ground._subdivisions = subdivisions;
  8408. ground._setReady(false);
  8409. var onload = function (img) {
  8410. var canvas = document.createElement("canvas");
  8411. var context = canvas.getContext("2d");
  8412. var heightMapWidth = img.width;
  8413. var heightMapHeight = img.height;
  8414. canvas.width = heightMapWidth;
  8415. canvas.height = heightMapHeight;
  8416. context.drawImage(img, 0, 0);
  8417. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8418. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8419. vertexData.applyToMesh(ground, updatable);
  8420. ground._setReady(true);
  8421. };
  8422. BABYLON.Tools.LoadImage(url, onload, function () {
  8423. }, scene.database);
  8424. return ground;
  8425. };
  8426. Mesh.MinMax = function (meshes) {
  8427. var minVector = null;
  8428. var maxVector = null;
  8429. for (var i in meshes) {
  8430. var mesh = meshes[i];
  8431. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8432. if (!minVector) {
  8433. minVector = boundingBox.minimumWorld;
  8434. maxVector = boundingBox.maximumWorld;
  8435. continue;
  8436. }
  8437. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8438. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8439. }
  8440. return {
  8441. min: minVector,
  8442. max: maxVector
  8443. };
  8444. };
  8445. Mesh.Center = function (meshesOrMinMaxVector) {
  8446. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8447. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8448. };
  8449. return Mesh;
  8450. })(BABYLON.AbstractMesh);
  8451. BABYLON.Mesh = Mesh;
  8452. })(BABYLON || (BABYLON = {}));
  8453. var __extends = this.__extends || function (d, b) {
  8454. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8455. function __() { this.constructor = d; }
  8456. __.prototype = b.prototype;
  8457. d.prototype = new __();
  8458. };
  8459. var BABYLON;
  8460. (function (BABYLON) {
  8461. var GroundMesh = (function (_super) {
  8462. __extends(GroundMesh, _super);
  8463. function GroundMesh(name, scene) {
  8464. _super.call(this, name, scene);
  8465. this.generateOctree = false;
  8466. this._worldInverse = new BABYLON.Matrix();
  8467. }
  8468. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8469. get: function () {
  8470. return this._subdivisions;
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. GroundMesh.prototype.optimize = function (chunksCount) {
  8476. this.subdivide(this._subdivisions);
  8477. this.createOrUpdateSubmeshesOctree(32);
  8478. };
  8479. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8480. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8481. this.getWorldMatrix().invertToRef(this._worldInverse);
  8482. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8483. var pickInfo = this.intersects(ray);
  8484. if (pickInfo.hit) {
  8485. return pickInfo.pickedPoint.y;
  8486. }
  8487. return 0;
  8488. };
  8489. return GroundMesh;
  8490. })(BABYLON.Mesh);
  8491. BABYLON.GroundMesh = GroundMesh;
  8492. })(BABYLON || (BABYLON = {}));
  8493. var __extends = this.__extends || function (d, b) {
  8494. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8495. function __() { this.constructor = d; }
  8496. __.prototype = b.prototype;
  8497. d.prototype = new __();
  8498. };
  8499. var BABYLON;
  8500. (function (BABYLON) {
  8501. var InstancedMesh = (function (_super) {
  8502. __extends(InstancedMesh, _super);
  8503. function InstancedMesh(name, source) {
  8504. _super.call(this, name, source.getScene());
  8505. source.instances.push(this);
  8506. this._sourceMesh = source;
  8507. this.position.copyFrom(source.position);
  8508. this.rotation.copyFrom(source.rotation);
  8509. this.scaling.copyFrom(source.scaling);
  8510. if (source.rotationQuaternion) {
  8511. this.rotationQuaternion = source.rotationQuaternion.clone();
  8512. }
  8513. this.infiniteDistance = source.infiniteDistance;
  8514. this.setPivotMatrix(source.getPivotMatrix());
  8515. this.refreshBoundingInfo();
  8516. this._syncSubMeshes();
  8517. }
  8518. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8519. get: function () {
  8520. return this._sourceMesh.receiveShadows;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. Object.defineProperty(InstancedMesh.prototype, "material", {
  8526. get: function () {
  8527. return this._sourceMesh.material;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8533. get: function () {
  8534. return this._sourceMesh.visibility;
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8540. get: function () {
  8541. return this._sourceMesh.skeleton;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. InstancedMesh.prototype.getTotalVertices = function () {
  8547. return this._sourceMesh.getTotalVertices();
  8548. };
  8549. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8550. get: function () {
  8551. return this._sourceMesh;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. InstancedMesh.prototype.getVerticesData = function (kind) {
  8557. return this._sourceMesh.getVerticesData(kind);
  8558. };
  8559. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8560. return this._sourceMesh.isVerticesDataPresent(kind);
  8561. };
  8562. InstancedMesh.prototype.getIndices = function () {
  8563. return this._sourceMesh.getIndices();
  8564. };
  8565. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8566. get: function () {
  8567. return this._sourceMesh._positions;
  8568. },
  8569. enumerable: true,
  8570. configurable: true
  8571. });
  8572. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8573. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8574. if (data) {
  8575. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8576. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8577. }
  8578. this._updateBoundingInfo();
  8579. };
  8580. InstancedMesh.prototype._preActivate = function () {
  8581. this.sourceMesh._preActivate();
  8582. };
  8583. InstancedMesh.prototype._activate = function (renderId) {
  8584. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8585. };
  8586. InstancedMesh.prototype._syncSubMeshes = function () {
  8587. this.releaseSubMeshes();
  8588. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8589. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8590. }
  8591. };
  8592. InstancedMesh.prototype._generatePointsArray = function () {
  8593. return this._sourceMesh._generatePointsArray();
  8594. };
  8595. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8596. var result = this._sourceMesh.createInstance(name);
  8597. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8598. this.refreshBoundingInfo();
  8599. if (newParent) {
  8600. result.parent = newParent;
  8601. }
  8602. if (!doNotCloneChildren) {
  8603. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8604. var mesh = this.getScene().meshes[index];
  8605. if (mesh.parent == this) {
  8606. mesh.clone(mesh.name, result);
  8607. }
  8608. }
  8609. }
  8610. result.computeWorldMatrix(true);
  8611. return result;
  8612. };
  8613. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8614. var index = this._sourceMesh.instances.indexOf(this);
  8615. this._sourceMesh.instances.splice(index, 1);
  8616. _super.prototype.dispose.call(this, doNotRecurse);
  8617. };
  8618. return InstancedMesh;
  8619. })(BABYLON.AbstractMesh);
  8620. BABYLON.InstancedMesh = InstancedMesh;
  8621. })(BABYLON || (BABYLON = {}));
  8622. var BABYLON;
  8623. (function (BABYLON) {
  8624. var SubMesh = (function () {
  8625. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8626. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8627. this.materialIndex = materialIndex;
  8628. this.verticesStart = verticesStart;
  8629. this.verticesCount = verticesCount;
  8630. this.indexStart = indexStart;
  8631. this.indexCount = indexCount;
  8632. this._renderId = 0;
  8633. this._mesh = mesh;
  8634. this._renderingMesh = renderingMesh || mesh;
  8635. mesh.subMeshes.push(this);
  8636. this._id = mesh.subMeshes.length - 1;
  8637. if (createBoundingBox) {
  8638. this.refreshBoundingInfo();
  8639. }
  8640. }
  8641. SubMesh.prototype.getBoundingInfo = function () {
  8642. return this._boundingInfo;
  8643. };
  8644. SubMesh.prototype.getMesh = function () {
  8645. return this._mesh;
  8646. };
  8647. SubMesh.prototype.getRenderingMesh = function () {
  8648. return this._renderingMesh;
  8649. };
  8650. SubMesh.prototype.getMaterial = function () {
  8651. var rootMaterial = this._renderingMesh.material;
  8652. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8653. var multiMaterial = rootMaterial;
  8654. return multiMaterial.getSubMaterial(this.materialIndex);
  8655. }
  8656. if (!rootMaterial) {
  8657. return this._mesh.getScene().defaultMaterial;
  8658. }
  8659. return rootMaterial;
  8660. };
  8661. SubMesh.prototype.refreshBoundingInfo = function () {
  8662. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8663. if (!data) {
  8664. this._boundingInfo = this._mesh._boundingInfo;
  8665. return;
  8666. }
  8667. var indices = this._renderingMesh.getIndices();
  8668. var extend;
  8669. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8670. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8671. } else {
  8672. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8673. }
  8674. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8675. };
  8676. SubMesh.prototype._checkCollision = function (collider) {
  8677. return this._boundingInfo._checkCollision(collider);
  8678. };
  8679. SubMesh.prototype.updateBoundingInfo = function (world) {
  8680. if (!this._boundingInfo) {
  8681. this.refreshBoundingInfo();
  8682. }
  8683. this._boundingInfo._update(world);
  8684. };
  8685. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8686. return this._boundingInfo.isInFrustum(frustumPlanes);
  8687. };
  8688. SubMesh.prototype.render = function () {
  8689. this._renderingMesh.render(this);
  8690. };
  8691. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8692. if (!this._linesIndexBuffer) {
  8693. var linesIndices = [];
  8694. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8695. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8696. }
  8697. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8698. this.linesIndexCount = linesIndices.length;
  8699. }
  8700. return this._linesIndexBuffer;
  8701. };
  8702. SubMesh.prototype.canIntersects = function (ray) {
  8703. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8704. };
  8705. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8706. var intersectInfo = null;
  8707. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8708. var p0 = positions[indices[index]];
  8709. var p1 = positions[indices[index + 1]];
  8710. var p2 = positions[indices[index + 2]];
  8711. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8712. if (currentIntersectInfo) {
  8713. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8714. intersectInfo = currentIntersectInfo;
  8715. intersectInfo.faceId = index / 3;
  8716. if (fastCheck) {
  8717. break;
  8718. }
  8719. }
  8720. }
  8721. }
  8722. return intersectInfo;
  8723. };
  8724. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8725. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8726. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8727. return result;
  8728. };
  8729. SubMesh.prototype.dispose = function () {
  8730. if (this._linesIndexBuffer) {
  8731. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8732. this._linesIndexBuffer = null;
  8733. }
  8734. var index = this._mesh.subMeshes.indexOf(this);
  8735. this._mesh.subMeshes.splice(index, 1);
  8736. };
  8737. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8738. var minVertexIndex = Number.MAX_VALUE;
  8739. var maxVertexIndex = -Number.MAX_VALUE;
  8740. renderingMesh = renderingMesh || mesh;
  8741. var indices = renderingMesh.getIndices();
  8742. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8743. var vertexIndex = indices[index];
  8744. if (vertexIndex < minVertexIndex)
  8745. minVertexIndex = vertexIndex;
  8746. if (vertexIndex > maxVertexIndex)
  8747. maxVertexIndex = vertexIndex;
  8748. }
  8749. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8750. };
  8751. return SubMesh;
  8752. })();
  8753. BABYLON.SubMesh = SubMesh;
  8754. })(BABYLON || (BABYLON = {}));
  8755. var BABYLON;
  8756. (function (BABYLON) {
  8757. var BaseTexture = (function () {
  8758. function BaseTexture(scene) {
  8759. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8760. this.hasAlpha = false;
  8761. this.getAlphaFromRGB = false;
  8762. this.level = 1;
  8763. this.isCube = false;
  8764. this.isRenderTarget = false;
  8765. this.animations = new Array();
  8766. this.coordinatesIndex = 0;
  8767. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8768. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8769. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8770. this.anisotropicFilteringLevel = 4;
  8771. this._scene = scene;
  8772. this._scene.textures.push(this);
  8773. }
  8774. BaseTexture.prototype.getScene = function () {
  8775. return this._scene;
  8776. };
  8777. BaseTexture.prototype.getTextureMatrix = function () {
  8778. return null;
  8779. };
  8780. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8781. return null;
  8782. };
  8783. BaseTexture.prototype.getInternalTexture = function () {
  8784. return this._texture;
  8785. };
  8786. BaseTexture.prototype.isReady = function () {
  8787. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8788. return true;
  8789. }
  8790. if (this._texture) {
  8791. return this._texture.isReady;
  8792. }
  8793. return false;
  8794. };
  8795. BaseTexture.prototype.getSize = function () {
  8796. if (this._texture._width) {
  8797. return { width: this._texture._width, height: this._texture._height };
  8798. }
  8799. if (this._texture._size) {
  8800. return { width: this._texture._size, height: this._texture._size };
  8801. }
  8802. return { width: 0, height: 0 };
  8803. };
  8804. BaseTexture.prototype.getBaseSize = function () {
  8805. if (!this.isReady())
  8806. return { width: 0, height: 0 };
  8807. if (this._texture._size) {
  8808. return { width: this._texture._size, height: this._texture._size };
  8809. }
  8810. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8811. };
  8812. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8813. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8814. for (var index = 0; index < texturesCache.length; index++) {
  8815. var texturesCacheEntry = texturesCache[index];
  8816. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8817. texturesCacheEntry.references++;
  8818. return texturesCacheEntry;
  8819. }
  8820. }
  8821. return null;
  8822. };
  8823. BaseTexture.prototype.delayLoad = function () {
  8824. };
  8825. BaseTexture.prototype.releaseInternalTexture = function () {
  8826. if (!this._texture) {
  8827. return;
  8828. }
  8829. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8830. this._texture.references--;
  8831. if (this._texture.references == 0) {
  8832. var index = texturesCache.indexOf(this._texture);
  8833. texturesCache.splice(index, 1);
  8834. this._scene.getEngine()._releaseTexture(this._texture);
  8835. delete this._texture;
  8836. }
  8837. };
  8838. BaseTexture.prototype.clone = function () {
  8839. return null;
  8840. };
  8841. BaseTexture.prototype.dispose = function () {
  8842. var index = this._scene.textures.indexOf(this);
  8843. if (index >= 0) {
  8844. this._scene.textures.splice(index, 1);
  8845. }
  8846. if (this._texture === undefined) {
  8847. return;
  8848. }
  8849. this.releaseInternalTexture();
  8850. if (this.onDispose) {
  8851. this.onDispose();
  8852. }
  8853. };
  8854. return BaseTexture;
  8855. })();
  8856. BABYLON.BaseTexture = BaseTexture;
  8857. })(BABYLON || (BABYLON = {}));
  8858. var BABYLON;
  8859. (function (BABYLON) {
  8860. var RenderingGroup = (function () {
  8861. function RenderingGroup(index, scene) {
  8862. this.index = index;
  8863. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8864. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8865. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8866. this._scene = scene;
  8867. }
  8868. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8869. if (customRenderFunction) {
  8870. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8871. return true;
  8872. }
  8873. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8874. return false;
  8875. }
  8876. var engine = this._scene.getEngine();
  8877. var subIndex;
  8878. var submesh;
  8879. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8880. submesh = this._opaqueSubMeshes.data[subIndex];
  8881. this._activeVertices += submesh.verticesCount;
  8882. submesh.render();
  8883. }
  8884. engine.setAlphaTesting(true);
  8885. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8886. submesh = this._alphaTestSubMeshes.data[subIndex];
  8887. this._activeVertices += submesh.verticesCount;
  8888. submesh.render();
  8889. }
  8890. engine.setAlphaTesting(false);
  8891. if (beforeTransparents) {
  8892. beforeTransparents();
  8893. }
  8894. if (this._transparentSubMeshes.length) {
  8895. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8896. submesh = this._transparentSubMeshes.data[subIndex];
  8897. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8898. }
  8899. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8900. sortedArray.sort(function (a, b) {
  8901. if (a._distanceToCamera < b._distanceToCamera) {
  8902. return 1;
  8903. }
  8904. if (a._distanceToCamera > b._distanceToCamera) {
  8905. return -1;
  8906. }
  8907. return 0;
  8908. });
  8909. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8910. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8911. submesh = sortedArray[subIndex];
  8912. this._activeVertices += submesh.verticesCount;
  8913. submesh.render();
  8914. }
  8915. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8916. }
  8917. return true;
  8918. };
  8919. RenderingGroup.prototype.prepare = function () {
  8920. this._opaqueSubMeshes.reset();
  8921. this._transparentSubMeshes.reset();
  8922. this._alphaTestSubMeshes.reset();
  8923. };
  8924. RenderingGroup.prototype.dispatch = function (subMesh) {
  8925. var material = subMesh.getMaterial();
  8926. var mesh = subMesh.getMesh();
  8927. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8928. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8929. this._transparentSubMeshes.push(subMesh);
  8930. }
  8931. } else if (material.needAlphaTesting()) {
  8932. this._alphaTestSubMeshes.push(subMesh);
  8933. } else {
  8934. this._opaqueSubMeshes.push(subMesh);
  8935. }
  8936. };
  8937. return RenderingGroup;
  8938. })();
  8939. BABYLON.RenderingGroup = RenderingGroup;
  8940. })(BABYLON || (BABYLON = {}));
  8941. var BABYLON;
  8942. (function (BABYLON) {
  8943. var RenderingManager = (function () {
  8944. function RenderingManager(scene) {
  8945. this._renderingGroups = new Array();
  8946. this._scene = scene;
  8947. }
  8948. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8949. if (this._scene._activeParticleSystems.length === 0) {
  8950. return;
  8951. }
  8952. var beforeParticlesDate = new Date().getTime();
  8953. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8954. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8955. if (particleSystem.renderingGroupId !== index) {
  8956. continue;
  8957. }
  8958. this._clearDepthBuffer();
  8959. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8960. this._scene._activeParticles += particleSystem.render();
  8961. }
  8962. }
  8963. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8964. };
  8965. RenderingManager.prototype._renderSprites = function (index) {
  8966. if (this._scene.spriteManagers.length === 0) {
  8967. return;
  8968. }
  8969. var beforeSpritessDate = new Date().getTime();
  8970. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8971. var spriteManager = this._scene.spriteManagers[id];
  8972. if (spriteManager.renderingGroupId === index) {
  8973. this._clearDepthBuffer();
  8974. spriteManager.render();
  8975. }
  8976. }
  8977. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8978. };
  8979. RenderingManager.prototype._clearDepthBuffer = function () {
  8980. if (this._depthBufferAlreadyCleaned) {
  8981. return;
  8982. }
  8983. this._scene.getEngine().clear(0, false, true);
  8984. this._depthBufferAlreadyCleaned = true;
  8985. };
  8986. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8987. var _this = this;
  8988. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8989. this._depthBufferAlreadyCleaned = false;
  8990. var renderingGroup = this._renderingGroups[index];
  8991. if (renderingGroup) {
  8992. this._clearDepthBuffer();
  8993. if (!renderingGroup.render(customRenderFunction, function () {
  8994. if (renderSprites) {
  8995. _this._renderSprites(index);
  8996. }
  8997. })) {
  8998. this._renderingGroups.splice(index, 1);
  8999. }
  9000. } else if (renderSprites) {
  9001. this._renderSprites(index);
  9002. }
  9003. if (renderParticles) {
  9004. this._renderParticles(index, activeMeshes);
  9005. }
  9006. }
  9007. };
  9008. RenderingManager.prototype.reset = function () {
  9009. for (var index in this._renderingGroups) {
  9010. var renderingGroup = this._renderingGroups[index];
  9011. renderingGroup.prepare();
  9012. }
  9013. };
  9014. RenderingManager.prototype.dispatch = function (subMesh) {
  9015. var mesh = subMesh.getMesh();
  9016. var renderingGroupId = mesh.renderingGroupId || 0;
  9017. if (!this._renderingGroups[renderingGroupId]) {
  9018. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9019. }
  9020. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9021. };
  9022. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9023. return RenderingManager;
  9024. })();
  9025. BABYLON.RenderingManager = RenderingManager;
  9026. })(BABYLON || (BABYLON = {}));
  9027. var __extends = this.__extends || function (d, b) {
  9028. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9029. function __() { this.constructor = d; }
  9030. __.prototype = b.prototype;
  9031. d.prototype = new __();
  9032. };
  9033. var BABYLON;
  9034. (function (BABYLON) {
  9035. var Texture = (function (_super) {
  9036. __extends(Texture, _super);
  9037. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  9038. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9039. _super.call(this, scene);
  9040. this.uOffset = 0;
  9041. this.vOffset = 0;
  9042. this.uScale = 1.0;
  9043. this.vScale = 1.0;
  9044. this.uAng = 0;
  9045. this.vAng = 0;
  9046. this.wAng = 0;
  9047. this.name = url;
  9048. this.url = url;
  9049. this._noMipmap = noMipmap;
  9050. this._invertY = invertY;
  9051. this._samplingMode = samplingMode;
  9052. if (!url) {
  9053. return;
  9054. }
  9055. this._texture = this._getFromCache(url, noMipmap);
  9056. if (!this._texture) {
  9057. if (!scene.useDelayedTextureLoading) {
  9058. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9059. } else {
  9060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9061. }
  9062. }
  9063. }
  9064. Texture.prototype.delayLoad = function () {
  9065. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9066. return;
  9067. }
  9068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9069. this._texture = this._getFromCache(this.url, this._noMipmap);
  9070. if (!this._texture) {
  9071. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9072. }
  9073. };
  9074. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9075. x -= this.uOffset + 0.5;
  9076. y -= this.vOffset + 0.5;
  9077. z -= 0.5;
  9078. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9079. t.x *= this.uScale;
  9080. t.y *= this.vScale;
  9081. t.x += 0.5;
  9082. t.y += 0.5;
  9083. t.z += 0.5;
  9084. };
  9085. Texture.prototype.getTextureMatrix = function () {
  9086. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  9087. return this._cachedTextureMatrix;
  9088. }
  9089. this._cachedUOffset = this.uOffset;
  9090. this._cachedVOffset = this.vOffset;
  9091. this._cachedUScale = this.uScale;
  9092. this._cachedVScale = this.vScale;
  9093. this._cachedUAng = this.uAng;
  9094. this._cachedVAng = this.vAng;
  9095. this._cachedWAng = this.wAng;
  9096. if (!this._cachedTextureMatrix) {
  9097. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9098. this._rowGenerationMatrix = new BABYLON.Matrix();
  9099. this._t0 = BABYLON.Vector3.Zero();
  9100. this._t1 = BABYLON.Vector3.Zero();
  9101. this._t2 = BABYLON.Vector3.Zero();
  9102. }
  9103. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9104. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9105. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9106. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9107. this._t1.subtractInPlace(this._t0);
  9108. this._t2.subtractInPlace(this._t0);
  9109. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9110. this._cachedTextureMatrix.m[0] = this._t1.x;
  9111. this._cachedTextureMatrix.m[1] = this._t1.y;
  9112. this._cachedTextureMatrix.m[2] = this._t1.z;
  9113. this._cachedTextureMatrix.m[4] = this._t2.x;
  9114. this._cachedTextureMatrix.m[5] = this._t2.y;
  9115. this._cachedTextureMatrix.m[6] = this._t2.z;
  9116. this._cachedTextureMatrix.m[8] = this._t0.x;
  9117. this._cachedTextureMatrix.m[9] = this._t0.y;
  9118. this._cachedTextureMatrix.m[10] = this._t0.z;
  9119. return this._cachedTextureMatrix;
  9120. };
  9121. Texture.prototype.getReflectionTextureMatrix = function () {
  9122. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9123. return this._cachedTextureMatrix;
  9124. }
  9125. if (!this._cachedTextureMatrix) {
  9126. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9127. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9128. }
  9129. switch (this.coordinatesMode) {
  9130. case BABYLON.Texture.SPHERICAL_MODE:
  9131. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9132. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9133. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9134. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9135. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9136. break;
  9137. case BABYLON.Texture.PLANAR_MODE:
  9138. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9139. this._cachedTextureMatrix[0] = this.uScale;
  9140. this._cachedTextureMatrix[5] = this.vScale;
  9141. this._cachedTextureMatrix[12] = this.uOffset;
  9142. this._cachedTextureMatrix[13] = this.vOffset;
  9143. break;
  9144. case BABYLON.Texture.PROJECTION_MODE:
  9145. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9146. this._projectionModeMatrix.m[0] = 0.5;
  9147. this._projectionModeMatrix.m[5] = -0.5;
  9148. this._projectionModeMatrix.m[10] = 0.0;
  9149. this._projectionModeMatrix.m[12] = 0.5;
  9150. this._projectionModeMatrix.m[13] = 0.5;
  9151. this._projectionModeMatrix.m[14] = 1.0;
  9152. this._projectionModeMatrix.m[15] = 1.0;
  9153. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9154. break;
  9155. default:
  9156. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9157. break;
  9158. }
  9159. return this._cachedTextureMatrix;
  9160. };
  9161. Texture.prototype.clone = function () {
  9162. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9163. newTexture.hasAlpha = this.hasAlpha;
  9164. newTexture.level = this.level;
  9165. newTexture.wrapU = this.wrapU;
  9166. newTexture.wrapV = this.wrapV;
  9167. newTexture.coordinatesIndex = this.coordinatesIndex;
  9168. newTexture.coordinatesMode = this.coordinatesMode;
  9169. newTexture.uOffset = this.uOffset;
  9170. newTexture.vOffset = this.vOffset;
  9171. newTexture.uScale = this.uScale;
  9172. newTexture.vScale = this.vScale;
  9173. newTexture.uAng = this.uAng;
  9174. newTexture.vAng = this.vAng;
  9175. newTexture.wAng = this.wAng;
  9176. return newTexture;
  9177. };
  9178. Texture.NEAREST_SAMPLINGMODE = 1;
  9179. Texture.BILINEAR_SAMPLINGMODE = 2;
  9180. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9181. Texture.EXPLICIT_MODE = 0;
  9182. Texture.SPHERICAL_MODE = 1;
  9183. Texture.PLANAR_MODE = 2;
  9184. Texture.CUBIC_MODE = 3;
  9185. Texture.PROJECTION_MODE = 4;
  9186. Texture.SKYBOX_MODE = 5;
  9187. Texture.CLAMP_ADDRESSMODE = 0;
  9188. Texture.WRAP_ADDRESSMODE = 1;
  9189. Texture.MIRROR_ADDRESSMODE = 2;
  9190. return Texture;
  9191. })(BABYLON.BaseTexture);
  9192. BABYLON.Texture = Texture;
  9193. })(BABYLON || (BABYLON = {}));
  9194. var __extends = this.__extends || function (d, b) {
  9195. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9196. function __() { this.constructor = d; }
  9197. __.prototype = b.prototype;
  9198. d.prototype = new __();
  9199. };
  9200. var BABYLON;
  9201. (function (BABYLON) {
  9202. var CubeTexture = (function (_super) {
  9203. __extends(CubeTexture, _super);
  9204. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9205. _super.call(this, scene);
  9206. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9207. this.name = rootUrl;
  9208. this.url = rootUrl;
  9209. this._noMipmap = noMipmap;
  9210. this.hasAlpha = false;
  9211. this._texture = this._getFromCache(rootUrl, noMipmap);
  9212. if (!extensions) {
  9213. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9214. }
  9215. this._extensions = extensions;
  9216. if (!this._texture) {
  9217. if (!scene.useDelayedTextureLoading) {
  9218. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9219. } else {
  9220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9221. }
  9222. }
  9223. this.isCube = true;
  9224. this._textureMatrix = BABYLON.Matrix.Identity();
  9225. }
  9226. CubeTexture.prototype.clone = function () {
  9227. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9228. newTexture.level = this.level;
  9229. newTexture.wrapU = this.wrapU;
  9230. newTexture.wrapV = this.wrapV;
  9231. newTexture.coordinatesIndex = this.coordinatesIndex;
  9232. newTexture.coordinatesMode = this.coordinatesMode;
  9233. return newTexture;
  9234. };
  9235. CubeTexture.prototype.delayLoad = function () {
  9236. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9237. return;
  9238. }
  9239. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9240. this._texture = this._getFromCache(this.url, this._noMipmap);
  9241. if (!this._texture) {
  9242. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9243. }
  9244. };
  9245. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9246. return this._textureMatrix;
  9247. };
  9248. return CubeTexture;
  9249. })(BABYLON.BaseTexture);
  9250. BABYLON.CubeTexture = CubeTexture;
  9251. })(BABYLON || (BABYLON = {}));
  9252. var __extends = this.__extends || function (d, b) {
  9253. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9254. function __() { this.constructor = d; }
  9255. __.prototype = b.prototype;
  9256. d.prototype = new __();
  9257. };
  9258. var BABYLON;
  9259. (function (BABYLON) {
  9260. var RenderTargetTexture = (function (_super) {
  9261. __extends(RenderTargetTexture, _super);
  9262. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9263. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9264. _super.call(this, null, scene, !generateMipMaps);
  9265. this.renderList = new Array();
  9266. this.renderParticles = true;
  9267. this.renderSprites = false;
  9268. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9269. this._currentRefreshId = -1;
  9270. this._refreshRate = 1;
  9271. this.name = name;
  9272. this.isRenderTarget = true;
  9273. this._size = size;
  9274. this._generateMipMaps = generateMipMaps;
  9275. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9276. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9277. this._renderingManager = new BABYLON.RenderingManager(scene);
  9278. }
  9279. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9280. this._currentRefreshId = -1;
  9281. };
  9282. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9283. get: function () {
  9284. return this._refreshRate;
  9285. },
  9286. set: function (value) {
  9287. this._refreshRate = value;
  9288. this.resetRefreshCounter();
  9289. },
  9290. enumerable: true,
  9291. configurable: true
  9292. });
  9293. RenderTargetTexture.prototype._shouldRender = function () {
  9294. if (this._currentRefreshId === -1) {
  9295. this._currentRefreshId = 1;
  9296. return true;
  9297. }
  9298. if (this.refreshRate == this._currentRefreshId) {
  9299. this._currentRefreshId = 1;
  9300. return true;
  9301. }
  9302. this._currentRefreshId++;
  9303. return false;
  9304. };
  9305. RenderTargetTexture.prototype.getRenderSize = function () {
  9306. return this._size;
  9307. };
  9308. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9309. this.releaseInternalTexture();
  9310. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9311. };
  9312. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9313. var scene = this.getScene();
  9314. var engine = scene.getEngine();
  9315. if (this._waitingRenderList) {
  9316. this.renderList = [];
  9317. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9318. var id = this._waitingRenderList[index];
  9319. this.renderList.push(scene.getMeshByID(id));
  9320. }
  9321. delete this._waitingRenderList;
  9322. }
  9323. if (!this.renderList) {
  9324. return;
  9325. }
  9326. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9327. engine.bindFramebuffer(this._texture);
  9328. }
  9329. engine.clear(scene.clearColor, true, true);
  9330. this._renderingManager.reset();
  9331. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9332. var mesh = this.renderList[meshIndex];
  9333. if (mesh) {
  9334. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9335. this.resetRefreshCounter();
  9336. continue;
  9337. }
  9338. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9339. mesh._activate(scene.getRenderId());
  9340. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9341. var subMesh = mesh.subMeshes[subIndex];
  9342. scene._activeVertices += subMesh.verticesCount;
  9343. this._renderingManager.dispatch(subMesh);
  9344. }
  9345. }
  9346. }
  9347. }
  9348. if (!this._doNotChangeAspectRatio) {
  9349. scene.updateTransformMatrix(true);
  9350. }
  9351. if (this.onBeforeRender) {
  9352. this.onBeforeRender();
  9353. }
  9354. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9355. if (useCameraPostProcess) {
  9356. scene.postProcessManager._finalizeFrame(false, this._texture);
  9357. }
  9358. if (this.onAfterRender) {
  9359. this.onAfterRender();
  9360. }
  9361. engine.unBindFramebuffer(this._texture);
  9362. if (!this._doNotChangeAspectRatio) {
  9363. scene.updateTransformMatrix(true);
  9364. }
  9365. };
  9366. RenderTargetTexture.prototype.clone = function () {
  9367. var textureSize = this.getSize();
  9368. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9369. newTexture.hasAlpha = this.hasAlpha;
  9370. newTexture.level = this.level;
  9371. newTexture.coordinatesMode = this.coordinatesMode;
  9372. newTexture.renderList = this.renderList.slice(0);
  9373. return newTexture;
  9374. };
  9375. return RenderTargetTexture;
  9376. })(BABYLON.Texture);
  9377. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9378. })(BABYLON || (BABYLON = {}));
  9379. var __extends = this.__extends || function (d, b) {
  9380. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9381. function __() { this.constructor = d; }
  9382. __.prototype = b.prototype;
  9383. d.prototype = new __();
  9384. };
  9385. var BABYLON;
  9386. (function (BABYLON) {
  9387. var MirrorTexture = (function (_super) {
  9388. __extends(MirrorTexture, _super);
  9389. function MirrorTexture(name, size, scene, generateMipMaps) {
  9390. var _this = this;
  9391. _super.call(this, name, size, scene, generateMipMaps, true);
  9392. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9393. this._transformMatrix = BABYLON.Matrix.Zero();
  9394. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9395. this.onBeforeRender = function () {
  9396. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9397. _this._savedViewMatrix = scene.getViewMatrix();
  9398. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9399. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9400. scene.clipPlane = _this.mirrorPlane;
  9401. scene.getEngine().cullBackFaces = false;
  9402. };
  9403. this.onAfterRender = function () {
  9404. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9405. scene.getEngine().cullBackFaces = true;
  9406. delete scene.clipPlane;
  9407. };
  9408. }
  9409. MirrorTexture.prototype.clone = function () {
  9410. var textureSize = this.getSize();
  9411. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9412. newTexture.hasAlpha = this.hasAlpha;
  9413. newTexture.level = this.level;
  9414. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9415. newTexture.renderList = this.renderList.slice(0);
  9416. return newTexture;
  9417. };
  9418. return MirrorTexture;
  9419. })(BABYLON.RenderTargetTexture);
  9420. BABYLON.MirrorTexture = MirrorTexture;
  9421. })(BABYLON || (BABYLON = {}));
  9422. var __extends = this.__extends || function (d, b) {
  9423. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9424. function __() { this.constructor = d; }
  9425. __.prototype = b.prototype;
  9426. d.prototype = new __();
  9427. };
  9428. var BABYLON;
  9429. (function (BABYLON) {
  9430. var DynamicTexture = (function (_super) {
  9431. __extends(DynamicTexture, _super);
  9432. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9433. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9434. _super.call(this, null, scene, !generateMipMaps);
  9435. this.name = name;
  9436. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9437. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9438. this._generateMipMaps = generateMipMaps;
  9439. if (options.getContext) {
  9440. this._canvas = options;
  9441. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9442. } else {
  9443. this._canvas = document.createElement("canvas");
  9444. if (options.width) {
  9445. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9446. } else {
  9447. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9448. }
  9449. }
  9450. var textureSize = this.getSize();
  9451. this._canvas.width = textureSize.width;
  9452. this._canvas.height = textureSize.height;
  9453. this._context = this._canvas.getContext("2d");
  9454. }
  9455. DynamicTexture.prototype.getContext = function () {
  9456. return this._context;
  9457. };
  9458. DynamicTexture.prototype.update = function (invertY) {
  9459. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9460. };
  9461. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9462. var size = this.getSize();
  9463. if (clearColor) {
  9464. this._context.fillStyle = clearColor;
  9465. this._context.fillRect(0, 0, size.width, size.height);
  9466. }
  9467. this._context.font = font;
  9468. if (x === null) {
  9469. var textSize = this._context.measureText(text);
  9470. x = (size.width - textSize.width) / 2;
  9471. }
  9472. this._context.fillStyle = color;
  9473. this._context.fillText(text, x, y);
  9474. this.update(invertY);
  9475. };
  9476. DynamicTexture.prototype.clone = function () {
  9477. var textureSize = this.getSize();
  9478. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9479. newTexture.hasAlpha = this.hasAlpha;
  9480. newTexture.level = this.level;
  9481. newTexture.wrapU = this.wrapU;
  9482. newTexture.wrapV = this.wrapV;
  9483. return newTexture;
  9484. };
  9485. return DynamicTexture;
  9486. })(BABYLON.Texture);
  9487. BABYLON.DynamicTexture = DynamicTexture;
  9488. })(BABYLON || (BABYLON = {}));
  9489. var __extends = this.__extends || function (d, b) {
  9490. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9491. function __() { this.constructor = d; }
  9492. __.prototype = b.prototype;
  9493. d.prototype = new __();
  9494. };
  9495. var BABYLON;
  9496. (function (BABYLON) {
  9497. var VideoTexture = (function (_super) {
  9498. __extends(VideoTexture, _super);
  9499. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9500. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9501. var _this = this;
  9502. _super.call(this, null, scene, !generateMipMaps, invertY);
  9503. this._autoLaunch = true;
  9504. this.name = name;
  9505. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9506. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9507. var requiredWidth = size.width || size;
  9508. var requiredHeight = size.height || size;
  9509. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9510. var textureSize = this.getSize();
  9511. this.video = document.createElement("video");
  9512. this.video.width = textureSize.width;
  9513. this.video.height = textureSize.height;
  9514. this.video.autoplay = false;
  9515. this.video.loop = true;
  9516. this.video.addEventListener("canplaythrough", function () {
  9517. if (_this._texture) {
  9518. _this._texture.isReady = true;
  9519. }
  9520. });
  9521. urls.forEach(function (url) {
  9522. var source = document.createElement("source");
  9523. source.src = url;
  9524. _this.video.appendChild(source);
  9525. });
  9526. this._lastUpdate = new Date().getTime();
  9527. }
  9528. VideoTexture.prototype.update = function () {
  9529. if (this._autoLaunch) {
  9530. this._autoLaunch = false;
  9531. this.video.play();
  9532. }
  9533. var now = new Date().getTime();
  9534. if (now - this._lastUpdate < 15) {
  9535. return false;
  9536. }
  9537. this._lastUpdate = now;
  9538. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9539. return true;
  9540. };
  9541. return VideoTexture;
  9542. })(BABYLON.Texture);
  9543. BABYLON.VideoTexture = VideoTexture;
  9544. })(BABYLON || (BABYLON = {}));
  9545. var BABYLON;
  9546. (function (BABYLON) {
  9547. var EffectFallbacks = (function () {
  9548. function EffectFallbacks() {
  9549. this._defines = {};
  9550. this._currentRank = 32;
  9551. this._maxRank = -1;
  9552. }
  9553. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9554. if (!this._defines[rank]) {
  9555. if (rank < this._currentRank) {
  9556. this._currentRank = rank;
  9557. }
  9558. if (rank > this._maxRank) {
  9559. this._maxRank = rank;
  9560. }
  9561. this._defines[rank] = new Array();
  9562. }
  9563. this._defines[rank].push(define);
  9564. };
  9565. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9566. get: function () {
  9567. return this._currentRank <= this._maxRank;
  9568. },
  9569. enumerable: true,
  9570. configurable: true
  9571. });
  9572. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9573. var currentFallbacks = this._defines[this._currentRank];
  9574. for (var index = 0; index < currentFallbacks.length; index++) {
  9575. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9576. }
  9577. this._currentRank++;
  9578. return currentDefines;
  9579. };
  9580. return EffectFallbacks;
  9581. })();
  9582. BABYLON.EffectFallbacks = EffectFallbacks;
  9583. var Effect = (function () {
  9584. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9585. var _this = this;
  9586. this._isReady = false;
  9587. this._compilationError = "";
  9588. this._valueCache = [];
  9589. this._engine = engine;
  9590. this.name = baseName;
  9591. this.defines = defines;
  9592. this._uniformsNames = uniformsNames.concat(samplers);
  9593. this._samplers = samplers;
  9594. this._attributesNames = attributesNames;
  9595. this.onError = onError;
  9596. this.onCompiled = onCompiled;
  9597. var vertexSource;
  9598. var fragmentSource;
  9599. if (baseName.vertexElement) {
  9600. vertexSource = document.getElementById(baseName.vertexElement);
  9601. if (!vertexSource) {
  9602. vertexSource = baseName.vertexElement;
  9603. }
  9604. } else {
  9605. vertexSource = baseName.vertex || baseName;
  9606. }
  9607. if (baseName.fragmentElement) {
  9608. fragmentSource = document.getElementById(baseName.fragmentElement);
  9609. if (!fragmentSource) {
  9610. fragmentSource = baseName.fragmentElement;
  9611. }
  9612. } else {
  9613. fragmentSource = baseName.fragment || baseName;
  9614. }
  9615. this._loadVertexShader(vertexSource, function (vertexCode) {
  9616. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9617. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9618. });
  9619. });
  9620. }
  9621. Effect.prototype.isReady = function () {
  9622. return this._isReady;
  9623. };
  9624. Effect.prototype.getProgram = function () {
  9625. return this._program;
  9626. };
  9627. Effect.prototype.getAttributesNames = function () {
  9628. return this._attributesNames;
  9629. };
  9630. Effect.prototype.getAttributeLocation = function (index) {
  9631. return this._attributes[index];
  9632. };
  9633. Effect.prototype.getAttributeLocationByName = function (name) {
  9634. var index = this._attributesNames.indexOf(name);
  9635. return this._attributes[index];
  9636. };
  9637. Effect.prototype.getAttributesCount = function () {
  9638. return this._attributes.length;
  9639. };
  9640. Effect.prototype.getUniformIndex = function (uniformName) {
  9641. return this._uniformsNames.indexOf(uniformName);
  9642. };
  9643. Effect.prototype.getUniform = function (uniformName) {
  9644. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9645. };
  9646. Effect.prototype.getSamplers = function () {
  9647. return this._samplers;
  9648. };
  9649. Effect.prototype.getCompilationError = function () {
  9650. return this._compilationError;
  9651. };
  9652. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9653. if (vertex instanceof HTMLElement) {
  9654. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9655. callback(vertexCode);
  9656. return;
  9657. }
  9658. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9659. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9660. return;
  9661. }
  9662. var vertexShaderUrl;
  9663. if (vertex[0] === ".") {
  9664. vertexShaderUrl = vertex;
  9665. } else {
  9666. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9667. }
  9668. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9669. };
  9670. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9671. if (fragment instanceof HTMLElement) {
  9672. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9673. callback(fragmentCode);
  9674. return;
  9675. }
  9676. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9677. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9678. return;
  9679. }
  9680. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  9681. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  9682. return;
  9683. }
  9684. var fragmentShaderUrl;
  9685. if (fragment[0] === ".") {
  9686. fragmentShaderUrl = fragment;
  9687. } else {
  9688. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9689. }
  9690. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9691. };
  9692. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9693. try {
  9694. var engine = this._engine;
  9695. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9696. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9697. this._attributes = engine.getAttributes(this._program, attributesNames);
  9698. for (var index = 0; index < this._samplers.length; index++) {
  9699. var sampler = this.getUniform(this._samplers[index]);
  9700. if (sampler == null) {
  9701. this._samplers.splice(index, 1);
  9702. index--;
  9703. }
  9704. }
  9705. engine.bindSamplers(this);
  9706. this._isReady = true;
  9707. if (this.onCompiled) {
  9708. this.onCompiled(this);
  9709. }
  9710. } catch (e) {
  9711. if (fallbacks && fallbacks.isMoreFallbacks) {
  9712. defines = fallbacks.reduce(defines);
  9713. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9714. } else {
  9715. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9716. BABYLON.Tools.Error("Defines: " + defines);
  9717. BABYLON.Tools.Error("Error: " + e.message);
  9718. this._compilationError = e.message;
  9719. if (this.onError) {
  9720. this.onError(this, this._compilationError);
  9721. }
  9722. }
  9723. }
  9724. };
  9725. Effect.prototype._bindTexture = function (channel, texture) {
  9726. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9727. };
  9728. Effect.prototype.setTexture = function (channel, texture) {
  9729. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9730. };
  9731. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9732. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9733. };
  9734. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9735. if (!this._valueCache[uniformName]) {
  9736. this._valueCache[uniformName] = [x, y];
  9737. return;
  9738. }
  9739. this._valueCache[uniformName][0] = x;
  9740. this._valueCache[uniformName][1] = y;
  9741. };
  9742. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9743. if (!this._valueCache[uniformName]) {
  9744. this._valueCache[uniformName] = [x, y, z];
  9745. return;
  9746. }
  9747. this._valueCache[uniformName][0] = x;
  9748. this._valueCache[uniformName][1] = y;
  9749. this._valueCache[uniformName][2] = z;
  9750. };
  9751. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9752. if (!this._valueCache[uniformName]) {
  9753. this._valueCache[uniformName] = [x, y, z, w];
  9754. return;
  9755. }
  9756. this._valueCache[uniformName][0] = x;
  9757. this._valueCache[uniformName][1] = y;
  9758. this._valueCache[uniformName][2] = z;
  9759. this._valueCache[uniformName][3] = w;
  9760. };
  9761. Effect.prototype.setArray = function (uniformName, array) {
  9762. this._engine.setArray(this.getUniform(uniformName), array);
  9763. return this;
  9764. };
  9765. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9766. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9767. return this;
  9768. };
  9769. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9770. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9771. return this;
  9772. };
  9773. Effect.prototype.setFloat = function (uniformName, value) {
  9774. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9775. return this;
  9776. this._valueCache[uniformName] = value;
  9777. this._engine.setFloat(this.getUniform(uniformName), value);
  9778. return this;
  9779. };
  9780. Effect.prototype.setBool = function (uniformName, bool) {
  9781. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9782. return this;
  9783. this._valueCache[uniformName] = bool;
  9784. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9785. return this;
  9786. };
  9787. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9788. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9789. return this;
  9790. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9791. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9792. return this;
  9793. };
  9794. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9795. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9796. return this;
  9797. this._cacheFloat2(uniformName, x, y);
  9798. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9799. return this;
  9800. };
  9801. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9802. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9803. return this;
  9804. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9805. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9806. return this;
  9807. };
  9808. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9809. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9810. return this;
  9811. this._cacheFloat3(uniformName, x, y, z);
  9812. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9813. return this;
  9814. };
  9815. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9816. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9817. return this;
  9818. this._cacheFloat4(uniformName, x, y, z, w);
  9819. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9820. return this;
  9821. };
  9822. Effect.prototype.setColor3 = function (uniformName, color3) {
  9823. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9824. return this;
  9825. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9826. this._engine.setColor3(this.getUniform(uniformName), color3);
  9827. return this;
  9828. };
  9829. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9830. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b && this._valueCache[uniformName][3] == alpha)
  9831. return this;
  9832. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9833. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9834. return this;
  9835. };
  9836. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  9837. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  9838. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  9839. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9840. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  9841. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  9842. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\n }\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9843. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  9844. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  9845. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  9846. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  9847. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  9848. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  9849. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  9850. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  9851. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  9852. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  9853. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\n\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  9854. outlinePixelShader:"precision highp float;\n\nuniform vec3 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = vec4(color, 1.);\n}",
  9855. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  9856. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  9857. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  9858. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  9859. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  9860. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  9861. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  9862. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  9863. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  9864. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  9865. };
  9866. return Effect;
  9867. })();
  9868. BABYLON.Effect = Effect;
  9869. })(BABYLON || (BABYLON = {}));
  9870. var BABYLON;
  9871. (function (BABYLON) {
  9872. var Material = (function () {
  9873. function Material(name, scene, doNotAdd) {
  9874. this.name = name;
  9875. this.checkReadyOnEveryCall = true;
  9876. this.checkReadyOnlyOnce = false;
  9877. this.state = "";
  9878. this.alpha = 1.0;
  9879. this.wireframe = false;
  9880. this.backFaceCulling = true;
  9881. this._wasPreviouslyReady = false;
  9882. this.id = name;
  9883. this._scene = scene;
  9884. if (!doNotAdd) {
  9885. scene.materials.push(this);
  9886. }
  9887. }
  9888. Material.prototype.isReady = function (mesh, useInstances) {
  9889. return true;
  9890. };
  9891. Material.prototype.getEffect = function () {
  9892. return this._effect;
  9893. };
  9894. Material.prototype.getScene = function () {
  9895. return this._scene;
  9896. };
  9897. Material.prototype.needAlphaBlending = function () {
  9898. return (this.alpha < 1.0);
  9899. };
  9900. Material.prototype.needAlphaTesting = function () {
  9901. return false;
  9902. };
  9903. Material.prototype.getAlphaTestTexture = function () {
  9904. return null;
  9905. };
  9906. Material.prototype.trackCreation = function (onCompiled, onError) {
  9907. };
  9908. Material.prototype._preBind = function () {
  9909. var engine = this._scene.getEngine();
  9910. engine.enableEffect(this._effect);
  9911. engine.setState(this.backFaceCulling);
  9912. };
  9913. Material.prototype.bind = function (world, mesh) {
  9914. };
  9915. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9916. };
  9917. Material.prototype.unbind = function () {
  9918. };
  9919. Material.prototype.dispose = function (forceDisposeEffect) {
  9920. var index = this._scene.materials.indexOf(this);
  9921. this._scene.materials.splice(index, 1);
  9922. if (forceDisposeEffect && this._effect) {
  9923. this._scene.getEngine()._releaseEffect(this._effect);
  9924. this._effect = null;
  9925. }
  9926. if (this.onDispose) {
  9927. this.onDispose();
  9928. }
  9929. };
  9930. return Material;
  9931. })();
  9932. BABYLON.Material = Material;
  9933. })(BABYLON || (BABYLON = {}));
  9934. var __extends = this.__extends || function (d, b) {
  9935. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9936. function __() { this.constructor = d; }
  9937. __.prototype = b.prototype;
  9938. d.prototype = new __();
  9939. };
  9940. var BABYLON;
  9941. (function (BABYLON) {
  9942. var maxSimultaneousLights = 4;
  9943. var FresnelParameters = (function () {
  9944. function FresnelParameters() {
  9945. this.isEnabled = true;
  9946. this.leftColor = BABYLON.Color3.White();
  9947. this.rightColor = BABYLON.Color3.Black();
  9948. this.bias = 0;
  9949. this.power = 1;
  9950. }
  9951. return FresnelParameters;
  9952. })();
  9953. BABYLON.FresnelParameters = FresnelParameters;
  9954. var StandardMaterial = (function (_super) {
  9955. __extends(StandardMaterial, _super);
  9956. function StandardMaterial(name, scene) {
  9957. var _this = this;
  9958. _super.call(this, name, scene);
  9959. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9960. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9961. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9962. this.specularPower = 64;
  9963. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9964. this.useAlphaFromDiffuseTexture = false;
  9965. this.useSpecularOverAlpha = true;
  9966. this._cachedDefines = null;
  9967. this._renderTargets = new BABYLON.SmartArray(16);
  9968. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9969. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9970. this._scaledDiffuse = new BABYLON.Color3();
  9971. this._scaledSpecular = new BABYLON.Color3();
  9972. this.getRenderTargetTextures = function () {
  9973. _this._renderTargets.reset();
  9974. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9975. _this._renderTargets.push(_this.reflectionTexture);
  9976. }
  9977. return _this._renderTargets;
  9978. };
  9979. }
  9980. StandardMaterial.prototype.needAlphaBlending = function () {
  9981. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  9982. };
  9983. StandardMaterial.prototype.needAlphaTesting = function () {
  9984. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9985. };
  9986. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9987. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9988. };
  9989. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9990. return this.diffuseTexture;
  9991. };
  9992. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9993. if (this.checkReadyOnlyOnce) {
  9994. if (this._wasPreviouslyReady) {
  9995. return true;
  9996. }
  9997. }
  9998. var scene = this.getScene();
  9999. if (!this.checkReadyOnEveryCall) {
  10000. if (this._renderId === scene.getRenderId()) {
  10001. return true;
  10002. }
  10003. }
  10004. var engine = scene.getEngine();
  10005. var defines = [];
  10006. var fallbacks = new BABYLON.EffectFallbacks();
  10007. if (scene.texturesEnabled) {
  10008. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10009. if (!this.diffuseTexture.isReady()) {
  10010. return false;
  10011. } else {
  10012. defines.push("#define DIFFUSE");
  10013. }
  10014. }
  10015. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10016. if (!this.ambientTexture.isReady()) {
  10017. return false;
  10018. } else {
  10019. defines.push("#define AMBIENT");
  10020. }
  10021. }
  10022. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10023. if (!this.opacityTexture.isReady()) {
  10024. return false;
  10025. } else {
  10026. defines.push("#define OPACITY");
  10027. if (this.opacityTexture.getAlphaFromRGB) {
  10028. defines.push("#define OPACITYRGB");
  10029. }
  10030. }
  10031. }
  10032. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10033. if (!this.reflectionTexture.isReady()) {
  10034. return false;
  10035. } else {
  10036. defines.push("#define REFLECTION");
  10037. fallbacks.addFallback(0, "REFLECTION");
  10038. }
  10039. }
  10040. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10041. if (!this.emissiveTexture.isReady()) {
  10042. return false;
  10043. } else {
  10044. defines.push("#define EMISSIVE");
  10045. }
  10046. }
  10047. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10048. if (!this.specularTexture.isReady()) {
  10049. return false;
  10050. } else {
  10051. defines.push("#define SPECULAR");
  10052. fallbacks.addFallback(0, "SPECULAR");
  10053. }
  10054. }
  10055. }
  10056. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10057. if (!this.bumpTexture.isReady()) {
  10058. return false;
  10059. } else {
  10060. defines.push("#define BUMP");
  10061. fallbacks.addFallback(0, "BUMP");
  10062. }
  10063. }
  10064. if (this.useSpecularOverAlpha) {
  10065. defines.push("#define SPECULAROVERALPHA");
  10066. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10067. }
  10068. if (scene.clipPlane) {
  10069. defines.push("#define CLIPPLANE");
  10070. }
  10071. if (engine.getAlphaTesting()) {
  10072. defines.push("#define ALPHATEST");
  10073. }
  10074. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10075. defines.push("#define ALPHAFROMDIFFUSE");
  10076. }
  10077. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10078. defines.push("#define FOG");
  10079. fallbacks.addFallback(1, "FOG");
  10080. }
  10081. var shadowsActivated = false;
  10082. var lightIndex = 0;
  10083. if (scene.lightsEnabled) {
  10084. for (var index = 0; index < scene.lights.length; index++) {
  10085. var light = scene.lights[index];
  10086. if (!light.isEnabled()) {
  10087. continue;
  10088. }
  10089. if (light._excludedMeshesIds.length > 0) {
  10090. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10091. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10092. if (excludedMesh) {
  10093. light.excludedMeshes.push(excludedMesh);
  10094. }
  10095. }
  10096. light._excludedMeshesIds = [];
  10097. }
  10098. if (light._includedOnlyMeshesIds.length > 0) {
  10099. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10100. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10101. if (includedOnlyMesh) {
  10102. light.includedOnlyMeshes.push(includedOnlyMesh);
  10103. }
  10104. }
  10105. light._includedOnlyMeshesIds = [];
  10106. }
  10107. if (!light.canAffectMesh(mesh)) {
  10108. continue;
  10109. }
  10110. defines.push("#define LIGHT" + lightIndex);
  10111. if (lightIndex > 0) {
  10112. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10113. }
  10114. var type;
  10115. if (light instanceof BABYLON.SpotLight) {
  10116. type = "#define SPOTLIGHT" + lightIndex;
  10117. } else if (light instanceof BABYLON.HemisphericLight) {
  10118. type = "#define HEMILIGHT" + lightIndex;
  10119. } else {
  10120. type = "#define POINTDIRLIGHT" + lightIndex;
  10121. }
  10122. defines.push(type);
  10123. if (lightIndex > 0) {
  10124. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10125. }
  10126. var shadowGenerator = light.getShadowGenerator();
  10127. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10128. defines.push("#define SHADOW" + lightIndex);
  10129. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10130. if (!shadowsActivated) {
  10131. defines.push("#define SHADOWS");
  10132. shadowsActivated = true;
  10133. }
  10134. if (shadowGenerator.useVarianceShadowMap) {
  10135. defines.push("#define SHADOWVSM" + lightIndex);
  10136. if (lightIndex > 0) {
  10137. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10138. }
  10139. }
  10140. if (shadowGenerator.usePoissonSampling) {
  10141. defines.push("#define SHADOWPCF" + lightIndex);
  10142. if (lightIndex > 0) {
  10143. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10144. }
  10145. }
  10146. }
  10147. lightIndex++;
  10148. if (lightIndex == maxSimultaneousLights)
  10149. break;
  10150. }
  10151. }
  10152. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10153. var fresnelRank = 1;
  10154. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10155. defines.push("#define DIFFUSEFRESNEL");
  10156. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10157. fresnelRank++;
  10158. }
  10159. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10160. defines.push("#define OPACITYFRESNEL");
  10161. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10162. fresnelRank++;
  10163. }
  10164. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10165. defines.push("#define REFLECTIONFRESNEL");
  10166. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10167. fresnelRank++;
  10168. }
  10169. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10170. defines.push("#define EMISSIVEFRESNEL");
  10171. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10172. fresnelRank++;
  10173. }
  10174. defines.push("#define FRESNEL");
  10175. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10176. }
  10177. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10178. if (mesh) {
  10179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10180. attribs.push(BABYLON.VertexBuffer.UVKind);
  10181. defines.push("#define UV1");
  10182. }
  10183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10185. defines.push("#define UV2");
  10186. }
  10187. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10188. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10189. defines.push("#define VERTEXCOLOR");
  10190. }
  10191. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10192. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10193. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10194. defines.push("#define BONES");
  10195. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10196. defines.push("#define BONES4");
  10197. fallbacks.addFallback(0, "BONES4");
  10198. }
  10199. if (useInstances) {
  10200. defines.push("#define INSTANCES");
  10201. attribs.push("world0");
  10202. attribs.push("world1");
  10203. attribs.push("world2");
  10204. attribs.push("world3");
  10205. }
  10206. }
  10207. var join = defines.join("\n");
  10208. if (this._cachedDefines != join) {
  10209. this._cachedDefines = join;
  10210. var shaderName = "default";
  10211. if (!scene.getEngine().getCaps().standardDerivatives) {
  10212. shaderName = "legacydefault";
  10213. }
  10214. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10215. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10216. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10217. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10218. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10219. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10220. "vFogInfos", "vFogColor",
  10221. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10222. "mBones",
  10223. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10224. "darkness0", "darkness1", "darkness2", "darkness3",
  10225. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10226. ], [
  10227. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10228. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10229. ], join, fallbacks, this.onCompiled, this.onError);
  10230. }
  10231. if (!this._effect.isReady()) {
  10232. return false;
  10233. }
  10234. this._renderId = scene.getRenderId();
  10235. this._wasPreviouslyReady = true;
  10236. return true;
  10237. };
  10238. StandardMaterial.prototype.unbind = function () {
  10239. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10240. this._effect.setTexture("reflection2DSampler", null);
  10241. }
  10242. };
  10243. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10244. this._effect.setMatrix("world", world);
  10245. };
  10246. StandardMaterial.prototype.bind = function (world, mesh) {
  10247. var scene = this.getScene();
  10248. this.bindOnlyWorldMatrix(world);
  10249. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10250. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10251. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10252. }
  10253. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10254. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10255. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10256. }
  10257. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10258. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10259. }
  10260. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10261. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10262. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10263. }
  10264. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10265. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10266. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10267. }
  10268. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10269. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10270. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10271. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10272. }
  10273. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10274. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10275. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10276. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10277. }
  10278. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10279. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10280. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10281. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10282. }
  10283. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10284. if (this.reflectionTexture.isCube) {
  10285. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10286. } else {
  10287. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10288. }
  10289. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10290. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10291. }
  10292. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10293. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10294. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10295. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10296. }
  10297. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10298. this._effect.setTexture("specularSampler", this.specularTexture);
  10299. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10300. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10301. }
  10302. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10303. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10304. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10305. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10306. }
  10307. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10308. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10309. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10310. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10311. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10312. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10313. if (scene.lightsEnabled) {
  10314. var lightIndex = 0;
  10315. for (var index = 0; index < scene.lights.length; index++) {
  10316. var light = scene.lights[index];
  10317. if (!light.isEnabled()) {
  10318. continue;
  10319. }
  10320. if (!light.canAffectMesh(mesh)) {
  10321. continue;
  10322. }
  10323. if (light instanceof BABYLON.PointLight) {
  10324. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10325. } else if (light instanceof BABYLON.DirectionalLight) {
  10326. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10327. } else if (light instanceof BABYLON.SpotLight) {
  10328. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10329. } else if (light instanceof BABYLON.HemisphericLight) {
  10330. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10331. }
  10332. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10333. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10334. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10335. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10336. var shadowGenerator = light.getShadowGenerator();
  10337. if (mesh.receiveShadows && shadowGenerator) {
  10338. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10339. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10340. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10341. }
  10342. lightIndex++;
  10343. if (lightIndex == maxSimultaneousLights)
  10344. break;
  10345. }
  10346. }
  10347. if (scene.clipPlane) {
  10348. var clipPlane = scene.clipPlane;
  10349. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10350. }
  10351. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10352. this._effect.setMatrix("view", scene.getViewMatrix());
  10353. }
  10354. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10355. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10356. this._effect.setColor3("vFogColor", scene.fogColor);
  10357. }
  10358. };
  10359. StandardMaterial.prototype.getAnimatables = function () {
  10360. var results = [];
  10361. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10362. results.push(this.diffuseTexture);
  10363. }
  10364. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10365. results.push(this.ambientTexture);
  10366. }
  10367. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10368. results.push(this.opacityTexture);
  10369. }
  10370. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10371. results.push(this.reflectionTexture);
  10372. }
  10373. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10374. results.push(this.emissiveTexture);
  10375. }
  10376. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10377. results.push(this.specularTexture);
  10378. }
  10379. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10380. results.push(this.bumpTexture);
  10381. }
  10382. return results;
  10383. };
  10384. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10385. if (this.diffuseTexture) {
  10386. this.diffuseTexture.dispose();
  10387. }
  10388. if (this.ambientTexture) {
  10389. this.ambientTexture.dispose();
  10390. }
  10391. if (this.opacityTexture) {
  10392. this.opacityTexture.dispose();
  10393. }
  10394. if (this.reflectionTexture) {
  10395. this.reflectionTexture.dispose();
  10396. }
  10397. if (this.emissiveTexture) {
  10398. this.emissiveTexture.dispose();
  10399. }
  10400. if (this.specularTexture) {
  10401. this.specularTexture.dispose();
  10402. }
  10403. if (this.bumpTexture) {
  10404. this.bumpTexture.dispose();
  10405. }
  10406. _super.prototype.dispose.call(this, forceDisposeEffect);
  10407. };
  10408. StandardMaterial.prototype.clone = function (name) {
  10409. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10410. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10411. newStandardMaterial.alpha = this.alpha;
  10412. newStandardMaterial.wireframe = this.wireframe;
  10413. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10414. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10415. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10416. }
  10417. if (this.ambientTexture && this.ambientTexture.clone) {
  10418. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10419. }
  10420. if (this.opacityTexture && this.opacityTexture.clone) {
  10421. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10422. }
  10423. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10424. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10425. }
  10426. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10427. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10428. }
  10429. if (this.specularTexture && this.specularTexture.clone) {
  10430. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10431. }
  10432. if (this.bumpTexture && this.bumpTexture.clone) {
  10433. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10434. }
  10435. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10436. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10437. newStandardMaterial.specularColor = this.specularColor.clone();
  10438. newStandardMaterial.specularPower = this.specularPower;
  10439. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10440. return newStandardMaterial;
  10441. };
  10442. StandardMaterial.DiffuseTextureEnabled = true;
  10443. StandardMaterial.AmbientTextureEnabled = true;
  10444. StandardMaterial.OpacityTextureEnabled = true;
  10445. StandardMaterial.ReflectionTextureEnabled = true;
  10446. StandardMaterial.EmissiveTextureEnabled = true;
  10447. StandardMaterial.SpecularTextureEnabled = true;
  10448. StandardMaterial.BumpTextureEnabled = true;
  10449. return StandardMaterial;
  10450. })(BABYLON.Material);
  10451. BABYLON.StandardMaterial = StandardMaterial;
  10452. })(BABYLON || (BABYLON = {}));
  10453. var __extends = this.__extends || function (d, b) {
  10454. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10455. function __() { this.constructor = d; }
  10456. __.prototype = b.prototype;
  10457. d.prototype = new __();
  10458. };
  10459. var BABYLON;
  10460. (function (BABYLON) {
  10461. var MultiMaterial = (function (_super) {
  10462. __extends(MultiMaterial, _super);
  10463. function MultiMaterial(name, scene) {
  10464. _super.call(this, name, scene, true);
  10465. this.subMaterials = new Array();
  10466. scene.multiMaterials.push(this);
  10467. }
  10468. MultiMaterial.prototype.getSubMaterial = function (index) {
  10469. if (index < 0 || index >= this.subMaterials.length) {
  10470. return this.getScene().defaultMaterial;
  10471. }
  10472. return this.subMaterials[index];
  10473. };
  10474. MultiMaterial.prototype.isReady = function (mesh) {
  10475. for (var index = 0; index < this.subMaterials.length; index++) {
  10476. var subMaterial = this.subMaterials[index];
  10477. if (subMaterial) {
  10478. if (!this.subMaterials[index].isReady(mesh)) {
  10479. return false;
  10480. }
  10481. }
  10482. }
  10483. return true;
  10484. };
  10485. return MultiMaterial;
  10486. })(BABYLON.Material);
  10487. BABYLON.MultiMaterial = MultiMaterial;
  10488. })(BABYLON || (BABYLON = {}));
  10489. var BABYLON;
  10490. (function (BABYLON) {
  10491. var Database = (function () {
  10492. function Database(urlToScene, callbackManifestChecked) {
  10493. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10494. this.callbackManifestChecked = callbackManifestChecked;
  10495. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10496. this.db = null;
  10497. this.enableSceneOffline = false;
  10498. this.enableTexturesOffline = false;
  10499. this.manifestVersionFound = 0;
  10500. this.mustUpdateRessources = false;
  10501. this.hasReachedQuota = false;
  10502. this.checkManifestFile();
  10503. }
  10504. Database.prototype.checkManifestFile = function () {
  10505. var _this = this;
  10506. function noManifestFile() {
  10507. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10508. that.enableSceneOffline = false;
  10509. that.enableTexturesOffline = false;
  10510. that.callbackManifestChecked(false);
  10511. }
  10512. var that = this;
  10513. var manifestURL = this.currentSceneUrl + ".manifest";
  10514. var xhr = new XMLHttpRequest();
  10515. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10516. xhr.open("GET", manifestURLTimeStamped, true);
  10517. xhr.addEventListener("load", function () {
  10518. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10519. try {
  10520. var manifestFile = JSON.parse(xhr.response);
  10521. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10522. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10523. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10524. _this.manifestVersionFound = manifestFile.version;
  10525. }
  10526. if (_this.callbackManifestChecked) {
  10527. _this.callbackManifestChecked(true);
  10528. }
  10529. } catch (ex) {
  10530. noManifestFile();
  10531. }
  10532. } else {
  10533. noManifestFile();
  10534. }
  10535. }, false);
  10536. xhr.addEventListener("error", function (event) {
  10537. noManifestFile();
  10538. }, false);
  10539. try {
  10540. xhr.send();
  10541. } catch (ex) {
  10542. BABYLON.Tools.Error("Error on XHR send request.");
  10543. that.callbackManifestChecked(false);
  10544. }
  10545. };
  10546. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10547. var _this = this;
  10548. function handleError() {
  10549. that.isSupported = false;
  10550. if (errorCallback)
  10551. errorCallback();
  10552. }
  10553. var that = this;
  10554. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10555. this.isSupported = false;
  10556. if (errorCallback)
  10557. errorCallback();
  10558. } else {
  10559. if (!this.db) {
  10560. this.hasReachedQuota = false;
  10561. this.isSupported = true;
  10562. var request = this.idbFactory.open("babylonjs", 1);
  10563. request.onerror = function (event) {
  10564. handleError();
  10565. };
  10566. request.onblocked = function (event) {
  10567. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10568. handleError();
  10569. };
  10570. request.onsuccess = function (event) {
  10571. _this.db = request.result;
  10572. successCallback();
  10573. };
  10574. request.onupgradeneeded = function (event) {
  10575. _this.db = (event.target).result;
  10576. try {
  10577. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10578. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10579. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10580. } catch (ex) {
  10581. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10582. handleError();
  10583. }
  10584. };
  10585. } else {
  10586. if (successCallback)
  10587. successCallback();
  10588. }
  10589. }
  10590. };
  10591. Database.prototype.loadImageFromDB = function (url, image) {
  10592. var _this = this;
  10593. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10594. var saveAndLoadImage = function () {
  10595. if (!_this.hasReachedQuota && _this.db !== null) {
  10596. _this._saveImageIntoDBAsync(completeURL, image);
  10597. } else {
  10598. image.src = url;
  10599. }
  10600. };
  10601. if (!this.mustUpdateRessources) {
  10602. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10603. } else {
  10604. saveAndLoadImage();
  10605. }
  10606. };
  10607. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10608. if (this.isSupported && this.db !== null) {
  10609. var texture;
  10610. var transaction = this.db.transaction(["textures"]);
  10611. transaction.onabort = function (event) {
  10612. image.src = url;
  10613. };
  10614. transaction.oncomplete = function (event) {
  10615. var blobTextureURL;
  10616. if (texture) {
  10617. var URL = window.URL || window.webkitURL;
  10618. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10619. image.onerror = function () {
  10620. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10621. image.src = url;
  10622. };
  10623. image.src = blobTextureURL;
  10624. } else {
  10625. notInDBCallback();
  10626. }
  10627. };
  10628. var getRequest = transaction.objectStore("textures").get(url);
  10629. getRequest.onsuccess = function (event) {
  10630. texture = (event.target).result;
  10631. };
  10632. getRequest.onerror = function (event) {
  10633. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10634. image.src = url;
  10635. };
  10636. } else {
  10637. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10638. image.src = url;
  10639. }
  10640. };
  10641. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10642. var _this = this;
  10643. if (this.isSupported) {
  10644. var generateBlobUrl = function () {
  10645. var blobTextureURL;
  10646. if (blob) {
  10647. var URL = window.URL || window.webkitURL;
  10648. try {
  10649. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10650. } catch (ex) {
  10651. blobTextureURL = URL.createObjectURL(blob);
  10652. }
  10653. }
  10654. image.src = blobTextureURL;
  10655. };
  10656. if (BABYLON.Database.isUASupportingBlobStorage) {
  10657. var xhr = new XMLHttpRequest(), blob;
  10658. xhr.open("GET", url, true);
  10659. xhr.responseType = "blob";
  10660. xhr.addEventListener("load", function () {
  10661. if (xhr.status === 200) {
  10662. blob = xhr.response;
  10663. var transaction = _this.db.transaction(["textures"], "readwrite");
  10664. transaction.onabort = function (event) {
  10665. try {
  10666. if (event.srcElement.error.name === "QuotaExceededError") {
  10667. this.hasReachedQuota = true;
  10668. }
  10669. } catch (ex) {
  10670. }
  10671. generateBlobUrl();
  10672. };
  10673. transaction.oncomplete = function (event) {
  10674. generateBlobUrl();
  10675. };
  10676. var newTexture = { textureUrl: url, data: blob };
  10677. try {
  10678. var addRequest = transaction.objectStore("textures").put(newTexture);
  10679. addRequest.onsuccess = function (event) {
  10680. };
  10681. addRequest.onerror = function (event) {
  10682. generateBlobUrl();
  10683. };
  10684. } catch (ex) {
  10685. if (ex.code === 25) {
  10686. BABYLON.Database.isUASupportingBlobStorage = false;
  10687. }
  10688. image.src = url;
  10689. }
  10690. } else {
  10691. image.src = url;
  10692. }
  10693. }, false);
  10694. xhr.addEventListener("error", function (event) {
  10695. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10696. image.src = url;
  10697. }, false);
  10698. xhr.send();
  10699. } else {
  10700. image.src = url;
  10701. }
  10702. } else {
  10703. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10704. image.src = url;
  10705. }
  10706. };
  10707. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10708. var _this = this;
  10709. var updateVersion = function (event) {
  10710. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10711. };
  10712. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10713. };
  10714. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10715. var _this = this;
  10716. if (this.isSupported) {
  10717. var version;
  10718. try {
  10719. var transaction = this.db.transaction(["versions"]);
  10720. transaction.oncomplete = function (event) {
  10721. if (version) {
  10722. if (_this.manifestVersionFound > version.data) {
  10723. _this.mustUpdateRessources = true;
  10724. updateInDBCallback();
  10725. } else {
  10726. callback(version.data);
  10727. }
  10728. } else {
  10729. _this.mustUpdateRessources = true;
  10730. updateInDBCallback();
  10731. }
  10732. };
  10733. transaction.onabort = function (event) {
  10734. callback(-1);
  10735. };
  10736. var getRequest = transaction.objectStore("versions").get(url);
  10737. getRequest.onsuccess = function (event) {
  10738. version = (event.target).result;
  10739. };
  10740. getRequest.onerror = function (event) {
  10741. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10742. callback(-1);
  10743. };
  10744. } catch (ex) {
  10745. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10746. callback(-1);
  10747. }
  10748. } else {
  10749. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10750. callback(-1);
  10751. }
  10752. };
  10753. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10754. var _this = this;
  10755. if (this.isSupported && !this.hasReachedQuota) {
  10756. try {
  10757. var transaction = this.db.transaction(["versions"], "readwrite");
  10758. transaction.onabort = function (event) {
  10759. try {
  10760. if (event.srcElement.error.name === "QuotaExceededError") {
  10761. _this.hasReachedQuota = true;
  10762. }
  10763. } catch (ex) {
  10764. }
  10765. callback(-1);
  10766. };
  10767. transaction.oncomplete = function (event) {
  10768. callback(_this.manifestVersionFound);
  10769. };
  10770. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10771. var addRequest = transaction.objectStore("versions").put(newVersion);
  10772. addRequest.onsuccess = function (event) {
  10773. };
  10774. addRequest.onerror = function (event) {
  10775. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10776. };
  10777. } catch (ex) {
  10778. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10779. callback(-1);
  10780. }
  10781. } else {
  10782. callback(-1);
  10783. }
  10784. };
  10785. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10786. var _this = this;
  10787. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10788. var saveAndLoadFile = function (event) {
  10789. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10790. };
  10791. this._checkVersionFromDB(completeUrl, function (version) {
  10792. if (version !== -1) {
  10793. if (!_this.mustUpdateRessources) {
  10794. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10795. } else {
  10796. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10797. }
  10798. } else {
  10799. errorCallback();
  10800. }
  10801. });
  10802. };
  10803. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10804. if (this.isSupported) {
  10805. var targetStore;
  10806. if (url.indexOf(".babylon") !== -1) {
  10807. targetStore = "scenes";
  10808. } else {
  10809. targetStore = "textures";
  10810. }
  10811. var file;
  10812. var transaction = this.db.transaction([targetStore]);
  10813. transaction.oncomplete = function (event) {
  10814. if (file) {
  10815. callback(file.data);
  10816. } else {
  10817. notInDBCallback();
  10818. }
  10819. };
  10820. transaction.onabort = function (event) {
  10821. notInDBCallback();
  10822. };
  10823. var getRequest = transaction.objectStore(targetStore).get(url);
  10824. getRequest.onsuccess = function (event) {
  10825. file = (event.target).result;
  10826. };
  10827. getRequest.onerror = function (event) {
  10828. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10829. notInDBCallback();
  10830. };
  10831. } else {
  10832. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10833. callback();
  10834. }
  10835. };
  10836. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10837. var _this = this;
  10838. if (this.isSupported) {
  10839. var targetStore;
  10840. if (url.indexOf(".babylon") !== -1) {
  10841. targetStore = "scenes";
  10842. } else {
  10843. targetStore = "textures";
  10844. }
  10845. var xhr = new XMLHttpRequest(), fileData;
  10846. xhr.open("GET", url, true);
  10847. if (useArrayBuffer) {
  10848. xhr.responseType = "arraybuffer";
  10849. }
  10850. xhr.onprogress = progressCallback;
  10851. xhr.addEventListener("load", function () {
  10852. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10853. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10854. if (!_this.hasReachedQuota) {
  10855. var transaction = _this.db.transaction([targetStore], "readwrite");
  10856. transaction.onabort = function (event) {
  10857. try {
  10858. if (event.srcElement.error.name === "QuotaExceededError") {
  10859. this.hasReachedQuota = true;
  10860. }
  10861. } catch (ex) {
  10862. }
  10863. callback(fileData);
  10864. };
  10865. transaction.oncomplete = function (event) {
  10866. callback(fileData);
  10867. };
  10868. var newFile;
  10869. if (targetStore === "scenes") {
  10870. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10871. } else {
  10872. newFile = { textureUrl: url, data: fileData };
  10873. }
  10874. try {
  10875. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10876. addRequest.onsuccess = function (event) {
  10877. };
  10878. addRequest.onerror = function (event) {
  10879. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10880. };
  10881. } catch (ex) {
  10882. callback(fileData);
  10883. }
  10884. } else {
  10885. callback(fileData);
  10886. }
  10887. } else {
  10888. callback();
  10889. }
  10890. }, false);
  10891. xhr.addEventListener("error", function (event) {
  10892. BABYLON.Tools.Error("error on XHR request.");
  10893. callback();
  10894. }, false);
  10895. xhr.send();
  10896. } else {
  10897. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10898. callback();
  10899. }
  10900. };
  10901. Database.isUASupportingBlobStorage = true;
  10902. Database.parseURL = function (url) {
  10903. var a = document.createElement('a');
  10904. a.href = url;
  10905. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10906. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10907. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10908. return absLocation;
  10909. };
  10910. Database.ReturnFullUrlLocation = function (url) {
  10911. if (url.indexOf("http:/") === -1) {
  10912. return (BABYLON.Database.parseURL(window.location.href) + url);
  10913. } else {
  10914. return url;
  10915. }
  10916. };
  10917. return Database;
  10918. })();
  10919. BABYLON.Database = Database;
  10920. })(BABYLON || (BABYLON = {}));
  10921. var BABYLON;
  10922. (function (BABYLON) {
  10923. var SpriteManager = (function () {
  10924. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10925. this.name = name;
  10926. this.cellSize = cellSize;
  10927. this.sprites = new Array();
  10928. this.renderingGroupId = 0;
  10929. this._vertexDeclaration = [3, 4, 4, 4];
  10930. this._vertexStrideSize = 15 * 4;
  10931. this._capacity = capacity;
  10932. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10933. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10934. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10935. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10936. this._scene = scene;
  10937. this._scene.spriteManagers.push(this);
  10938. this._vertexDeclaration = [3, 4, 4, 4];
  10939. this._vertexStrideSize = 15 * 4;
  10940. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10941. var indices = [];
  10942. var index = 0;
  10943. for (var count = 0; count < capacity; count++) {
  10944. indices.push(index);
  10945. indices.push(index + 1);
  10946. indices.push(index + 2);
  10947. indices.push(index);
  10948. indices.push(index + 2);
  10949. indices.push(index + 3);
  10950. index += 4;
  10951. }
  10952. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10953. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10954. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10955. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10956. }
  10957. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10958. var arrayOffset = index * 15;
  10959. if (offsetX == 0)
  10960. offsetX = this._epsilon;
  10961. else if (offsetX == 1)
  10962. offsetX = 1 - this._epsilon;
  10963. if (offsetY == 0)
  10964. offsetY = this._epsilon;
  10965. else if (offsetY == 1)
  10966. offsetY = 1 - this._epsilon;
  10967. this._vertices[arrayOffset] = sprite.position.x;
  10968. this._vertices[arrayOffset + 1] = sprite.position.y;
  10969. this._vertices[arrayOffset + 2] = sprite.position.z;
  10970. this._vertices[arrayOffset + 3] = sprite.angle;
  10971. this._vertices[arrayOffset + 4] = sprite.size;
  10972. this._vertices[arrayOffset + 5] = offsetX;
  10973. this._vertices[arrayOffset + 6] = offsetY;
  10974. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10975. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10976. var offset = (sprite.cellIndex / rowSize) >> 0;
  10977. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10978. this._vertices[arrayOffset + 10] = offset;
  10979. this._vertices[arrayOffset + 11] = sprite.color.r;
  10980. this._vertices[arrayOffset + 12] = sprite.color.g;
  10981. this._vertices[arrayOffset + 13] = sprite.color.b;
  10982. this._vertices[arrayOffset + 14] = sprite.color.a;
  10983. };
  10984. SpriteManager.prototype.render = function () {
  10985. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10986. return;
  10987. var engine = this._scene.getEngine();
  10988. var baseSize = this._spriteTexture.getBaseSize();
  10989. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10990. var max = Math.min(this._capacity, this.sprites.length);
  10991. var rowSize = baseSize.width / this.cellSize;
  10992. var offset = 0;
  10993. for (var index = 0; index < max; index++) {
  10994. var sprite = this.sprites[index];
  10995. if (!sprite) {
  10996. continue;
  10997. }
  10998. sprite._animate(deltaTime);
  10999. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11000. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11001. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11002. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11003. }
  11004. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11005. var effect = this._effectBase;
  11006. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11007. effect = this._effectFog;
  11008. }
  11009. engine.enableEffect(effect);
  11010. var viewMatrix = this._scene.getViewMatrix();
  11011. effect.setTexture("diffuseSampler", this._spriteTexture);
  11012. effect.setMatrix("view", viewMatrix);
  11013. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11014. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11015. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11016. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11017. effect.setColor3("vFogColor", this._scene.fogColor);
  11018. }
  11019. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11020. effect.setBool("alphaTest", true);
  11021. engine.setColorWrite(false);
  11022. engine.draw(true, 0, max * 6);
  11023. engine.setColorWrite(true);
  11024. effect.setBool("alphaTest", false);
  11025. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11026. engine.draw(true, 0, max * 6);
  11027. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11028. };
  11029. SpriteManager.prototype.dispose = function () {
  11030. if (this._vertexBuffer) {
  11031. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11032. this._vertexBuffer = null;
  11033. }
  11034. if (this._indexBuffer) {
  11035. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11036. this._indexBuffer = null;
  11037. }
  11038. if (this._spriteTexture) {
  11039. this._spriteTexture.dispose();
  11040. this._spriteTexture = null;
  11041. }
  11042. var index = this._scene.spriteManagers.indexOf(this);
  11043. this._scene.spriteManagers.splice(index, 1);
  11044. if (this.onDispose) {
  11045. this.onDispose();
  11046. }
  11047. };
  11048. return SpriteManager;
  11049. })();
  11050. BABYLON.SpriteManager = SpriteManager;
  11051. })(BABYLON || (BABYLON = {}));
  11052. var BABYLON;
  11053. (function (BABYLON) {
  11054. var Sprite = (function () {
  11055. function Sprite(name, manager) {
  11056. this.name = name;
  11057. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11058. this.size = 1.0;
  11059. this.angle = 0;
  11060. this.cellIndex = 0;
  11061. this.invertU = 0;
  11062. this.invertV = 0;
  11063. this.animations = new Array();
  11064. this._animationStarted = false;
  11065. this._loopAnimation = false;
  11066. this._fromIndex = 0;
  11067. this._toIndex = 0;
  11068. this._delay = 0;
  11069. this._direction = 1;
  11070. this._frameCount = 0;
  11071. this._time = 0;
  11072. this._manager = manager;
  11073. this._manager.sprites.push(this);
  11074. this.position = BABYLON.Vector3.Zero();
  11075. }
  11076. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11077. this._fromIndex = from;
  11078. this._toIndex = to;
  11079. this._loopAnimation = loop;
  11080. this._delay = delay;
  11081. this._animationStarted = true;
  11082. this._direction = from < to ? 1 : -1;
  11083. this.cellIndex = from;
  11084. this._time = 0;
  11085. };
  11086. Sprite.prototype.stopAnimation = function () {
  11087. this._animationStarted = false;
  11088. };
  11089. Sprite.prototype._animate = function (deltaTime) {
  11090. if (!this._animationStarted)
  11091. return;
  11092. this._time += deltaTime;
  11093. if (this._time > this._delay) {
  11094. this._time = this._time % this._delay;
  11095. this.cellIndex += this._direction;
  11096. if (this.cellIndex == this._toIndex) {
  11097. if (this._loopAnimation) {
  11098. this.cellIndex = this._fromIndex;
  11099. } else {
  11100. this._animationStarted = false;
  11101. if (this.disposeWhenFinishedAnimating) {
  11102. this.dispose();
  11103. }
  11104. }
  11105. }
  11106. }
  11107. };
  11108. Sprite.prototype.dispose = function () {
  11109. for (var i = 0; i < this._manager.sprites.length; i++) {
  11110. if (this._manager.sprites[i] == this) {
  11111. this._manager.sprites.splice(i, 1);
  11112. }
  11113. }
  11114. };
  11115. return Sprite;
  11116. })();
  11117. BABYLON.Sprite = Sprite;
  11118. })(BABYLON || (BABYLON = {}));
  11119. var BABYLON;
  11120. (function (BABYLON) {
  11121. var Layer = (function () {
  11122. function Layer(name, imgUrl, scene, isBackground, color) {
  11123. this.name = name;
  11124. this._vertexDeclaration = [2];
  11125. this._vertexStrideSize = 2 * 4;
  11126. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11127. this.isBackground = isBackground === undefined ? true : isBackground;
  11128. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11129. this._scene = scene;
  11130. this._scene.layers.push(this);
  11131. var vertices = [];
  11132. vertices.push(1, 1);
  11133. vertices.push(-1, 1);
  11134. vertices.push(-1, -1);
  11135. vertices.push(1, -1);
  11136. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11137. var indices = [];
  11138. indices.push(0);
  11139. indices.push(1);
  11140. indices.push(2);
  11141. indices.push(0);
  11142. indices.push(2);
  11143. indices.push(3);
  11144. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11145. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11146. }
  11147. Layer.prototype.render = function () {
  11148. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11149. return;
  11150. var engine = this._scene.getEngine();
  11151. engine.enableEffect(this._effect);
  11152. engine.setState(false);
  11153. this._effect.setTexture("textureSampler", this.texture);
  11154. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11155. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11156. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11157. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11158. engine.draw(true, 0, 6);
  11159. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11160. };
  11161. Layer.prototype.dispose = function () {
  11162. if (this._vertexBuffer) {
  11163. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11164. this._vertexBuffer = null;
  11165. }
  11166. if (this._indexBuffer) {
  11167. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11168. this._indexBuffer = null;
  11169. }
  11170. if (this.texture) {
  11171. this.texture.dispose();
  11172. this.texture = null;
  11173. }
  11174. var index = this._scene.layers.indexOf(this);
  11175. this._scene.layers.splice(index, 1);
  11176. if (this.onDispose) {
  11177. this.onDispose();
  11178. }
  11179. };
  11180. return Layer;
  11181. })();
  11182. BABYLON.Layer = Layer;
  11183. })(BABYLON || (BABYLON = {}));
  11184. var BABYLON;
  11185. (function (BABYLON) {
  11186. var Particle = (function () {
  11187. function Particle() {
  11188. this.position = BABYLON.Vector3.Zero();
  11189. this.direction = BABYLON.Vector3.Zero();
  11190. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11191. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11192. this.lifeTime = 1.0;
  11193. this.age = 0;
  11194. this.size = 0;
  11195. this.angle = 0;
  11196. this.angularSpeed = 0;
  11197. }
  11198. return Particle;
  11199. })();
  11200. BABYLON.Particle = Particle;
  11201. })(BABYLON || (BABYLON = {}));
  11202. var BABYLON;
  11203. (function (BABYLON) {
  11204. var randomNumber = function (min, max) {
  11205. if (min == max) {
  11206. return (min);
  11207. }
  11208. var random = Math.random();
  11209. return ((random * (max - min)) + min);
  11210. };
  11211. var ParticleSystem = (function () {
  11212. function ParticleSystem(name, capacity, scene, customEffect) {
  11213. var _this = this;
  11214. this.name = name;
  11215. this.renderingGroupId = 0;
  11216. this.emitter = null;
  11217. this.emitRate = 10;
  11218. this.manualEmitCount = -1;
  11219. this.updateSpeed = 0.01;
  11220. this.targetStopDuration = 0;
  11221. this.disposeOnStop = false;
  11222. this.minEmitPower = 1;
  11223. this.maxEmitPower = 1;
  11224. this.minLifeTime = 1;
  11225. this.maxLifeTime = 1;
  11226. this.minSize = 1;
  11227. this.maxSize = 1;
  11228. this.minAngularSpeed = 0;
  11229. this.maxAngularSpeed = 0;
  11230. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11231. this.forceDepthWrite = false;
  11232. this.gravity = BABYLON.Vector3.Zero();
  11233. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11234. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11235. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11236. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11237. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11238. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11239. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11240. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11241. this.particles = new Array();
  11242. this._vertexDeclaration = [3, 4, 4];
  11243. this._vertexStrideSize = 11 * 4;
  11244. this._stockParticles = new Array();
  11245. this._newPartsExcess = 0;
  11246. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11247. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11248. this._scaledDirection = BABYLON.Vector3.Zero();
  11249. this._scaledGravity = BABYLON.Vector3.Zero();
  11250. this._currentRenderId = -1;
  11251. this._started = false;
  11252. this._stopped = false;
  11253. this._actualFrame = 0;
  11254. this.id = name;
  11255. this._capacity = capacity;
  11256. this._scene = scene;
  11257. this._customEffect = customEffect;
  11258. scene.particleSystems.push(this);
  11259. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11260. var indices = [];
  11261. var index = 0;
  11262. for (var count = 0; count < capacity; count++) {
  11263. indices.push(index);
  11264. indices.push(index + 1);
  11265. indices.push(index + 2);
  11266. indices.push(index);
  11267. indices.push(index + 2);
  11268. indices.push(index + 3);
  11269. index += 4;
  11270. }
  11271. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11272. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11273. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11274. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11275. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11276. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11277. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11278. };
  11279. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11280. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11281. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11282. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11283. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11284. };
  11285. }
  11286. ParticleSystem.prototype.getCapacity = function () {
  11287. return this._capacity;
  11288. };
  11289. ParticleSystem.prototype.isAlive = function () {
  11290. return this._alive;
  11291. };
  11292. ParticleSystem.prototype.isStarted = function () {
  11293. return this._started;
  11294. };
  11295. ParticleSystem.prototype.start = function () {
  11296. this._started = true;
  11297. this._stopped = false;
  11298. this._actualFrame = 0;
  11299. };
  11300. ParticleSystem.prototype.stop = function () {
  11301. this._stopped = true;
  11302. };
  11303. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11304. var offset = index * 11;
  11305. this._vertices[offset] = particle.position.x;
  11306. this._vertices[offset + 1] = particle.position.y;
  11307. this._vertices[offset + 2] = particle.position.z;
  11308. this._vertices[offset + 3] = particle.color.r;
  11309. this._vertices[offset + 4] = particle.color.g;
  11310. this._vertices[offset + 5] = particle.color.b;
  11311. this._vertices[offset + 6] = particle.color.a;
  11312. this._vertices[offset + 7] = particle.angle;
  11313. this._vertices[offset + 8] = particle.size;
  11314. this._vertices[offset + 9] = offsetX;
  11315. this._vertices[offset + 10] = offsetY;
  11316. };
  11317. ParticleSystem.prototype._update = function (newParticles) {
  11318. this._alive = this.particles.length > 0;
  11319. for (var index = 0; index < this.particles.length; index++) {
  11320. var particle = this.particles[index];
  11321. particle.age += this._scaledUpdateSpeed;
  11322. if (particle.age >= particle.lifeTime) {
  11323. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11324. index--;
  11325. continue;
  11326. } else {
  11327. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11328. particle.color.addInPlace(this._scaledColorStep);
  11329. if (particle.color.a < 0)
  11330. particle.color.a = 0;
  11331. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11332. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11333. particle.position.addInPlace(this._scaledDirection);
  11334. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11335. particle.direction.addInPlace(this._scaledGravity);
  11336. }
  11337. }
  11338. var worldMatrix;
  11339. if (this.emitter.position) {
  11340. worldMatrix = this.emitter.getWorldMatrix();
  11341. } else {
  11342. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11343. }
  11344. for (index = 0; index < newParticles; index++) {
  11345. if (this.particles.length == this._capacity) {
  11346. break;
  11347. }
  11348. if (this._stockParticles.length !== 0) {
  11349. particle = this._stockParticles.pop();
  11350. particle.age = 0;
  11351. } else {
  11352. particle = new BABYLON.Particle();
  11353. }
  11354. this.particles.push(particle);
  11355. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11356. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11357. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11358. particle.size = randomNumber(this.minSize, this.maxSize);
  11359. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11360. this.startPositionFunction(worldMatrix, particle.position);
  11361. var step = randomNumber(0, 1.0);
  11362. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11363. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11364. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11365. }
  11366. };
  11367. ParticleSystem.prototype._getEffect = function () {
  11368. if (this._customEffect) {
  11369. return this._customEffect;
  11370. }
  11371. ;
  11372. var defines = [];
  11373. if (this._scene.clipPlane) {
  11374. defines.push("#define CLIPPLANE");
  11375. }
  11376. var join = defines.join("\n");
  11377. if (this._cachedDefines != join) {
  11378. this._cachedDefines = join;
  11379. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11380. }
  11381. return this._effect;
  11382. };
  11383. ParticleSystem.prototype.animate = function () {
  11384. if (!this._started)
  11385. return;
  11386. var effect = this._getEffect();
  11387. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11388. return;
  11389. if (this._currentRenderId === this._scene.getRenderId()) {
  11390. return;
  11391. }
  11392. this._currentRenderId = this._scene.getRenderId();
  11393. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11394. var emitCout;
  11395. if (this.manualEmitCount > -1) {
  11396. emitCout = this.manualEmitCount;
  11397. this.manualEmitCount = 0;
  11398. } else {
  11399. emitCout = this.emitRate;
  11400. }
  11401. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11402. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11403. if (this._newPartsExcess > 1.0) {
  11404. newParticles += this._newPartsExcess >> 0;
  11405. this._newPartsExcess -= this._newPartsExcess >> 0;
  11406. }
  11407. this._alive = false;
  11408. if (!this._stopped) {
  11409. this._actualFrame += this._scaledUpdateSpeed;
  11410. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11411. this.stop();
  11412. } else {
  11413. newParticles = 0;
  11414. }
  11415. this._update(newParticles);
  11416. if (this._stopped) {
  11417. if (!this._alive) {
  11418. this._started = false;
  11419. if (this.disposeOnStop) {
  11420. this._scene._toBeDisposed.push(this);
  11421. }
  11422. }
  11423. }
  11424. var offset = 0;
  11425. for (var index = 0; index < this.particles.length; index++) {
  11426. var particle = this.particles[index];
  11427. this._appendParticleVertex(offset++, particle, 0, 0);
  11428. this._appendParticleVertex(offset++, particle, 1, 0);
  11429. this._appendParticleVertex(offset++, particle, 1, 1);
  11430. this._appendParticleVertex(offset++, particle, 0, 1);
  11431. }
  11432. var engine = this._scene.getEngine();
  11433. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11434. };
  11435. ParticleSystem.prototype.render = function () {
  11436. var effect = this._getEffect();
  11437. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11438. return 0;
  11439. var engine = this._scene.getEngine();
  11440. engine.enableEffect(effect);
  11441. var viewMatrix = this._scene.getViewMatrix();
  11442. effect.setTexture("diffuseSampler", this.particleTexture);
  11443. effect.setMatrix("view", viewMatrix);
  11444. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11445. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11446. if (this._scene.clipPlane) {
  11447. var clipPlane = this._scene.clipPlane;
  11448. var invView = viewMatrix.clone();
  11449. invView.invert();
  11450. effect.setMatrix("invView", invView);
  11451. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11452. }
  11453. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11454. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11455. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11456. } else {
  11457. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11458. }
  11459. if (this.forceDepthWrite) {
  11460. engine.setDepthWrite(true);
  11461. }
  11462. engine.draw(true, 0, this.particles.length * 6);
  11463. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11464. return this.particles.length;
  11465. };
  11466. ParticleSystem.prototype.dispose = function () {
  11467. if (this._vertexBuffer) {
  11468. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11469. this._vertexBuffer = null;
  11470. }
  11471. if (this._indexBuffer) {
  11472. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11473. this._indexBuffer = null;
  11474. }
  11475. if (this.particleTexture) {
  11476. this.particleTexture.dispose();
  11477. this.particleTexture = null;
  11478. }
  11479. var index = this._scene.particleSystems.indexOf(this);
  11480. this._scene.particleSystems.splice(index, 1);
  11481. if (this.onDispose) {
  11482. this.onDispose();
  11483. }
  11484. };
  11485. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11486. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11487. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11488. if (newEmitter === undefined) {
  11489. newEmitter = this.emitter;
  11490. }
  11491. result.emitter = newEmitter;
  11492. if (this.particleTexture) {
  11493. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11494. }
  11495. result.start();
  11496. return result;
  11497. };
  11498. ParticleSystem.BLENDMODE_ONEONE = 0;
  11499. ParticleSystem.BLENDMODE_STANDARD = 1;
  11500. return ParticleSystem;
  11501. })();
  11502. BABYLON.ParticleSystem = ParticleSystem;
  11503. })(BABYLON || (BABYLON = {}));
  11504. var BABYLON;
  11505. (function (BABYLON) {
  11506. var Animation = (function () {
  11507. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11508. this.name = name;
  11509. this.targetProperty = targetProperty;
  11510. this.framePerSecond = framePerSecond;
  11511. this.dataType = dataType;
  11512. this.loopMode = loopMode;
  11513. this._offsetsCache = {};
  11514. this._highLimitsCache = {};
  11515. this._stopped = false;
  11516. this.targetPropertyPath = targetProperty.split(".");
  11517. this.dataType = dataType;
  11518. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11519. }
  11520. Animation.prototype.isStopped = function () {
  11521. return this._stopped;
  11522. };
  11523. Animation.prototype.getKeys = function () {
  11524. return this._keys;
  11525. };
  11526. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11527. return startValue + (endValue - startValue) * gradient;
  11528. };
  11529. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11530. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11531. };
  11532. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11533. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11534. };
  11535. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11536. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11537. };
  11538. Animation.prototype.clone = function () {
  11539. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11540. clone.setKeys(this._keys);
  11541. return clone;
  11542. };
  11543. Animation.prototype.setKeys = function (values) {
  11544. this._keys = values.slice(0);
  11545. this._offsetsCache = {};
  11546. this._highLimitsCache = {};
  11547. };
  11548. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11549. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11550. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11551. }
  11552. this.currentFrame = currentFrame;
  11553. for (var key = 0; key < this._keys.length; key++) {
  11554. if (this._keys[key + 1].frame >= currentFrame) {
  11555. var startValue = this._keys[key].value;
  11556. var endValue = this._keys[key + 1].value;
  11557. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11558. switch (this.dataType) {
  11559. case Animation.ANIMATIONTYPE_FLOAT:
  11560. switch (loopMode) {
  11561. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11562. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11563. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11564. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11565. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11566. }
  11567. break;
  11568. case Animation.ANIMATIONTYPE_QUATERNION:
  11569. var quaternion = null;
  11570. switch (loopMode) {
  11571. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11572. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11573. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11574. break;
  11575. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11576. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11577. break;
  11578. }
  11579. return quaternion;
  11580. case Animation.ANIMATIONTYPE_VECTOR3:
  11581. switch (loopMode) {
  11582. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11583. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11584. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11585. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11586. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11587. }
  11588. case Animation.ANIMATIONTYPE_COLOR3:
  11589. switch (loopMode) {
  11590. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11591. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11592. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11593. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11594. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11595. }
  11596. case Animation.ANIMATIONTYPE_MATRIX:
  11597. switch (loopMode) {
  11598. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11599. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11600. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11601. return startValue;
  11602. }
  11603. default:
  11604. break;
  11605. }
  11606. break;
  11607. }
  11608. }
  11609. return this._keys[this._keys.length - 1].value;
  11610. };
  11611. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11612. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11613. this._stopped = true;
  11614. return false;
  11615. }
  11616. var returnValue = true;
  11617. if (this._keys[0].frame != 0) {
  11618. var newKey = {
  11619. frame: 0,
  11620. value: this._keys[0].value
  11621. };
  11622. this._keys.splice(0, 0, newKey);
  11623. }
  11624. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11625. from = this._keys[0].frame;
  11626. }
  11627. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11628. to = this._keys[this._keys.length - 1].frame;
  11629. }
  11630. var range = to - from;
  11631. var offsetValue;
  11632. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11633. if (ratio > range && !loop) {
  11634. returnValue = false;
  11635. highLimitValue = this._keys[this._keys.length - 1].value;
  11636. } else {
  11637. var highLimitValue = 0;
  11638. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11639. var keyOffset = to.toString() + from.toString();
  11640. if (!this._offsetsCache[keyOffset]) {
  11641. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11642. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11643. switch (this.dataType) {
  11644. case Animation.ANIMATIONTYPE_FLOAT:
  11645. this._offsetsCache[keyOffset] = toValue - fromValue;
  11646. break;
  11647. case Animation.ANIMATIONTYPE_QUATERNION:
  11648. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11649. break;
  11650. case Animation.ANIMATIONTYPE_VECTOR3:
  11651. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11652. case Animation.ANIMATIONTYPE_COLOR3:
  11653. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11654. default:
  11655. break;
  11656. }
  11657. this._highLimitsCache[keyOffset] = toValue;
  11658. }
  11659. highLimitValue = this._highLimitsCache[keyOffset];
  11660. offsetValue = this._offsetsCache[keyOffset];
  11661. }
  11662. }
  11663. if (offsetValue === undefined) {
  11664. switch (this.dataType) {
  11665. case Animation.ANIMATIONTYPE_FLOAT:
  11666. offsetValue = 0;
  11667. break;
  11668. case Animation.ANIMATIONTYPE_QUATERNION:
  11669. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11670. break;
  11671. case Animation.ANIMATIONTYPE_VECTOR3:
  11672. offsetValue = BABYLON.Vector3.Zero();
  11673. break;
  11674. case Animation.ANIMATIONTYPE_COLOR3:
  11675. offsetValue = BABYLON.Color3.Black();
  11676. }
  11677. }
  11678. var repeatCount = (ratio / range) >> 0;
  11679. var currentFrame = returnValue ? from + ratio % range : to;
  11680. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11681. if (this.targetPropertyPath.length > 1) {
  11682. var property = this._target[this.targetPropertyPath[0]];
  11683. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11684. property = property[this.targetPropertyPath[index]];
  11685. }
  11686. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11687. } else {
  11688. this._target[this.targetPropertyPath[0]] = currentValue;
  11689. }
  11690. if (this._target.markAsDirty) {
  11691. this._target.markAsDirty(this.targetProperty);
  11692. }
  11693. if (!returnValue) {
  11694. this._stopped = true;
  11695. }
  11696. return returnValue;
  11697. };
  11698. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11699. get: function () {
  11700. return Animation._ANIMATIONTYPE_FLOAT;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11706. get: function () {
  11707. return Animation._ANIMATIONTYPE_VECTOR3;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11713. get: function () {
  11714. return Animation._ANIMATIONTYPE_QUATERNION;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11720. get: function () {
  11721. return Animation._ANIMATIONTYPE_MATRIX;
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11727. get: function () {
  11728. return Animation._ANIMATIONTYPE_COLOR3;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11734. get: function () {
  11735. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11741. get: function () {
  11742. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11748. get: function () {
  11749. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Animation._ANIMATIONTYPE_FLOAT = 0;
  11755. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11756. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11757. Animation._ANIMATIONTYPE_MATRIX = 3;
  11758. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11759. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11760. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11761. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11762. return Animation;
  11763. })();
  11764. BABYLON.Animation = Animation;
  11765. })(BABYLON || (BABYLON = {}));
  11766. var BABYLON;
  11767. (function (BABYLON) {
  11768. var Animatable = (function () {
  11769. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11770. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11771. if (typeof toFrame === "undefined") { toFrame = 100; }
  11772. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11773. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11774. this.target = target;
  11775. this.fromFrame = fromFrame;
  11776. this.toFrame = toFrame;
  11777. this.loopAnimation = loopAnimation;
  11778. this.speedRatio = speedRatio;
  11779. this.onAnimationEnd = onAnimationEnd;
  11780. this._animations = new Array();
  11781. this._paused = false;
  11782. this.animationStarted = false;
  11783. if (animations) {
  11784. this.appendAnimations(target, animations);
  11785. }
  11786. this._scene = scene;
  11787. scene._activeAnimatables.push(this);
  11788. }
  11789. Animatable.prototype.appendAnimations = function (target, animations) {
  11790. for (var index = 0; index < animations.length; index++) {
  11791. var animation = animations[index];
  11792. animation._target = target;
  11793. this._animations.push(animation);
  11794. }
  11795. };
  11796. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11797. var animations = this._animations;
  11798. for (var index = 0; index < animations.length; index++) {
  11799. if (animations[index].targetProperty === property) {
  11800. return animations[index];
  11801. }
  11802. }
  11803. return null;
  11804. };
  11805. Animatable.prototype.pause = function () {
  11806. this._paused = true;
  11807. };
  11808. Animatable.prototype.restart = function () {
  11809. this._paused = false;
  11810. };
  11811. Animatable.prototype.stop = function () {
  11812. var index = this._scene._activeAnimatables.indexOf(this);
  11813. if (index > -1) {
  11814. this._scene._activeAnimatables.splice(index, 1);
  11815. }
  11816. if (this.onAnimationEnd) {
  11817. this.onAnimationEnd();
  11818. }
  11819. };
  11820. Animatable.prototype._animate = function (delay) {
  11821. if (this._paused) {
  11822. return true;
  11823. }
  11824. if (!this._localDelayOffset) {
  11825. this._localDelayOffset = delay;
  11826. }
  11827. var running = false;
  11828. var animations = this._animations;
  11829. for (var index = 0; index < animations.length; index++) {
  11830. var animation = animations[index];
  11831. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11832. running = running || isRunning;
  11833. }
  11834. if (!running && this.onAnimationEnd) {
  11835. this.onAnimationEnd();
  11836. }
  11837. return running;
  11838. };
  11839. return Animatable;
  11840. })();
  11841. BABYLON.Animatable = Animatable;
  11842. })(BABYLON || (BABYLON = {}));
  11843. var BABYLON;
  11844. (function (BABYLON) {
  11845. var Octree = (function () {
  11846. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11847. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11848. this.maxDepth = maxDepth;
  11849. this.dynamicContent = new Array();
  11850. this._maxBlockCapacity = maxBlockCapacity || 64;
  11851. this._selectionContent = new BABYLON.SmartArray(1024);
  11852. this._creationFunc = creationFunc;
  11853. }
  11854. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11855. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11856. };
  11857. Octree.prototype.addMesh = function (entry) {
  11858. for (var index = 0; index < this.blocks.length; index++) {
  11859. var block = this.blocks[index];
  11860. block.addEntry(entry);
  11861. }
  11862. };
  11863. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11864. this._selectionContent.reset();
  11865. for (var index = 0; index < this.blocks.length; index++) {
  11866. var block = this.blocks[index];
  11867. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11868. }
  11869. if (allowDuplicate) {
  11870. this._selectionContent.concat(this.dynamicContent);
  11871. } else {
  11872. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11873. }
  11874. return this._selectionContent;
  11875. };
  11876. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11877. this._selectionContent.reset();
  11878. for (var index = 0; index < this.blocks.length; index++) {
  11879. var block = this.blocks[index];
  11880. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11881. }
  11882. if (allowDuplicate) {
  11883. this._selectionContent.concat(this.dynamicContent);
  11884. } else {
  11885. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11886. }
  11887. return this._selectionContent;
  11888. };
  11889. Octree.prototype.intersectsRay = function (ray) {
  11890. this._selectionContent.reset();
  11891. for (var index = 0; index < this.blocks.length; index++) {
  11892. var block = this.blocks[index];
  11893. block.intersectsRay(ray, this._selectionContent);
  11894. }
  11895. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11896. return this._selectionContent;
  11897. };
  11898. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11899. target.blocks = new Array();
  11900. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11901. for (var x = 0; x < 2; x++) {
  11902. for (var y = 0; y < 2; y++) {
  11903. for (var z = 0; z < 2; z++) {
  11904. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11905. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11906. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11907. block.addEntries(entries);
  11908. target.blocks.push(block);
  11909. }
  11910. }
  11911. }
  11912. };
  11913. Octree.CreationFuncForMeshes = function (entry, block) {
  11914. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11915. block.entries.push(entry);
  11916. }
  11917. };
  11918. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11919. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11920. block.entries.push(entry);
  11921. }
  11922. };
  11923. return Octree;
  11924. })();
  11925. BABYLON.Octree = Octree;
  11926. })(BABYLON || (BABYLON = {}));
  11927. var BABYLON;
  11928. (function (BABYLON) {
  11929. var OctreeBlock = (function () {
  11930. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11931. this.entries = new Array();
  11932. this._boundingVectors = new Array();
  11933. this._capacity = capacity;
  11934. this._depth = depth;
  11935. this._maxDepth = maxDepth;
  11936. this._creationFunc = creationFunc;
  11937. this._minPoint = minPoint;
  11938. this._maxPoint = maxPoint;
  11939. this._boundingVectors.push(minPoint.clone());
  11940. this._boundingVectors.push(maxPoint.clone());
  11941. this._boundingVectors.push(minPoint.clone());
  11942. this._boundingVectors[2].x = maxPoint.x;
  11943. this._boundingVectors.push(minPoint.clone());
  11944. this._boundingVectors[3].y = maxPoint.y;
  11945. this._boundingVectors.push(minPoint.clone());
  11946. this._boundingVectors[4].z = maxPoint.z;
  11947. this._boundingVectors.push(maxPoint.clone());
  11948. this._boundingVectors[5].z = minPoint.z;
  11949. this._boundingVectors.push(maxPoint.clone());
  11950. this._boundingVectors[6].x = minPoint.x;
  11951. this._boundingVectors.push(maxPoint.clone());
  11952. this._boundingVectors[7].y = minPoint.y;
  11953. }
  11954. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11955. get: function () {
  11956. return this._capacity;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11962. get: function () {
  11963. return this._minPoint;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11969. get: function () {
  11970. return this._maxPoint;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. OctreeBlock.prototype.addEntry = function (entry) {
  11976. if (this.blocks) {
  11977. for (var index = 0; index < this.blocks.length; index++) {
  11978. var block = this.blocks[index];
  11979. block.addEntry(entry);
  11980. }
  11981. return;
  11982. }
  11983. this._creationFunc(entry, this);
  11984. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11985. this.createInnerBlocks();
  11986. }
  11987. };
  11988. OctreeBlock.prototype.addEntries = function (entries) {
  11989. for (var index = 0; index < entries.length; index++) {
  11990. var mesh = entries[index];
  11991. this.addEntry(mesh);
  11992. }
  11993. };
  11994. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11995. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11996. if (this.blocks) {
  11997. for (var index = 0; index < this.blocks.length; index++) {
  11998. var block = this.blocks[index];
  11999. block.select(frustumPlanes, selection, allowDuplicate);
  12000. }
  12001. return;
  12002. }
  12003. if (allowDuplicate) {
  12004. selection.concat(this.entries);
  12005. } else {
  12006. selection.concatWithNoDuplicate(this.entries);
  12007. }
  12008. }
  12009. };
  12010. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12011. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12012. if (this.blocks) {
  12013. for (var index = 0; index < this.blocks.length; index++) {
  12014. var block = this.blocks[index];
  12015. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12016. }
  12017. return;
  12018. }
  12019. if (allowDuplicate) {
  12020. selection.concat(this.entries);
  12021. } else {
  12022. selection.concatWithNoDuplicate(this.entries);
  12023. }
  12024. }
  12025. };
  12026. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12027. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12028. if (this.blocks) {
  12029. for (var index = 0; index < this.blocks.length; index++) {
  12030. var block = this.blocks[index];
  12031. block.intersectsRay(ray, selection);
  12032. }
  12033. return;
  12034. }
  12035. selection.concatWithNoDuplicate(this.entries);
  12036. }
  12037. };
  12038. OctreeBlock.prototype.createInnerBlocks = function () {
  12039. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12040. };
  12041. return OctreeBlock;
  12042. })();
  12043. BABYLON.OctreeBlock = OctreeBlock;
  12044. })(BABYLON || (BABYLON = {}));
  12045. var BABYLON;
  12046. (function (BABYLON) {
  12047. var Bone = (function () {
  12048. function Bone(name, skeleton, parentBone, matrix) {
  12049. this.name = name;
  12050. this.children = new Array();
  12051. this.animations = new Array();
  12052. this._worldTransform = new BABYLON.Matrix();
  12053. this._absoluteTransform = new BABYLON.Matrix();
  12054. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12055. this._skeleton = skeleton;
  12056. this._matrix = matrix;
  12057. this._baseMatrix = matrix;
  12058. skeleton.bones.push(this);
  12059. if (parentBone) {
  12060. this._parent = parentBone;
  12061. parentBone.children.push(this);
  12062. } else {
  12063. this._parent = null;
  12064. }
  12065. this._updateDifferenceMatrix();
  12066. }
  12067. Bone.prototype.getParent = function () {
  12068. return this._parent;
  12069. };
  12070. Bone.prototype.getLocalMatrix = function () {
  12071. return this._matrix;
  12072. };
  12073. Bone.prototype.getBaseMatrix = function () {
  12074. return this._baseMatrix;
  12075. };
  12076. Bone.prototype.getWorldMatrix = function () {
  12077. return this._worldTransform;
  12078. };
  12079. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12080. return this._invertedAbsoluteTransform;
  12081. };
  12082. Bone.prototype.getAbsoluteMatrix = function () {
  12083. var matrix = this._matrix.clone();
  12084. var parent = this._parent;
  12085. while (parent) {
  12086. matrix = matrix.multiply(parent.getLocalMatrix());
  12087. parent = parent.getParent();
  12088. }
  12089. return matrix;
  12090. };
  12091. Bone.prototype.updateMatrix = function (matrix) {
  12092. this._matrix = matrix;
  12093. this._skeleton._markAsDirty();
  12094. this._updateDifferenceMatrix();
  12095. };
  12096. Bone.prototype._updateDifferenceMatrix = function () {
  12097. if (this._parent) {
  12098. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12099. } else {
  12100. this._absoluteTransform.copyFrom(this._matrix);
  12101. }
  12102. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12103. for (var index = 0; index < this.children.length; index++) {
  12104. this.children[index]._updateDifferenceMatrix();
  12105. }
  12106. };
  12107. Bone.prototype.markAsDirty = function () {
  12108. this._skeleton._markAsDirty();
  12109. };
  12110. return Bone;
  12111. })();
  12112. BABYLON.Bone = Bone;
  12113. })(BABYLON || (BABYLON = {}));
  12114. var BABYLON;
  12115. (function (BABYLON) {
  12116. var Skeleton = (function () {
  12117. function Skeleton(name, id, scene) {
  12118. this.name = name;
  12119. this.id = id;
  12120. this.bones = new Array();
  12121. this._isDirty = true;
  12122. this._identity = BABYLON.Matrix.Identity();
  12123. this.bones = [];
  12124. this._scene = scene;
  12125. scene.skeletons.push(this);
  12126. }
  12127. Skeleton.prototype.getTransformMatrices = function () {
  12128. return this._transformMatrices;
  12129. };
  12130. Skeleton.prototype._markAsDirty = function () {
  12131. this._isDirty = true;
  12132. };
  12133. Skeleton.prototype.prepare = function () {
  12134. if (!this._isDirty) {
  12135. return;
  12136. }
  12137. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12138. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12139. }
  12140. for (var index = 0; index < this.bones.length; index++) {
  12141. var bone = this.bones[index];
  12142. var parentBone = bone.getParent();
  12143. if (parentBone) {
  12144. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12145. } else {
  12146. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12147. }
  12148. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12149. }
  12150. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12151. this._isDirty = false;
  12152. };
  12153. Skeleton.prototype.getAnimatables = function () {
  12154. if (!this._animatables || this._animatables.length != this.bones.length) {
  12155. this._animatables = [];
  12156. for (var index = 0; index < this.bones.length; index++) {
  12157. this._animatables.push(this.bones[index]);
  12158. }
  12159. }
  12160. return this._animatables;
  12161. };
  12162. Skeleton.prototype.clone = function (name, id) {
  12163. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12164. for (var index = 0; index < this.bones.length; index++) {
  12165. var source = this.bones[index];
  12166. var parentBone = null;
  12167. if (source.getParent()) {
  12168. var parentIndex = this.bones.indexOf(source.getParent());
  12169. parentBone = result.bones[parentIndex];
  12170. }
  12171. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12172. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12173. }
  12174. return result;
  12175. };
  12176. return Skeleton;
  12177. })();
  12178. BABYLON.Skeleton = Skeleton;
  12179. })(BABYLON || (BABYLON = {}));
  12180. var BABYLON;
  12181. (function (BABYLON) {
  12182. var PostProcess = (function () {
  12183. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12184. this.name = name;
  12185. this.width = -1;
  12186. this.height = -1;
  12187. this._reusable = false;
  12188. this._textures = new BABYLON.SmartArray(2);
  12189. this._currentRenderTextureInd = 0;
  12190. if (camera != null) {
  12191. this._camera = camera;
  12192. this._scene = camera.getScene();
  12193. camera.attachPostProcess(this);
  12194. this._engine = this._scene.getEngine();
  12195. } else {
  12196. this._engine = engine;
  12197. }
  12198. this._renderRatio = ratio;
  12199. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12200. this._reusable = reusable || false;
  12201. samplers = samplers || [];
  12202. samplers.push("textureSampler");
  12203. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12204. }
  12205. PostProcess.prototype.isReusable = function () {
  12206. return this._reusable;
  12207. };
  12208. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12209. camera = camera || this._camera;
  12210. var scene = camera.getScene();
  12211. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12212. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12213. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12214. if (this._textures.length > 0) {
  12215. for (var i = 0; i < this._textures.length; i++) {
  12216. this._engine._releaseTexture(this._textures.data[i]);
  12217. }
  12218. this._textures.reset();
  12219. }
  12220. this.width = desiredWidth;
  12221. this.height = desiredHeight;
  12222. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  12223. if (this._reusable) {
  12224. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  12225. }
  12226. if (this.onSizeChanged) {
  12227. this.onSizeChanged();
  12228. }
  12229. }
  12230. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12231. if (this.onActivate) {
  12232. this.onActivate(camera);
  12233. }
  12234. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12235. if (this._reusable) {
  12236. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12237. }
  12238. };
  12239. PostProcess.prototype.apply = function () {
  12240. if (!this._effect.isReady())
  12241. return null;
  12242. this._engine.enableEffect(this._effect);
  12243. this._engine.setState(false);
  12244. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12245. this._engine.setDepthBuffer(false);
  12246. this._engine.setDepthWrite(false);
  12247. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12248. if (this.onApply) {
  12249. this.onApply(this._effect);
  12250. }
  12251. return this._effect;
  12252. };
  12253. PostProcess.prototype.dispose = function (camera) {
  12254. camera = camera || this._camera;
  12255. if (this._textures.length > 0) {
  12256. for (var i = 0; i < this._textures.length; i++) {
  12257. this._engine._releaseTexture(this._textures.data[i]);
  12258. }
  12259. this._textures.reset();
  12260. }
  12261. camera.detachPostProcess(this);
  12262. var index = camera._postProcesses.indexOf(this);
  12263. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12264. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12265. }
  12266. };
  12267. return PostProcess;
  12268. })();
  12269. BABYLON.PostProcess = PostProcess;
  12270. })(BABYLON || (BABYLON = {}));
  12271. var BABYLON;
  12272. (function (BABYLON) {
  12273. var PostProcessManager = (function () {
  12274. function PostProcessManager(scene) {
  12275. this._vertexDeclaration = [2];
  12276. this._vertexStrideSize = 2 * 4;
  12277. this._scene = scene;
  12278. var vertices = [];
  12279. vertices.push(1, 1);
  12280. vertices.push(-1, 1);
  12281. vertices.push(-1, -1);
  12282. vertices.push(1, -1);
  12283. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12284. var indices = [];
  12285. indices.push(0);
  12286. indices.push(1);
  12287. indices.push(2);
  12288. indices.push(0);
  12289. indices.push(2);
  12290. indices.push(3);
  12291. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12292. }
  12293. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12294. var postProcesses = this._scene.activeCamera._postProcesses;
  12295. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12296. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12297. return false;
  12298. }
  12299. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12300. return true;
  12301. };
  12302. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12303. var postProcesses = this._scene.activeCamera._postProcesses;
  12304. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12305. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12306. return;
  12307. }
  12308. var engine = this._scene.getEngine();
  12309. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12310. if (index < postProcessesTakenIndices.length - 1) {
  12311. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12312. } else {
  12313. if (targetTexture) {
  12314. engine.bindFramebuffer(targetTexture);
  12315. } else {
  12316. engine.restoreDefaultFramebuffer();
  12317. }
  12318. }
  12319. if (doNotPresent) {
  12320. break;
  12321. }
  12322. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12323. if (effect) {
  12324. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12325. engine.draw(true, 0, 6);
  12326. }
  12327. }
  12328. engine.setDepthBuffer(true);
  12329. engine.setDepthWrite(true);
  12330. };
  12331. PostProcessManager.prototype.dispose = function () {
  12332. if (this._vertexBuffer) {
  12333. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12334. this._vertexBuffer = null;
  12335. }
  12336. if (this._indexBuffer) {
  12337. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12338. this._indexBuffer = null;
  12339. }
  12340. };
  12341. return PostProcessManager;
  12342. })();
  12343. BABYLON.PostProcessManager = PostProcessManager;
  12344. })(BABYLON || (BABYLON = {}));
  12345. var __extends = this.__extends || function (d, b) {
  12346. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12347. function __() { this.constructor = d; }
  12348. __.prototype = b.prototype;
  12349. d.prototype = new __();
  12350. };
  12351. var BABYLON;
  12352. (function (BABYLON) {
  12353. var PassPostProcess = (function (_super) {
  12354. __extends(PassPostProcess, _super);
  12355. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12356. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12357. }
  12358. return PassPostProcess;
  12359. })(BABYLON.PostProcess);
  12360. BABYLON.PassPostProcess = PassPostProcess;
  12361. })(BABYLON || (BABYLON = {}));
  12362. var __extends = this.__extends || function (d, b) {
  12363. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12364. function __() { this.constructor = d; }
  12365. __.prototype = b.prototype;
  12366. d.prototype = new __();
  12367. };
  12368. var BABYLON;
  12369. (function (BABYLON) {
  12370. var BlurPostProcess = (function (_super) {
  12371. __extends(BlurPostProcess, _super);
  12372. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12373. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12374. var _this = this;
  12375. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12376. this.direction = direction;
  12377. this.blurWidth = blurWidth;
  12378. this.onApply = function (effect) {
  12379. effect.setFloat2("screenSize", _this.width, _this.height);
  12380. effect.setVector2("direction", _this.direction);
  12381. effect.setFloat("blurWidth", _this.blurWidth);
  12382. };
  12383. }
  12384. return BlurPostProcess;
  12385. })(BABYLON.PostProcess);
  12386. BABYLON.BlurPostProcess = BlurPostProcess;
  12387. })(BABYLON || (BABYLON = {}));
  12388. var __extends = this.__extends || function (d, b) {
  12389. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12390. function __() { this.constructor = d; }
  12391. __.prototype = b.prototype;
  12392. d.prototype = new __();
  12393. };
  12394. var BABYLON;
  12395. (function (BABYLON) {
  12396. var FilterPostProcess = (function (_super) {
  12397. __extends(FilterPostProcess, _super);
  12398. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12399. var _this = this;
  12400. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12401. this.kernelMatrix = kernelMatrix;
  12402. this.onApply = function (effect) {
  12403. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12404. };
  12405. }
  12406. return FilterPostProcess;
  12407. })(BABYLON.PostProcess);
  12408. BABYLON.FilterPostProcess = FilterPostProcess;
  12409. })(BABYLON || (BABYLON = {}));
  12410. var __extends = this.__extends || function (d, b) {
  12411. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12412. function __() { this.constructor = d; }
  12413. __.prototype = b.prototype;
  12414. d.prototype = new __();
  12415. };
  12416. var BABYLON;
  12417. (function (BABYLON) {
  12418. var RefractionPostProcess = (function (_super) {
  12419. __extends(RefractionPostProcess, _super);
  12420. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12421. var _this = this;
  12422. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12423. this.color = color;
  12424. this.depth = depth;
  12425. this.colorLevel = colorLevel;
  12426. this.onActivate = function (cam) {
  12427. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12428. };
  12429. this.onApply = function (effect) {
  12430. effect.setColor3("baseColor", _this.color);
  12431. effect.setFloat("depth", _this.depth);
  12432. effect.setFloat("colorLevel", _this.colorLevel);
  12433. effect.setTexture("refractionSampler", _this._refRexture);
  12434. };
  12435. }
  12436. RefractionPostProcess.prototype.dispose = function (camera) {
  12437. if (this._refRexture) {
  12438. this._refRexture.dispose();
  12439. }
  12440. _super.prototype.dispose.call(this, camera);
  12441. };
  12442. return RefractionPostProcess;
  12443. })(BABYLON.PostProcess);
  12444. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12445. })(BABYLON || (BABYLON = {}));
  12446. var __extends = this.__extends || function (d, b) {
  12447. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12448. function __() { this.constructor = d; }
  12449. __.prototype = b.prototype;
  12450. d.prototype = new __();
  12451. };
  12452. var BABYLON;
  12453. (function (BABYLON) {
  12454. var BlackAndWhitePostProcess = (function (_super) {
  12455. __extends(BlackAndWhitePostProcess, _super);
  12456. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12457. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12458. }
  12459. return BlackAndWhitePostProcess;
  12460. })(BABYLON.PostProcess);
  12461. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12462. })(BABYLON || (BABYLON = {}));
  12463. var __extends = this.__extends || function (d, b) {
  12464. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12465. function __() { this.constructor = d; }
  12466. __.prototype = b.prototype;
  12467. d.prototype = new __();
  12468. };
  12469. var BABYLON;
  12470. (function (BABYLON) {
  12471. var ConvolutionPostProcess = (function (_super) {
  12472. __extends(ConvolutionPostProcess, _super);
  12473. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12474. var _this = this;
  12475. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12476. this.kernel = kernel;
  12477. this.onApply = function (effect) {
  12478. effect.setFloat2("screenSize", _this.width, _this.height);
  12479. effect.setArray("kernel", _this.kernel);
  12480. };
  12481. }
  12482. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12483. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12484. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12485. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12486. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12487. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12488. return ConvolutionPostProcess;
  12489. })(BABYLON.PostProcess);
  12490. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12491. })(BABYLON || (BABYLON = {}));
  12492. var __extends = this.__extends || function (d, b) {
  12493. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12494. function __() { this.constructor = d; }
  12495. __.prototype = b.prototype;
  12496. d.prototype = new __();
  12497. };
  12498. var BABYLON;
  12499. (function (BABYLON) {
  12500. var FxaaPostProcess = (function (_super) {
  12501. __extends(FxaaPostProcess, _super);
  12502. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12503. var _this = this;
  12504. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12505. this.onSizeChanged = function () {
  12506. _this.texelWidth = 1.0 / _this.width;
  12507. _this.texelHeight = 1.0 / _this.height;
  12508. };
  12509. this.onApply = function (effect) {
  12510. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12511. };
  12512. }
  12513. return FxaaPostProcess;
  12514. })(BABYLON.PostProcess);
  12515. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12516. })(BABYLON || (BABYLON = {}));
  12517. var BABYLON;
  12518. (function (BABYLON) {
  12519. var LensFlare = (function () {
  12520. function LensFlare(size, position, color, imgUrl, system) {
  12521. this.size = size;
  12522. this.position = position;
  12523. this.dispose = function () {
  12524. if (this.texture) {
  12525. this.texture.dispose();
  12526. }
  12527. var index = this._system.lensFlares.indexOf(this);
  12528. this._system.lensFlares.splice(index, 1);
  12529. };
  12530. this.color = color || new BABYLON.Color3(1, 1, 1);
  12531. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12532. this._system = system;
  12533. system.lensFlares.push(this);
  12534. }
  12535. return LensFlare;
  12536. })();
  12537. BABYLON.LensFlare = LensFlare;
  12538. })(BABYLON || (BABYLON = {}));
  12539. var BABYLON;
  12540. (function (BABYLON) {
  12541. var LensFlareSystem = (function () {
  12542. function LensFlareSystem(name, emitter, scene) {
  12543. this.name = name;
  12544. this.lensFlares = new Array();
  12545. this.borderLimit = 300;
  12546. this._vertexDeclaration = [2];
  12547. this._vertexStrideSize = 2 * 4;
  12548. this._isEnabled = true;
  12549. this._scene = scene;
  12550. this._emitter = emitter;
  12551. scene.lensFlareSystems.push(this);
  12552. this.meshesSelectionPredicate = function (m) {
  12553. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12554. };
  12555. var vertices = [];
  12556. vertices.push(1, 1);
  12557. vertices.push(-1, 1);
  12558. vertices.push(-1, -1);
  12559. vertices.push(1, -1);
  12560. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12561. var indices = [];
  12562. indices.push(0);
  12563. indices.push(1);
  12564. indices.push(2);
  12565. indices.push(0);
  12566. indices.push(2);
  12567. indices.push(3);
  12568. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12569. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12570. }
  12571. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12572. get: function () {
  12573. return this._isEnabled;
  12574. },
  12575. set: function (value) {
  12576. this._isEnabled = value;
  12577. },
  12578. enumerable: true,
  12579. configurable: true
  12580. });
  12581. LensFlareSystem.prototype.getScene = function () {
  12582. return this._scene;
  12583. };
  12584. LensFlareSystem.prototype.getEmitter = function () {
  12585. return this._emitter;
  12586. };
  12587. LensFlareSystem.prototype.getEmitterPosition = function () {
  12588. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12589. };
  12590. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12591. var position = this.getEmitterPosition();
  12592. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12593. this._positionX = position.x;
  12594. this._positionY = position.y;
  12595. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12596. if (position.z > 0) {
  12597. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12598. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12599. return true;
  12600. }
  12601. }
  12602. return false;
  12603. };
  12604. LensFlareSystem.prototype._isVisible = function () {
  12605. if (!this._isEnabled) {
  12606. return false;
  12607. }
  12608. var emitterPosition = this.getEmitterPosition();
  12609. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12610. var distance = direction.length();
  12611. direction.normalize();
  12612. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12613. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12614. return !pickInfo.hit || pickInfo.distance > distance;
  12615. };
  12616. LensFlareSystem.prototype.render = function () {
  12617. if (!this._effect.isReady())
  12618. return false;
  12619. var engine = this._scene.getEngine();
  12620. var viewport = this._scene.activeCamera.viewport;
  12621. var globalViewport = viewport.toGlobal(engine);
  12622. if (!this.computeEffectivePosition(globalViewport)) {
  12623. return false;
  12624. }
  12625. if (!this._isVisible()) {
  12626. return false;
  12627. }
  12628. var awayX;
  12629. var awayY;
  12630. if (this._positionX < this.borderLimit + globalViewport.x) {
  12631. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12632. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12633. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12634. } else {
  12635. awayX = 0;
  12636. }
  12637. if (this._positionY < this.borderLimit + globalViewport.y) {
  12638. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12639. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12640. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12641. } else {
  12642. awayY = 0;
  12643. }
  12644. var away = (awayX > awayY) ? awayX : awayY;
  12645. if (away > this.borderLimit) {
  12646. away = this.borderLimit;
  12647. }
  12648. var intensity = 1.0 - (away / this.borderLimit);
  12649. if (intensity < 0) {
  12650. return false;
  12651. }
  12652. if (intensity > 1.0) {
  12653. intensity = 1.0;
  12654. }
  12655. var centerX = globalViewport.x + globalViewport.width / 2;
  12656. var centerY = globalViewport.y + globalViewport.height / 2;
  12657. var distX = centerX - this._positionX;
  12658. var distY = centerY - this._positionY;
  12659. engine.enableEffect(this._effect);
  12660. engine.setState(false);
  12661. engine.setDepthBuffer(false);
  12662. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12663. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12664. for (var index = 0; index < this.lensFlares.length; index++) {
  12665. var flare = this.lensFlares[index];
  12666. var x = centerX - (distX * flare.position);
  12667. var y = centerY - (distY * flare.position);
  12668. var cw = flare.size;
  12669. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12670. var cx = 2 * (x / globalViewport.width) - 1.0;
  12671. var cy = 1.0 - 2 * (y / globalViewport.height);
  12672. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12673. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12674. this._effect.setTexture("textureSampler", flare.texture);
  12675. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12676. engine.draw(true, 0, 6);
  12677. }
  12678. engine.setDepthBuffer(true);
  12679. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12680. return true;
  12681. };
  12682. LensFlareSystem.prototype.dispose = function () {
  12683. if (this._vertexBuffer) {
  12684. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12685. this._vertexBuffer = null;
  12686. }
  12687. if (this._indexBuffer) {
  12688. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12689. this._indexBuffer = null;
  12690. }
  12691. while (this.lensFlares.length) {
  12692. this.lensFlares[0].dispose();
  12693. }
  12694. var index = this._scene.lensFlareSystems.indexOf(this);
  12695. this._scene.lensFlareSystems.splice(index, 1);
  12696. };
  12697. return LensFlareSystem;
  12698. })();
  12699. BABYLON.LensFlareSystem = LensFlareSystem;
  12700. })(BABYLON || (BABYLON = {}));
  12701. var BABYLON;
  12702. (function (BABYLON) {
  12703. var IntersectionInfo = (function () {
  12704. function IntersectionInfo(bu, bv, distance) {
  12705. this.bu = bu;
  12706. this.bv = bv;
  12707. this.distance = distance;
  12708. this.faceId = 0;
  12709. }
  12710. return IntersectionInfo;
  12711. })();
  12712. BABYLON.IntersectionInfo = IntersectionInfo;
  12713. var PickingInfo = (function () {
  12714. function PickingInfo() {
  12715. this.hit = false;
  12716. this.distance = 0;
  12717. this.pickedPoint = null;
  12718. this.pickedMesh = null;
  12719. this.bu = 0;
  12720. this.bv = 0;
  12721. this.faceId = -1;
  12722. }
  12723. PickingInfo.prototype.getNormal = function () {
  12724. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12725. return null;
  12726. }
  12727. var indices = this.pickedMesh.getIndices();
  12728. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12729. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12730. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12731. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12732. normal0 = normal0.scale(this.bu);
  12733. normal1 = normal1.scale(this.bv);
  12734. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12735. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12736. };
  12737. PickingInfo.prototype.getTextureCoordinates = function () {
  12738. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12739. return null;
  12740. }
  12741. var indices = this.pickedMesh.getIndices();
  12742. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12743. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12744. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12745. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12746. uv0 = uv0.scale(this.bu);
  12747. uv1 = uv1.scale(this.bv);
  12748. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12749. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12750. };
  12751. return PickingInfo;
  12752. })();
  12753. BABYLON.PickingInfo = PickingInfo;
  12754. })(BABYLON || (BABYLON = {}));
  12755. var BABYLON;
  12756. (function (BABYLON) {
  12757. var FilesInput = (function () {
  12758. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12759. this.engine = p_engine;
  12760. this.canvas = p_canvas;
  12761. this.currentScene = p_scene;
  12762. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12763. this.progressCallback = p_progressCallback;
  12764. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12765. this.textureLoadingCallback = p_textureLoadingCallback;
  12766. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12767. }
  12768. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12769. var _this = this;
  12770. if (p_elementToMonitor) {
  12771. this.elementToMonitor = p_elementToMonitor;
  12772. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12773. _this.drag(e);
  12774. }, false);
  12775. this.elementToMonitor.addEventListener("dragover", function (e) {
  12776. _this.drag(e);
  12777. }, false);
  12778. this.elementToMonitor.addEventListener("drop", function (e) {
  12779. _this.drop(e);
  12780. }, false);
  12781. }
  12782. };
  12783. FilesInput.prototype.renderFunction = function () {
  12784. if (this.additionnalRenderLoopLogicCallback) {
  12785. this.additionnalRenderLoopLogicCallback();
  12786. }
  12787. if (this.currentScene) {
  12788. if (this.textureLoadingCallback) {
  12789. var remaining = this.currentScene.getWaitingItemsCount();
  12790. if (remaining > 0) {
  12791. this.textureLoadingCallback(remaining);
  12792. }
  12793. }
  12794. this.currentScene.render();
  12795. }
  12796. };
  12797. FilesInput.prototype.drag = function (e) {
  12798. e.stopPropagation();
  12799. e.preventDefault();
  12800. };
  12801. FilesInput.prototype.drop = function (eventDrop) {
  12802. eventDrop.stopPropagation();
  12803. eventDrop.preventDefault();
  12804. this.loadFiles(eventDrop);
  12805. };
  12806. FilesInput.prototype.loadFiles = function (event) {
  12807. var _this = this;
  12808. var that = this;
  12809. if (this.startingProcessingFilesCallback)
  12810. this.startingProcessingFilesCallback();
  12811. var sceneFileToLoad;
  12812. var filesToLoad;
  12813. if (event && event.dataTransfer && event.dataTransfer.files) {
  12814. filesToLoad = event.dataTransfer.files;
  12815. }
  12816. if (event && event.target && event.target.files) {
  12817. filesToLoad = event.target.files;
  12818. }
  12819. if (filesToLoad && filesToLoad.length > 0) {
  12820. for (var i = 0; i < filesToLoad.length; i++) {
  12821. switch (filesToLoad[i].type) {
  12822. case "image/jpeg":
  12823. case "image/png":
  12824. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12825. break;
  12826. case "image/targa":
  12827. case "image/vnd.ms-dds":
  12828. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12829. break;
  12830. default:
  12831. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  12832. sceneFileToLoad = filesToLoad[i];
  12833. }
  12834. break;
  12835. }
  12836. }
  12837. if (sceneFileToLoad) {
  12838. if (this.currentScene) {
  12839. this.engine.stopRenderLoop();
  12840. this.currentScene.dispose();
  12841. }
  12842. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12843. that.currentScene = newScene;
  12844. that.currentScene.executeWhenReady(function () {
  12845. if (that.currentScene.activeCamera) {
  12846. that.currentScene.activeCamera.attachControl(that.canvas);
  12847. }
  12848. if (that.sceneLoadedCallback) {
  12849. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12850. }
  12851. that.engine.runRenderLoop(function () {
  12852. that.renderFunction();
  12853. });
  12854. });
  12855. }, function (progress) {
  12856. if (_this.progressCallback) {
  12857. _this.progressCallback(progress);
  12858. }
  12859. });
  12860. } else {
  12861. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12862. }
  12863. }
  12864. };
  12865. FilesInput.FilesTextures = new Array();
  12866. FilesInput.FilesToLoad = new Array();
  12867. return FilesInput;
  12868. })();
  12869. BABYLON.FilesInput = FilesInput;
  12870. })(BABYLON || (BABYLON = {}));
  12871. var BABYLON;
  12872. (function (BABYLON) {
  12873. var OimoJSPlugin = (function () {
  12874. function OimoJSPlugin() {
  12875. this._registeredMeshes = [];
  12876. /**
  12877. * Update the body position according to the mesh position
  12878. * @param mesh
  12879. */
  12880. this.updateBodyPosition = function (mesh) {
  12881. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12882. var registeredMesh = this._registeredMeshes[index];
  12883. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12884. var body = registeredMesh.body.body;
  12885. var center = mesh.getBoundingInfo().boundingBox.center;
  12886. body.setPosition(center.x, center.y, center.z);
  12887. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12888. return;
  12889. }
  12890. if (registeredMesh.mesh.parent === mesh) {
  12891. mesh.computeWorldMatrix(true);
  12892. registeredMesh.mesh.computeWorldMatrix(true);
  12893. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12894. var absoluteRotation = mesh.rotation;
  12895. body = registeredMesh.body.body;
  12896. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12897. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12898. return;
  12899. }
  12900. }
  12901. };
  12902. }
  12903. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12904. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12905. };
  12906. OimoJSPlugin.prototype.initialize = function (iterations) {
  12907. this._world = new OIMO.World();
  12908. this._world.clear();
  12909. };
  12910. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12911. this._world.gravity = gravity;
  12912. };
  12913. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12914. var body = null;
  12915. this.unregisterMesh(mesh);
  12916. mesh.computeWorldMatrix(true);
  12917. switch (impostor) {
  12918. case BABYLON.PhysicsEngine.SphereImpostor:
  12919. var bbox = mesh.getBoundingInfo().boundingBox;
  12920. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12921. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12922. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12923. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12924. var deltaPosition = mesh.position.subtract(bbox.center);
  12925. body = new OIMO.Body({
  12926. type: 'sphere',
  12927. size: [size],
  12928. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12929. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12930. move: options.mass != 0,
  12931. config: [options.mass, options.friction, options.restitution],
  12932. world: this._world
  12933. });
  12934. this._registeredMeshes.push({
  12935. mesh: mesh,
  12936. body: body,
  12937. delta: deltaPosition
  12938. });
  12939. break;
  12940. case BABYLON.PhysicsEngine.PlaneImpostor:
  12941. case BABYLON.PhysicsEngine.BoxImpostor:
  12942. bbox = mesh.getBoundingInfo().boundingBox;
  12943. var min = bbox.minimumWorld;
  12944. var max = bbox.maximumWorld;
  12945. var box = max.subtract(min);
  12946. var sizeX = this._checkWithEpsilon(box.x);
  12947. var sizeY = this._checkWithEpsilon(box.y);
  12948. var sizeZ = this._checkWithEpsilon(box.z);
  12949. var deltaPosition = mesh.position.subtract(bbox.center);
  12950. body = new OIMO.Body({
  12951. type: 'box',
  12952. size: [sizeX, sizeY, sizeZ],
  12953. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12954. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12955. move: options.mass != 0,
  12956. config: [options.mass, options.friction, options.restitution],
  12957. world: this._world
  12958. });
  12959. this._registeredMeshes.push({
  12960. mesh: mesh,
  12961. body: body,
  12962. delta: deltaPosition
  12963. });
  12964. break;
  12965. }
  12966. return body;
  12967. };
  12968. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12969. var types = [], sizes = [], positions = [], rotations = [];
  12970. var initialMesh = parts[0].mesh;
  12971. for (var index = 0; index < parts.length; index++) {
  12972. var part = parts[index];
  12973. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12974. types.push(bodyParameters.type);
  12975. sizes.push.apply(sizes, bodyParameters.size);
  12976. positions.push.apply(positions, bodyParameters.pos);
  12977. rotations.push.apply(rotations, bodyParameters.rot);
  12978. }
  12979. var body = new OIMO.Body({
  12980. type: types,
  12981. size: sizes,
  12982. pos: positions,
  12983. rot: rotations,
  12984. move: options.mass != 0,
  12985. config: [options.mass, options.friction, options.restitution],
  12986. world: this._world
  12987. });
  12988. this._registeredMeshes.push({
  12989. mesh: initialMesh,
  12990. body: body
  12991. });
  12992. return body;
  12993. };
  12994. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12995. var bodyParameters = null;
  12996. var mesh = part.mesh;
  12997. switch (part.impostor) {
  12998. case BABYLON.PhysicsEngine.SphereImpostor:
  12999. var bbox = mesh.getBoundingInfo().boundingBox;
  13000. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13001. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13002. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13003. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13004. bodyParameters = {
  13005. type: 'sphere',
  13006. /* bug with oimo : sphere needs 3 sizes in this case */
  13007. size: [size, -1, -1],
  13008. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13009. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13010. };
  13011. break;
  13012. case BABYLON.PhysicsEngine.PlaneImpostor:
  13013. case BABYLON.PhysicsEngine.BoxImpostor:
  13014. bbox = mesh.getBoundingInfo().boundingBox;
  13015. var min = bbox.minimumWorld;
  13016. var max = bbox.maximumWorld;
  13017. var box = max.subtract(min);
  13018. var sizeX = this._checkWithEpsilon(box.x);
  13019. var sizeY = this._checkWithEpsilon(box.y);
  13020. var sizeZ = this._checkWithEpsilon(box.z);
  13021. var relativePosition = mesh.position;
  13022. bodyParameters = {
  13023. type: 'box',
  13024. size: [sizeX, sizeY, sizeZ],
  13025. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13026. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13027. };
  13028. break;
  13029. }
  13030. return bodyParameters;
  13031. };
  13032. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13033. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13034. var registeredMesh = this._registeredMeshes[index];
  13035. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13036. if (registeredMesh.body) {
  13037. this._world.removeRigidBody(registeredMesh.body.body);
  13038. this._unbindBody(registeredMesh.body);
  13039. }
  13040. this._registeredMeshes.splice(index, 1);
  13041. return;
  13042. }
  13043. }
  13044. };
  13045. OimoJSPlugin.prototype._unbindBody = function (body) {
  13046. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13047. var registeredMesh = this._registeredMeshes[index];
  13048. if (registeredMesh.body === body) {
  13049. registeredMesh.body = null;
  13050. }
  13051. }
  13052. };
  13053. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13054. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13055. var registeredMesh = this._registeredMeshes[index];
  13056. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13057. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  13058. return;
  13059. }
  13060. }
  13061. };
  13062. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13063. var body1 = null, body2 = null;
  13064. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13065. var registeredMesh = this._registeredMeshes[index];
  13066. if (registeredMesh.mesh === mesh1) {
  13067. body1 = registeredMesh.body.body;
  13068. } else if (registeredMesh.mesh === mesh2) {
  13069. body2 = registeredMesh.body.body;
  13070. }
  13071. }
  13072. if (!body1 || !body2) {
  13073. return false;
  13074. }
  13075. if (!options) {
  13076. options = {};
  13077. }
  13078. new OIMO.Link({
  13079. type: options.type,
  13080. body1: body1,
  13081. body2: body2,
  13082. min: options.min,
  13083. max: options.max,
  13084. axe1: options.axe1,
  13085. axe2: options.axe2,
  13086. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13087. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13088. collision: options.collision,
  13089. spring: options.spring,
  13090. world: this._world
  13091. });
  13092. return true;
  13093. };
  13094. OimoJSPlugin.prototype.dispose = function () {
  13095. this._world.clear();
  13096. while (this._registeredMeshes.length) {
  13097. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13098. }
  13099. };
  13100. OimoJSPlugin.prototype.isSupported = function () {
  13101. return OIMO !== undefined;
  13102. };
  13103. OimoJSPlugin.prototype._getLastShape = function (body) {
  13104. var lastShape = body.shapes;
  13105. while (lastShape.next) {
  13106. lastShape = lastShape.next;
  13107. }
  13108. return lastShape;
  13109. };
  13110. OimoJSPlugin.prototype.runOneStep = function (time) {
  13111. this._world.step();
  13112. var i = this._registeredMeshes.length;
  13113. var m;
  13114. while (i--) {
  13115. var body = this._registeredMeshes[i].body.body;
  13116. var mesh = this._registeredMeshes[i].mesh;
  13117. var delta = this._registeredMeshes[i].delta;
  13118. if (!body.sleeping) {
  13119. if (body.shapes.next) {
  13120. var parentShape = this._getLastShape(body);
  13121. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13122. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13123. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13124. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13125. if (!mesh.rotationQuaternion) {
  13126. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13127. }
  13128. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13129. } else {
  13130. m = body.getMatrix();
  13131. mtx = BABYLON.Matrix.FromArray(m);
  13132. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13133. if (!delta) {
  13134. mesh.position.x = bodyX;
  13135. mesh.position.y = bodyY;
  13136. mesh.position.z = bodyZ;
  13137. } else {
  13138. mesh.position.x = bodyX + delta.x;
  13139. mesh.position.y = bodyY + delta.y;
  13140. mesh.position.z = bodyZ + delta.z;
  13141. }
  13142. if (!mesh.rotationQuaternion) {
  13143. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13144. }
  13145. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13146. }
  13147. }
  13148. }
  13149. };
  13150. return OimoJSPlugin;
  13151. })();
  13152. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13153. })(BABYLON || (BABYLON = {}));
  13154. var BABYLON;
  13155. (function (BABYLON) {
  13156. var PhysicsEngine = (function () {
  13157. function PhysicsEngine(plugin) {
  13158. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13159. }
  13160. PhysicsEngine.prototype._initialize = function (gravity) {
  13161. this._currentPlugin.initialize();
  13162. this._setGravity(gravity);
  13163. };
  13164. PhysicsEngine.prototype._runOneStep = function (delta) {
  13165. if (delta > 0.1) {
  13166. delta = 0.1;
  13167. } else if (delta <= 0) {
  13168. delta = 1.0 / 60.0;
  13169. }
  13170. this._currentPlugin.runOneStep(delta);
  13171. };
  13172. PhysicsEngine.prototype._setGravity = function (gravity) {
  13173. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13174. this._currentPlugin.setGravity(this.gravity);
  13175. };
  13176. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13177. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13178. };
  13179. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13180. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13181. };
  13182. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13183. this._currentPlugin.unregisterMesh(mesh);
  13184. };
  13185. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13186. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13187. };
  13188. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13189. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13190. };
  13191. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13192. this._currentPlugin.updateBodyPosition(mesh);
  13193. };
  13194. PhysicsEngine.prototype.dispose = function () {
  13195. this._currentPlugin.dispose();
  13196. };
  13197. PhysicsEngine.prototype.isSupported = function () {
  13198. return this._currentPlugin.isSupported();
  13199. };
  13200. PhysicsEngine.NoImpostor = 0;
  13201. PhysicsEngine.SphereImpostor = 1;
  13202. PhysicsEngine.BoxImpostor = 2;
  13203. PhysicsEngine.PlaneImpostor = 3;
  13204. PhysicsEngine.CompoundImpostor = 4;
  13205. PhysicsEngine.MeshImpostor = 4;
  13206. PhysicsEngine.CapsuleImpostor = 5;
  13207. PhysicsEngine.ConeImpostor = 6;
  13208. PhysicsEngine.CylinderImpostor = 7;
  13209. PhysicsEngine.ConvexHullImpostor = 8;
  13210. PhysicsEngine.Epsilon = 0.001;
  13211. return PhysicsEngine;
  13212. })();
  13213. BABYLON.PhysicsEngine = PhysicsEngine;
  13214. })(BABYLON || (BABYLON = {}));
  13215. var BABYLON;
  13216. (function (BABYLON) {
  13217. var serializeLight = function (light) {
  13218. var serializationObject = {};
  13219. serializationObject.name = light.name;
  13220. serializationObject.id = light.id;
  13221. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13222. if (light instanceof BABYLON.PointLight) {
  13223. serializationObject.type = 0;
  13224. serializationObject.position = light.position.asArray();
  13225. } else if (light instanceof BABYLON.DirectionalLight) {
  13226. serializationObject.type = 1;
  13227. var directionalLight = light;
  13228. serializationObject.position = directionalLight.position.asArray();
  13229. serializationObject.direction = directionalLight.direction.asArray();
  13230. } else if (light instanceof BABYLON.SpotLight) {
  13231. serializationObject.type = 2;
  13232. var spotLight = light;
  13233. serializationObject.position = spotLight.position.asArray();
  13234. serializationObject.direction = spotLight.position.asArray();
  13235. serializationObject.angle = spotLight.angle;
  13236. serializationObject.exponent = spotLight.exponent;
  13237. } else if (light instanceof BABYLON.HemisphericLight) {
  13238. serializationObject.type = 3;
  13239. var hemisphericLight = light;
  13240. serializationObject.direction = hemisphericLight.direction.asArray();
  13241. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13242. }
  13243. if (light.intensity) {
  13244. serializationObject.intensity = light.intensity;
  13245. }
  13246. serializationObject.range = light.range;
  13247. serializationObject.diffuse = light.diffuse.asArray();
  13248. serializationObject.specular = light.specular.asArray();
  13249. return serializationObject;
  13250. };
  13251. var serializeFresnelParameter = function (fresnelParameter) {
  13252. var serializationObject = {};
  13253. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13254. serializationObject.leftColor = fresnelParameter.leftColor;
  13255. serializationObject.rightColor = fresnelParameter.rightColor;
  13256. serializationObject.bias = fresnelParameter.bias;
  13257. serializationObject.power = fresnelParameter.power;
  13258. return serializationObject;
  13259. };
  13260. var serializeCamera = function (camera) {
  13261. var serializationObject = {};
  13262. serializationObject.name = camera.name;
  13263. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13264. serializationObject.id = camera.id;
  13265. serializationObject.position = camera.position.asArray();
  13266. if (camera.parent) {
  13267. serializationObject.parentId = camera.parent.id;
  13268. }
  13269. serializationObject.rotation = camera.rotation.asArray();
  13270. if (camera.lockedTarget && camera.lockedTarget.id) {
  13271. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13272. }
  13273. serializationObject.fov = camera.fov;
  13274. serializationObject.minZ = camera.minZ;
  13275. serializationObject.maxZ = camera.maxZ;
  13276. serializationObject.speed = camera.speed;
  13277. serializationObject.inertia = camera.inertia;
  13278. serializationObject.checkCollisions = camera.checkCollisions;
  13279. serializationObject.applyGravity = camera.applyGravity;
  13280. if (camera.ellipsoid) {
  13281. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13282. }
  13283. appendAnimations(camera, serializationObject);
  13284. serializationObject.layerMask = camera.layerMask;
  13285. return serializationObject;
  13286. };
  13287. var appendAnimations = function (source, destination) {
  13288. if (source.animations) {
  13289. destination.animations = [];
  13290. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13291. var animation = source.animations[animationIndex];
  13292. destination.animations.push(serializeAnimation(animation));
  13293. }
  13294. }
  13295. };
  13296. var serializeAnimation = function (animation) {
  13297. var serializationObject = {};
  13298. serializationObject.name = animation.name;
  13299. serializationObject.property = animation.targetProperty;
  13300. serializationObject.framePerSecond = animation.framePerSecond;
  13301. serializationObject.dataType = animation.dataType;
  13302. serializationObject.loopBehavior = animation.loopMode;
  13303. var dataType = animation.dataType;
  13304. serializationObject.keys = [];
  13305. var keys = animation.getKeys();
  13306. for (var index = 0; index < keys.length; index++) {
  13307. var animationKey = keys[index];
  13308. var key = {};
  13309. key.frame = animationKey.frame;
  13310. switch (dataType) {
  13311. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13312. key.values = [animationKey.value];
  13313. break;
  13314. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13315. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13316. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13317. key.values = animationKey.value.asArray();
  13318. break;
  13319. }
  13320. serializationObject.keys.push(key);
  13321. }
  13322. return serializationObject;
  13323. };
  13324. var serializeMultiMaterial = function (material) {
  13325. var serializationObject = {};
  13326. serializationObject.name = material.name;
  13327. serializationObject.id = material.id;
  13328. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13329. serializationObject.materials = [];
  13330. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13331. var subMat = material.subMaterials[matIndex];
  13332. if (subMat) {
  13333. serializationObject.materials.push(subMat.id);
  13334. } else {
  13335. serializationObject.materials.push(null);
  13336. }
  13337. }
  13338. return serializationObject;
  13339. };
  13340. var serializeMaterial = function (material) {
  13341. var serializationObject = {};
  13342. serializationObject.name = material.name;
  13343. serializationObject.ambient = material.ambientColor.asArray();
  13344. serializationObject.diffuse = material.diffuseColor.asArray();
  13345. serializationObject.specular = material.specularColor.asArray();
  13346. serializationObject.specularPower = material.specularPower;
  13347. serializationObject.emissive = material.emissiveColor.asArray();
  13348. serializationObject.alpha = material.alpha;
  13349. serializationObject.id = material.id;
  13350. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13351. serializationObject.backFaceCulling = material.backFaceCulling;
  13352. if (material.diffuseTexture) {
  13353. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13354. }
  13355. if (material.diffuseFresnelParameters) {
  13356. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13357. }
  13358. if (material.ambientTexture) {
  13359. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13360. }
  13361. if (material.opacityTexture) {
  13362. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13363. }
  13364. if (material.opacityFresnelParameters) {
  13365. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13366. }
  13367. if (material.reflectionTexture) {
  13368. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13369. }
  13370. if (material.reflectionFresnelParameters) {
  13371. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13372. }
  13373. if (material.emissiveTexture) {
  13374. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13375. }
  13376. if (material.emissiveFresnelParameters) {
  13377. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13378. }
  13379. if (material.specularTexture) {
  13380. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13381. }
  13382. if (material.bumpTexture) {
  13383. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13384. }
  13385. return serializationObject;
  13386. };
  13387. var serializeTexture = function (texture) {
  13388. var serializationObject = {};
  13389. if (!texture.name) {
  13390. return null;
  13391. }
  13392. if (texture instanceof BABYLON.CubeTexture) {
  13393. serializationObject.name = texture.name;
  13394. serializationObject.hasAlpha = texture.hasAlpha;
  13395. serializationObject.level = texture.level;
  13396. serializationObject.coordinatesMode = texture.coordinatesMode;
  13397. return serializationObject;
  13398. }
  13399. if (texture instanceof BABYLON.MirrorTexture) {
  13400. var mirrorTexture = texture;
  13401. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13402. serializationObject.renderList = [];
  13403. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13404. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13405. }
  13406. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13407. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13408. var renderTargetTexture = texture;
  13409. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13410. serializationObject.renderList = [];
  13411. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13412. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13413. }
  13414. }
  13415. var regularTexture = texture;
  13416. serializationObject.name = texture.name;
  13417. serializationObject.hasAlpha = texture.hasAlpha;
  13418. serializationObject.level = texture.level;
  13419. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13420. serializationObject.coordinatesMode = texture.coordinatesMode;
  13421. serializationObject.uOffset = regularTexture.uOffset;
  13422. serializationObject.vOffset = regularTexture.vOffset;
  13423. serializationObject.uScale = regularTexture.uScale;
  13424. serializationObject.vScale = regularTexture.vScale;
  13425. serializationObject.uAng = regularTexture.uAng;
  13426. serializationObject.vAng = regularTexture.vAng;
  13427. serializationObject.wAng = regularTexture.wAng;
  13428. serializationObject.wrapU = texture.wrapU;
  13429. serializationObject.wrapV = texture.wrapV;
  13430. appendAnimations(texture, serializationObject);
  13431. return serializationObject;
  13432. };
  13433. var serializeSkeleton = function (skeleton) {
  13434. var serializationObject = {};
  13435. serializationObject.name = skeleton.name;
  13436. serializationObject.id = skeleton.id;
  13437. serializationObject.bones = [];
  13438. for (var index = 0; index < skeleton.bones.length; index++) {
  13439. var bone = skeleton.bones[index];
  13440. var serializedBone = {
  13441. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13442. name: bone.name,
  13443. matrix: bone.getLocalMatrix().toArray()
  13444. };
  13445. serializationObject.bones.push(serializedBone);
  13446. if (bone.animations && bone.animations.length > 0) {
  13447. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13448. }
  13449. }
  13450. return serializationObject;
  13451. };
  13452. var serializeParticleSystem = function (particleSystem) {
  13453. var serializationObject = {};
  13454. serializationObject.emitterId = particleSystem.emitter.id;
  13455. serializationObject.capacity = particleSystem.getCapacity();
  13456. if (particleSystem.particleTexture) {
  13457. serializationObject.textureName = particleSystem.particleTexture.name;
  13458. }
  13459. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13460. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13461. serializationObject.minSize = particleSystem.minSize;
  13462. serializationObject.maxSize = particleSystem.maxSize;
  13463. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13464. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13465. serializationObject.emitRate = particleSystem.emitRate;
  13466. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13467. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13468. serializationObject.gravity = particleSystem.gravity.asArray();
  13469. serializationObject.direction1 = particleSystem.direction1.asArray();
  13470. serializationObject.direction2 = particleSystem.direction2.asArray();
  13471. serializationObject.color1 = particleSystem.color1.asArray();
  13472. serializationObject.color2 = particleSystem.color2.asArray();
  13473. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13474. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13475. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13476. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13477. serializationObject.blendMode = particleSystem.blendMode;
  13478. return serializationObject;
  13479. };
  13480. var serializeLensFlareSystem = function (lensFlareSystem) {
  13481. var serializationObject = {};
  13482. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13483. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13484. serializationObject.flares = [];
  13485. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13486. var flare = lensFlareSystem.lensFlares[index];
  13487. serializationObject.flares.push({
  13488. size: flare.size,
  13489. position: flare.position,
  13490. color: flare.color.asArray(),
  13491. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13492. });
  13493. }
  13494. return serializationObject;
  13495. };
  13496. var serializeShadowGenerator = function (light) {
  13497. var serializationObject = {};
  13498. var shadowGenerator = light.getShadowGenerator();
  13499. serializationObject.lightId = light.id;
  13500. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13501. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13502. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13503. serializationObject.renderList = [];
  13504. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13505. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13506. serializationObject.renderList.push(mesh.id);
  13507. }
  13508. return serializationObject;
  13509. };
  13510. var serializedGeometries = [];
  13511. var serializeGeometry = function (geometry, serializationGeometries) {
  13512. if (serializedGeometries[geometry.id]) {
  13513. return;
  13514. }
  13515. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13516. serializationGeometries.boxes.push(serializeBox(geometry));
  13517. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13518. serializationGeometries.spheres.push(serializeSphere(geometry));
  13519. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13520. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13521. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13522. serializationGeometries.toruses.push(serializeTorus(geometry));
  13523. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13524. serializationGeometries.grounds.push(serializeGround(geometry));
  13525. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13526. serializationGeometries.planes.push(serializePlane(geometry));
  13527. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13528. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13529. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13530. throw new Error("Unknow primitive type");
  13531. } else {
  13532. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13533. }
  13534. serializedGeometries[geometry.id] = true;
  13535. };
  13536. var serializeGeometryBase = function (geometry) {
  13537. var serializationObject = {};
  13538. serializationObject.id = geometry.id;
  13539. if (BABYLON.Tags.HasTags(geometry)) {
  13540. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13541. }
  13542. return serializationObject;
  13543. };
  13544. var serializeVertexData = function (vertexData) {
  13545. var serializationObject = serializeGeometryBase(vertexData);
  13546. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13547. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13548. }
  13549. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13550. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13551. }
  13552. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13553. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13554. }
  13555. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13556. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13557. }
  13558. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13559. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13560. }
  13561. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13562. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13563. serializationObject.matricesIndices._isExpanded = true;
  13564. }
  13565. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13566. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13567. }
  13568. serializationObject.indices = vertexData.getIndices();
  13569. return serializationObject;
  13570. };
  13571. var serializePrimitive = function (primitive) {
  13572. var serializationObject = serializeGeometryBase(primitive);
  13573. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13574. return serializationObject;
  13575. };
  13576. var serializeBox = function (box) {
  13577. var serializationObject = serializePrimitive(box);
  13578. serializationObject.size = box.size;
  13579. return serializationObject;
  13580. };
  13581. var serializeSphere = function (sphere) {
  13582. var serializationObject = serializePrimitive(sphere);
  13583. serializationObject.segments = sphere.segments;
  13584. serializationObject.diameter = sphere.diameter;
  13585. return serializationObject;
  13586. };
  13587. var serializeCylinder = function (cylinder) {
  13588. var serializationObject = serializePrimitive(cylinder);
  13589. serializationObject.height = cylinder.height;
  13590. serializationObject.diameterTop = cylinder.diameterTop;
  13591. serializationObject.diameterBottom = cylinder.diameterBottom;
  13592. serializationObject.tessellation = cylinder.tessellation;
  13593. return serializationObject;
  13594. };
  13595. var serializeTorus = function (torus) {
  13596. var serializationObject = serializePrimitive(torus);
  13597. serializationObject.diameter = torus.diameter;
  13598. serializationObject.thickness = torus.thickness;
  13599. serializationObject.tessellation = torus.tessellation;
  13600. return serializationObject;
  13601. };
  13602. var serializeGround = function (ground) {
  13603. var serializationObject = serializePrimitive(ground);
  13604. serializationObject.width = ground.width;
  13605. serializationObject.height = ground.height;
  13606. serializationObject.subdivisions = ground.subdivisions;
  13607. return serializationObject;
  13608. };
  13609. var serializePlane = function (plane) {
  13610. var serializationObject = serializePrimitive(plane);
  13611. serializationObject.size = plane.size;
  13612. return serializationObject;
  13613. };
  13614. var serializeTorusKnot = function (torusKnot) {
  13615. var serializationObject = serializePrimitive(torusKnot);
  13616. serializationObject.radius = torusKnot.radius;
  13617. serializationObject.tube = torusKnot.tube;
  13618. serializationObject.radialSegments = torusKnot.radialSegments;
  13619. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13620. serializationObject.p = torusKnot.p;
  13621. serializationObject.q = torusKnot.q;
  13622. return serializationObject;
  13623. };
  13624. var serializeMesh = function (mesh, serializationScene) {
  13625. var serializationObject = {};
  13626. serializationObject.name = mesh.name;
  13627. serializationObject.id = mesh.id;
  13628. if (BABYLON.Tags.HasTags(mesh)) {
  13629. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13630. }
  13631. serializationObject.position = mesh.position.asArray();
  13632. if (mesh.rotationQuaternion) {
  13633. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13634. } else if (mesh.rotation) {
  13635. serializationObject.rotation = mesh.rotation.asArray();
  13636. }
  13637. serializationObject.scaling = mesh.scaling.asArray();
  13638. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13639. serializationObject.isEnabled = mesh.isEnabled();
  13640. serializationObject.isVisible = mesh.isVisible;
  13641. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13642. serializationObject.pickable = mesh.isPickable;
  13643. serializationObject.receiveShadows = mesh.receiveShadows;
  13644. serializationObject.billboardMode = mesh.billboardMode;
  13645. serializationObject.visibility = mesh.visibility;
  13646. serializationObject.checkCollisions = mesh.checkCollisions;
  13647. if (mesh.parent) {
  13648. serializationObject.parentId = mesh.parent.id;
  13649. }
  13650. var geometry = mesh._geometry;
  13651. if (geometry) {
  13652. var geometryId = geometry.id;
  13653. serializationObject.geometryId = geometryId;
  13654. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13655. serializeGeometry(geometry, serializationScene.geometries);
  13656. }
  13657. serializationObject.subMeshes = [];
  13658. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13659. var subMesh = mesh.subMeshes[subIndex];
  13660. serializationObject.subMeshes.push({
  13661. materialIndex: subMesh.materialIndex,
  13662. verticesStart: subMesh.verticesStart,
  13663. verticesCount: subMesh.verticesCount,
  13664. indexStart: subMesh.indexStart,
  13665. indexCount: subMesh.indexCount
  13666. });
  13667. }
  13668. }
  13669. if (mesh.material) {
  13670. serializationObject.materialId = mesh.material.id;
  13671. } else {
  13672. mesh.material = null;
  13673. }
  13674. if (mesh.skeleton) {
  13675. serializationObject.skeletonId = mesh.skeleton.id;
  13676. }
  13677. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13678. serializationObject.physicsMass = mesh.getPhysicsMass();
  13679. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13680. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13681. switch (mesh.getPhysicsImpostor()) {
  13682. case BABYLON.PhysicsEngine.BoxImpostor:
  13683. serializationObject.physicsImpostor = 1;
  13684. break;
  13685. case BABYLON.PhysicsEngine.SphereImpostor:
  13686. serializationObject.physicsImpostor = 2;
  13687. break;
  13688. }
  13689. }
  13690. serializationObject.instances = [];
  13691. for (var index = 0; index < mesh.instances.length; index++) {
  13692. var instance = mesh.instances[index];
  13693. var serializationInstance = {
  13694. name: instance.name,
  13695. position: instance.position,
  13696. rotation: instance.rotation,
  13697. rotationQuaternion: instance.rotationQuaternion,
  13698. scaling: instance.scaling
  13699. };
  13700. serializationObject.instances.push(serializationInstance);
  13701. appendAnimations(instance, serializationInstance);
  13702. }
  13703. appendAnimations(mesh, serializationObject);
  13704. serializationObject.layerMask = mesh.layerMask;
  13705. return serializationObject;
  13706. };
  13707. var SceneSerializer = (function () {
  13708. function SceneSerializer() {
  13709. }
  13710. SceneSerializer.Serialize = function (scene) {
  13711. var serializationObject = {};
  13712. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13713. serializationObject.autoClear = scene.autoClear;
  13714. serializationObject.clearColor = scene.clearColor.asArray();
  13715. serializationObject.ambientColor = scene.ambientColor.asArray();
  13716. serializationObject.gravity = scene.gravity.asArray();
  13717. if (scene.fogMode && scene.fogMode !== 0) {
  13718. serializationObject.fogMode = scene.fogMode;
  13719. serializationObject.fogColor = scene.fogColor.asArray();
  13720. serializationObject.fogStart = scene.fogStart;
  13721. serializationObject.fogEnd = scene.fogEnd;
  13722. serializationObject.fogDensity = scene.fogDensity;
  13723. }
  13724. serializationObject.lights = [];
  13725. for (var index = 0; index < scene.lights.length; index++) {
  13726. var light = scene.lights[index];
  13727. serializationObject.lights.push(serializeLight(light));
  13728. }
  13729. serializationObject.cameras = [];
  13730. for (index = 0; index < scene.cameras.length; index++) {
  13731. var camera = scene.cameras[index];
  13732. if (camera instanceof BABYLON.FreeCamera) {
  13733. serializationObject.cameras.push(serializeCamera(camera));
  13734. }
  13735. }
  13736. if (scene.activeCamera) {
  13737. serializationObject.activeCameraID = scene.activeCamera.id;
  13738. }
  13739. serializationObject.materials = [];
  13740. serializationObject.multiMaterials = [];
  13741. for (index = 0; index < scene.materials.length; index++) {
  13742. var material = scene.materials[index];
  13743. if (material instanceof BABYLON.StandardMaterial) {
  13744. serializationObject.materials.push(serializeMaterial(material));
  13745. } else if (material instanceof BABYLON.MultiMaterial) {
  13746. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13747. }
  13748. }
  13749. serializationObject.skeletons = [];
  13750. for (index = 0; index < scene.skeletons.length; index++) {
  13751. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13752. }
  13753. serializationObject.geometries = {};
  13754. serializationObject.geometries.boxes = [];
  13755. serializationObject.geometries.spheres = [];
  13756. serializationObject.geometries.cylinders = [];
  13757. serializationObject.geometries.toruses = [];
  13758. serializationObject.geometries.grounds = [];
  13759. serializationObject.geometries.planes = [];
  13760. serializationObject.geometries.torusKnots = [];
  13761. serializationObject.geometries.vertexData = [];
  13762. serializedGeometries = [];
  13763. var geometries = scene.getGeometries();
  13764. for (var index = 0; index < geometries.length; index++) {
  13765. var geometry = geometries[index];
  13766. if (geometry.isReady()) {
  13767. serializeGeometry(geometry, serializationObject.geometries);
  13768. }
  13769. }
  13770. serializationObject.meshes = [];
  13771. for (index = 0; index < scene.meshes.length; index++) {
  13772. var abstractMesh = scene.meshes[index];
  13773. if (abstractMesh instanceof BABYLON.Mesh) {
  13774. var mesh = abstractMesh;
  13775. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13776. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13777. }
  13778. }
  13779. }
  13780. serializationObject.particleSystems = [];
  13781. for (index = 0; index < scene.particleSystems.length; index++) {
  13782. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13783. }
  13784. serializationObject.lensFlareSystems = [];
  13785. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13786. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13787. }
  13788. serializationObject.shadowGenerators = [];
  13789. for (index = 0; index < scene.lights.length; index++) {
  13790. light = scene.lights[index];
  13791. if (light.getShadowGenerator()) {
  13792. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13793. }
  13794. }
  13795. return serializationObject;
  13796. };
  13797. return SceneSerializer;
  13798. })();
  13799. BABYLON.SceneSerializer = SceneSerializer;
  13800. })(BABYLON || (BABYLON = {}));
  13801. var BABYLON;
  13802. (function (BABYLON) {
  13803. var SceneLoader = (function () {
  13804. function SceneLoader() {
  13805. }
  13806. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13807. get: function () {
  13808. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13809. },
  13810. set: function (value) {
  13811. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13812. },
  13813. enumerable: true,
  13814. configurable: true
  13815. });
  13816. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13817. get: function () {
  13818. return SceneLoader._ShowLoadingScreen;
  13819. },
  13820. set: function (value) {
  13821. SceneLoader._ShowLoadingScreen = value;
  13822. },
  13823. enumerable: true,
  13824. configurable: true
  13825. });
  13826. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13827. var dotPosition = sceneFilename.lastIndexOf(".");
  13828. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13829. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13830. var plugin = this._registeredPlugins[index];
  13831. if (plugin.extensions.indexOf(extension) !== -1) {
  13832. return plugin;
  13833. }
  13834. }
  13835. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13836. };
  13837. SceneLoader.RegisterPlugin = function (plugin) {
  13838. plugin.extensions = plugin.extensions.toLowerCase();
  13839. SceneLoader._registeredPlugins.push(plugin);
  13840. };
  13841. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13842. var _this = this;
  13843. var manifestChecked = function (success) {
  13844. scene.database = database;
  13845. var plugin = _this._getPluginForFilename(sceneFilename);
  13846. var importMeshFromData = function (data) {
  13847. var meshes = [];
  13848. var particleSystems = [];
  13849. var skeletons = [];
  13850. try {
  13851. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13852. if (onerror) {
  13853. onerror(scene);
  13854. }
  13855. return;
  13856. }
  13857. } catch (e) {
  13858. if (onerror) {
  13859. onerror(scene);
  13860. }
  13861. return;
  13862. }
  13863. if (onsuccess) {
  13864. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13865. onsuccess(meshes, particleSystems, skeletons);
  13866. }
  13867. };
  13868. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13869. importMeshFromData(sceneFilename.substr(5));
  13870. return;
  13871. }
  13872. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13873. importMeshFromData(data);
  13874. }, progressCallBack, database);
  13875. };
  13876. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13877. };
  13878. /**
  13879. * Load a scene
  13880. * @param rootUrl a string that defines the root url for scene and resources
  13881. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13882. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13883. */
  13884. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13885. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13886. };
  13887. /**
  13888. * Append a scene
  13889. * @param rootUrl a string that defines the root url for scene and resources
  13890. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13891. * @param scene is the instance of BABYLON.Scene to append to
  13892. */
  13893. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13894. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13895. var database;
  13896. if (SceneLoader.ShowLoadingScreen) {
  13897. scene.getEngine().displayLoadingUI();
  13898. }
  13899. var loadSceneFromData = function (data) {
  13900. scene.database = database;
  13901. if (!plugin.load(scene, data, rootUrl)) {
  13902. if (onerror) {
  13903. onerror(scene);
  13904. }
  13905. scene.getEngine().hideLoadingUI();
  13906. return;
  13907. }
  13908. if (onsuccess) {
  13909. onsuccess(scene);
  13910. }
  13911. if (SceneLoader.ShowLoadingScreen) {
  13912. scene.executeWhenReady(function () {
  13913. scene.getEngine().hideLoadingUI();
  13914. });
  13915. }
  13916. };
  13917. var manifestChecked = function (success) {
  13918. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13919. };
  13920. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13921. loadSceneFromData(sceneFilename.substr(5));
  13922. return;
  13923. }
  13924. if (rootUrl.indexOf("file:") === -1) {
  13925. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13926. } else {
  13927. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13928. }
  13929. };
  13930. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13931. SceneLoader._ShowLoadingScreen = true;
  13932. SceneLoader._registeredPlugins = new Array();
  13933. return SceneLoader;
  13934. })();
  13935. BABYLON.SceneLoader = SceneLoader;
  13936. ;
  13937. })(BABYLON || (BABYLON = {}));
  13938. var BABYLON;
  13939. (function (BABYLON) {
  13940. (function (Internals) {
  13941. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13942. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13943. texture.name = parsedTexture.name;
  13944. texture.hasAlpha = parsedTexture.hasAlpha;
  13945. texture.level = parsedTexture.level;
  13946. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13947. return texture;
  13948. };
  13949. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13950. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13951. return null;
  13952. }
  13953. if (parsedTexture.isCube) {
  13954. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13955. }
  13956. var texture;
  13957. if (parsedTexture.mirrorPlane) {
  13958. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13959. texture._waitingRenderList = parsedTexture.renderList;
  13960. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13961. } else if (parsedTexture.isRenderTarget) {
  13962. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13963. texture._waitingRenderList = parsedTexture.renderList;
  13964. } else {
  13965. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13966. }
  13967. texture.name = parsedTexture.name;
  13968. texture.hasAlpha = parsedTexture.hasAlpha;
  13969. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13970. texture.level = parsedTexture.level;
  13971. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13972. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13973. texture.uOffset = parsedTexture.uOffset;
  13974. texture.vOffset = parsedTexture.vOffset;
  13975. texture.uScale = parsedTexture.uScale;
  13976. texture.vScale = parsedTexture.vScale;
  13977. texture.uAng = parsedTexture.uAng;
  13978. texture.vAng = parsedTexture.vAng;
  13979. texture.wAng = parsedTexture.wAng;
  13980. texture.wrapU = parsedTexture.wrapU;
  13981. texture.wrapV = parsedTexture.wrapV;
  13982. if (parsedTexture.animations) {
  13983. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13984. var parsedAnimation = parsedTexture.animations[animationIndex];
  13985. texture.animations.push(parseAnimation(parsedAnimation));
  13986. }
  13987. }
  13988. return texture;
  13989. };
  13990. var parseSkeleton = function (parsedSkeleton, scene) {
  13991. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13992. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13993. var parsedBone = parsedSkeleton.bones[index];
  13994. var parentBone = null;
  13995. if (parsedBone.parentBoneIndex > -1) {
  13996. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13997. }
  13998. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13999. if (parsedBone.animation) {
  14000. bone.animations.push(parseAnimation(parsedBone.animation));
  14001. }
  14002. }
  14003. return skeleton;
  14004. };
  14005. var parseFresnelParameters = function (parsedFresnelParameters) {
  14006. var fresnelParameters = new BABYLON.FresnelParameters();
  14007. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14008. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14009. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14010. fresnelParameters.bias = parsedFresnelParameters.bias;
  14011. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14012. return fresnelParameters;
  14013. };
  14014. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14015. var material;
  14016. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14017. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14018. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14019. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14020. material.specularPower = parsedMaterial.specularPower;
  14021. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14022. material.alpha = parsedMaterial.alpha;
  14023. material.id = parsedMaterial.id;
  14024. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14025. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14026. material.wireframe = parsedMaterial.wireframe;
  14027. if (parsedMaterial.diffuseTexture) {
  14028. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14029. }
  14030. if (parsedMaterial.diffuseFresnelParameters) {
  14031. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14032. }
  14033. if (parsedMaterial.ambientTexture) {
  14034. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14035. }
  14036. if (parsedMaterial.opacityTexture) {
  14037. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14038. }
  14039. if (parsedMaterial.opacityFresnelParameters) {
  14040. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14041. }
  14042. if (parsedMaterial.reflectionTexture) {
  14043. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14044. }
  14045. if (parsedMaterial.reflectionFresnelParameters) {
  14046. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14047. }
  14048. if (parsedMaterial.emissiveTexture) {
  14049. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14050. }
  14051. if (parsedMaterial.emissiveFresnelParameters) {
  14052. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14053. }
  14054. if (parsedMaterial.specularTexture) {
  14055. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14056. }
  14057. if (parsedMaterial.bumpTexture) {
  14058. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14059. }
  14060. return material;
  14061. };
  14062. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14063. for (var index = 0; index < parsedData.materials.length; index++) {
  14064. var parsedMaterial = parsedData.materials[index];
  14065. if (parsedMaterial.id === id) {
  14066. return parseMaterial(parsedMaterial, scene, rootUrl);
  14067. }
  14068. }
  14069. return null;
  14070. };
  14071. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14072. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14073. multiMaterial.id = parsedMultiMaterial.id;
  14074. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14075. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14076. var subMatId = parsedMultiMaterial.materials[matIndex];
  14077. if (subMatId) {
  14078. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14079. } else {
  14080. multiMaterial.subMaterials.push(null);
  14081. }
  14082. }
  14083. return multiMaterial;
  14084. };
  14085. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14086. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14087. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14088. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14089. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14090. var parsedFlare = parsedLensFlareSystem.flares[index];
  14091. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14092. }
  14093. return lensFlareSystem;
  14094. };
  14095. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14096. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14097. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14098. if (parsedParticleSystem.textureName) {
  14099. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14100. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14101. }
  14102. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14103. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14104. particleSystem.minSize = parsedParticleSystem.minSize;
  14105. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14106. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14107. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14108. particleSystem.emitter = emitter;
  14109. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14110. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14111. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14112. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14113. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14114. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14115. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14116. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14117. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14118. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14119. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14120. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14121. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14122. particleSystem.start();
  14123. return particleSystem;
  14124. };
  14125. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14126. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14127. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14128. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14129. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14130. shadowGenerator.getShadowMap().renderList.push(mesh);
  14131. }
  14132. if (parsedShadowGenerator.usePoissonSampling) {
  14133. shadowGenerator.usePoissonSampling = true;
  14134. } else {
  14135. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14136. }
  14137. return shadowGenerator;
  14138. };
  14139. var parseAnimation = function (parsedAnimation) {
  14140. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14141. var dataType = parsedAnimation.dataType;
  14142. var keys = [];
  14143. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14144. var key = parsedAnimation.keys[index];
  14145. var data;
  14146. switch (dataType) {
  14147. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14148. data = key.values[0];
  14149. break;
  14150. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14151. data = BABYLON.Quaternion.FromArray(key.values);
  14152. break;
  14153. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14154. data = BABYLON.Matrix.FromArray(key.values);
  14155. break;
  14156. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14157. default:
  14158. data = BABYLON.Vector3.FromArray(key.values);
  14159. break;
  14160. }
  14161. keys.push({
  14162. frame: key.frame,
  14163. value: data
  14164. });
  14165. }
  14166. animation.setKeys(keys);
  14167. return animation;
  14168. };
  14169. var parseLight = function (parsedLight, scene) {
  14170. var light;
  14171. switch (parsedLight.type) {
  14172. case 0:
  14173. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14174. break;
  14175. case 1:
  14176. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14177. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14178. break;
  14179. case 2:
  14180. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14181. break;
  14182. case 3:
  14183. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14184. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14185. break;
  14186. }
  14187. light.id = parsedLight.id;
  14188. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14189. if (parsedLight.intensity !== undefined) {
  14190. light.intensity = parsedLight.intensity;
  14191. }
  14192. if (parsedLight.range) {
  14193. light.range = parsedLight.range;
  14194. }
  14195. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14196. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14197. if (parsedLight.excludedMeshesIds) {
  14198. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14199. }
  14200. if (parsedLight.includedOnlyMeshesIds) {
  14201. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14202. }
  14203. if (parsedLight.animations) {
  14204. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14205. var parsedAnimation = parsedLight.animations[animationIndex];
  14206. light.animations.push(parseAnimation(parsedAnimation));
  14207. }
  14208. }
  14209. if (parsedLight.autoAnimate) {
  14210. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14211. }
  14212. };
  14213. var parseCamera = function (parsedCamera, scene) {
  14214. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14215. camera.id = parsedCamera.id;
  14216. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14217. if (parsedCamera.parentId) {
  14218. camera._waitingParentId = parsedCamera.parentId;
  14219. }
  14220. if (parsedCamera.target) {
  14221. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14222. } else {
  14223. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14224. }
  14225. if (parsedCamera.lockedTargetId) {
  14226. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14227. }
  14228. camera.fov = parsedCamera.fov;
  14229. camera.minZ = parsedCamera.minZ;
  14230. camera.maxZ = parsedCamera.maxZ;
  14231. camera.speed = parsedCamera.speed;
  14232. camera.inertia = parsedCamera.inertia;
  14233. camera.checkCollisions = parsedCamera.checkCollisions;
  14234. camera.applyGravity = parsedCamera.applyGravity;
  14235. if (parsedCamera.ellipsoid) {
  14236. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14237. }
  14238. if (parsedCamera.animations) {
  14239. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14240. var parsedAnimation = parsedCamera.animations[animationIndex];
  14241. camera.animations.push(parseAnimation(parsedAnimation));
  14242. }
  14243. }
  14244. if (parsedCamera.autoAnimate) {
  14245. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14246. }
  14247. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14248. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14249. } else {
  14250. camera.layerMask = 0xFFFFFFFF;
  14251. }
  14252. return camera;
  14253. };
  14254. var parseGeometry = function (parsedGeometry, scene) {
  14255. var id = parsedGeometry.id;
  14256. return scene.getGeometryByID(id);
  14257. };
  14258. var parseBox = function (parsedBox, scene) {
  14259. if (parseGeometry(parsedBox, scene)) {
  14260. return null;
  14261. }
  14262. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14263. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14264. scene.pushGeometry(box, true);
  14265. return box;
  14266. };
  14267. var parseSphere = function (parsedSphere, scene) {
  14268. if (parseGeometry(parsedSphere, scene)) {
  14269. return null;
  14270. }
  14271. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14272. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14273. scene.pushGeometry(sphere, true);
  14274. return sphere;
  14275. };
  14276. var parseCylinder = function (parsedCylinder, scene) {
  14277. if (parseGeometry(parsedCylinder, scene)) {
  14278. return null;
  14279. }
  14280. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14281. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14282. scene.pushGeometry(cylinder, true);
  14283. return cylinder;
  14284. };
  14285. var parseTorus = function (parsedTorus, scene) {
  14286. if (parseGeometry(parsedTorus, scene)) {
  14287. return null;
  14288. }
  14289. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14290. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14291. scene.pushGeometry(torus, true);
  14292. return torus;
  14293. };
  14294. var parseGround = function (parsedGround, scene) {
  14295. if (parseGeometry(parsedGround, scene)) {
  14296. return null;
  14297. }
  14298. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14299. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14300. scene.pushGeometry(ground, true);
  14301. return ground;
  14302. };
  14303. var parsePlane = function (parsedPlane, scene) {
  14304. if (parseGeometry(parsedPlane, scene)) {
  14305. return null;
  14306. }
  14307. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14308. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14309. scene.pushGeometry(plane, true);
  14310. return plane;
  14311. };
  14312. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14313. if (parseGeometry(parsedTorusKnot, scene)) {
  14314. return null;
  14315. }
  14316. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  14317. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14318. scene.pushGeometry(torusKnot, true);
  14319. return torusKnot;
  14320. };
  14321. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14322. if (parseGeometry(parsedVertexData, scene)) {
  14323. return null;
  14324. }
  14325. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14326. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14327. if (parsedVertexData.delayLoadingFile) {
  14328. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14329. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14330. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14331. geometry._delayInfo = [];
  14332. if (parsedVertexData.hasUVs) {
  14333. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14334. }
  14335. if (parsedVertexData.hasUVs2) {
  14336. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14337. }
  14338. if (parsedVertexData.hasColors) {
  14339. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14340. }
  14341. if (parsedVertexData.hasMatricesIndices) {
  14342. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14343. }
  14344. if (parsedVertexData.hasMatricesWeights) {
  14345. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14346. }
  14347. geometry._delayLoadingFunction = importVertexData;
  14348. } else {
  14349. importVertexData(parsedVertexData, geometry);
  14350. }
  14351. scene.pushGeometry(geometry, true);
  14352. return geometry;
  14353. };
  14354. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14355. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14356. mesh.id = parsedMesh.id;
  14357. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14358. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14359. if (parsedMesh.rotationQuaternion) {
  14360. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14361. } else if (parsedMesh.rotation) {
  14362. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14363. }
  14364. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14365. if (parsedMesh.localMatrix) {
  14366. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14367. } else if (parsedMesh.pivotMatrix) {
  14368. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14369. }
  14370. mesh.setEnabled(parsedMesh.isEnabled);
  14371. mesh.isVisible = parsedMesh.isVisible;
  14372. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14373. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14374. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14375. if (parsedMesh.pickable !== undefined) {
  14376. mesh.isPickable = parsedMesh.pickable;
  14377. }
  14378. mesh.receiveShadows = parsedMesh.receiveShadows;
  14379. mesh.billboardMode = parsedMesh.billboardMode;
  14380. if (parsedMesh.visibility !== undefined) {
  14381. mesh.visibility = parsedMesh.visibility;
  14382. }
  14383. mesh.checkCollisions = parsedMesh.checkCollisions;
  14384. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14385. if (parsedMesh.parentId) {
  14386. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14387. }
  14388. if (parsedMesh.delayLoadingFile) {
  14389. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14390. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14391. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14392. if (parsedMesh._binaryInfo) {
  14393. mesh._binaryInfo = parsedMesh._binaryInfo;
  14394. }
  14395. mesh._delayInfo = [];
  14396. if (parsedMesh.hasUVs) {
  14397. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14398. }
  14399. if (parsedMesh.hasUVs2) {
  14400. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14401. }
  14402. if (parsedMesh.hasColors) {
  14403. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14404. }
  14405. if (parsedMesh.hasMatricesIndices) {
  14406. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14407. }
  14408. if (parsedMesh.hasMatricesWeights) {
  14409. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14410. }
  14411. mesh._delayLoadingFunction = importGeometry;
  14412. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14413. mesh._checkDelayState();
  14414. }
  14415. } else {
  14416. importGeometry(parsedMesh, mesh);
  14417. }
  14418. if (parsedMesh.materialId) {
  14419. mesh.setMaterialByID(parsedMesh.materialId);
  14420. } else {
  14421. mesh.material = null;
  14422. }
  14423. if (parsedMesh.skeletonId > -1) {
  14424. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14425. }
  14426. if (parsedMesh.physicsImpostor) {
  14427. if (!scene.isPhysicsEnabled()) {
  14428. scene.enablePhysics();
  14429. }
  14430. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14431. }
  14432. if (parsedMesh.animations) {
  14433. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14434. var parsedAnimation = parsedMesh.animations[animationIndex];
  14435. mesh.animations.push(parseAnimation(parsedAnimation));
  14436. }
  14437. }
  14438. if (parsedMesh.autoAnimate) {
  14439. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14440. }
  14441. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14442. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14443. } else {
  14444. mesh.layerMask = 0xFFFFFFFF;
  14445. }
  14446. if (parsedMesh.instances) {
  14447. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14448. var parsedInstance = parsedMesh.instances[index];
  14449. var instance = mesh.createInstance(parsedInstance.name);
  14450. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14451. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14452. if (parsedInstance.rotationQuaternion) {
  14453. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14454. } else if (parsedInstance.rotation) {
  14455. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14456. }
  14457. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14458. instance.checkCollisions = mesh.checkCollisions;
  14459. if (parsedMesh.animations) {
  14460. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14461. parsedAnimation = parsedMesh.animations[animationIndex];
  14462. instance.animations.push(parseAnimation(parsedAnimation));
  14463. }
  14464. }
  14465. }
  14466. }
  14467. return mesh;
  14468. };
  14469. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14470. names = (names instanceof Array) ? names : [names];
  14471. for (var i in names) {
  14472. if (mesh.name === names[i]) {
  14473. hierarchyIds.push(mesh.id);
  14474. return true;
  14475. }
  14476. }
  14477. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14478. hierarchyIds.push(mesh.id);
  14479. return true;
  14480. }
  14481. return false;
  14482. };
  14483. var importVertexData = function (parsedVertexData, geometry) {
  14484. var vertexData = new BABYLON.VertexData();
  14485. var positions = parsedVertexData.positions;
  14486. if (positions) {
  14487. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14488. }
  14489. var normals = parsedVertexData.normals;
  14490. if (normals) {
  14491. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14492. }
  14493. var uvs = parsedVertexData.uvs;
  14494. if (uvs) {
  14495. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14496. }
  14497. var uv2s = parsedVertexData.uv2s;
  14498. if (uv2s) {
  14499. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14500. }
  14501. var colors = parsedVertexData.colors;
  14502. if (colors) {
  14503. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14504. }
  14505. var matricesIndices = parsedVertexData.matricesIndices;
  14506. if (matricesIndices) {
  14507. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14508. }
  14509. var matricesWeights = parsedVertexData.matricesWeights;
  14510. if (matricesWeights) {
  14511. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14512. }
  14513. var indices = parsedVertexData.indices;
  14514. if (indices) {
  14515. vertexData.indices = indices;
  14516. }
  14517. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14518. };
  14519. var importGeometry = function (parsedGeometry, mesh) {
  14520. var scene = mesh.getScene();
  14521. var geometryId = parsedGeometry.geometryId;
  14522. if (geometryId) {
  14523. var geometry = scene.getGeometryByID(geometryId);
  14524. if (geometry) {
  14525. geometry.applyToMesh(mesh);
  14526. }
  14527. } else if (parsedGeometry instanceof ArrayBuffer) {
  14528. var binaryInfo = mesh._binaryInfo;
  14529. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  14530. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  14531. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  14532. }
  14533. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  14534. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  14535. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  14536. }
  14537. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  14538. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  14539. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  14540. }
  14541. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  14542. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  14543. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  14544. }
  14545. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  14546. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  14547. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  14548. }
  14549. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  14550. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  14551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  14552. }
  14553. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  14554. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  14555. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  14556. }
  14557. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  14558. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  14559. mesh.setIndices(indicesData);
  14560. }
  14561. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  14562. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  14563. mesh.subMeshes = [];
  14564. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  14565. var materialIndex = subMeshesData[(i * 5) + 0];
  14566. var verticesStart = subMeshesData[(i * 5) + 1];
  14567. var verticesCount = subMeshesData[(i * 5) + 2];
  14568. var indexStart = subMeshesData[(i * 5) + 3];
  14569. var indexCount = subMeshesData[(i * 5) + 4];
  14570. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  14571. }
  14572. }
  14573. return;
  14574. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14575. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14576. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14577. if (parsedGeometry.uvs) {
  14578. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14579. }
  14580. if (parsedGeometry.uvs2) {
  14581. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14582. }
  14583. if (parsedGeometry.colors) {
  14584. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14585. }
  14586. if (parsedGeometry.matricesIndices) {
  14587. if (!parsedGeometry.matricesIndices._isExpanded) {
  14588. var floatIndices = [];
  14589. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14590. var matricesIndex = parsedGeometry.matricesIndices[i];
  14591. floatIndices.push(matricesIndex & 0x000000FF);
  14592. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14593. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14594. floatIndices.push(matricesIndex >> 24);
  14595. }
  14596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14597. } else {
  14598. delete parsedGeometry.matricesIndices._isExpanded;
  14599. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14600. }
  14601. }
  14602. if (parsedGeometry.matricesWeights) {
  14603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14604. }
  14605. mesh.setIndices(parsedGeometry.indices);
  14606. }
  14607. if (parsedGeometry.subMeshes) {
  14608. mesh.subMeshes = [];
  14609. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14610. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14611. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14612. }
  14613. }
  14614. if (mesh._shouldGenerateFlatShading) {
  14615. mesh.convertToFlatShadedMesh();
  14616. delete mesh._shouldGenerateFlatShading;
  14617. }
  14618. mesh.computeWorldMatrix(true);
  14619. if (scene._selectionOctree) {
  14620. scene._selectionOctree.addMesh(mesh);
  14621. }
  14622. };
  14623. BABYLON.SceneLoader.RegisterPlugin({
  14624. extensions: ".babylon",
  14625. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14626. var parsedData = JSON.parse(data);
  14627. var loadedSkeletonsIds = [];
  14628. var loadedMaterialsIds = [];
  14629. var hierarchyIds = [];
  14630. for (var index = 0; index < parsedData.meshes.length; index++) {
  14631. var parsedMesh = parsedData.meshes[index];
  14632. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14633. if (meshesNames instanceof Array) {
  14634. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14635. }
  14636. if (parsedMesh.materialId) {
  14637. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14638. if (!materialFound) {
  14639. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14640. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14641. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14642. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14643. var subMatId = parsedMultiMaterial.materials[matIndex];
  14644. loadedMaterialsIds.push(subMatId);
  14645. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14646. }
  14647. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14648. parseMultiMaterial(parsedMultiMaterial, scene);
  14649. materialFound = true;
  14650. break;
  14651. }
  14652. }
  14653. }
  14654. if (!materialFound) {
  14655. loadedMaterialsIds.push(parsedMesh.materialId);
  14656. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14657. }
  14658. }
  14659. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14660. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14661. if (!skeletonAlreadyLoaded) {
  14662. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14663. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14664. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14665. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14666. loadedSkeletonsIds.push(parsedSkeleton.id);
  14667. }
  14668. }
  14669. }
  14670. }
  14671. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14672. meshes.push(mesh);
  14673. }
  14674. }
  14675. if (parsedData.particleSystems) {
  14676. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14677. var parsedParticleSystem = parsedData.particleSystems[index];
  14678. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14679. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14680. }
  14681. }
  14682. }
  14683. return true;
  14684. },
  14685. load: function (scene, data, rootUrl) {
  14686. var parsedData = JSON.parse(data);
  14687. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14688. scene.autoClear = parsedData.autoClear;
  14689. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14690. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14691. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14692. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14693. scene.fogMode = parsedData.fogMode;
  14694. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14695. scene.fogStart = parsedData.fogStart;
  14696. scene.fogEnd = parsedData.fogEnd;
  14697. scene.fogDensity = parsedData.fogDensity;
  14698. }
  14699. for (var index = 0; index < parsedData.lights.length; index++) {
  14700. var parsedLight = parsedData.lights[index];
  14701. parseLight(parsedLight, scene);
  14702. }
  14703. for (index = 0; index < parsedData.cameras.length; index++) {
  14704. var parsedCamera = parsedData.cameras[index];
  14705. parseCamera(parsedCamera, scene);
  14706. }
  14707. if (parsedData.activeCameraID) {
  14708. scene.setActiveCameraByID(parsedData.activeCameraID);
  14709. }
  14710. if (parsedData.materials) {
  14711. for (index = 0; index < parsedData.materials.length; index++) {
  14712. var parsedMaterial = parsedData.materials[index];
  14713. parseMaterial(parsedMaterial, scene, rootUrl);
  14714. }
  14715. }
  14716. if (parsedData.multiMaterials) {
  14717. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14718. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14719. parseMultiMaterial(parsedMultiMaterial, scene);
  14720. }
  14721. }
  14722. if (parsedData.skeletons) {
  14723. for (index = 0; index < parsedData.skeletons.length; index++) {
  14724. var parsedSkeleton = parsedData.skeletons[index];
  14725. parseSkeleton(parsedSkeleton, scene);
  14726. }
  14727. }
  14728. var geometries = parsedData.geometries;
  14729. if (geometries) {
  14730. var boxes = geometries.boxes;
  14731. if (boxes) {
  14732. for (index = 0; index < boxes.length; index++) {
  14733. var parsedBox = boxes[index];
  14734. parseBox(parsedBox, scene);
  14735. }
  14736. }
  14737. var spheres = geometries.spheres;
  14738. if (spheres) {
  14739. for (index = 0; index < spheres.length; index++) {
  14740. var parsedSphere = spheres[index];
  14741. parseSphere(parsedSphere, scene);
  14742. }
  14743. }
  14744. var cylinders = geometries.cylinders;
  14745. if (cylinders) {
  14746. for (index = 0; index < cylinders.length; index++) {
  14747. var parsedCylinder = cylinders[index];
  14748. parseCylinder(parsedCylinder, scene);
  14749. }
  14750. }
  14751. var toruses = geometries.toruses;
  14752. if (toruses) {
  14753. for (index = 0; index < toruses.length; index++) {
  14754. var parsedTorus = toruses[index];
  14755. parseTorus(parsedTorus, scene);
  14756. }
  14757. }
  14758. var grounds = geometries.grounds;
  14759. if (grounds) {
  14760. for (index = 0; index < grounds.length; index++) {
  14761. var parsedGround = grounds[index];
  14762. parseGround(parsedGround, scene);
  14763. }
  14764. }
  14765. var planes = geometries.planes;
  14766. if (planes) {
  14767. for (index = 0; index < planes.length; index++) {
  14768. var parsedPlane = planes[index];
  14769. parsePlane(parsedPlane, scene);
  14770. }
  14771. }
  14772. var torusKnots = geometries.torusKnots;
  14773. if (torusKnots) {
  14774. for (index = 0; index < torusKnots.length; index++) {
  14775. var parsedTorusKnot = torusKnots[index];
  14776. parseTorusKnot(parsedTorusKnot, scene);
  14777. }
  14778. }
  14779. var vertexData = geometries.vertexData;
  14780. if (vertexData) {
  14781. for (index = 0; index < vertexData.length; index++) {
  14782. var parsedVertexData = vertexData[index];
  14783. parseVertexData(parsedVertexData, scene, rootUrl);
  14784. }
  14785. }
  14786. }
  14787. for (index = 0; index < parsedData.meshes.length; index++) {
  14788. var parsedMesh = parsedData.meshes[index];
  14789. parseMesh(parsedMesh, scene, rootUrl);
  14790. }
  14791. for (index = 0; index < scene.cameras.length; index++) {
  14792. var camera = scene.cameras[index];
  14793. if (camera._waitingParentId) {
  14794. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14795. delete camera._waitingParentId;
  14796. }
  14797. if (camera instanceof BABYLON.FreeCamera) {
  14798. var freecamera = camera;
  14799. if (freecamera._waitingLockedTargetId) {
  14800. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14801. delete freecamera._waitingLockedTargetId;
  14802. }
  14803. }
  14804. }
  14805. if (parsedData.particleSystems) {
  14806. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14807. var parsedParticleSystem = parsedData.particleSystems[index];
  14808. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14809. }
  14810. }
  14811. if (parsedData.lensFlareSystems) {
  14812. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14813. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14814. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14815. }
  14816. }
  14817. if (parsedData.shadowGenerators) {
  14818. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14819. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14820. parseShadowGenerator(parsedShadowGenerator, scene);
  14821. }
  14822. }
  14823. return true;
  14824. }
  14825. });
  14826. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14827. var Internals = BABYLON.Internals;
  14828. })(BABYLON || (BABYLON = {}));
  14829. var BABYLON;
  14830. (function (BABYLON) {
  14831. var currentCSGMeshId = 0;
  14832. var Vertex = (function () {
  14833. function Vertex(pos, normal, uv) {
  14834. this.pos = pos;
  14835. this.normal = normal;
  14836. this.uv = uv;
  14837. }
  14838. Vertex.prototype.clone = function () {
  14839. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14840. };
  14841. Vertex.prototype.flip = function () {
  14842. this.normal = this.normal.scale(-1);
  14843. };
  14844. Vertex.prototype.interpolate = function (other, t) {
  14845. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  14846. };
  14847. return Vertex;
  14848. })();
  14849. var Plane = (function () {
  14850. function Plane(normal, w) {
  14851. this.normal = normal;
  14852. this.w = w;
  14853. }
  14854. Plane.FromPoints = function (a, b, c) {
  14855. var v0 = c.subtract(a);
  14856. var v1 = b.subtract(a);
  14857. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14858. return null;
  14859. }
  14860. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14861. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14862. };
  14863. Plane.prototype.clone = function () {
  14864. return new Plane(this.normal.clone(), this.w);
  14865. };
  14866. Plane.prototype.flip = function () {
  14867. this.normal.scaleInPlace(-1);
  14868. this.w = -this.w;
  14869. };
  14870. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14871. var COPLANAR = 0;
  14872. var FRONT = 1;
  14873. var BACK = 2;
  14874. var SPANNING = 3;
  14875. var polygonType = 0;
  14876. var types = [];
  14877. for (var i = 0; i < polygon.vertices.length; i++) {
  14878. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14879. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14880. polygonType |= type;
  14881. types.push(type);
  14882. }
  14883. switch (polygonType) {
  14884. case COPLANAR:
  14885. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14886. break;
  14887. case FRONT:
  14888. front.push(polygon);
  14889. break;
  14890. case BACK:
  14891. back.push(polygon);
  14892. break;
  14893. case SPANNING:
  14894. var f = [], b = [];
  14895. for (i = 0; i < polygon.vertices.length; i++) {
  14896. var j = (i + 1) % polygon.vertices.length;
  14897. var ti = types[i], tj = types[j];
  14898. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14899. if (ti != BACK)
  14900. f.push(vi);
  14901. if (ti != FRONT)
  14902. b.push(ti != BACK ? vi.clone() : vi);
  14903. if ((ti | tj) == SPANNING) {
  14904. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14905. var v = vi.interpolate(vj, t);
  14906. f.push(v);
  14907. b.push(v.clone());
  14908. }
  14909. }
  14910. if (f.length >= 3) {
  14911. var poly = new Polygon(f, polygon.shared);
  14912. if (poly.plane)
  14913. front.push(poly);
  14914. }
  14915. if (b.length >= 3) {
  14916. poly = new Polygon(b, polygon.shared);
  14917. if (poly.plane)
  14918. back.push(poly);
  14919. }
  14920. break;
  14921. }
  14922. };
  14923. Plane.EPSILON = 1e-5;
  14924. return Plane;
  14925. })();
  14926. var Polygon = (function () {
  14927. function Polygon(vertices, shared) {
  14928. this.vertices = vertices;
  14929. this.shared = shared;
  14930. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14931. }
  14932. Polygon.prototype.clone = function () {
  14933. var vertices = this.vertices.map(function (v) {
  14934. return v.clone();
  14935. });
  14936. return new Polygon(vertices, this.shared);
  14937. };
  14938. Polygon.prototype.flip = function () {
  14939. this.vertices.reverse().map(function (v) {
  14940. v.flip();
  14941. });
  14942. this.plane.flip();
  14943. };
  14944. return Polygon;
  14945. })();
  14946. var Node = (function () {
  14947. function Node(polygons) {
  14948. this.plane = null;
  14949. this.front = null;
  14950. this.back = null;
  14951. this.polygons = [];
  14952. if (polygons) {
  14953. this.build(polygons);
  14954. }
  14955. }
  14956. Node.prototype.clone = function () {
  14957. var node = new Node();
  14958. node.plane = this.plane && this.plane.clone();
  14959. node.front = this.front && this.front.clone();
  14960. node.back = this.back && this.back.clone();
  14961. node.polygons = this.polygons.map(function (p) {
  14962. return p.clone();
  14963. });
  14964. return node;
  14965. };
  14966. Node.prototype.invert = function () {
  14967. for (var i = 0; i < this.polygons.length; i++) {
  14968. this.polygons[i].flip();
  14969. }
  14970. if (this.plane) {
  14971. this.plane.flip();
  14972. }
  14973. if (this.front) {
  14974. this.front.invert();
  14975. }
  14976. if (this.back) {
  14977. this.back.invert();
  14978. }
  14979. var temp = this.front;
  14980. this.front = this.back;
  14981. this.back = temp;
  14982. };
  14983. Node.prototype.clipPolygons = function (polygons) {
  14984. if (!this.plane)
  14985. return polygons.slice();
  14986. var front = [], back = [];
  14987. for (var i = 0; i < polygons.length; i++) {
  14988. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14989. }
  14990. if (this.front) {
  14991. front = this.front.clipPolygons(front);
  14992. }
  14993. if (this.back) {
  14994. back = this.back.clipPolygons(back);
  14995. } else {
  14996. back = [];
  14997. }
  14998. return front.concat(back);
  14999. };
  15000. Node.prototype.clipTo = function (bsp) {
  15001. this.polygons = bsp.clipPolygons(this.polygons);
  15002. if (this.front)
  15003. this.front.clipTo(bsp);
  15004. if (this.back)
  15005. this.back.clipTo(bsp);
  15006. };
  15007. Node.prototype.allPolygons = function () {
  15008. var polygons = this.polygons.slice();
  15009. if (this.front)
  15010. polygons = polygons.concat(this.front.allPolygons());
  15011. if (this.back)
  15012. polygons = polygons.concat(this.back.allPolygons());
  15013. return polygons;
  15014. };
  15015. Node.prototype.build = function (polygons) {
  15016. if (!polygons.length)
  15017. return;
  15018. if (!this.plane)
  15019. this.plane = polygons[0].plane.clone();
  15020. var front = [], back = [];
  15021. for (var i = 0; i < polygons.length; i++) {
  15022. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15023. }
  15024. if (front.length) {
  15025. if (!this.front)
  15026. this.front = new Node();
  15027. this.front.build(front);
  15028. }
  15029. if (back.length) {
  15030. if (!this.back)
  15031. this.back = new Node();
  15032. this.back.build(back);
  15033. }
  15034. };
  15035. return Node;
  15036. })();
  15037. var CSG = (function () {
  15038. function CSG() {
  15039. this.polygons = new Array();
  15040. }
  15041. CSG.FromMesh = function (mesh) {
  15042. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15043. if (mesh instanceof BABYLON.Mesh) {
  15044. mesh.computeWorldMatrix(true);
  15045. var matrix = mesh.getWorldMatrix();
  15046. var meshPosition = mesh.position.clone();
  15047. var meshRotation = mesh.rotation.clone();
  15048. var meshScaling = mesh.scaling.clone();
  15049. } else {
  15050. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15051. }
  15052. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15053. var subMeshes = mesh.subMeshes;
  15054. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15055. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15056. vertices = [];
  15057. for (var j = 0; j < 3; j++) {
  15058. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15059. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15060. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15061. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15062. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15063. vertex = new Vertex(position, normal, uv);
  15064. vertices.push(vertex);
  15065. }
  15066. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15067. if (polygon.plane)
  15068. polygons.push(polygon);
  15069. }
  15070. }
  15071. var csg = CSG.FromPolygons(polygons);
  15072. csg.matrix = matrix;
  15073. csg.position = meshPosition;
  15074. csg.rotation = meshRotation;
  15075. csg.scaling = meshScaling;
  15076. currentCSGMeshId++;
  15077. return csg;
  15078. };
  15079. CSG.FromPolygons = function (polygons) {
  15080. var csg = new BABYLON.CSG();
  15081. csg.polygons = polygons;
  15082. return csg;
  15083. };
  15084. CSG.prototype.clone = function () {
  15085. var csg = new BABYLON.CSG();
  15086. csg.polygons = this.polygons.map(function (p) {
  15087. return p.clone();
  15088. });
  15089. csg.copyTransformAttributes(this);
  15090. return csg;
  15091. };
  15092. CSG.prototype.toPolygons = function () {
  15093. return this.polygons;
  15094. };
  15095. CSG.prototype.union = function (csg) {
  15096. var a = new Node(this.clone().polygons);
  15097. var b = new Node(csg.clone().polygons);
  15098. a.clipTo(b);
  15099. b.clipTo(a);
  15100. b.invert();
  15101. b.clipTo(a);
  15102. b.invert();
  15103. a.build(b.allPolygons());
  15104. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15105. };
  15106. CSG.prototype.unionInPlace = function (csg) {
  15107. var a = new Node(this.polygons);
  15108. var b = new Node(csg.polygons);
  15109. a.clipTo(b);
  15110. b.clipTo(a);
  15111. b.invert();
  15112. b.clipTo(a);
  15113. b.invert();
  15114. a.build(b.allPolygons());
  15115. this.polygons = a.allPolygons();
  15116. };
  15117. CSG.prototype.subtract = function (csg) {
  15118. var a = new Node(this.clone().polygons);
  15119. var b = new Node(csg.clone().polygons);
  15120. a.invert();
  15121. a.clipTo(b);
  15122. b.clipTo(a);
  15123. b.invert();
  15124. b.clipTo(a);
  15125. b.invert();
  15126. a.build(b.allPolygons());
  15127. a.invert();
  15128. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15129. };
  15130. CSG.prototype.subtractInPlace = function (csg) {
  15131. var a = new Node(this.polygons);
  15132. var b = new Node(csg.polygons);
  15133. a.invert();
  15134. a.clipTo(b);
  15135. b.clipTo(a);
  15136. b.invert();
  15137. b.clipTo(a);
  15138. b.invert();
  15139. a.build(b.allPolygons());
  15140. a.invert();
  15141. this.polygons = a.allPolygons();
  15142. };
  15143. CSG.prototype.intersect = function (csg) {
  15144. var a = new Node(this.clone().polygons);
  15145. var b = new Node(csg.clone().polygons);
  15146. a.invert();
  15147. b.clipTo(a);
  15148. b.invert();
  15149. a.clipTo(b);
  15150. b.clipTo(a);
  15151. a.build(b.allPolygons());
  15152. a.invert();
  15153. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15154. };
  15155. CSG.prototype.intersectInPlace = function (csg) {
  15156. var a = new Node(this.polygons);
  15157. var b = new Node(csg.polygons);
  15158. a.invert();
  15159. b.clipTo(a);
  15160. b.invert();
  15161. a.clipTo(b);
  15162. b.clipTo(a);
  15163. a.build(b.allPolygons());
  15164. a.invert();
  15165. this.polygons = a.allPolygons();
  15166. };
  15167. CSG.prototype.inverse = function () {
  15168. var csg = this.clone();
  15169. csg.inverseInPlace();
  15170. return csg;
  15171. };
  15172. CSG.prototype.inverseInPlace = function () {
  15173. this.polygons.map(function (p) {
  15174. p.flip();
  15175. });
  15176. };
  15177. CSG.prototype.copyTransformAttributes = function (csg) {
  15178. this.matrix = csg.matrix;
  15179. this.position = csg.position;
  15180. this.rotation = csg.rotation;
  15181. this.scaling = csg.scaling;
  15182. return this;
  15183. };
  15184. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15185. var matrix = this.matrix.clone();
  15186. matrix.invert();
  15187. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  15188. if (keepSubMeshes) {
  15189. polygons.sort(function (a, b) {
  15190. if (a.shared.meshId === b.shared.meshId) {
  15191. return a.shared.subMeshId - b.shared.subMeshId;
  15192. } else {
  15193. return a.shared.meshId - b.shared.meshId;
  15194. }
  15195. });
  15196. }
  15197. for (var i = 0, il = polygons.length; i < il; i++) {
  15198. polygon = polygons[i];
  15199. if (!subMesh_dict[polygon.shared.meshId]) {
  15200. subMesh_dict[polygon.shared.meshId] = {};
  15201. }
  15202. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15203. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15204. indexStart: +Infinity,
  15205. indexEnd: -Infinity,
  15206. materialIndex: polygon.shared.materialIndex
  15207. };
  15208. }
  15209. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15210. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15211. polygonIndices[0] = 0;
  15212. polygonIndices[1] = j - 1;
  15213. polygonIndices[2] = j;
  15214. for (var k = 0; k < 3; k++) {
  15215. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15216. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15217. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15218. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15219. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15220. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15221. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  15222. vertices.push(vertex.x, vertex.y, vertex.z);
  15223. uvs.push(uv.x, uv.y);
  15224. normals.push(normal.x, normal.y, normal.z);
  15225. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15226. }
  15227. indices.push(vertex_idx);
  15228. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15229. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15230. currentIndex++;
  15231. }
  15232. }
  15233. }
  15234. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15235. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15236. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15237. mesh.setIndices(indices);
  15238. if (keepSubMeshes) {
  15239. var materialIndexOffset = 0, materialMaxIndex;
  15240. mesh.subMeshes.length = 0;
  15241. for (var m in subMesh_dict) {
  15242. materialMaxIndex = -1;
  15243. for (var sm in subMesh_dict[m]) {
  15244. subMesh_obj = subMesh_dict[m][sm];
  15245. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15246. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15247. }
  15248. materialIndexOffset += ++materialMaxIndex;
  15249. }
  15250. }
  15251. return mesh;
  15252. };
  15253. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15254. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15255. mesh.material = material;
  15256. mesh.position.copyFrom(this.position);
  15257. mesh.rotation.copyFrom(this.rotation);
  15258. mesh.scaling.copyFrom(this.scaling);
  15259. mesh.computeWorldMatrix(true);
  15260. return mesh;
  15261. };
  15262. return CSG;
  15263. })();
  15264. BABYLON.CSG = CSG;
  15265. })(BABYLON || (BABYLON = {}));
  15266. var __extends = this.__extends || function (d, b) {
  15267. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15268. function __() { this.constructor = d; }
  15269. __.prototype = b.prototype;
  15270. d.prototype = new __();
  15271. };
  15272. var BABYLON;
  15273. (function (BABYLON) {
  15274. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15275. __extends(OculusDistortionCorrectionPostProcess, _super);
  15276. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15277. var _this = this;
  15278. _super.call(this, name, "oculusDistortionCorrection", [
  15279. 'LensCenter',
  15280. 'Scale',
  15281. 'ScaleIn',
  15282. 'HmdWarpParam'
  15283. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15284. this._isRightEye = isRightEye;
  15285. this._distortionFactors = cameraSettings.DistortionK;
  15286. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15287. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15288. this.onSizeChanged = function () {
  15289. _this.aspectRatio = _this.width * .5 / _this.height;
  15290. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15291. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15292. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15293. };
  15294. this.onApply = function (effect) {
  15295. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15296. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15297. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15298. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15299. };
  15300. }
  15301. return OculusDistortionCorrectionPostProcess;
  15302. })(BABYLON.PostProcess);
  15303. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15304. })(BABYLON || (BABYLON = {}));
  15305. var BABYLON;
  15306. (function (BABYLON) {
  15307. (function (JoystickAxis) {
  15308. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15309. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15310. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15311. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15312. var JoystickAxis = BABYLON.JoystickAxis;
  15313. var VirtualJoystick = (function () {
  15314. function VirtualJoystick(leftJoystick) {
  15315. var _this = this;
  15316. if (leftJoystick) {
  15317. this._leftJoystick = true;
  15318. } else {
  15319. this._leftJoystick = false;
  15320. }
  15321. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15322. VirtualJoystick._globalJoystickIndex++;
  15323. this._axisTargetedByLeftAndRight = 0 /* X */;
  15324. this._axisTargetedByUpAndDown = 1 /* Y */;
  15325. this.reverseLeftRight = false;
  15326. this.reverseUpDown = false;
  15327. this._touches = new BABYLON.VirtualJoystick.Collection();
  15328. this.deltaPosition = BABYLON.Vector3.Zero();
  15329. this._joystickSensibility = 25;
  15330. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15331. this._rotationSpeed = 25;
  15332. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15333. this._rotateOnAxisRelativeToMesh = false;
  15334. if (!VirtualJoystick.vjCanvas) {
  15335. window.addEventListener("resize", function () {
  15336. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15337. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15338. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15339. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15340. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15341. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15342. }, false);
  15343. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15344. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15345. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15346. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15347. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15348. VirtualJoystick.vjCanvas.style.width = "100%";
  15349. VirtualJoystick.vjCanvas.style.height = "100%";
  15350. VirtualJoystick.vjCanvas.style.position = "absolute";
  15351. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15352. VirtualJoystick.vjCanvas.style.top = "0px";
  15353. VirtualJoystick.vjCanvas.style.left = "0px";
  15354. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15355. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15356. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15357. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15358. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15359. document.body.appendChild(VirtualJoystick.vjCanvas);
  15360. }
  15361. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15362. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15363. this.pressed = false;
  15364. this._joystickColor = "cyan";
  15365. this._joystickPointerID = -1;
  15366. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15367. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15368. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15369. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15370. _this._onPointerDown(evt);
  15371. }, false);
  15372. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15373. _this._onPointerMove(evt);
  15374. }, false);
  15375. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15376. _this._onPointerUp(evt);
  15377. }, false);
  15378. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15379. _this._onPointerUp(evt);
  15380. }, false);
  15381. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15382. evt.preventDefault();
  15383. }, false);
  15384. requestAnimationFrame(function () {
  15385. _this._drawVirtualJoystick();
  15386. });
  15387. }
  15388. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15389. this._joystickSensibility = newJoystickSensibility;
  15390. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15391. };
  15392. VirtualJoystick.prototype._onPointerDown = function (e) {
  15393. var positionOnScreenCondition;
  15394. e.preventDefault();
  15395. if (this._leftJoystick === true) {
  15396. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15397. } else {
  15398. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15399. }
  15400. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15401. this._joystickPointerID = e.pointerId;
  15402. this._joystickPointerStartPos.x = e.clientX;
  15403. this._joystickPointerStartPos.y = e.clientY;
  15404. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15405. this._deltaJoystickVector.x = 0;
  15406. this._deltaJoystickVector.y = 0;
  15407. this.pressed = true;
  15408. this._touches.add(e.pointerId.toString(), e);
  15409. } else {
  15410. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15411. this._action();
  15412. this._touches.add(e.pointerId.toString(), e);
  15413. }
  15414. }
  15415. };
  15416. VirtualJoystick.prototype._onPointerMove = function (e) {
  15417. if (this._joystickPointerID == e.pointerId) {
  15418. this._joystickPointerPos.x = e.clientX;
  15419. this._joystickPointerPos.y = e.clientY;
  15420. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15421. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15422. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15423. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15424. switch (this._axisTargetedByLeftAndRight) {
  15425. case 0 /* X */:
  15426. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15427. break;
  15428. case 1 /* Y */:
  15429. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15430. break;
  15431. case 2 /* Z */:
  15432. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15433. break;
  15434. }
  15435. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15436. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15437. switch (this._axisTargetedByUpAndDown) {
  15438. case 0 /* X */:
  15439. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15440. break;
  15441. case 1 /* Y */:
  15442. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15443. break;
  15444. case 2 /* Z */:
  15445. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15446. break;
  15447. }
  15448. } else {
  15449. if (this._touches.item(e.pointerId.toString())) {
  15450. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15451. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15452. }
  15453. }
  15454. };
  15455. VirtualJoystick.prototype._onPointerUp = function (e) {
  15456. this._clearCanvas();
  15457. if (this._joystickPointerID == e.pointerId) {
  15458. this._joystickPointerID = -1;
  15459. this.pressed = false;
  15460. }
  15461. this._deltaJoystickVector.x = 0;
  15462. this._deltaJoystickVector.y = 0;
  15463. this._touches.remove(e.pointerId.toString());
  15464. };
  15465. /**
  15466. * Change the color of the virtual joystick
  15467. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15468. */
  15469. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15470. this._joystickColor = newColor;
  15471. };
  15472. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15473. this._action = action;
  15474. };
  15475. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15476. switch (axis) {
  15477. case 0 /* X */:
  15478. case 1 /* Y */:
  15479. case 2 /* Z */:
  15480. this._axisTargetedByLeftAndRight = axis;
  15481. break;
  15482. default:
  15483. this._axisTargetedByLeftAndRight = 0 /* X */;
  15484. break;
  15485. }
  15486. };
  15487. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15488. switch (axis) {
  15489. case 0 /* X */:
  15490. case 1 /* Y */:
  15491. case 2 /* Z */:
  15492. this._axisTargetedByUpAndDown = axis;
  15493. break;
  15494. default:
  15495. this._axisTargetedByUpAndDown = 1 /* Y */;
  15496. break;
  15497. }
  15498. };
  15499. VirtualJoystick.prototype._clearCanvas = function () {
  15500. if (this._leftJoystick) {
  15501. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15502. } else {
  15503. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15504. }
  15505. };
  15506. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15507. var _this = this;
  15508. if (this.pressed) {
  15509. this._clearCanvas();
  15510. this._touches.forEach(function (touch) {
  15511. if (touch.pointerId === _this._joystickPointerID) {
  15512. VirtualJoystick.vjCanvasContext.beginPath();
  15513. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15514. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15515. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15516. VirtualJoystick.vjCanvasContext.stroke();
  15517. VirtualJoystick.vjCanvasContext.beginPath();
  15518. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15519. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15520. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15521. VirtualJoystick.vjCanvasContext.stroke();
  15522. VirtualJoystick.vjCanvasContext.beginPath();
  15523. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15524. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15525. VirtualJoystick.vjCanvasContext.stroke();
  15526. } else {
  15527. VirtualJoystick.vjCanvasContext.beginPath();
  15528. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15529. VirtualJoystick.vjCanvasContext.beginPath();
  15530. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15531. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15532. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15533. VirtualJoystick.vjCanvasContext.stroke();
  15534. }
  15535. ;
  15536. });
  15537. }
  15538. requestAnimationFrame(function () {
  15539. _this._drawVirtualJoystick();
  15540. });
  15541. };
  15542. VirtualJoystick.prototype.releaseCanvas = function () {
  15543. if (VirtualJoystick.vjCanvas) {
  15544. document.body.removeChild(VirtualJoystick.vjCanvas);
  15545. VirtualJoystick.vjCanvas = null;
  15546. }
  15547. };
  15548. VirtualJoystick._globalJoystickIndex = 0;
  15549. return VirtualJoystick;
  15550. })();
  15551. BABYLON.VirtualJoystick = VirtualJoystick;
  15552. })(BABYLON || (BABYLON = {}));
  15553. var BABYLON;
  15554. (function (BABYLON) {
  15555. (function (VirtualJoystick) {
  15556. var Collection = (function () {
  15557. function Collection() {
  15558. this._count = 0;
  15559. this._collection = new Array();
  15560. }
  15561. Collection.prototype.Count = function () {
  15562. return this._count;
  15563. };
  15564. Collection.prototype.add = function (key, item) {
  15565. if (this._collection[key] != undefined) {
  15566. return undefined;
  15567. }
  15568. this._collection[key] = item;
  15569. return ++this._count;
  15570. };
  15571. Collection.prototype.remove = function (key) {
  15572. if (this._collection[key] == undefined) {
  15573. return undefined;
  15574. }
  15575. delete this._collection[key];
  15576. return --this._count;
  15577. };
  15578. Collection.prototype.item = function (key) {
  15579. return this._collection[key];
  15580. };
  15581. Collection.prototype.forEach = function (block) {
  15582. var key;
  15583. for (key in this._collection) {
  15584. if (this._collection.hasOwnProperty(key)) {
  15585. block(this._collection[key]);
  15586. }
  15587. }
  15588. };
  15589. return Collection;
  15590. })();
  15591. VirtualJoystick.Collection = Collection;
  15592. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15593. var VirtualJoystick = BABYLON.VirtualJoystick;
  15594. })(BABYLON || (BABYLON = {}));
  15595. var __extends = this.__extends || function (d, b) {
  15596. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15597. function __() { this.constructor = d; }
  15598. __.prototype = b.prototype;
  15599. d.prototype = new __();
  15600. };
  15601. var BABYLON;
  15602. (function (BABYLON) {
  15603. var OculusRiftDevKit2013_Metric = {
  15604. HResolution: 1280,
  15605. VResolution: 800,
  15606. HScreenSize: 0.149759993,
  15607. VScreenSize: 0.0935999975,
  15608. VScreenCenter: 0.0467999987,
  15609. EyeToScreenDistance: 0.0410000011,
  15610. LensSeparationDistance: 0.0635000020,
  15611. InterpupillaryDistance: 0.0640000030,
  15612. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15613. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15614. PostProcessScaleFactor: 1.714605507808412,
  15615. LensCenterOffset: 0.151976421
  15616. };
  15617. var _OculusInnerCamera = (function (_super) {
  15618. __extends(_OculusInnerCamera, _super);
  15619. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15620. _super.call(this, name, position, scene);
  15621. this._workMatrix = new BABYLON.Matrix();
  15622. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15623. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15624. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15625. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15626. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15627. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15628. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15629. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15630. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15631. }
  15632. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15633. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15634. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15635. return this._projectionMatrix;
  15636. };
  15637. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15638. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15639. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15640. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15641. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15642. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15643. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15644. return this._viewMatrix;
  15645. };
  15646. return _OculusInnerCamera;
  15647. })(BABYLON.FreeCamera);
  15648. var OculusCamera = (function (_super) {
  15649. __extends(OculusCamera, _super);
  15650. function OculusCamera(name, position, scene) {
  15651. _super.call(this, name, position, scene);
  15652. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15653. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15654. this.subCameras.push(this._leftCamera);
  15655. this.subCameras.push(this._rightCamera);
  15656. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15657. }
  15658. OculusCamera.prototype._update = function () {
  15659. this._leftCamera.position.copyFrom(this.position);
  15660. this._rightCamera.position.copyFrom(this.position);
  15661. this._updateCamera(this._leftCamera);
  15662. this._updateCamera(this._rightCamera);
  15663. _super.prototype._update.call(this);
  15664. };
  15665. OculusCamera.prototype._updateCamera = function (camera) {
  15666. camera.minZ = this.minZ;
  15667. camera.maxZ = this.maxZ;
  15668. camera.rotation.x = this.rotation.x;
  15669. camera.rotation.y = this.rotation.y;
  15670. camera.rotation.z = this.rotation.z;
  15671. };
  15672. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15673. var yaw = evt.alpha / 180 * Math.PI;
  15674. var pitch = evt.beta / 180 * Math.PI;
  15675. var roll = evt.gamma / 180 * Math.PI;
  15676. if (!this._offsetOrientation) {
  15677. this._offsetOrientation = {
  15678. yaw: yaw,
  15679. pitch: pitch,
  15680. roll: roll
  15681. };
  15682. return;
  15683. } else {
  15684. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15685. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15686. this.rotation.z += this._offsetOrientation.roll - roll;
  15687. this._offsetOrientation.yaw = yaw;
  15688. this._offsetOrientation.pitch = pitch;
  15689. this._offsetOrientation.roll = roll;
  15690. }
  15691. };
  15692. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15693. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15694. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15695. };
  15696. OculusCamera.prototype.detachControl = function (element) {
  15697. _super.prototype.detachControl.call(this, element);
  15698. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15699. };
  15700. return OculusCamera;
  15701. })(BABYLON.FreeCamera);
  15702. BABYLON.OculusCamera = OculusCamera;
  15703. })(BABYLON || (BABYLON = {}));
  15704. var __extends = this.__extends || function (d, b) {
  15705. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15706. function __() { this.constructor = d; }
  15707. __.prototype = b.prototype;
  15708. d.prototype = new __();
  15709. };
  15710. var BABYLON;
  15711. (function (BABYLON) {
  15712. var VirtualJoysticksCamera = (function (_super) {
  15713. __extends(VirtualJoysticksCamera, _super);
  15714. function VirtualJoysticksCamera(name, position, scene) {
  15715. _super.call(this, name, position, scene);
  15716. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15717. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15718. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15719. this._leftjoystick.setJoystickSensibility(0.15);
  15720. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15721. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15722. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15723. this._rightjoystick.reverseUpDown = true;
  15724. this._rightjoystick.setJoystickSensibility(0.05);
  15725. this._rightjoystick.setJoystickColor("yellow");
  15726. }
  15727. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15728. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15729. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15730. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15731. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15732. if (!this._leftjoystick.pressed) {
  15733. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15734. }
  15735. if (!this._rightjoystick.pressed) {
  15736. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15737. }
  15738. };
  15739. VirtualJoysticksCamera.prototype.dispose = function () {
  15740. this._leftjoystick.releaseCanvas();
  15741. _super.prototype.dispose.call(this);
  15742. };
  15743. return VirtualJoysticksCamera;
  15744. })(BABYLON.FreeCamera);
  15745. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15746. })(BABYLON || (BABYLON = {}));
  15747. var __extends = this.__extends || function (d, b) {
  15748. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15749. function __() { this.constructor = d; }
  15750. __.prototype = b.prototype;
  15751. d.prototype = new __();
  15752. };
  15753. var BABYLON;
  15754. (function (BABYLON) {
  15755. var ShaderMaterial = (function (_super) {
  15756. __extends(ShaderMaterial, _super);
  15757. function ShaderMaterial(name, scene, shaderPath, options) {
  15758. _super.call(this, name, scene);
  15759. this._textures = new Array();
  15760. this._floats = new Array();
  15761. this._floatsArrays = {};
  15762. this._colors3 = new Array();
  15763. this._colors4 = new Array();
  15764. this._vectors2 = new Array();
  15765. this._vectors3 = new Array();
  15766. this._matrices = new Array();
  15767. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15768. this._shaderPath = shaderPath;
  15769. options.needAlphaBlending = options.needAlphaBlending || false;
  15770. options.needAlphaTesting = options.needAlphaTesting || false;
  15771. options.attributes = options.attributes || ["position", "normal", "uv"];
  15772. options.uniforms = options.uniforms || ["worldViewProjection"];
  15773. options.samplers = options.samplers || [];
  15774. this._options = options;
  15775. }
  15776. ShaderMaterial.prototype.needAlphaBlending = function () {
  15777. return this._options.needAlphaBlending;
  15778. };
  15779. ShaderMaterial.prototype.needAlphaTesting = function () {
  15780. return this._options.needAlphaTesting;
  15781. };
  15782. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15783. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15784. this._options.uniforms.push(uniformName);
  15785. }
  15786. };
  15787. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15788. if (this._options.samplers.indexOf(name) === -1) {
  15789. this._options.samplers.push(name);
  15790. }
  15791. this._textures[name] = texture;
  15792. return this;
  15793. };
  15794. ShaderMaterial.prototype.setFloat = function (name, value) {
  15795. this._checkUniform(name);
  15796. this._floats[name] = value;
  15797. return this;
  15798. };
  15799. ShaderMaterial.prototype.setFloats = function (name, value) {
  15800. this._checkUniform(name);
  15801. this._floatsArrays[name] = value;
  15802. return this;
  15803. };
  15804. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15805. this._checkUniform(name);
  15806. this._colors3[name] = value;
  15807. return this;
  15808. };
  15809. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15810. this._checkUniform(name);
  15811. this._colors4[name] = value;
  15812. return this;
  15813. };
  15814. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15815. this._checkUniform(name);
  15816. this._vectors2[name] = value;
  15817. return this;
  15818. };
  15819. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15820. this._checkUniform(name);
  15821. this._vectors3[name] = value;
  15822. return this;
  15823. };
  15824. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15825. this._checkUniform(name);
  15826. this._matrices[name] = value;
  15827. return this;
  15828. };
  15829. ShaderMaterial.prototype.isReady = function () {
  15830. var engine = this.getScene().getEngine();
  15831. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15832. if (!this._effect.isReady()) {
  15833. return false;
  15834. }
  15835. return true;
  15836. };
  15837. ShaderMaterial.prototype.bind = function (world) {
  15838. if (this._options.uniforms.indexOf("world") !== -1) {
  15839. this._effect.setMatrix("world", world);
  15840. }
  15841. if (this._options.uniforms.indexOf("view") !== -1) {
  15842. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15843. }
  15844. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15845. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15846. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15847. }
  15848. if (this._options.uniforms.indexOf("projection") !== -1) {
  15849. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15850. }
  15851. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15852. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15853. }
  15854. for (var name in this._textures) {
  15855. this._effect.setTexture(name, this._textures[name]);
  15856. }
  15857. for (name in this._floats) {
  15858. this._effect.setFloat(name, this._floats[name]);
  15859. }
  15860. for (name in this._floatsArrays) {
  15861. this._effect.setArray(name, this._floatsArrays[name]);
  15862. }
  15863. for (name in this._colors3) {
  15864. this._effect.setColor3(name, this._colors3[name]);
  15865. }
  15866. for (name in this._colors4) {
  15867. var color = this._colors4[name];
  15868. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15869. }
  15870. for (name in this._vectors2) {
  15871. this._effect.setVector2(name, this._vectors2[name]);
  15872. }
  15873. for (name in this._vectors3) {
  15874. this._effect.setVector3(name, this._vectors3[name]);
  15875. }
  15876. for (name in this._matrices) {
  15877. this._effect.setMatrix(name, this._matrices[name]);
  15878. }
  15879. };
  15880. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15881. for (var name in this._textures) {
  15882. this._textures[name].dispose();
  15883. }
  15884. this._textures = [];
  15885. _super.prototype.dispose.call(this, forceDisposeEffect);
  15886. };
  15887. return ShaderMaterial;
  15888. })(BABYLON.Material);
  15889. BABYLON.ShaderMaterial = ShaderMaterial;
  15890. })(BABYLON || (BABYLON = {}));
  15891. var BABYLON;
  15892. (function (BABYLON) {
  15893. var VertexData = (function () {
  15894. function VertexData() {
  15895. }
  15896. VertexData.prototype.set = function (data, kind) {
  15897. switch (kind) {
  15898. case BABYLON.VertexBuffer.PositionKind:
  15899. this.positions = data;
  15900. break;
  15901. case BABYLON.VertexBuffer.NormalKind:
  15902. this.normals = data;
  15903. break;
  15904. case BABYLON.VertexBuffer.UVKind:
  15905. this.uvs = data;
  15906. break;
  15907. case BABYLON.VertexBuffer.UV2Kind:
  15908. this.uv2s = data;
  15909. break;
  15910. case BABYLON.VertexBuffer.ColorKind:
  15911. this.colors = data;
  15912. break;
  15913. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15914. this.matricesIndices = data;
  15915. break;
  15916. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15917. this.matricesWeights = data;
  15918. break;
  15919. }
  15920. };
  15921. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15922. this._applyTo(mesh, updatable);
  15923. };
  15924. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15925. this._applyTo(geometry, updatable);
  15926. };
  15927. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15928. this._update(mesh);
  15929. };
  15930. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15931. this._update(geometry);
  15932. };
  15933. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15934. if (this.positions) {
  15935. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15936. }
  15937. if (this.normals) {
  15938. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15939. }
  15940. if (this.uvs) {
  15941. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15942. }
  15943. if (this.uv2s) {
  15944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15945. }
  15946. if (this.colors) {
  15947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15948. }
  15949. if (this.matricesIndices) {
  15950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15951. }
  15952. if (this.matricesWeights) {
  15953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15954. }
  15955. if (this.indices) {
  15956. meshOrGeometry.setIndices(this.indices);
  15957. }
  15958. };
  15959. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15960. if (this.positions) {
  15961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15962. }
  15963. if (this.normals) {
  15964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15965. }
  15966. if (this.uvs) {
  15967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15968. }
  15969. if (this.uv2s) {
  15970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15971. }
  15972. if (this.colors) {
  15973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15974. }
  15975. if (this.matricesIndices) {
  15976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15977. }
  15978. if (this.matricesWeights) {
  15979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15980. }
  15981. if (this.indices) {
  15982. meshOrGeometry.setIndices(this.indices);
  15983. }
  15984. };
  15985. VertexData.prototype.transform = function (matrix) {
  15986. var transformed = BABYLON.Vector3.Zero();
  15987. if (this.positions) {
  15988. var position = BABYLON.Vector3.Zero();
  15989. for (var index = 0; index < this.positions.length; index += 3) {
  15990. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15991. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15992. this.positions[index] = transformed.x;
  15993. this.positions[index + 1] = transformed.y;
  15994. this.positions[index + 2] = transformed.z;
  15995. }
  15996. }
  15997. if (this.normals) {
  15998. var normal = BABYLON.Vector3.Zero();
  15999. for (index = 0; index < this.normals.length; index += 3) {
  16000. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16001. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16002. this.normals[index] = transformed.x;
  16003. this.normals[index + 1] = transformed.y;
  16004. this.normals[index + 2] = transformed.z;
  16005. }
  16006. }
  16007. };
  16008. VertexData.prototype.merge = function (other) {
  16009. if (other.indices) {
  16010. if (!this.indices) {
  16011. this.indices = [];
  16012. }
  16013. var offset = this.positions ? this.positions.length / 3 : 0;
  16014. for (var index = 0; index < other.indices.length; index++) {
  16015. this.indices.push(other.indices[index] + offset);
  16016. }
  16017. }
  16018. if (other.positions) {
  16019. if (!this.positions) {
  16020. this.positions = [];
  16021. }
  16022. for (index = 0; index < other.positions.length; index++) {
  16023. this.positions.push(other.positions[index]);
  16024. }
  16025. }
  16026. if (other.normals) {
  16027. if (!this.normals) {
  16028. this.normals = [];
  16029. }
  16030. for (index = 0; index < other.normals.length; index++) {
  16031. this.normals.push(other.normals[index]);
  16032. }
  16033. }
  16034. if (other.uvs) {
  16035. if (!this.uvs) {
  16036. this.uvs = [];
  16037. }
  16038. for (index = 0; index < other.uvs.length; index++) {
  16039. this.uvs.push(other.uvs[index]);
  16040. }
  16041. }
  16042. if (other.uv2s) {
  16043. if (!this.uv2s) {
  16044. this.uv2s = [];
  16045. }
  16046. for (index = 0; index < other.uv2s.length; index++) {
  16047. this.uv2s.push(other.uv2s[index]);
  16048. }
  16049. }
  16050. if (other.matricesIndices) {
  16051. if (!this.matricesIndices) {
  16052. this.matricesIndices = [];
  16053. }
  16054. for (index = 0; index < other.matricesIndices.length; index++) {
  16055. this.matricesIndices.push(other.matricesIndices[index]);
  16056. }
  16057. }
  16058. if (other.matricesWeights) {
  16059. if (!this.matricesWeights) {
  16060. this.matricesWeights = [];
  16061. }
  16062. for (index = 0; index < other.matricesWeights.length; index++) {
  16063. this.matricesWeights.push(other.matricesWeights[index]);
  16064. }
  16065. }
  16066. if (other.colors) {
  16067. if (!this.colors) {
  16068. this.colors = [];
  16069. }
  16070. for (index = 0; index < other.colors.length; index++) {
  16071. this.colors.push(other.colors[index]);
  16072. }
  16073. }
  16074. };
  16075. VertexData.ExtractFromMesh = function (mesh) {
  16076. return VertexData._ExtractFrom(mesh);
  16077. };
  16078. VertexData.ExtractFromGeometry = function (geometry) {
  16079. return VertexData._ExtractFrom(geometry);
  16080. };
  16081. VertexData._ExtractFrom = function (meshOrGeometry) {
  16082. var result = new BABYLON.VertexData();
  16083. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16084. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16085. }
  16086. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16087. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16088. }
  16089. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16090. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16091. }
  16092. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16093. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16094. }
  16095. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16096. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16097. }
  16098. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16099. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16100. }
  16101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16102. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16103. }
  16104. result.indices = meshOrGeometry.getIndices();
  16105. return result;
  16106. };
  16107. VertexData.CreateBox = function (size) {
  16108. var normalsSource = [
  16109. new BABYLON.Vector3(0, 0, 1),
  16110. new BABYLON.Vector3(0, 0, -1),
  16111. new BABYLON.Vector3(1, 0, 0),
  16112. new BABYLON.Vector3(-1, 0, 0),
  16113. new BABYLON.Vector3(0, 1, 0),
  16114. new BABYLON.Vector3(0, -1, 0)
  16115. ];
  16116. var indices = [];
  16117. var positions = [];
  16118. var normals = [];
  16119. var uvs = [];
  16120. size = size || 1;
  16121. for (var index = 0; index < normalsSource.length; index++) {
  16122. var normal = normalsSource[index];
  16123. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16124. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16125. var verticesLength = positions.length / 3;
  16126. indices.push(verticesLength);
  16127. indices.push(verticesLength + 1);
  16128. indices.push(verticesLength + 2);
  16129. indices.push(verticesLength);
  16130. indices.push(verticesLength + 2);
  16131. indices.push(verticesLength + 3);
  16132. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16133. positions.push(vertex.x, vertex.y, vertex.z);
  16134. normals.push(normal.x, normal.y, normal.z);
  16135. uvs.push(1.0, 1.0);
  16136. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16137. positions.push(vertex.x, vertex.y, vertex.z);
  16138. normals.push(normal.x, normal.y, normal.z);
  16139. uvs.push(0.0, 1.0);
  16140. vertex = normal.add(side1).add(side2).scale(size / 2);
  16141. positions.push(vertex.x, vertex.y, vertex.z);
  16142. normals.push(normal.x, normal.y, normal.z);
  16143. uvs.push(0.0, 0.0);
  16144. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16145. positions.push(vertex.x, vertex.y, vertex.z);
  16146. normals.push(normal.x, normal.y, normal.z);
  16147. uvs.push(1.0, 0.0);
  16148. }
  16149. var vertexData = new BABYLON.VertexData();
  16150. vertexData.indices = indices;
  16151. vertexData.positions = positions;
  16152. vertexData.normals = normals;
  16153. vertexData.uvs = uvs;
  16154. return vertexData;
  16155. };
  16156. VertexData.CreateSphere = function (segments, diameter) {
  16157. segments = segments || 32;
  16158. diameter = diameter || 1;
  16159. var radius = diameter / 2;
  16160. var totalZRotationSteps = 2 + segments;
  16161. var totalYRotationSteps = 2 * totalZRotationSteps;
  16162. var indices = [];
  16163. var positions = [];
  16164. var normals = [];
  16165. var uvs = [];
  16166. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16167. var normalizedZ = zRotationStep / totalZRotationSteps;
  16168. var angleZ = (normalizedZ * Math.PI);
  16169. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16170. var normalizedY = yRotationStep / totalYRotationSteps;
  16171. var angleY = normalizedY * Math.PI * 2;
  16172. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16173. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16174. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16175. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16176. var vertex = complete.scale(radius);
  16177. var normal = BABYLON.Vector3.Normalize(vertex);
  16178. positions.push(vertex.x, vertex.y, vertex.z);
  16179. normals.push(normal.x, normal.y, normal.z);
  16180. uvs.push(normalizedZ, normalizedY);
  16181. }
  16182. if (zRotationStep > 0) {
  16183. var verticesCount = positions.length / 3;
  16184. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16185. indices.push((firstIndex));
  16186. indices.push((firstIndex + 1));
  16187. indices.push(firstIndex + totalYRotationSteps + 1);
  16188. indices.push((firstIndex + totalYRotationSteps + 1));
  16189. indices.push((firstIndex + 1));
  16190. indices.push((firstIndex + totalYRotationSteps + 2));
  16191. }
  16192. }
  16193. }
  16194. var vertexData = new BABYLON.VertexData();
  16195. vertexData.indices = indices;
  16196. vertexData.positions = positions;
  16197. vertexData.normals = normals;
  16198. vertexData.uvs = uvs;
  16199. return vertexData;
  16200. };
  16201. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16202. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16203. var radiusTop = diameterTop / 2;
  16204. var radiusBottom = diameterBottom / 2;
  16205. var indices = [];
  16206. var positions = [];
  16207. var normals = [];
  16208. var uvs = [];
  16209. height = height || 1;
  16210. diameterTop = diameterTop || 0.5;
  16211. diameterBottom = diameterBottom || 1;
  16212. tessellation = tessellation || 16;
  16213. subdivisions = subdivisions || 1;
  16214. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16215. var getCircleVector = function (i) {
  16216. var angle = (i * 2.0 * Math.PI / tessellation);
  16217. var dx = Math.cos(angle);
  16218. var dz = Math.sin(angle);
  16219. return new BABYLON.Vector3(dx, 0, dz);
  16220. };
  16221. var createCylinderCap = function (isTop) {
  16222. var radius = isTop ? radiusTop : radiusBottom;
  16223. if (radius == 0) {
  16224. return;
  16225. }
  16226. var vbase = positions.length / 3;
  16227. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16228. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16229. if (!isTop) {
  16230. offset.scaleInPlace(-1);
  16231. textureScale.x = -textureScale.x;
  16232. }
  16233. for (i = 0; i < tessellation; i++) {
  16234. var circleVector = getCircleVector(i);
  16235. var position = circleVector.scale(radius).add(offset);
  16236. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16237. positions.push(position.x, position.y, position.z);
  16238. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16239. }
  16240. for (var i = 0; i < tessellation - 2; i++) {
  16241. if (!isTop) {
  16242. indices.push(vbase);
  16243. indices.push(vbase + (i + 2) % tessellation);
  16244. indices.push(vbase + (i + 1) % tessellation);
  16245. } else {
  16246. indices.push(vbase);
  16247. indices.push(vbase + (i + 1) % tessellation);
  16248. indices.push(vbase + (i + 2) % tessellation);
  16249. }
  16250. }
  16251. };
  16252. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16253. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16254. var stride = tessellation + 1;
  16255. for (var i = 0; i <= tessellation; i++) {
  16256. var circleVector = getCircleVector(i);
  16257. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16258. var position, radius = radiusBottom;
  16259. for (var s = 0; s <= subdivisions; s++) {
  16260. position = circleVector.scale(radius);
  16261. position.addInPlace(base.add(offset.scale(s)));
  16262. textureCoordinate.y += 1 / subdivisions;
  16263. radius += (radiusTop - radiusBottom) / subdivisions;
  16264. positions.push(position.x, position.y, position.z);
  16265. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16266. }
  16267. }
  16268. subdivisions += 1;
  16269. for (var s = 0; s < subdivisions - 1; s++) {
  16270. for (var i = 0; i <= tessellation; i++) {
  16271. indices.push(i * subdivisions + s);
  16272. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16273. indices.push(i * subdivisions + (s + 1));
  16274. indices.push(i * subdivisions + (s + 1));
  16275. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16276. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16277. }
  16278. }
  16279. createCylinderCap(true);
  16280. createCylinderCap(false);
  16281. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16282. var vertexData = new BABYLON.VertexData();
  16283. vertexData.indices = indices;
  16284. vertexData.positions = positions;
  16285. vertexData.normals = normals;
  16286. vertexData.uvs = uvs;
  16287. return vertexData;
  16288. };
  16289. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16290. var indices = [];
  16291. var positions = [];
  16292. var normals = [];
  16293. var uvs = [];
  16294. diameter = diameter || 1;
  16295. thickness = thickness || 0.5;
  16296. tessellation = tessellation || 16;
  16297. var stride = tessellation + 1;
  16298. for (var i = 0; i <= tessellation; i++) {
  16299. var u = i / tessellation;
  16300. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16301. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16302. for (var j = 0; j <= tessellation; j++) {
  16303. var v = 1 - j / tessellation;
  16304. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16305. var dx = Math.cos(innerAngle);
  16306. var dy = Math.sin(innerAngle);
  16307. var normal = new BABYLON.Vector3(dx, dy, 0);
  16308. var position = normal.scale(thickness / 2);
  16309. var textureCoordinate = new BABYLON.Vector2(u, v);
  16310. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16311. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16312. positions.push(position.x, position.y, position.z);
  16313. normals.push(normal.x, normal.y, normal.z);
  16314. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16315. var nextI = (i + 1) % stride;
  16316. var nextJ = (j + 1) % stride;
  16317. indices.push(i * stride + j);
  16318. indices.push(i * stride + nextJ);
  16319. indices.push(nextI * stride + j);
  16320. indices.push(i * stride + nextJ);
  16321. indices.push(nextI * stride + nextJ);
  16322. indices.push(nextI * stride + j);
  16323. }
  16324. }
  16325. var vertexData = new BABYLON.VertexData();
  16326. vertexData.indices = indices;
  16327. vertexData.positions = positions;
  16328. vertexData.normals = normals;
  16329. vertexData.uvs = uvs;
  16330. return vertexData;
  16331. };
  16332. VertexData.CreateLines = function (points) {
  16333. var indices = [];
  16334. var positions = [];
  16335. for (var index = 0; index < points.length; index++) {
  16336. positions.push(points[index].x, points[index].y, points[index].z);
  16337. if (index > 0) {
  16338. indices.push(index - 1);
  16339. indices.push(index);
  16340. }
  16341. }
  16342. var vertexData = new BABYLON.VertexData();
  16343. vertexData.indices = indices;
  16344. vertexData.positions = positions;
  16345. return vertexData;
  16346. };
  16347. VertexData.CreateGround = function (width, height, subdivisions) {
  16348. var indices = [];
  16349. var positions = [];
  16350. var normals = [];
  16351. var uvs = [];
  16352. var row, col;
  16353. width = width || 1;
  16354. height = height || 1;
  16355. subdivisions = subdivisions || 1;
  16356. for (row = 0; row <= subdivisions; row++) {
  16357. for (col = 0; col <= subdivisions; col++) {
  16358. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16359. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16360. positions.push(position.x, position.y, position.z);
  16361. normals.push(normal.x, normal.y, normal.z);
  16362. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16363. }
  16364. }
  16365. for (row = 0; row < subdivisions; row++) {
  16366. for (col = 0; col < subdivisions; col++) {
  16367. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16368. indices.push(col + 1 + row * (subdivisions + 1));
  16369. indices.push(col + row * (subdivisions + 1));
  16370. indices.push(col + (row + 1) * (subdivisions + 1));
  16371. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16372. indices.push(col + row * (subdivisions + 1));
  16373. }
  16374. }
  16375. var vertexData = new BABYLON.VertexData();
  16376. vertexData.indices = indices;
  16377. vertexData.positions = positions;
  16378. vertexData.normals = normals;
  16379. vertexData.uvs = uvs;
  16380. return vertexData;
  16381. };
  16382. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16383. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16384. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16385. var indices = [];
  16386. var positions = [];
  16387. var normals = [];
  16388. var uvs = [];
  16389. var row, col, tileRow, tileCol;
  16390. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16391. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16392. precision.w = (precision.w < 1) ? 1 : precision.w;
  16393. precision.h = (precision.h < 1) ? 1 : precision.h;
  16394. var tileSize = {
  16395. 'w': (xmax - xmin) / subdivisions.w,
  16396. 'h': (zmax - zmin) / subdivisions.h
  16397. };
  16398. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16399. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16400. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16401. }
  16402. }
  16403. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16404. var base = positions.length / 3;
  16405. var rowLength = precision.w + 1;
  16406. for (row = 0; row < precision.h; row++) {
  16407. for (col = 0; col < precision.w; col++) {
  16408. var square = [
  16409. base + col + row * rowLength,
  16410. base + (col + 1) + row * rowLength,
  16411. base + (col + 1) + (row + 1) * rowLength,
  16412. base + col + (row + 1) * rowLength
  16413. ];
  16414. indices.push(square[1]);
  16415. indices.push(square[2]);
  16416. indices.push(square[3]);
  16417. indices.push(square[0]);
  16418. indices.push(square[1]);
  16419. indices.push(square[3]);
  16420. }
  16421. }
  16422. var position = BABYLON.Vector3.Zero();
  16423. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16424. for (row = 0; row <= precision.h; row++) {
  16425. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16426. for (col = 0; col <= precision.w; col++) {
  16427. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16428. position.y = 0;
  16429. positions.push(position.x, position.y, position.z);
  16430. normals.push(normal.x, normal.y, normal.z);
  16431. uvs.push(col / precision.w, row / precision.h);
  16432. }
  16433. }
  16434. }
  16435. var vertexData = new BABYLON.VertexData();
  16436. vertexData.indices = indices;
  16437. vertexData.positions = positions;
  16438. vertexData.normals = normals;
  16439. vertexData.uvs = uvs;
  16440. return vertexData;
  16441. };
  16442. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16443. var indices = [];
  16444. var positions = [];
  16445. var normals = [];
  16446. var uvs = [];
  16447. var row, col;
  16448. for (row = 0; row <= subdivisions; row++) {
  16449. for (col = 0; col <= subdivisions; col++) {
  16450. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16451. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16452. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16453. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16454. var r = buffer[pos] / 255.0;
  16455. var g = buffer[pos + 1] / 255.0;
  16456. var b = buffer[pos + 2] / 255.0;
  16457. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16458. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16459. positions.push(position.x, position.y, position.z);
  16460. normals.push(0, 0, 0);
  16461. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16462. }
  16463. }
  16464. for (row = 0; row < subdivisions; row++) {
  16465. for (col = 0; col < subdivisions; col++) {
  16466. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16467. indices.push(col + 1 + row * (subdivisions + 1));
  16468. indices.push(col + row * (subdivisions + 1));
  16469. indices.push(col + (row + 1) * (subdivisions + 1));
  16470. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16471. indices.push(col + row * (subdivisions + 1));
  16472. }
  16473. }
  16474. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16475. var vertexData = new BABYLON.VertexData();
  16476. vertexData.indices = indices;
  16477. vertexData.positions = positions;
  16478. vertexData.normals = normals;
  16479. vertexData.uvs = uvs;
  16480. return vertexData;
  16481. };
  16482. VertexData.CreatePlane = function (size) {
  16483. var indices = [];
  16484. var positions = [];
  16485. var normals = [];
  16486. var uvs = [];
  16487. size = size || 1;
  16488. var halfSize = size / 2.0;
  16489. positions.push(-halfSize, -halfSize, 0);
  16490. normals.push(0, 0, -1.0);
  16491. uvs.push(0.0, 0.0);
  16492. positions.push(halfSize, -halfSize, 0);
  16493. normals.push(0, 0, -1.0);
  16494. uvs.push(1.0, 0.0);
  16495. positions.push(halfSize, halfSize, 0);
  16496. normals.push(0, 0, -1.0);
  16497. uvs.push(1.0, 1.0);
  16498. positions.push(-halfSize, halfSize, 0);
  16499. normals.push(0, 0, -1.0);
  16500. uvs.push(0.0, 1.0);
  16501. indices.push(0);
  16502. indices.push(1);
  16503. indices.push(2);
  16504. indices.push(0);
  16505. indices.push(2);
  16506. indices.push(3);
  16507. var vertexData = new BABYLON.VertexData();
  16508. vertexData.indices = indices;
  16509. vertexData.positions = positions;
  16510. vertexData.normals = normals;
  16511. vertexData.uvs = uvs;
  16512. return vertexData;
  16513. };
  16514. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16515. var indices = [];
  16516. var positions = [];
  16517. var normals = [];
  16518. var uvs = [];
  16519. radius = radius || 2;
  16520. tube = tube || 0.5;
  16521. radialSegments = radialSegments || 32;
  16522. tubularSegments = tubularSegments || 32;
  16523. p = p || 2;
  16524. q = q || 3;
  16525. var getPos = function (angle) {
  16526. var cu = Math.cos(angle);
  16527. var su = Math.sin(angle);
  16528. var quOverP = q / p * angle;
  16529. var cs = Math.cos(quOverP);
  16530. var tx = radius * (2 + cs) * 0.5 * cu;
  16531. var ty = radius * (2 + cs) * su * 0.5;
  16532. var tz = radius * Math.sin(quOverP) * 0.5;
  16533. return new BABYLON.Vector3(tx, ty, tz);
  16534. };
  16535. for (var i = 0; i <= radialSegments; i++) {
  16536. var modI = i % radialSegments;
  16537. var u = modI / radialSegments * 2 * p * Math.PI;
  16538. var p1 = getPos(u);
  16539. var p2 = getPos(u + 0.01);
  16540. var tang = p2.subtract(p1);
  16541. var n = p2.add(p1);
  16542. var bitan = BABYLON.Vector3.Cross(tang, n);
  16543. n = BABYLON.Vector3.Cross(bitan, tang);
  16544. bitan.normalize();
  16545. n.normalize();
  16546. for (var j = 0; j < tubularSegments; j++) {
  16547. var modJ = j % tubularSegments;
  16548. var v = modJ / tubularSegments * 2 * Math.PI;
  16549. var cx = -tube * Math.cos(v);
  16550. var cy = tube * Math.sin(v);
  16551. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16552. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16553. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16554. uvs.push(i / radialSegments);
  16555. uvs.push(j / tubularSegments);
  16556. }
  16557. }
  16558. for (i = 0; i < radialSegments; i++) {
  16559. for (j = 0; j < tubularSegments; j++) {
  16560. var jNext = (j + 1) % tubularSegments;
  16561. var a = i * tubularSegments + j;
  16562. var b = (i + 1) * tubularSegments + j;
  16563. var c = (i + 1) * tubularSegments + jNext;
  16564. var d = i * tubularSegments + jNext;
  16565. indices.push(d);
  16566. indices.push(b);
  16567. indices.push(a);
  16568. indices.push(d);
  16569. indices.push(c);
  16570. indices.push(b);
  16571. }
  16572. }
  16573. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16574. var vertexData = new BABYLON.VertexData();
  16575. vertexData.indices = indices;
  16576. vertexData.positions = positions;
  16577. vertexData.normals = normals;
  16578. vertexData.uvs = uvs;
  16579. return vertexData;
  16580. };
  16581. VertexData.ComputeNormals = function (positions, indices, normals) {
  16582. var positionVectors = [];
  16583. var facesOfVertices = [];
  16584. var index;
  16585. for (index = 0; index < positions.length; index += 3) {
  16586. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16587. positionVectors.push(vector3);
  16588. facesOfVertices.push([]);
  16589. }
  16590. var facesNormals = [];
  16591. for (index = 0; index < indices.length / 3; index++) {
  16592. var i1 = indices[index * 3];
  16593. var i2 = indices[index * 3 + 1];
  16594. var i3 = indices[index * 3 + 2];
  16595. var p1 = positionVectors[i1];
  16596. var p2 = positionVectors[i2];
  16597. var p3 = positionVectors[i3];
  16598. var p1p2 = p1.subtract(p2);
  16599. var p3p2 = p3.subtract(p2);
  16600. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16601. facesOfVertices[i1].push(index);
  16602. facesOfVertices[i2].push(index);
  16603. facesOfVertices[i3].push(index);
  16604. }
  16605. for (index = 0; index < positionVectors.length; index++) {
  16606. var faces = facesOfVertices[index];
  16607. var normal = BABYLON.Vector3.Zero();
  16608. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16609. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16610. }
  16611. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16612. normals[index * 3] = normal.x;
  16613. normals[index * 3 + 1] = normal.y;
  16614. normals[index * 3 + 2] = normal.z;
  16615. }
  16616. };
  16617. return VertexData;
  16618. })();
  16619. BABYLON.VertexData = VertexData;
  16620. })(BABYLON || (BABYLON = {}));
  16621. var __extends = this.__extends || function (d, b) {
  16622. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16623. function __() { this.constructor = d; }
  16624. __.prototype = b.prototype;
  16625. d.prototype = new __();
  16626. };
  16627. var BABYLON;
  16628. (function (BABYLON) {
  16629. var buildCamera = function (that, name) {
  16630. that._leftCamera.isIntermediate = true;
  16631. that.subCameras.push(that._leftCamera);
  16632. that.subCameras.push(that._rightCamera);
  16633. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16634. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16635. that._anaglyphPostProcess.onApply = function (effect) {
  16636. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16637. };
  16638. that._update();
  16639. };
  16640. var AnaglyphArcRotateCamera = (function (_super) {
  16641. __extends(AnaglyphArcRotateCamera, _super);
  16642. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16643. _super.call(this, name, alpha, beta, radius, target, scene);
  16644. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16645. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16646. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16647. buildCamera(this, name);
  16648. }
  16649. AnaglyphArcRotateCamera.prototype._update = function () {
  16650. this._updateCamera(this._leftCamera);
  16651. this._updateCamera(this._rightCamera);
  16652. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16653. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16654. _super.prototype._update.call(this);
  16655. };
  16656. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16657. camera.beta = this.beta;
  16658. camera.radius = this.radius;
  16659. camera.minZ = this.minZ;
  16660. camera.maxZ = this.maxZ;
  16661. camera.fov = this.fov;
  16662. camera.target = this.target;
  16663. };
  16664. return AnaglyphArcRotateCamera;
  16665. })(BABYLON.ArcRotateCamera);
  16666. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16667. var AnaglyphFreeCamera = (function (_super) {
  16668. __extends(AnaglyphFreeCamera, _super);
  16669. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16670. _super.call(this, name, position, scene);
  16671. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16672. this._transformMatrix = new BABYLON.Matrix();
  16673. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16674. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16675. buildCamera(this, name);
  16676. }
  16677. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16678. var target = this.getTarget();
  16679. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16680. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16681. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16682. };
  16683. AnaglyphFreeCamera.prototype._update = function () {
  16684. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16685. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16686. this._updateCamera(this._leftCamera);
  16687. this._updateCamera(this._rightCamera);
  16688. _super.prototype._update.call(this);
  16689. };
  16690. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16691. camera.minZ = this.minZ;
  16692. camera.maxZ = this.maxZ;
  16693. camera.fov = this.fov;
  16694. camera.viewport = this.viewport;
  16695. camera.setTarget(this.getTarget());
  16696. };
  16697. return AnaglyphFreeCamera;
  16698. })(BABYLON.FreeCamera);
  16699. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16700. })(BABYLON || (BABYLON = {}));
  16701. var __extends = this.__extends || function (d, b) {
  16702. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16703. function __() { this.constructor = d; }
  16704. __.prototype = b.prototype;
  16705. d.prototype = new __();
  16706. };
  16707. var BABYLON;
  16708. (function (BABYLON) {
  16709. var AnaglyphPostProcess = (function (_super) {
  16710. __extends(AnaglyphPostProcess, _super);
  16711. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16712. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16713. }
  16714. return AnaglyphPostProcess;
  16715. })(BABYLON.PostProcess);
  16716. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16717. })(BABYLON || (BABYLON = {}));
  16718. var BABYLON;
  16719. (function (BABYLON) {
  16720. var Tags = (function () {
  16721. function Tags() {
  16722. }
  16723. Tags.EnableFor = function (obj) {
  16724. obj._tags = obj._tags || {};
  16725. obj.hasTags = function () {
  16726. return Tags.HasTags(obj);
  16727. };
  16728. obj.addTags = function (tagsString) {
  16729. return Tags.AddTagsTo(obj, tagsString);
  16730. };
  16731. obj.removeTags = function (tagsString) {
  16732. return Tags.RemoveTagsFrom(obj, tagsString);
  16733. };
  16734. obj.matchesTagsQuery = function (tagsQuery) {
  16735. return Tags.MatchesQuery(obj, tagsQuery);
  16736. };
  16737. };
  16738. Tags.DisableFor = function (obj) {
  16739. delete obj._tags;
  16740. delete obj.hasTags;
  16741. delete obj.addTags;
  16742. delete obj.removeTags;
  16743. delete obj.matchesTagsQuery;
  16744. };
  16745. Tags.HasTags = function (obj) {
  16746. if (!obj._tags) {
  16747. return false;
  16748. }
  16749. return !BABYLON.Tools.IsEmpty(obj._tags);
  16750. };
  16751. Tags.GetTags = function (obj) {
  16752. if (!obj._tags) {
  16753. return null;
  16754. }
  16755. return obj._tags;
  16756. };
  16757. Tags.AddTagsTo = function (obj, tagsString) {
  16758. if (!tagsString) {
  16759. return;
  16760. }
  16761. var tags = tagsString.split(" ");
  16762. for (var t in tags) {
  16763. Tags._AddTagTo(obj, tags[t]);
  16764. }
  16765. };
  16766. Tags._AddTagTo = function (obj, tag) {
  16767. tag = tag.trim();
  16768. if (tag === "" || tag === "true" || tag === "false") {
  16769. return;
  16770. }
  16771. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16772. return;
  16773. }
  16774. Tags.EnableFor(obj);
  16775. obj._tags[tag] = true;
  16776. };
  16777. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16778. if (!Tags.HasTags(obj)) {
  16779. return;
  16780. }
  16781. var tags = tagsString.split(" ");
  16782. for (var t in tags) {
  16783. Tags._RemoveTagFrom(obj, tags[t]);
  16784. }
  16785. };
  16786. Tags._RemoveTagFrom = function (obj, tag) {
  16787. delete obj._tags[tag];
  16788. };
  16789. Tags.MatchesQuery = function (obj, tagsQuery) {
  16790. if (tagsQuery === undefined) {
  16791. return true;
  16792. }
  16793. if (tagsQuery === "") {
  16794. return Tags.HasTags(obj);
  16795. }
  16796. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16797. return Tags.HasTags(obj) && obj._tags[r];
  16798. });
  16799. };
  16800. return Tags;
  16801. })();
  16802. BABYLON.Tags = Tags;
  16803. })(BABYLON || (BABYLON = {}));
  16804. var BABYLON;
  16805. (function (BABYLON) {
  16806. (function (Internals) {
  16807. var AndOrNotEvaluator = (function () {
  16808. function AndOrNotEvaluator() {
  16809. }
  16810. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16811. if (!query.match(/\([^\(\)]*\)/g)) {
  16812. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16813. } else {
  16814. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16815. r = r.slice(1, r.length - 1);
  16816. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16817. });
  16818. }
  16819. if (query === "true") {
  16820. return true;
  16821. }
  16822. if (query === "false") {
  16823. return false;
  16824. }
  16825. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16826. };
  16827. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16828. evaluateCallback = evaluateCallback || (function (r) {
  16829. return r === "true" ? true : false;
  16830. });
  16831. var result;
  16832. var or = parenthesisContent.split("||");
  16833. for (var i in or) {
  16834. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16835. var and = ori.split("&&");
  16836. if (and.length > 1) {
  16837. for (var j = 0; j < and.length; ++j) {
  16838. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16839. if (andj !== "true" && andj !== "false") {
  16840. if (andj[0] === "!") {
  16841. result = !evaluateCallback(andj.substring(1));
  16842. } else {
  16843. result = evaluateCallback(andj);
  16844. }
  16845. } else {
  16846. result = andj === "true" ? true : false;
  16847. }
  16848. if (!result) {
  16849. ori = "false";
  16850. break;
  16851. }
  16852. }
  16853. }
  16854. if (result || ori === "true") {
  16855. result = true;
  16856. break;
  16857. }
  16858. if (ori !== "true" && ori !== "false") {
  16859. if (ori[0] === "!") {
  16860. result = !evaluateCallback(ori.substring(1));
  16861. } else {
  16862. result = evaluateCallback(ori);
  16863. }
  16864. } else {
  16865. result = ori === "true" ? true : false;
  16866. }
  16867. }
  16868. return result ? "true" : "false";
  16869. };
  16870. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16871. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16872. r = r.replace(/[\s]/g, function () {
  16873. return "";
  16874. });
  16875. return r.length % 2 ? "!" : "";
  16876. });
  16877. booleanString = booleanString.trim();
  16878. if (booleanString === "!true") {
  16879. booleanString = "false";
  16880. } else if (booleanString === "!false") {
  16881. booleanString = "true";
  16882. }
  16883. return booleanString;
  16884. };
  16885. return AndOrNotEvaluator;
  16886. })();
  16887. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16888. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16889. var Internals = BABYLON.Internals;
  16890. })(BABYLON || (BABYLON = {}));
  16891. var BABYLON;
  16892. (function (BABYLON) {
  16893. var PostProcessRenderPass = (function () {
  16894. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16895. this._enabled = true;
  16896. this._refCount = 0;
  16897. this._name = name;
  16898. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16899. this.setRenderList(renderList);
  16900. this._renderTexture.onBeforeRender = beforeRender;
  16901. this._renderTexture.onAfterRender = afterRender;
  16902. this._scene = scene;
  16903. }
  16904. PostProcessRenderPass.prototype._incRefCount = function () {
  16905. if (this._refCount === 0) {
  16906. this._scene.customRenderTargets.push(this._renderTexture);
  16907. }
  16908. return ++this._refCount;
  16909. };
  16910. PostProcessRenderPass.prototype._decRefCount = function () {
  16911. this._refCount--;
  16912. if (this._refCount <= 0) {
  16913. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16914. }
  16915. return this._refCount;
  16916. };
  16917. PostProcessRenderPass.prototype._update = function () {
  16918. this.setRenderList(this._renderList);
  16919. };
  16920. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16921. this._renderTexture.renderList = renderList;
  16922. };
  16923. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16924. return this._renderTexture;
  16925. };
  16926. return PostProcessRenderPass;
  16927. })();
  16928. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16929. })(BABYLON || (BABYLON = {}));
  16930. var BABYLON;
  16931. (function (BABYLON) {
  16932. var PostProcessRenderEffect = (function () {
  16933. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16934. this._engine = engine;
  16935. this._name = name;
  16936. this._postProcessType = postProcessType;
  16937. this._ratio = ratio || 1.0;
  16938. this._samplingMode = samplingMode || null;
  16939. this._singleInstance = singleInstance || true;
  16940. this._cameras = [];
  16941. this._postProcesses = [];
  16942. this._indicesForCamera = [];
  16943. this._renderPasses = [];
  16944. this._renderEffectAsPasses = [];
  16945. this.parameters = function (effect) {
  16946. };
  16947. }
  16948. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16949. var postProcess;
  16950. var instance;
  16951. var args = [];
  16952. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16953. for (var i = 0; i < parameters.length; i++) {
  16954. switch (parameters[i]) {
  16955. case "name":
  16956. args[i] = postProcessType.toString();
  16957. break;
  16958. case "ratio":
  16959. args[i] = ratio;
  16960. break;
  16961. case "camera":
  16962. args[i] = null;
  16963. break;
  16964. case "samplingMode":
  16965. args[i] = samplingMode;
  16966. break;
  16967. case "engine":
  16968. args[i] = engine;
  16969. break;
  16970. case "reusable":
  16971. args[i] = true;
  16972. break;
  16973. default:
  16974. args[i] = null;
  16975. break;
  16976. }
  16977. }
  16978. postProcess = function () {
  16979. };
  16980. postProcess.prototype = postProcessType.prototype;
  16981. instance = new postProcess();
  16982. postProcessType.apply(instance, args);
  16983. return instance;
  16984. };
  16985. PostProcessRenderEffect._GetParametersNames = function (func) {
  16986. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16987. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16988. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16989. if (parameters === null)
  16990. parameters = [];
  16991. return parameters;
  16992. };
  16993. PostProcessRenderEffect.prototype._update = function () {
  16994. for (var renderPassName in this._renderPasses) {
  16995. this._renderPasses[renderPassName]._update();
  16996. }
  16997. };
  16998. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16999. this._renderPasses[renderPass._name] = renderPass;
  17000. this._linkParameters();
  17001. };
  17002. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17003. delete this._renderPasses[renderPass._name];
  17004. this._linkParameters();
  17005. };
  17006. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17007. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17008. this._linkParameters();
  17009. };
  17010. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17011. for (var renderPassName in this._renderPasses) {
  17012. if (renderPassName === passName) {
  17013. return this._renderPasses[passName];
  17014. }
  17015. }
  17016. };
  17017. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17018. this._renderPasses.length = 0;
  17019. this._linkParameters();
  17020. };
  17021. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17022. var cameraKey;
  17023. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17024. for (var i = 0; i < _cam.length; i++) {
  17025. var camera = _cam[i];
  17026. var cameraName = camera.name;
  17027. if (this._singleInstance) {
  17028. cameraKey = 0;
  17029. } else {
  17030. cameraKey = cameraName;
  17031. }
  17032. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  17033. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17034. if (this._indicesForCamera[cameraName] === null) {
  17035. this._indicesForCamera[cameraName] = [];
  17036. }
  17037. this._indicesForCamera[cameraName].push(index);
  17038. if (this._cameras.indexOf(camera) === -1) {
  17039. this._cameras[cameraName] = camera;
  17040. }
  17041. for (var passName in this._renderPasses) {
  17042. this._renderPasses[passName]._incRefCount();
  17043. }
  17044. }
  17045. this._linkParameters();
  17046. };
  17047. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17048. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17049. for (var i = 0; i < _cam.length; i++) {
  17050. var camera = _cam[i];
  17051. var cameraName = camera.name;
  17052. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17053. var index = this._cameras.indexOf(cameraName);
  17054. this._indicesForCamera.splice(index, 1);
  17055. this._cameras.splice(index, 1);
  17056. for (var passName in this._renderPasses) {
  17057. this._renderPasses[passName]._decRefCount();
  17058. }
  17059. }
  17060. };
  17061. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17062. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17063. for (var i = 0; i < _cam.length; i++) {
  17064. var camera = _cam[i];
  17065. var cameraName = camera.name;
  17066. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17067. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17068. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17069. }
  17070. }
  17071. for (var passName in this._renderPasses) {
  17072. this._renderPasses[passName]._incRefCount();
  17073. }
  17074. }
  17075. };
  17076. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17077. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17078. for (var i = 0; i < _cam.length; i++) {
  17079. var camera = _cam[i];
  17080. var cameraName = camera.Name;
  17081. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17082. for (var passName in this._renderPasses) {
  17083. this._renderPasses[passName]._decRefCount();
  17084. }
  17085. }
  17086. };
  17087. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17088. if (this._singleInstance) {
  17089. return this._postProcesses[0];
  17090. } else {
  17091. return this._postProcesses[camera.name];
  17092. }
  17093. };
  17094. PostProcessRenderEffect.prototype._linkParameters = function () {
  17095. var _this = this;
  17096. for (var index in this._postProcesses) {
  17097. this._postProcesses[index].onApply = function (effect) {
  17098. _this.parameters(effect);
  17099. _this._linkTextures(effect);
  17100. };
  17101. }
  17102. };
  17103. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17104. for (var renderPassName in this._renderPasses) {
  17105. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17106. }
  17107. for (var renderEffectName in this._renderEffectAsPasses) {
  17108. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17109. }
  17110. };
  17111. return PostProcessRenderEffect;
  17112. })();
  17113. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17114. })(BABYLON || (BABYLON = {}));
  17115. var BABYLON;
  17116. (function (BABYLON) {
  17117. var PostProcessRenderPipeline = (function () {
  17118. function PostProcessRenderPipeline(engine, name) {
  17119. this._engine = engine;
  17120. this._name = name;
  17121. this._renderEffects = [];
  17122. this._renderEffectsForIsolatedPass = [];
  17123. this._cameras = [];
  17124. }
  17125. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17126. this._renderEffects[renderEffect._name] = renderEffect;
  17127. };
  17128. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17129. var renderEffects = this._renderEffects[renderEffectName];
  17130. if (!renderEffects) {
  17131. return;
  17132. }
  17133. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17134. };
  17135. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17136. var renderEffects = this._renderEffects[renderEffectName];
  17137. if (!renderEffects) {
  17138. return;
  17139. }
  17140. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17141. };
  17142. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17143. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17144. var indicesToDelete = [];
  17145. for (var i = 0; i < _cam.length; i++) {
  17146. var camera = _cam[i];
  17147. var cameraName = camera.name;
  17148. if (this._cameras.indexOf(camera) === -1) {
  17149. this._cameras[cameraName] = camera;
  17150. } else if (unique) {
  17151. indicesToDelete.push(i);
  17152. }
  17153. }
  17154. for (var i = 0; i < indicesToDelete.length; i++) {
  17155. cameras.splice(indicesToDelete[i], 1);
  17156. }
  17157. for (var renderEffectName in this._renderEffects) {
  17158. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17159. }
  17160. };
  17161. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17162. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17163. for (var renderEffectName in this._renderEffects) {
  17164. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17165. }
  17166. for (var i = 0; i < _cam.length; i++) {
  17167. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17168. }
  17169. };
  17170. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17171. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17172. var pass = null;
  17173. for (var renderEffectName in this._renderEffects) {
  17174. pass = this._renderEffects[renderEffectName].getPass(passName);
  17175. if (pass != null) {
  17176. break;
  17177. }
  17178. }
  17179. if (pass === null) {
  17180. return;
  17181. }
  17182. for (var renderEffectName in this._renderEffects) {
  17183. this._renderEffects[renderEffectName]._disable(_cam);
  17184. }
  17185. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17186. for (var i = 0; i < _cam.length; i++) {
  17187. var camera = _cam[i];
  17188. var cameraName = camera.name;
  17189. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17190. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17191. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17192. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17193. }
  17194. };
  17195. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17196. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17197. for (var i = 0; i < _cam.length; i++) {
  17198. var camera = _cam[i];
  17199. var cameraName = camera.name;
  17200. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17201. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17202. }
  17203. for (var renderEffectName in this._renderEffects) {
  17204. this._renderEffects[renderEffectName]._enable(_cam);
  17205. }
  17206. };
  17207. PostProcessRenderPipeline.prototype._update = function () {
  17208. for (var renderEffectName in this._renderEffects) {
  17209. this._renderEffects[renderEffectName]._update();
  17210. }
  17211. for (var i = 0; i < this._cameras.length; i++) {
  17212. var cameraName = this._cameras[i].name;
  17213. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17214. this._renderEffectsForIsolatedPass[cameraName]._update();
  17215. }
  17216. }
  17217. };
  17218. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17219. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17220. return PostProcessRenderPipeline;
  17221. })();
  17222. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17223. })(BABYLON || (BABYLON = {}));
  17224. var BABYLON;
  17225. (function (BABYLON) {
  17226. var PostProcessRenderPipelineManager = (function () {
  17227. function PostProcessRenderPipelineManager() {
  17228. this._renderPipelines = [];
  17229. }
  17230. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17231. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17232. };
  17233. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17234. var renderPipeline = this._renderPipelines[renderPipelineName];
  17235. if (!renderPipeline) {
  17236. return;
  17237. }
  17238. renderPipeline.attachCameras(cameras, unique);
  17239. };
  17240. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17241. var renderPipeline = this._renderPipelines[renderPipelineName];
  17242. if (!renderPipeline) {
  17243. return;
  17244. }
  17245. renderPipeline.detachCameras(cameras);
  17246. };
  17247. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17248. var renderPipeline = this._renderPipelines[renderPipelineName];
  17249. if (!renderPipeline) {
  17250. return;
  17251. }
  17252. renderPipeline.enableEffect(renderEffectName, cameras);
  17253. };
  17254. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17255. var renderPipeline = this._renderPipelines[renderPipelineName];
  17256. if (!renderPipeline) {
  17257. return;
  17258. }
  17259. renderPipeline.disableEffect(renderEffectName, cameras);
  17260. };
  17261. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17262. var renderPipeline = this._renderPipelines[renderPipelineName];
  17263. if (!renderPipeline) {
  17264. return;
  17265. }
  17266. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17267. };
  17268. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17269. var renderPipeline = this._renderPipelines[renderPipelineName];
  17270. if (!renderPipeline) {
  17271. return;
  17272. }
  17273. renderPipeline.disableDisplayOnlyPass(cameras);
  17274. };
  17275. PostProcessRenderPipelineManager.prototype.update = function () {
  17276. for (var renderPipelineName in this._renderPipelines) {
  17277. this._renderPipelines[renderPipelineName]._update();
  17278. }
  17279. };
  17280. return PostProcessRenderPipelineManager;
  17281. })();
  17282. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17283. })(BABYLON || (BABYLON = {}));
  17284. var __extends = this.__extends || function (d, b) {
  17285. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17286. function __() { this.constructor = d; }
  17287. __.prototype = b.prototype;
  17288. d.prototype = new __();
  17289. };
  17290. var BABYLON;
  17291. (function (BABYLON) {
  17292. var DisplayPassPostProcess = (function (_super) {
  17293. __extends(DisplayPassPostProcess, _super);
  17294. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17295. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17296. }
  17297. return DisplayPassPostProcess;
  17298. })(BABYLON.PostProcess);
  17299. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17300. })(BABYLON || (BABYLON = {}));
  17301. var BABYLON;
  17302. (function (BABYLON) {
  17303. var BoundingBoxRenderer = (function () {
  17304. function BoundingBoxRenderer(scene) {
  17305. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17306. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17307. this.showBackLines = true;
  17308. this.renderList = new BABYLON.SmartArray(32);
  17309. this._scene = scene;
  17310. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17311. attributes: ["position"],
  17312. uniforms: ["worldViewProjection", "color"]
  17313. });
  17314. var engine = this._scene.getEngine();
  17315. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17316. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17317. this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  17318. }
  17319. BoundingBoxRenderer.prototype.reset = function () {
  17320. this.renderList.reset();
  17321. };
  17322. BoundingBoxRenderer.prototype.render = function () {
  17323. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17324. return;
  17325. }
  17326. var engine = this._scene.getEngine();
  17327. engine.setDepthWrite(false);
  17328. this._colorShader._preBind();
  17329. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17330. var boundingBox = this.renderList.data[boundingBoxIndex];
  17331. var min = boundingBox.minimum;
  17332. var max = boundingBox.maximum;
  17333. var diff = max.subtract(min);
  17334. var median = min.add(diff.scale(0.5));
  17335. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17336. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17337. if (this.showBackLines) {
  17338. engine.setDepthFunctionToGreaterOrEqual();
  17339. this._colorShader.setColor4("color", this.backColor.toColor4());
  17340. this._colorShader.bind(worldMatrix);
  17341. engine.draw(false, 0, 24);
  17342. }
  17343. engine.setDepthFunctionToLess();
  17344. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17345. this._colorShader.bind(worldMatrix);
  17346. engine.draw(false, 0, 24);
  17347. }
  17348. this._colorShader.unbind();
  17349. engine.setDepthFunctionToLessOrEqual();
  17350. engine.setDepthWrite(true);
  17351. };
  17352. BoundingBoxRenderer.prototype.dispose = function () {
  17353. this._colorShader.dispose();
  17354. this._vb.dispose();
  17355. this._scene.getEngine()._releaseBuffer(this._ib);
  17356. };
  17357. return BoundingBoxRenderer;
  17358. })();
  17359. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17360. })(BABYLON || (BABYLON = {}));
  17361. /**
  17362. * Based on jsTGALoader - Javascript loader for TGA file
  17363. * By Vincent Thibault
  17364. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17365. */
  17366. var BABYLON;
  17367. (function (BABYLON) {
  17368. (function (Internals) {
  17369. var TGATools = (function () {
  17370. function TGATools() {
  17371. }
  17372. TGATools.GetTGAHeader = function (data) {
  17373. var offset = 0;
  17374. var header = {
  17375. id_length: data[offset++],
  17376. colormap_type: data[offset++],
  17377. image_type: data[offset++],
  17378. colormap_index: data[offset++] | data[offset++] << 8,
  17379. colormap_length: data[offset++] | data[offset++] << 8,
  17380. colormap_size: data[offset++],
  17381. origin: [
  17382. data[offset++] | data[offset++] << 8,
  17383. data[offset++] | data[offset++] << 8
  17384. ],
  17385. width: data[offset++] | data[offset++] << 8,
  17386. height: data[offset++] | data[offset++] << 8,
  17387. pixel_size: data[offset++],
  17388. flags: data[offset++]
  17389. };
  17390. return header;
  17391. };
  17392. TGATools.UploadContent = function (gl, data) {
  17393. if (data.length < 19) {
  17394. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17395. return;
  17396. }
  17397. var offset = 18;
  17398. var header = TGATools.GetTGAHeader(data);
  17399. if (header.id_length + offset > data.length) {
  17400. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17401. return;
  17402. }
  17403. offset += header.id_length;
  17404. var use_rle = false;
  17405. var use_pal = false;
  17406. var use_rgb = false;
  17407. var use_grey = false;
  17408. switch (header.image_type) {
  17409. case TGATools._TYPE_RLE_INDEXED:
  17410. use_rle = true;
  17411. case TGATools._TYPE_INDEXED:
  17412. use_pal = true;
  17413. break;
  17414. case TGATools._TYPE_RLE_RGB:
  17415. use_rle = true;
  17416. case TGATools._TYPE_RGB:
  17417. use_rgb = true;
  17418. break;
  17419. case TGATools._TYPE_RLE_GREY:
  17420. use_rle = true;
  17421. case TGATools._TYPE_GREY:
  17422. use_grey = true;
  17423. break;
  17424. }
  17425. var pixel_data;
  17426. var numAlphaBits = header.flags & 0xf;
  17427. var pixel_size = header.pixel_size >> 3;
  17428. var pixel_total = header.width * header.height * pixel_size;
  17429. var palettes;
  17430. if (use_pal) {
  17431. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17432. }
  17433. if (use_rle) {
  17434. pixel_data = new Uint8Array(pixel_total);
  17435. var c, count, i;
  17436. var localOffset = 0;
  17437. var pixels = new Uint8Array(pixel_size);
  17438. while (offset < pixel_total && localOffset < pixel_total) {
  17439. c = data[offset++];
  17440. count = (c & 0x7f) + 1;
  17441. if (c & 0x80) {
  17442. for (i = 0; i < pixel_size; ++i) {
  17443. pixels[i] = data[offset++];
  17444. }
  17445. for (i = 0; i < count; ++i) {
  17446. pixel_data.set(pixels, localOffset + i * pixel_size);
  17447. }
  17448. localOffset += pixel_size * count;
  17449. } else {
  17450. count *= pixel_size;
  17451. for (i = 0; i < count; ++i) {
  17452. pixel_data[localOffset + i] = data[offset++];
  17453. }
  17454. localOffset += count;
  17455. }
  17456. }
  17457. } else {
  17458. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17459. }
  17460. var x_start, y_start, x_step, y_step, y_end, x_end;
  17461. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17462. default:
  17463. case TGATools._ORIGIN_UL:
  17464. x_start = 0;
  17465. x_step = 1;
  17466. x_end = header.width;
  17467. y_start = 0;
  17468. y_step = 1;
  17469. y_end = header.height;
  17470. break;
  17471. case TGATools._ORIGIN_BL:
  17472. x_start = 0;
  17473. x_step = 1;
  17474. x_end = header.width;
  17475. y_start = header.height - 1;
  17476. y_step = -1;
  17477. y_end = -1;
  17478. break;
  17479. case TGATools._ORIGIN_UR:
  17480. x_start = header.width - 1;
  17481. x_step = -1;
  17482. x_end = -1;
  17483. y_start = 0;
  17484. y_step = 1;
  17485. y_end = header.height;
  17486. break;
  17487. case TGATools._ORIGIN_BR:
  17488. x_start = header.width - 1;
  17489. x_step = -1;
  17490. x_end = -1;
  17491. y_start = header.height - 1;
  17492. y_step = -1;
  17493. y_end = -1;
  17494. break;
  17495. }
  17496. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17497. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17498. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17499. };
  17500. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17501. var image = pixel_data, colormap = palettes;
  17502. var width = header.width, height = header.height;
  17503. var color, i = 0, x, y;
  17504. var imageData = new Uint8Array(width * height * 4);
  17505. for (y = y_start; y !== y_end; y += y_step) {
  17506. for (x = x_start; x !== x_end; x += x_step, i++) {
  17507. color = image[i];
  17508. imageData[(x + width * y) * 4 + 3] = 255;
  17509. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17510. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17511. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17512. }
  17513. }
  17514. return imageData;
  17515. };
  17516. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17517. var image = pixel_data;
  17518. var width = header.width, height = header.height;
  17519. var color, i = 0, x, y;
  17520. var imageData = new Uint8Array(width * height * 4);
  17521. for (y = y_start; y !== y_end; y += y_step) {
  17522. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17523. color = image[i + 0] + (image[i + 1] << 8);
  17524. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17525. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17526. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17527. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17528. }
  17529. }
  17530. return imageData;
  17531. };
  17532. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17533. var image = pixel_data;
  17534. var width = header.width, height = header.height;
  17535. var i = 0, x, y;
  17536. var imageData = new Uint8Array(width * height * 4);
  17537. for (y = y_start; y !== y_end; y += y_step) {
  17538. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17539. imageData[(x + width * y) * 4 + 3] = 255;
  17540. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17541. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17542. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17543. }
  17544. }
  17545. return imageData;
  17546. };
  17547. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17548. var image = pixel_data;
  17549. var width = header.width, height = header.height;
  17550. var i = 0, x, y;
  17551. var imageData = new Uint8Array(width * height * 4);
  17552. for (y = y_start; y !== y_end; y += y_step) {
  17553. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17554. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17555. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17556. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17557. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17558. }
  17559. }
  17560. return imageData;
  17561. };
  17562. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17563. var image = pixel_data;
  17564. var width = header.width, height = header.height;
  17565. var color, i = 0, x, y;
  17566. var imageData = new Uint8Array(width * height * 4);
  17567. for (y = y_start; y !== y_end; y += y_step) {
  17568. for (x = x_start; x !== x_end; x += x_step, i++) {
  17569. color = image[i];
  17570. imageData[(x + width * y) * 4 + 0] = color;
  17571. imageData[(x + width * y) * 4 + 1] = color;
  17572. imageData[(x + width * y) * 4 + 2] = color;
  17573. imageData[(x + width * y) * 4 + 3] = 255;
  17574. }
  17575. }
  17576. return imageData;
  17577. };
  17578. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17579. var image = pixel_data;
  17580. var width = header.width, height = header.height;
  17581. var i = 0, x, y;
  17582. var imageData = new Uint8Array(width * height * 4);
  17583. for (y = y_start; y !== y_end; y += y_step) {
  17584. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17585. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17586. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17587. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17588. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17589. }
  17590. }
  17591. return imageData;
  17592. };
  17593. TGATools._TYPE_NO_DATA = 0;
  17594. TGATools._TYPE_INDEXED = 1;
  17595. TGATools._TYPE_RGB = 2;
  17596. TGATools._TYPE_GREY = 3;
  17597. TGATools._TYPE_RLE_INDEXED = 9;
  17598. TGATools._TYPE_RLE_RGB = 10;
  17599. TGATools._TYPE_RLE_GREY = 11;
  17600. TGATools._ORIGIN_MASK = 0x30;
  17601. TGATools._ORIGIN_SHIFT = 0x04;
  17602. TGATools._ORIGIN_BL = 0x00;
  17603. TGATools._ORIGIN_BR = 0x01;
  17604. TGATools._ORIGIN_UL = 0x02;
  17605. TGATools._ORIGIN_UR = 0x03;
  17606. return TGATools;
  17607. })();
  17608. Internals.TGATools = TGATools;
  17609. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17610. var Internals = BABYLON.Internals;
  17611. })(BABYLON || (BABYLON = {}));
  17612. var BABYLON;
  17613. (function (BABYLON) {
  17614. (function (Internals) {
  17615. var DDS_MAGIC = 0x20534444;
  17616. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  17617. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17618. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  17619. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17620. function FourCCToInt32(value) {
  17621. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17622. }
  17623. function Int32ToFourCC(value) {
  17624. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17625. }
  17626. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17627. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17628. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17629. var headerLengthInt = 31;
  17630. var off_magic = 0;
  17631. var off_size = 1;
  17632. var off_flags = 2;
  17633. var off_height = 3;
  17634. var off_width = 4;
  17635. var off_mipmapCount = 7;
  17636. var off_pfFlags = 20;
  17637. var off_pfFourCC = 21;
  17638. var off_RGBbpp = 22;
  17639. var off_RMask = 23;
  17640. var off_GMask = 24;
  17641. var off_BMask = 25;
  17642. var off_AMask = 26;
  17643. var off_caps1 = 27;
  17644. var off_caps2 = 28;
  17645. ;
  17646. var DDSTools = (function () {
  17647. function DDSTools() {
  17648. }
  17649. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17650. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17651. var mipmapCount = 1;
  17652. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17653. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17654. }
  17655. return {
  17656. width: header[off_width],
  17657. height: header[off_height],
  17658. mipmapCount: mipmapCount,
  17659. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17660. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17661. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17662. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17663. };
  17664. };
  17665. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17666. var byteArray = new Uint8Array(dataLength);
  17667. var srcData = new Uint8Array(arrayBuffer);
  17668. var index = 0;
  17669. for (var y = height - 1; y >= 0; y--) {
  17670. for (var x = 0; x < width; x++) {
  17671. var srcPos = dataOffset + (x + y * width) * 4;
  17672. byteArray[index + 2] = srcData[srcPos];
  17673. byteArray[index + 1] = srcData[srcPos + 1];
  17674. byteArray[index] = srcData[srcPos + 2];
  17675. byteArray[index + 3] = srcData[srcPos + 3];
  17676. index += 4;
  17677. }
  17678. }
  17679. return byteArray;
  17680. };
  17681. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17682. var byteArray = new Uint8Array(dataLength);
  17683. var srcData = new Uint8Array(arrayBuffer);
  17684. var index = 0;
  17685. for (var y = height - 1; y >= 0; y--) {
  17686. for (var x = 0; x < width; x++) {
  17687. var srcPos = dataOffset + (x + y * width) * 3;
  17688. byteArray[index + 2] = srcData[srcPos];
  17689. byteArray[index + 1] = srcData[srcPos + 1];
  17690. byteArray[index] = srcData[srcPos + 2];
  17691. index += 3;
  17692. }
  17693. }
  17694. return byteArray;
  17695. };
  17696. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17697. var byteArray = new Uint8Array(dataLength);
  17698. var srcData = new Uint8Array(arrayBuffer);
  17699. var index = 0;
  17700. for (var y = height - 1; y >= 0; y--) {
  17701. for (var x = 0; x < width; x++) {
  17702. var srcPos = dataOffset + (x + y * width);
  17703. byteArray[index] = srcData[srcPos];
  17704. index++;
  17705. }
  17706. }
  17707. return byteArray;
  17708. };
  17709. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17710. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17711. if (header[off_magic] != DDS_MAGIC) {
  17712. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17713. return;
  17714. }
  17715. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17716. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17717. return;
  17718. }
  17719. if (info.isFourCC) {
  17720. fourCC = header[off_pfFourCC];
  17721. switch (fourCC) {
  17722. case FOURCC_DXT1:
  17723. blockBytes = 8;
  17724. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17725. break;
  17726. case FOURCC_DXT3:
  17727. blockBytes = 16;
  17728. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17729. break;
  17730. case FOURCC_DXT5:
  17731. blockBytes = 16;
  17732. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17733. break;
  17734. default:
  17735. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17736. return;
  17737. }
  17738. }
  17739. mipmapCount = 1;
  17740. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17741. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17742. }
  17743. var bpp = header[off_RGBbpp];
  17744. for (var face = 0; face < faces; face++) {
  17745. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17746. width = header[off_width];
  17747. height = header[off_height];
  17748. dataOffset = header[off_size] + 4;
  17749. for (i = 0; i < mipmapCount; ++i) {
  17750. if (info.isRGB) {
  17751. if (bpp == 24) {
  17752. dataLength = width * height * 3;
  17753. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17754. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17755. } else {
  17756. dataLength = width * height * 4;
  17757. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17758. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17759. }
  17760. } else if (info.isLuminance) {
  17761. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17762. var unpaddedRowSize = width;
  17763. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17764. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17765. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17766. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17767. } else {
  17768. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17769. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17770. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17771. }
  17772. dataOffset += dataLength;
  17773. width *= 0.5;
  17774. height *= 0.5;
  17775. width = Math.max(1.0, width);
  17776. height = Math.max(1.0, height);
  17777. }
  17778. }
  17779. };
  17780. return DDSTools;
  17781. })();
  17782. Internals.DDSTools = DDSTools;
  17783. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17784. var Internals = BABYLON.Internals;
  17785. })(BABYLON || (BABYLON = {}));
  17786. var BABYLON;
  17787. (function (BABYLON) {
  17788. var SmartArray = (function () {
  17789. function SmartArray(capacity) {
  17790. this.length = 0;
  17791. this._duplicateId = 0;
  17792. this.data = new Array(capacity);
  17793. this._id = SmartArray._GlobalId++;
  17794. }
  17795. SmartArray.prototype.push = function (value) {
  17796. this.data[this.length++] = value;
  17797. if (this.length > this.data.length) {
  17798. this.data.length *= 2;
  17799. }
  17800. if (!value.__smartArrayFlags) {
  17801. value.__smartArrayFlags = {};
  17802. }
  17803. value.__smartArrayFlags[this._id] = this._duplicateId;
  17804. };
  17805. SmartArray.prototype.pushNoDuplicate = function (value) {
  17806. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17807. return;
  17808. }
  17809. this.push(value);
  17810. };
  17811. SmartArray.prototype.sort = function (compareFn) {
  17812. this.data.sort(compareFn);
  17813. };
  17814. SmartArray.prototype.reset = function () {
  17815. this.length = 0;
  17816. this._duplicateId++;
  17817. };
  17818. SmartArray.prototype.concat = function (array) {
  17819. if (array.length === 0) {
  17820. return;
  17821. }
  17822. if (this.length + array.length > this.data.length) {
  17823. this.data.length = (this.length + array.length) * 2;
  17824. }
  17825. for (var index = 0; index < array.length; index++) {
  17826. this.data[this.length++] = (array.data || array)[index];
  17827. }
  17828. };
  17829. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17830. if (array.length === 0) {
  17831. return;
  17832. }
  17833. if (this.length + array.length > this.data.length) {
  17834. this.data.length = (this.length + array.length) * 2;
  17835. }
  17836. for (var index = 0; index < array.length; index++) {
  17837. var item = (array.data || array)[index];
  17838. this.pushNoDuplicate(item);
  17839. }
  17840. };
  17841. SmartArray.prototype.indexOf = function (value) {
  17842. var position = this.data.indexOf(value);
  17843. if (position >= this.length) {
  17844. return -1;
  17845. }
  17846. return position;
  17847. };
  17848. SmartArray._GlobalId = 0;
  17849. return SmartArray;
  17850. })();
  17851. BABYLON.SmartArray = SmartArray;
  17852. })(BABYLON || (BABYLON = {}));
  17853. var BABYLON;
  17854. (function (BABYLON) {
  17855. var CannonJSPlugin = (function () {
  17856. function CannonJSPlugin() {
  17857. this._registeredMeshes = [];
  17858. this._physicsMaterials = [];
  17859. this.updateBodyPosition = function (mesh) {
  17860. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17861. var registeredMesh = this._registeredMeshes[index];
  17862. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17863. var body = registeredMesh.body.body;
  17864. var center = mesh.getBoundingInfo().boundingBox.center;
  17865. body.position.set(center.x, center.z, center.y);
  17866. body.quaternion.x = mesh.rotationQuaternion.x;
  17867. body.quaternion.z = mesh.rotationQuaternion.y;
  17868. body.quaternion.y = mesh.rotationQuaternion.z;
  17869. body.quaternion.w = -mesh.rotationQuaternion.w;
  17870. return;
  17871. }
  17872. }
  17873. };
  17874. }
  17875. CannonJSPlugin.prototype.initialize = function (iterations) {
  17876. if (typeof iterations === "undefined") { iterations = 10; }
  17877. this._world = new CANNON.World();
  17878. this._world.broadphase = new CANNON.NaiveBroadphase();
  17879. this._world.solver.iterations = iterations;
  17880. };
  17881. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17882. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17883. };
  17884. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17885. this._world.step(delta);
  17886. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17887. var registeredMesh = this._registeredMeshes[index];
  17888. if (registeredMesh.isChild) {
  17889. continue;
  17890. }
  17891. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17892. var deltaPos = registeredMesh.delta;
  17893. if (deltaPos) {
  17894. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17895. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17896. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17897. } else {
  17898. registeredMesh.mesh.position.x = bodyX;
  17899. registeredMesh.mesh.position.y = bodyZ;
  17900. registeredMesh.mesh.position.z = bodyY;
  17901. }
  17902. if (!registeredMesh.mesh.rotationQuaternion) {
  17903. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17904. }
  17905. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17906. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17907. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17908. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17909. }
  17910. };
  17911. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17912. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17913. };
  17914. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17915. this.unregisterMesh(mesh);
  17916. mesh.computeWorldMatrix(true);
  17917. switch (impostor) {
  17918. case BABYLON.PhysicsEngine.SphereImpostor:
  17919. var bbox = mesh.getBoundingInfo().boundingBox;
  17920. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17921. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17922. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17923. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17924. case BABYLON.PhysicsEngine.BoxImpostor:
  17925. bbox = mesh.getBoundingInfo().boundingBox;
  17926. var min = bbox.minimumWorld;
  17927. var max = bbox.maximumWorld;
  17928. var box = max.subtract(min).scale(0.5);
  17929. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17930. case BABYLON.PhysicsEngine.PlaneImpostor:
  17931. return this._createPlane(mesh, options);
  17932. case BABYLON.PhysicsEngine.MeshImpostor:
  17933. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17934. var rawFaces = mesh.getIndices();
  17935. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17936. }
  17937. return null;
  17938. };
  17939. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17940. var shape = new CANNON.Sphere(radius);
  17941. if (!options) {
  17942. return shape;
  17943. }
  17944. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17945. };
  17946. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17947. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17948. if (!options) {
  17949. return shape;
  17950. }
  17951. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17952. };
  17953. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17954. var shape = new CANNON.Plane();
  17955. if (!options) {
  17956. return shape;
  17957. }
  17958. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17959. };
  17960. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17961. var verts = [], faces = [];
  17962. mesh.computeWorldMatrix(true);
  17963. for (var i = 0; i < rawVerts.length; i += 3) {
  17964. var transformed = BABYLON.Vector3.Zero();
  17965. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17966. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17967. }
  17968. for (var j = 0; j < rawFaces.length; j += 3) {
  17969. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17970. }
  17971. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17972. if (!options) {
  17973. return shape;
  17974. }
  17975. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17976. };
  17977. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17978. var index;
  17979. var mat;
  17980. for (index = 0; index < this._physicsMaterials.length; index++) {
  17981. mat = this._physicsMaterials[index];
  17982. if (mat.friction === friction && mat.restitution === restitution) {
  17983. return mat;
  17984. }
  17985. }
  17986. var currentMat = new CANNON.Material();
  17987. currentMat.friction = friction;
  17988. currentMat.restitution = restitution;
  17989. this._physicsMaterials.push(currentMat);
  17990. for (index = 0; index < this._physicsMaterials.length; index++) {
  17991. mat = this._physicsMaterials[index];
  17992. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17993. contactMaterial.contactEquationStiffness = 1e10;
  17994. contactMaterial.contactEquationRegularizationTime = 10;
  17995. this._world.addContactMaterial(contactMaterial);
  17996. }
  17997. return currentMat;
  17998. };
  17999. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18000. var initialRotation = null;
  18001. if (mesh.rotationQuaternion) {
  18002. initialRotation = mesh.rotationQuaternion.clone();
  18003. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18004. }
  18005. var bbox = mesh.getBoundingInfo().boundingBox;
  18006. var deltaPosition = mesh.position.subtract(bbox.center);
  18007. var material = this._addMaterial(friction, restitution);
  18008. var body = new CANNON.RigidBody(mass, shape, material);
  18009. if (initialRotation) {
  18010. body.quaternion.x = initialRotation.x;
  18011. body.quaternion.z = initialRotation.y;
  18012. body.quaternion.y = initialRotation.z;
  18013. body.quaternion.w = -initialRotation.w;
  18014. }
  18015. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18016. this._world.add(body);
  18017. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18018. return body;
  18019. };
  18020. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18021. var compoundShape = new CANNON.Compound();
  18022. for (var index = 0; index < parts.length; index++) {
  18023. var mesh = parts[index].mesh;
  18024. var shape = this.registerMesh(mesh, parts[index].impostor);
  18025. if (index == 0) {
  18026. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18027. } else {
  18028. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18029. }
  18030. }
  18031. var initialMesh = parts[0].mesh;
  18032. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18033. body.parts = parts;
  18034. return body;
  18035. };
  18036. CannonJSPlugin.prototype._unbindBody = function (body) {
  18037. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18038. var registeredMesh = this._registeredMeshes[index];
  18039. if (registeredMesh.body === body) {
  18040. registeredMesh.body = null;
  18041. registeredMesh.delta = 0;
  18042. }
  18043. }
  18044. };
  18045. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18046. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18047. var registeredMesh = this._registeredMeshes[index];
  18048. if (registeredMesh.mesh === mesh) {
  18049. if (registeredMesh.body) {
  18050. this._world.remove(registeredMesh.body);
  18051. this._unbindBody(registeredMesh.body);
  18052. }
  18053. this._registeredMeshes.splice(index, 1);
  18054. return;
  18055. }
  18056. }
  18057. };
  18058. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18059. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18060. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18061. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18062. var registeredMesh = this._registeredMeshes[index];
  18063. if (registeredMesh.mesh === mesh) {
  18064. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18065. return;
  18066. }
  18067. }
  18068. };
  18069. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18070. var body1 = null, body2 = null;
  18071. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18072. var registeredMesh = this._registeredMeshes[index];
  18073. if (registeredMesh.mesh === mesh1) {
  18074. body1 = registeredMesh.body;
  18075. } else if (registeredMesh.mesh === mesh2) {
  18076. body2 = registeredMesh.body;
  18077. }
  18078. }
  18079. if (!body1 || !body2) {
  18080. return false;
  18081. }
  18082. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  18083. this._world.addConstraint(constraint);
  18084. return true;
  18085. };
  18086. CannonJSPlugin.prototype.dispose = function () {
  18087. while (this._registeredMeshes.length) {
  18088. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18089. }
  18090. };
  18091. CannonJSPlugin.prototype.isSupported = function () {
  18092. return window.CANNON !== undefined;
  18093. };
  18094. return CannonJSPlugin;
  18095. })();
  18096. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18097. })(BABYLON || (BABYLON = {}));
  18098. var __extends = this.__extends || function (d, b) {
  18099. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18100. function __() { this.constructor = d; }
  18101. __.prototype = b.prototype;
  18102. d.prototype = new __();
  18103. };
  18104. var BABYLON;
  18105. (function (BABYLON) {
  18106. var Condition = (function () {
  18107. function Condition(actionManager) {
  18108. this._actionManager = actionManager;
  18109. }
  18110. Condition.prototype.isValid = function () {
  18111. return true;
  18112. };
  18113. Condition.prototype._getProperty = function (propertyPath) {
  18114. return this._actionManager._getProperty(propertyPath);
  18115. };
  18116. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18117. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18118. };
  18119. return Condition;
  18120. })();
  18121. BABYLON.Condition = Condition;
  18122. var ValueCondition = (function (_super) {
  18123. __extends(ValueCondition, _super);
  18124. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18125. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18126. _super.call(this, actionManager);
  18127. this.propertyPath = propertyPath;
  18128. this.value = value;
  18129. this.operator = operator;
  18130. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18131. this._property = this._getProperty(this.propertyPath);
  18132. }
  18133. Object.defineProperty(ValueCondition, "IsEqual", {
  18134. get: function () {
  18135. return ValueCondition._IsEqual;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Object.defineProperty(ValueCondition, "IsDifferent", {
  18141. get: function () {
  18142. return ValueCondition._IsDifferent;
  18143. },
  18144. enumerable: true,
  18145. configurable: true
  18146. });
  18147. Object.defineProperty(ValueCondition, "IsGreater", {
  18148. get: function () {
  18149. return ValueCondition._IsGreater;
  18150. },
  18151. enumerable: true,
  18152. configurable: true
  18153. });
  18154. Object.defineProperty(ValueCondition, "IsLesser", {
  18155. get: function () {
  18156. return ValueCondition._IsLesser;
  18157. },
  18158. enumerable: true,
  18159. configurable: true
  18160. });
  18161. ValueCondition.prototype.isValid = function () {
  18162. switch (this.operator) {
  18163. case ValueCondition.IsGreater:
  18164. return this._target[this._property] > this.value;
  18165. case ValueCondition.IsLesser:
  18166. return this._target[this._property] < this.value;
  18167. case ValueCondition.IsEqual:
  18168. case ValueCondition.IsDifferent:
  18169. var check;
  18170. if (this.value.equals) {
  18171. check = this.value.equals(this._target[this._property]);
  18172. } else {
  18173. check = this.value === this._target[this._property];
  18174. }
  18175. return this.operator === ValueCondition.IsEqual ? check : !check;
  18176. }
  18177. return false;
  18178. };
  18179. ValueCondition._IsEqual = 0;
  18180. ValueCondition._IsDifferent = 1;
  18181. ValueCondition._IsGreater = 2;
  18182. ValueCondition._IsLesser = 3;
  18183. return ValueCondition;
  18184. })(Condition);
  18185. BABYLON.ValueCondition = ValueCondition;
  18186. var PredicateCondition = (function (_super) {
  18187. __extends(PredicateCondition, _super);
  18188. function PredicateCondition(actionManager, predicate) {
  18189. _super.call(this, actionManager);
  18190. this.predicate = predicate;
  18191. }
  18192. PredicateCondition.prototype.isValid = function () {
  18193. return this.predicate();
  18194. };
  18195. return PredicateCondition;
  18196. })(Condition);
  18197. BABYLON.PredicateCondition = PredicateCondition;
  18198. var StateCondition = (function (_super) {
  18199. __extends(StateCondition, _super);
  18200. function StateCondition(actionManager, target, value) {
  18201. _super.call(this, actionManager);
  18202. this.value = value;
  18203. this._target = target;
  18204. }
  18205. StateCondition.prototype.isValid = function () {
  18206. return this._target.state === this.value;
  18207. };
  18208. return StateCondition;
  18209. })(Condition);
  18210. BABYLON.StateCondition = StateCondition;
  18211. })(BABYLON || (BABYLON = {}));
  18212. var BABYLON;
  18213. (function (BABYLON) {
  18214. var Action = (function () {
  18215. function Action(triggerOptions, condition) {
  18216. this.triggerOptions = triggerOptions;
  18217. if (triggerOptions.parameter) {
  18218. this.trigger = triggerOptions.trigger;
  18219. this._triggerParameter = triggerOptions.parameter;
  18220. } else {
  18221. this.trigger = triggerOptions;
  18222. }
  18223. this._nextActiveAction = this;
  18224. this._condition = condition;
  18225. }
  18226. Action.prototype._prepare = function () {
  18227. };
  18228. Action.prototype.getTriggerParameter = function () {
  18229. return this._triggerParameter;
  18230. };
  18231. Action.prototype._executeCurrent = function (evt) {
  18232. if (this._condition) {
  18233. var currentRenderId = this._actionManager.getScene().getRenderId();
  18234. if (this._condition._evaluationId === currentRenderId) {
  18235. if (!this._condition._currentResult) {
  18236. return;
  18237. }
  18238. } else {
  18239. this._condition._evaluationId = currentRenderId;
  18240. if (!this._condition.isValid()) {
  18241. this._condition._currentResult = false;
  18242. return;
  18243. }
  18244. this._condition._currentResult = true;
  18245. }
  18246. }
  18247. this._nextActiveAction.execute(evt);
  18248. if (this._nextActiveAction._child) {
  18249. this._nextActiveAction = this._nextActiveAction._child;
  18250. } else {
  18251. this._nextActiveAction = this;
  18252. }
  18253. };
  18254. Action.prototype.execute = function (evt) {
  18255. };
  18256. Action.prototype.then = function (action) {
  18257. this._child = action;
  18258. action._actionManager = this._actionManager;
  18259. action._prepare();
  18260. return action;
  18261. };
  18262. Action.prototype._getProperty = function (propertyPath) {
  18263. return this._actionManager._getProperty(propertyPath);
  18264. };
  18265. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18266. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18267. };
  18268. return Action;
  18269. })();
  18270. BABYLON.Action = Action;
  18271. })(BABYLON || (BABYLON = {}));
  18272. var BABYLON;
  18273. (function (BABYLON) {
  18274. var ActionEvent = (function () {
  18275. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18276. this.source = source;
  18277. this.pointerX = pointerX;
  18278. this.pointerY = pointerY;
  18279. this.meshUnderPointer = meshUnderPointer;
  18280. this.sourceEvent = sourceEvent;
  18281. }
  18282. ActionEvent.CreateNew = function (source) {
  18283. var scene = source.getScene();
  18284. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18285. };
  18286. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18287. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18288. };
  18289. return ActionEvent;
  18290. })();
  18291. BABYLON.ActionEvent = ActionEvent;
  18292. var ActionManager = (function () {
  18293. function ActionManager(scene) {
  18294. this.actions = new Array();
  18295. this._scene = scene;
  18296. scene._actionManagers.push(this);
  18297. }
  18298. Object.defineProperty(ActionManager, "NothingTrigger", {
  18299. get: function () {
  18300. return ActionManager._NothingTrigger;
  18301. },
  18302. enumerable: true,
  18303. configurable: true
  18304. });
  18305. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18306. get: function () {
  18307. return ActionManager._OnPickTrigger;
  18308. },
  18309. enumerable: true,
  18310. configurable: true
  18311. });
  18312. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18313. get: function () {
  18314. return ActionManager._OnLeftPickTrigger;
  18315. },
  18316. enumerable: true,
  18317. configurable: true
  18318. });
  18319. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18320. get: function () {
  18321. return ActionManager._OnRightPickTrigger;
  18322. },
  18323. enumerable: true,
  18324. configurable: true
  18325. });
  18326. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18327. get: function () {
  18328. return ActionManager._OnCenterPickTrigger;
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18334. get: function () {
  18335. return ActionManager._OnPointerOverTrigger;
  18336. },
  18337. enumerable: true,
  18338. configurable: true
  18339. });
  18340. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18341. get: function () {
  18342. return ActionManager._OnPointerOutTrigger;
  18343. },
  18344. enumerable: true,
  18345. configurable: true
  18346. });
  18347. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18348. get: function () {
  18349. return ActionManager._OnEveryFrameTrigger;
  18350. },
  18351. enumerable: true,
  18352. configurable: true
  18353. });
  18354. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18355. get: function () {
  18356. return ActionManager._OnIntersectionEnterTrigger;
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18362. get: function () {
  18363. return ActionManager._OnIntersectionExitTrigger;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18369. get: function () {
  18370. return ActionManager._OnKeyDownTrigger;
  18371. },
  18372. enumerable: true,
  18373. configurable: true
  18374. });
  18375. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18376. get: function () {
  18377. return ActionManager._OnKeyUpTrigger;
  18378. },
  18379. enumerable: true,
  18380. configurable: true
  18381. });
  18382. ActionManager.prototype.dispose = function () {
  18383. var index = this._scene._actionManagers.indexOf(this);
  18384. if (index > -1) {
  18385. this._scene._actionManagers.splice(index, 1);
  18386. }
  18387. };
  18388. ActionManager.prototype.getScene = function () {
  18389. return this._scene;
  18390. };
  18391. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18392. for (var index = 0; index < this.actions.length; index++) {
  18393. var action = this.actions[index];
  18394. if (triggers.indexOf(action.trigger) > -1) {
  18395. return true;
  18396. }
  18397. }
  18398. return false;
  18399. };
  18400. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18401. get: function () {
  18402. for (var index = 0; index < this.actions.length; index++) {
  18403. var action = this.actions[index];
  18404. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18405. return true;
  18406. }
  18407. }
  18408. return false;
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18414. get: function () {
  18415. for (var index = 0; index < this.actions.length; index++) {
  18416. var action = this.actions[index];
  18417. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18418. return true;
  18419. }
  18420. }
  18421. return false;
  18422. },
  18423. enumerable: true,
  18424. configurable: true
  18425. });
  18426. ActionManager.prototype.registerAction = function (action) {
  18427. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18428. if (this.getScene().actionManager !== this) {
  18429. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18430. return null;
  18431. }
  18432. }
  18433. this.actions.push(action);
  18434. action._actionManager = this;
  18435. action._prepare();
  18436. return action;
  18437. };
  18438. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18439. for (var index = 0; index < this.actions.length; index++) {
  18440. var action = this.actions[index];
  18441. if (action.trigger === trigger) {
  18442. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18443. var parameter = action.getTriggerParameter();
  18444. if (parameter) {
  18445. if (evt.sourceEvent.key !== parameter) {
  18446. continue;
  18447. }
  18448. }
  18449. }
  18450. action._executeCurrent(evt);
  18451. }
  18452. }
  18453. };
  18454. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18455. var properties = propertyPath.split(".");
  18456. for (var index = 0; index < properties.length - 1; index++) {
  18457. target = target[properties[index]];
  18458. }
  18459. return target;
  18460. };
  18461. ActionManager.prototype._getProperty = function (propertyPath) {
  18462. var properties = propertyPath.split(".");
  18463. return properties[properties.length - 1];
  18464. };
  18465. ActionManager._NothingTrigger = 0;
  18466. ActionManager._OnPickTrigger = 1;
  18467. ActionManager._OnLeftPickTrigger = 2;
  18468. ActionManager._OnRightPickTrigger = 3;
  18469. ActionManager._OnCenterPickTrigger = 4;
  18470. ActionManager._OnPointerOverTrigger = 5;
  18471. ActionManager._OnPointerOutTrigger = 6;
  18472. ActionManager._OnEveryFrameTrigger = 7;
  18473. ActionManager._OnIntersectionEnterTrigger = 8;
  18474. ActionManager._OnIntersectionExitTrigger = 9;
  18475. ActionManager._OnKeyDownTrigger = 10;
  18476. ActionManager._OnKeyUpTrigger = 11;
  18477. return ActionManager;
  18478. })();
  18479. BABYLON.ActionManager = ActionManager;
  18480. })(BABYLON || (BABYLON = {}));
  18481. var __extends = this.__extends || function (d, b) {
  18482. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18483. function __() { this.constructor = d; }
  18484. __.prototype = b.prototype;
  18485. d.prototype = new __();
  18486. };
  18487. var BABYLON;
  18488. (function (BABYLON) {
  18489. var InterpolateValueAction = (function (_super) {
  18490. __extends(InterpolateValueAction, _super);
  18491. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18492. if (typeof duration === "undefined") { duration = 1000; }
  18493. _super.call(this, triggerOptions, condition);
  18494. this.propertyPath = propertyPath;
  18495. this.value = value;
  18496. this.duration = duration;
  18497. this.stopOtherAnimations = stopOtherAnimations;
  18498. this._target = target;
  18499. }
  18500. InterpolateValueAction.prototype._prepare = function () {
  18501. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18502. this._property = this._getProperty(this.propertyPath);
  18503. };
  18504. InterpolateValueAction.prototype.execute = function () {
  18505. var scene = this._actionManager.getScene();
  18506. var keys = [
  18507. {
  18508. frame: 0,
  18509. value: this._target[this._property]
  18510. }, {
  18511. frame: 100,
  18512. value: this.value
  18513. }
  18514. ];
  18515. var dataType;
  18516. if (typeof this.value === "number") {
  18517. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18518. } else if (this.value instanceof BABYLON.Color3) {
  18519. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18520. } else if (this.value instanceof BABYLON.Vector3) {
  18521. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18522. } else if (this.value instanceof BABYLON.Matrix) {
  18523. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18524. } else if (this.value instanceof BABYLON.Quaternion) {
  18525. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18526. } else {
  18527. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18528. return;
  18529. }
  18530. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18531. animation.setKeys(keys);
  18532. if (this.stopOtherAnimations) {
  18533. scene.stopAnimation(this._target);
  18534. }
  18535. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18536. };
  18537. return InterpolateValueAction;
  18538. })(BABYLON.Action);
  18539. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18540. })(BABYLON || (BABYLON = {}));
  18541. var __extends = this.__extends || function (d, b) {
  18542. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18543. function __() { this.constructor = d; }
  18544. __.prototype = b.prototype;
  18545. d.prototype = new __();
  18546. };
  18547. var BABYLON;
  18548. (function (BABYLON) {
  18549. var SwitchBooleanAction = (function (_super) {
  18550. __extends(SwitchBooleanAction, _super);
  18551. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18552. _super.call(this, triggerOptions, condition);
  18553. this.propertyPath = propertyPath;
  18554. this._target = target;
  18555. }
  18556. SwitchBooleanAction.prototype._prepare = function () {
  18557. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18558. this._property = this._getProperty(this.propertyPath);
  18559. };
  18560. SwitchBooleanAction.prototype.execute = function () {
  18561. this._target[this._property] = !this._target[this._property];
  18562. };
  18563. return SwitchBooleanAction;
  18564. })(BABYLON.Action);
  18565. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18566. var SetStateAction = (function (_super) {
  18567. __extends(SetStateAction, _super);
  18568. function SetStateAction(triggerOptions, target, value, condition) {
  18569. _super.call(this, triggerOptions, condition);
  18570. this.value = value;
  18571. this._target = target;
  18572. }
  18573. SetStateAction.prototype.execute = function () {
  18574. this._target.state = this.value;
  18575. };
  18576. return SetStateAction;
  18577. })(BABYLON.Action);
  18578. BABYLON.SetStateAction = SetStateAction;
  18579. var SetValueAction = (function (_super) {
  18580. __extends(SetValueAction, _super);
  18581. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18582. _super.call(this, triggerOptions, condition);
  18583. this.propertyPath = propertyPath;
  18584. this.value = value;
  18585. this._target = target;
  18586. }
  18587. SetValueAction.prototype._prepare = function () {
  18588. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18589. this._property = this._getProperty(this.propertyPath);
  18590. };
  18591. SetValueAction.prototype.execute = function () {
  18592. this._target[this._property] = this.value;
  18593. };
  18594. return SetValueAction;
  18595. })(BABYLON.Action);
  18596. BABYLON.SetValueAction = SetValueAction;
  18597. var IncrementValueAction = (function (_super) {
  18598. __extends(IncrementValueAction, _super);
  18599. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18600. _super.call(this, triggerOptions, condition);
  18601. this.propertyPath = propertyPath;
  18602. this.value = value;
  18603. this._target = target;
  18604. }
  18605. IncrementValueAction.prototype._prepare = function () {
  18606. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18607. this._property = this._getProperty(this.propertyPath);
  18608. if (typeof this._target[this._property] !== "number") {
  18609. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18610. }
  18611. };
  18612. IncrementValueAction.prototype.execute = function () {
  18613. this._target[this._property] += this.value;
  18614. };
  18615. return IncrementValueAction;
  18616. })(BABYLON.Action);
  18617. BABYLON.IncrementValueAction = IncrementValueAction;
  18618. var PlayAnimationAction = (function (_super) {
  18619. __extends(PlayAnimationAction, _super);
  18620. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18621. _super.call(this, triggerOptions, condition);
  18622. this.from = from;
  18623. this.to = to;
  18624. this.loop = loop;
  18625. this._target = target;
  18626. }
  18627. PlayAnimationAction.prototype._prepare = function () {
  18628. };
  18629. PlayAnimationAction.prototype.execute = function () {
  18630. var scene = this._actionManager.getScene();
  18631. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18632. };
  18633. return PlayAnimationAction;
  18634. })(BABYLON.Action);
  18635. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18636. var StopAnimationAction = (function (_super) {
  18637. __extends(StopAnimationAction, _super);
  18638. function StopAnimationAction(triggerOptions, target, condition) {
  18639. _super.call(this, triggerOptions, condition);
  18640. this._target = target;
  18641. }
  18642. StopAnimationAction.prototype._prepare = function () {
  18643. };
  18644. StopAnimationAction.prototype.execute = function () {
  18645. var scene = this._actionManager.getScene();
  18646. scene.stopAnimation(this._target);
  18647. };
  18648. return StopAnimationAction;
  18649. })(BABYLON.Action);
  18650. BABYLON.StopAnimationAction = StopAnimationAction;
  18651. var DoNothingAction = (function (_super) {
  18652. __extends(DoNothingAction, _super);
  18653. function DoNothingAction(triggerOptions, condition) {
  18654. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18655. _super.call(this, triggerOptions, condition);
  18656. }
  18657. DoNothingAction.prototype.execute = function () {
  18658. };
  18659. return DoNothingAction;
  18660. })(BABYLON.Action);
  18661. BABYLON.DoNothingAction = DoNothingAction;
  18662. var CombineAction = (function (_super) {
  18663. __extends(CombineAction, _super);
  18664. function CombineAction(triggerOptions, children, condition) {
  18665. _super.call(this, triggerOptions, condition);
  18666. this.children = children;
  18667. }
  18668. CombineAction.prototype._prepare = function () {
  18669. for (var index = 0; index < this.children.length; index++) {
  18670. this.children[index]._actionManager = this._actionManager;
  18671. this.children[index]._prepare();
  18672. }
  18673. };
  18674. CombineAction.prototype.execute = function (evt) {
  18675. for (var index = 0; index < this.children.length; index++) {
  18676. this.children[index].execute(evt);
  18677. }
  18678. };
  18679. return CombineAction;
  18680. })(BABYLON.Action);
  18681. BABYLON.CombineAction = CombineAction;
  18682. var ExecuteCodeAction = (function (_super) {
  18683. __extends(ExecuteCodeAction, _super);
  18684. function ExecuteCodeAction(triggerOptions, func, condition) {
  18685. _super.call(this, triggerOptions, condition);
  18686. this.func = func;
  18687. }
  18688. ExecuteCodeAction.prototype.execute = function (evt) {
  18689. this.func(evt);
  18690. };
  18691. return ExecuteCodeAction;
  18692. })(BABYLON.Action);
  18693. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18694. var SetParentAction = (function (_super) {
  18695. __extends(SetParentAction, _super);
  18696. function SetParentAction(triggerOptions, target, parent, condition) {
  18697. _super.call(this, triggerOptions, condition);
  18698. this._target = target;
  18699. this._parent = parent;
  18700. }
  18701. SetParentAction.prototype._prepare = function () {
  18702. };
  18703. SetParentAction.prototype.execute = function () {
  18704. if (this._target.parent === this._parent) {
  18705. return;
  18706. }
  18707. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18708. invertParentWorldMatrix.invert();
  18709. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18710. this._target.parent = this._parent;
  18711. };
  18712. return SetParentAction;
  18713. })(BABYLON.Action);
  18714. BABYLON.SetParentAction = SetParentAction;
  18715. })(BABYLON || (BABYLON = {}));
  18716. var __extends = this.__extends || function (d, b) {
  18717. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18718. function __() { this.constructor = d; }
  18719. __.prototype = b.prototype;
  18720. d.prototype = new __();
  18721. };
  18722. var BABYLON;
  18723. (function (BABYLON) {
  18724. var Geometry = (function () {
  18725. function Geometry(id, scene, vertexData, updatable, mesh) {
  18726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18727. this._totalVertices = 0;
  18728. this._indices = [];
  18729. this.id = id;
  18730. this._engine = scene.getEngine();
  18731. this._meshes = [];
  18732. this._scene = scene;
  18733. if (vertexData) {
  18734. this.setAllVerticesData(vertexData, updatable);
  18735. } else {
  18736. this._totalVertices = 0;
  18737. this._indices = [];
  18738. }
  18739. if (mesh) {
  18740. this.applyToMesh(mesh);
  18741. }
  18742. }
  18743. Geometry.prototype.getScene = function () {
  18744. return this._scene;
  18745. };
  18746. Geometry.prototype.getEngine = function () {
  18747. return this._engine;
  18748. };
  18749. Geometry.prototype.isReady = function () {
  18750. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18751. };
  18752. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18753. vertexData.applyToGeometry(this, updatable);
  18754. };
  18755. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18756. this._vertexBuffers = this._vertexBuffers || {};
  18757. if (this._vertexBuffers[kind]) {
  18758. this._vertexBuffers[kind].dispose();
  18759. }
  18760. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18761. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18762. var stride = this._vertexBuffers[kind].getStrideSize();
  18763. this._totalVertices = data.length / stride;
  18764. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18765. var meshes = this._meshes;
  18766. var numOfMeshes = meshes.length;
  18767. for (var index = 0; index < numOfMeshes; index++) {
  18768. var mesh = meshes[index];
  18769. mesh._resetPointsArrayCache();
  18770. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18771. mesh._createGlobalSubMesh();
  18772. mesh.computeWorldMatrix(true);
  18773. }
  18774. }
  18775. };
  18776. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18777. var vertexBuffer = this.getVertexBuffer(kind);
  18778. if (!vertexBuffer) {
  18779. return;
  18780. }
  18781. vertexBuffer.update(data);
  18782. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18783. var extend;
  18784. if (updateExtends) {
  18785. var stride = vertexBuffer.getStrideSize();
  18786. this._totalVertices = data.length / stride;
  18787. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18788. }
  18789. var meshes = this._meshes;
  18790. var numOfMeshes = meshes.length;
  18791. for (var index = 0; index < numOfMeshes; index++) {
  18792. var mesh = meshes[index];
  18793. mesh._resetPointsArrayCache();
  18794. if (updateExtends) {
  18795. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18796. }
  18797. }
  18798. }
  18799. };
  18800. Geometry.prototype.getTotalVertices = function () {
  18801. if (!this.isReady()) {
  18802. return 0;
  18803. }
  18804. return this._totalVertices;
  18805. };
  18806. Geometry.prototype.getVerticesData = function (kind) {
  18807. var vertexBuffer = this.getVertexBuffer(kind);
  18808. if (!vertexBuffer) {
  18809. return null;
  18810. }
  18811. return vertexBuffer.getData();
  18812. };
  18813. Geometry.prototype.getVertexBuffer = function (kind) {
  18814. if (!this.isReady()) {
  18815. return null;
  18816. }
  18817. return this._vertexBuffers[kind];
  18818. };
  18819. Geometry.prototype.getVertexBuffers = function () {
  18820. if (!this.isReady()) {
  18821. return null;
  18822. }
  18823. return this._vertexBuffers;
  18824. };
  18825. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18826. if (!this._vertexBuffers) {
  18827. if (this._delayInfo) {
  18828. return this._delayInfo.indexOf(kind) !== -1;
  18829. }
  18830. return false;
  18831. }
  18832. return this._vertexBuffers[kind] !== undefined;
  18833. };
  18834. Geometry.prototype.getVerticesDataKinds = function () {
  18835. var result = [];
  18836. if (!this._vertexBuffers && this._delayInfo) {
  18837. for (var kind in this._delayInfo) {
  18838. result.push(kind);
  18839. }
  18840. } else {
  18841. for (kind in this._vertexBuffers) {
  18842. result.push(kind);
  18843. }
  18844. }
  18845. return result;
  18846. };
  18847. Geometry.prototype.setIndices = function (indices) {
  18848. if (this._indexBuffer) {
  18849. this._engine._releaseBuffer(this._indexBuffer);
  18850. }
  18851. this._indices = indices;
  18852. if (this._meshes.length !== 0 && this._indices) {
  18853. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18854. }
  18855. var meshes = this._meshes;
  18856. var numOfMeshes = meshes.length;
  18857. for (var index = 0; index < numOfMeshes; index++) {
  18858. meshes[index]._createGlobalSubMesh();
  18859. }
  18860. };
  18861. Geometry.prototype.getTotalIndices = function () {
  18862. if (!this.isReady()) {
  18863. return 0;
  18864. }
  18865. return this._indices.length;
  18866. };
  18867. Geometry.prototype.getIndices = function () {
  18868. if (!this.isReady()) {
  18869. return null;
  18870. }
  18871. return this._indices;
  18872. };
  18873. Geometry.prototype.getIndexBuffer = function () {
  18874. if (!this.isReady()) {
  18875. return null;
  18876. }
  18877. return this._indexBuffer;
  18878. };
  18879. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18880. var meshes = this._meshes;
  18881. var index = meshes.indexOf(mesh);
  18882. if (index === -1) {
  18883. return;
  18884. }
  18885. for (var kind in this._vertexBuffers) {
  18886. this._vertexBuffers[kind].dispose();
  18887. }
  18888. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18889. this._indexBuffer = null;
  18890. }
  18891. meshes.splice(index, 1);
  18892. mesh._geometry = null;
  18893. if (meshes.length == 0 && shouldDispose) {
  18894. this.dispose();
  18895. }
  18896. };
  18897. Geometry.prototype.applyToMesh = function (mesh) {
  18898. if (mesh._geometry === this) {
  18899. return;
  18900. }
  18901. var previousGeometry = mesh._geometry;
  18902. if (previousGeometry) {
  18903. previousGeometry.releaseForMesh(mesh);
  18904. }
  18905. var meshes = this._meshes;
  18906. mesh._geometry = this;
  18907. this._scene.pushGeometry(this);
  18908. meshes.push(mesh);
  18909. if (this.isReady()) {
  18910. this._applyToMesh(mesh);
  18911. } else {
  18912. mesh._boundingInfo = this._boundingInfo;
  18913. }
  18914. };
  18915. Geometry.prototype._applyToMesh = function (mesh) {
  18916. var numOfMeshes = this._meshes.length;
  18917. for (var kind in this._vertexBuffers) {
  18918. if (numOfMeshes === 1) {
  18919. this._vertexBuffers[kind].create();
  18920. }
  18921. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18922. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18923. mesh._resetPointsArrayCache();
  18924. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18925. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18926. mesh._createGlobalSubMesh();
  18927. }
  18928. }
  18929. if (numOfMeshes === 1 && this._indices) {
  18930. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18931. }
  18932. if (this._indexBuffer) {
  18933. this._indexBuffer.references = numOfMeshes;
  18934. }
  18935. };
  18936. Geometry.prototype.load = function (scene, onLoaded) {
  18937. var _this = this;
  18938. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18939. return;
  18940. }
  18941. if (this.isReady()) {
  18942. if (onLoaded) {
  18943. onLoaded();
  18944. }
  18945. return;
  18946. }
  18947. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18948. scene._addPendingData(this);
  18949. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18950. _this._delayLoadingFunction(JSON.parse(data), _this);
  18951. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18952. _this._delayInfo = [];
  18953. scene._removePendingData(_this);
  18954. var meshes = _this._meshes;
  18955. var numOfMeshes = meshes.length;
  18956. for (var index = 0; index < numOfMeshes; index++) {
  18957. _this._applyToMesh(meshes[index]);
  18958. }
  18959. if (onLoaded) {
  18960. onLoaded();
  18961. }
  18962. }, function () {
  18963. }, scene.database);
  18964. };
  18965. Geometry.prototype.dispose = function () {
  18966. var meshes = this._meshes;
  18967. var numOfMeshes = meshes.length;
  18968. for (var index = 0; index < numOfMeshes; index++) {
  18969. this.releaseForMesh(meshes[index]);
  18970. }
  18971. this._meshes = [];
  18972. for (var kind in this._vertexBuffers) {
  18973. this._vertexBuffers[kind].dispose();
  18974. }
  18975. this._vertexBuffers = [];
  18976. this._totalVertices = 0;
  18977. if (this._indexBuffer) {
  18978. this._engine._releaseBuffer(this._indexBuffer);
  18979. }
  18980. this._indexBuffer = null;
  18981. this._indices = [];
  18982. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18983. this.delayLoadingFile = null;
  18984. this._delayLoadingFunction = null;
  18985. this._delayInfo = [];
  18986. this._boundingInfo = null;
  18987. var geometries = this._scene.getGeometries();
  18988. index = geometries.indexOf(this);
  18989. if (index > -1) {
  18990. geometries.splice(index, 1);
  18991. }
  18992. };
  18993. Geometry.prototype.copy = function (id) {
  18994. var vertexData = new BABYLON.VertexData();
  18995. vertexData.indices = [];
  18996. var indices = this.getIndices();
  18997. for (var index = 0; index < indices.length; index++) {
  18998. vertexData.indices.push(indices[index]);
  18999. }
  19000. var updatable = false;
  19001. var stopChecking = false;
  19002. for (var kind in this._vertexBuffers) {
  19003. vertexData.set(this.getVerticesData(kind), kind);
  19004. if (!stopChecking) {
  19005. updatable = this.getVertexBuffer(kind).isUpdatable();
  19006. stopChecking = !updatable;
  19007. }
  19008. }
  19009. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19010. geometry.delayLoadState = this.delayLoadState;
  19011. geometry.delayLoadingFile = this.delayLoadingFile;
  19012. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19013. for (kind in this._delayInfo) {
  19014. geometry._delayInfo = geometry._delayInfo || [];
  19015. geometry._delayInfo.push(kind);
  19016. }
  19017. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19018. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19019. return geometry;
  19020. };
  19021. Geometry.ExtractFromMesh = function (mesh, id) {
  19022. var geometry = mesh._geometry;
  19023. if (!geometry) {
  19024. return null;
  19025. }
  19026. return geometry.copy(id);
  19027. };
  19028. Geometry.RandomId = function () {
  19029. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19030. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19031. return v.toString(16);
  19032. });
  19033. };
  19034. return Geometry;
  19035. })();
  19036. BABYLON.Geometry = Geometry;
  19037. (function (Geometry) {
  19038. (function (Primitives) {
  19039. var _Primitive = (function (_super) {
  19040. __extends(_Primitive, _super);
  19041. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19042. this._beingRegenerated = true;
  19043. this._canBeRegenerated = canBeRegenerated;
  19044. _super.call(this, id, scene, vertexData, false, mesh);
  19045. this._beingRegenerated = false;
  19046. }
  19047. _Primitive.prototype.canBeRegenerated = function () {
  19048. return this._canBeRegenerated;
  19049. };
  19050. _Primitive.prototype.regenerate = function () {
  19051. if (!this._canBeRegenerated) {
  19052. return;
  19053. }
  19054. this._beingRegenerated = true;
  19055. this.setAllVerticesData(this._regenerateVertexData(), false);
  19056. this._beingRegenerated = false;
  19057. };
  19058. _Primitive.prototype.asNewGeometry = function (id) {
  19059. return _super.prototype.copy.call(this, id);
  19060. };
  19061. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19062. if (!this._beingRegenerated) {
  19063. return;
  19064. }
  19065. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19066. };
  19067. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19068. if (!this._beingRegenerated) {
  19069. return;
  19070. }
  19071. _super.prototype.setVerticesData.call(this, kind, data, false);
  19072. };
  19073. _Primitive.prototype._regenerateVertexData = function () {
  19074. throw new Error("Abstract method");
  19075. };
  19076. _Primitive.prototype.copy = function (id) {
  19077. throw new Error("Must be overriden in sub-classes.");
  19078. };
  19079. return _Primitive;
  19080. })(Geometry);
  19081. Primitives._Primitive = _Primitive;
  19082. var Box = (function (_super) {
  19083. __extends(Box, _super);
  19084. function Box(id, scene, size, canBeRegenerated, mesh) {
  19085. this.size = size;
  19086. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19087. }
  19088. Box.prototype._regenerateVertexData = function () {
  19089. return BABYLON.VertexData.CreateBox(this.size);
  19090. };
  19091. Box.prototype.copy = function (id) {
  19092. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19093. };
  19094. return Box;
  19095. })(_Primitive);
  19096. Primitives.Box = Box;
  19097. var Sphere = (function (_super) {
  19098. __extends(Sphere, _super);
  19099. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19100. this.segments = segments;
  19101. this.diameter = diameter;
  19102. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19103. }
  19104. Sphere.prototype._regenerateVertexData = function () {
  19105. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19106. };
  19107. Sphere.prototype.copy = function (id) {
  19108. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19109. };
  19110. return Sphere;
  19111. })(_Primitive);
  19112. Primitives.Sphere = Sphere;
  19113. var Cylinder = (function (_super) {
  19114. __extends(Cylinder, _super);
  19115. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19116. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19117. this.height = height;
  19118. this.diameterTop = diameterTop;
  19119. this.diameterBottom = diameterBottom;
  19120. this.tessellation = tessellation;
  19121. this.subdivisions = subdivisions;
  19122. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19123. }
  19124. Cylinder.prototype._regenerateVertexData = function () {
  19125. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19126. };
  19127. Cylinder.prototype.copy = function (id) {
  19128. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19129. };
  19130. return Cylinder;
  19131. })(_Primitive);
  19132. Primitives.Cylinder = Cylinder;
  19133. var Torus = (function (_super) {
  19134. __extends(Torus, _super);
  19135. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19136. this.diameter = diameter;
  19137. this.thickness = thickness;
  19138. this.tessellation = tessellation;
  19139. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19140. }
  19141. Torus.prototype._regenerateVertexData = function () {
  19142. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19143. };
  19144. Torus.prototype.copy = function (id) {
  19145. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19146. };
  19147. return Torus;
  19148. })(_Primitive);
  19149. Primitives.Torus = Torus;
  19150. var Ground = (function (_super) {
  19151. __extends(Ground, _super);
  19152. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19153. this.width = width;
  19154. this.height = height;
  19155. this.subdivisions = subdivisions;
  19156. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19157. }
  19158. Ground.prototype._regenerateVertexData = function () {
  19159. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19160. };
  19161. Ground.prototype.copy = function (id) {
  19162. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19163. };
  19164. return Ground;
  19165. })(_Primitive);
  19166. Primitives.Ground = Ground;
  19167. var TiledGround = (function (_super) {
  19168. __extends(TiledGround, _super);
  19169. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19170. this.xmin = xmin;
  19171. this.zmin = zmin;
  19172. this.xmax = xmax;
  19173. this.zmax = zmax;
  19174. this.subdivisions = subdivisions;
  19175. this.precision = precision;
  19176. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19177. }
  19178. TiledGround.prototype._regenerateVertexData = function () {
  19179. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19180. };
  19181. TiledGround.prototype.copy = function (id) {
  19182. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19183. };
  19184. return TiledGround;
  19185. })(_Primitive);
  19186. Primitives.TiledGround = TiledGround;
  19187. var Plane = (function (_super) {
  19188. __extends(Plane, _super);
  19189. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19190. this.size = size;
  19191. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19192. }
  19193. Plane.prototype._regenerateVertexData = function () {
  19194. return BABYLON.VertexData.CreatePlane(this.size);
  19195. };
  19196. Plane.prototype.copy = function (id) {
  19197. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19198. };
  19199. return Plane;
  19200. })(_Primitive);
  19201. Primitives.Plane = Plane;
  19202. var TorusKnot = (function (_super) {
  19203. __extends(TorusKnot, _super);
  19204. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19205. this.radius = radius;
  19206. this.tube = tube;
  19207. this.radialSegments = radialSegments;
  19208. this.tubularSegments = tubularSegments;
  19209. this.p = p;
  19210. this.q = q;
  19211. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19212. }
  19213. TorusKnot.prototype._regenerateVertexData = function () {
  19214. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19215. };
  19216. TorusKnot.prototype.copy = function (id) {
  19217. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19218. };
  19219. return TorusKnot;
  19220. })(_Primitive);
  19221. Primitives.TorusKnot = TorusKnot;
  19222. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19223. var Primitives = Geometry.Primitives;
  19224. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19225. var Geometry = BABYLON.Geometry;
  19226. })(BABYLON || (BABYLON = {}));
  19227. var __extends = this.__extends || function (d, b) {
  19228. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19229. function __() { this.constructor = d; }
  19230. __.prototype = b.prototype;
  19231. d.prototype = new __();
  19232. };
  19233. var BABYLON;
  19234. (function (BABYLON) {
  19235. var Gamepads = (function () {
  19236. function Gamepads(ongamedpadconnected) {
  19237. var _this = this;
  19238. this.babylonGamepads = [];
  19239. this.oneGamepadConnected = false;
  19240. this.isMonitoring = false;
  19241. this.gamepadEventSupported = 'GamepadEvent' in window;
  19242. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19243. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  19244. this._callbackGamepadConnected = ongamedpadconnected;
  19245. if (this.gamepadSupportAvailable) {
  19246. if (this.gamepadEventSupported) {
  19247. window.addEventListener('gamepadconnected', function (evt) {
  19248. _this._onGamepadConnected(evt);
  19249. }, false);
  19250. window.addEventListener('gamepaddisconnected', function (evt) {
  19251. _this._onGamepadDisconnected(evt);
  19252. }, false);
  19253. } else {
  19254. this._startMonitoringGamepads();
  19255. }
  19256. if (!this.oneGamepadConnected) {
  19257. this._insertGamepadDOMInstructions();
  19258. }
  19259. } else {
  19260. this._insertGamepadDOMNotSupported();
  19261. }
  19262. }
  19263. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19264. Gamepads.gamepadDOMInfo = document.createElement("div");
  19265. var buttonAImage = document.createElement("img");
  19266. buttonAImage.src = this.buttonADataURL;
  19267. var spanMessage = document.createElement("span");
  19268. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19269. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19270. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19271. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19272. Gamepads.gamepadDOMInfo.style.width = "100%";
  19273. Gamepads.gamepadDOMInfo.style.height = "48px";
  19274. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19275. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19276. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19277. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19278. buttonAImage.style.position = "relative";
  19279. buttonAImage.style.bottom = "8px";
  19280. spanMessage.style.position = "relative";
  19281. spanMessage.style.fontSize = "32px";
  19282. spanMessage.style.bottom = "32px";
  19283. spanMessage.style.color = "green";
  19284. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19285. };
  19286. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19287. Gamepads.gamepadDOMInfo = document.createElement("div");
  19288. var spanMessage = document.createElement("span");
  19289. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19290. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19291. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19292. Gamepads.gamepadDOMInfo.style.width = "100%";
  19293. Gamepads.gamepadDOMInfo.style.height = "40px";
  19294. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19295. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19296. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19297. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19298. spanMessage.style.position = "relative";
  19299. spanMessage.style.fontSize = "32px";
  19300. spanMessage.style.color = "red";
  19301. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19302. };
  19303. Gamepads.prototype.dispose = function () {
  19304. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19305. };
  19306. Gamepads.prototype._onGamepadConnected = function (evt) {
  19307. var newGamepad = this._addNewGamepad(evt.gamepad);
  19308. if (this._callbackGamepadConnected)
  19309. this._callbackGamepadConnected(newGamepad);
  19310. this._startMonitoringGamepads();
  19311. };
  19312. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19313. if (!this.oneGamepadConnected) {
  19314. this.oneGamepadConnected = true;
  19315. if (Gamepads.gamepadDOMInfo) {
  19316. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19317. Gamepads.gamepadDOMInfo = null;
  19318. }
  19319. }
  19320. var newGamepad;
  19321. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19322. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19323. } else {
  19324. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19325. }
  19326. this.babylonGamepads.push(newGamepad);
  19327. return newGamepad;
  19328. };
  19329. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19330. for (var i in this.babylonGamepads) {
  19331. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19332. this.babylonGamepads.splice(i, 1);
  19333. break;
  19334. }
  19335. }
  19336. if (this.babylonGamepads.length == 0) {
  19337. this._stopMonitoringGamepads();
  19338. }
  19339. };
  19340. Gamepads.prototype._startMonitoringGamepads = function () {
  19341. if (!this.isMonitoring) {
  19342. this.isMonitoring = true;
  19343. this._checkGamepadsStatus();
  19344. }
  19345. };
  19346. Gamepads.prototype._stopMonitoringGamepads = function () {
  19347. this.isMonitoring = false;
  19348. };
  19349. Gamepads.prototype._checkGamepadsStatus = function () {
  19350. var _this = this;
  19351. this._updateGamepadObjects();
  19352. for (var i in this.babylonGamepads) {
  19353. this.babylonGamepads[i].update();
  19354. }
  19355. if (this.isMonitoring) {
  19356. if (window.requestAnimationFrame) {
  19357. window.requestAnimationFrame(function () {
  19358. _this._checkGamepadsStatus();
  19359. });
  19360. } else if (window.mozRequestAnimationFrame) {
  19361. window.mozRequestAnimationFrame(function () {
  19362. _this._checkGamepadsStatus();
  19363. });
  19364. } else if (window.webkitRequestAnimationFrame) {
  19365. window.webkitRequestAnimationFrame(function () {
  19366. _this._checkGamepadsStatus();
  19367. });
  19368. }
  19369. }
  19370. };
  19371. Gamepads.prototype._updateGamepadObjects = function () {
  19372. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19373. for (var i = 0; i < gamepads.length; i++) {
  19374. if (gamepads[i]) {
  19375. if (!(gamepads[i].index in this.babylonGamepads)) {
  19376. var newGamepad = this._addNewGamepad(gamepads[i]);
  19377. if (this._callbackGamepadConnected) {
  19378. this._callbackGamepadConnected(newGamepad);
  19379. }
  19380. } else {
  19381. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19382. }
  19383. }
  19384. }
  19385. };
  19386. return Gamepads;
  19387. })();
  19388. BABYLON.Gamepads = Gamepads;
  19389. var StickValues = (function () {
  19390. function StickValues(x, y) {
  19391. this.x = x;
  19392. this.y = y;
  19393. }
  19394. return StickValues;
  19395. })();
  19396. BABYLON.StickValues = StickValues;
  19397. var Gamepad = (function () {
  19398. function Gamepad(id, index, browserGamepad) {
  19399. this.id = id;
  19400. this.index = index;
  19401. this.browserGamepad = browserGamepad;
  19402. if (this.browserGamepad.axes.length >= 2) {
  19403. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19404. }
  19405. if (this.browserGamepad.axes.length >= 4) {
  19406. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19407. }
  19408. }
  19409. Gamepad.prototype.onleftstickchanged = function (callback) {
  19410. this._onleftstickchanged = callback;
  19411. };
  19412. Gamepad.prototype.onrightstickchanged = function (callback) {
  19413. this._onrightstickchanged = callback;
  19414. };
  19415. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19416. get: function () {
  19417. return this._leftStick;
  19418. },
  19419. set: function (newValues) {
  19420. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19421. this._onleftstickchanged(newValues);
  19422. }
  19423. this._leftStick = newValues;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19429. get: function () {
  19430. return this._rightStick;
  19431. },
  19432. set: function (newValues) {
  19433. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19434. this._onrightstickchanged(newValues);
  19435. }
  19436. this._rightStick = newValues;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. Gamepad.prototype.update = function () {
  19442. if (this._leftStick) {
  19443. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19444. }
  19445. if (this._rightStick) {
  19446. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19447. }
  19448. };
  19449. return Gamepad;
  19450. })();
  19451. BABYLON.Gamepad = Gamepad;
  19452. var GenericPad = (function (_super) {
  19453. __extends(GenericPad, _super);
  19454. function GenericPad(id, index, gamepad) {
  19455. _super.call(this, id, index, gamepad);
  19456. this.id = id;
  19457. this.index = index;
  19458. this.gamepad = gamepad;
  19459. this._buttons = new Array(gamepad.buttons.length);
  19460. }
  19461. GenericPad.prototype.onbuttondown = function (callback) {
  19462. this._onbuttondown = callback;
  19463. };
  19464. GenericPad.prototype.onbuttonup = function (callback) {
  19465. this._onbuttonup = callback;
  19466. };
  19467. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19468. if (newValue !== currentValue) {
  19469. if (this._onbuttondown && newValue === 1) {
  19470. this._onbuttondown(buttonIndex);
  19471. }
  19472. if (this._onbuttonup && newValue === 0) {
  19473. this._onbuttonup(buttonIndex);
  19474. }
  19475. }
  19476. return newValue;
  19477. };
  19478. GenericPad.prototype.update = function () {
  19479. _super.prototype.update.call(this);
  19480. for (var index = 0; index < this._buttons.length; index++) {
  19481. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19482. }
  19483. };
  19484. return GenericPad;
  19485. })(Gamepad);
  19486. BABYLON.GenericPad = GenericPad;
  19487. (function (Xbox360Button) {
  19488. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19489. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19490. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19491. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19492. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19493. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19494. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19495. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19496. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19497. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19498. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19499. var Xbox360Button = BABYLON.Xbox360Button;
  19500. (function (Xbox360Dpad) {
  19501. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19502. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19503. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19504. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19505. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19506. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19507. var Xbox360Pad = (function (_super) {
  19508. __extends(Xbox360Pad, _super);
  19509. function Xbox360Pad() {
  19510. _super.apply(this, arguments);
  19511. this._leftTrigger = 0;
  19512. this._rightTrigger = 0;
  19513. this._buttonA = 0;
  19514. this._buttonB = 0;
  19515. this._buttonX = 0;
  19516. this._buttonY = 0;
  19517. this._buttonBack = 0;
  19518. this._buttonStart = 0;
  19519. this._buttonLB = 0;
  19520. this._buttonRB = 0;
  19521. this._buttonLeftStick = 0;
  19522. this._buttonRightStick = 0;
  19523. this._dPadUp = 0;
  19524. this._dPadDown = 0;
  19525. this._dPadLeft = 0;
  19526. this._dPadRight = 0;
  19527. }
  19528. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19529. this._onlefttriggerchanged = callback;
  19530. };
  19531. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19532. this._onrighttriggerchanged = callback;
  19533. };
  19534. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19535. get: function () {
  19536. return this._leftTrigger;
  19537. },
  19538. set: function (newValue) {
  19539. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19540. this._onlefttriggerchanged(newValue);
  19541. }
  19542. this._leftTrigger = newValue;
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19548. get: function () {
  19549. return this._rightTrigger;
  19550. },
  19551. set: function (newValue) {
  19552. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19553. this._onrighttriggerchanged(newValue);
  19554. }
  19555. this._rightTrigger = newValue;
  19556. },
  19557. enumerable: true,
  19558. configurable: true
  19559. });
  19560. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19561. this._onbuttondown = callback;
  19562. };
  19563. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19564. this._onbuttonup = callback;
  19565. };
  19566. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19567. this._ondpaddown = callback;
  19568. };
  19569. Xbox360Pad.prototype.ondpadup = function (callback) {
  19570. this._ondpadup = callback;
  19571. };
  19572. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19573. if (newValue !== currentValue) {
  19574. if (this._onbuttondown && newValue === 1) {
  19575. this._onbuttondown(buttonType);
  19576. }
  19577. if (this._onbuttonup && newValue === 0) {
  19578. this._onbuttonup(buttonType);
  19579. }
  19580. }
  19581. return newValue;
  19582. };
  19583. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19584. if (newValue !== currentValue) {
  19585. if (this._ondpaddown && newValue === 1) {
  19586. this._ondpaddown(buttonType);
  19587. }
  19588. if (this._ondpadup && newValue === 0) {
  19589. this._ondpadup(buttonType);
  19590. }
  19591. }
  19592. return newValue;
  19593. };
  19594. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19595. get: function () {
  19596. return this._buttonA;
  19597. },
  19598. set: function (value) {
  19599. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19605. get: function () {
  19606. return this._buttonB;
  19607. },
  19608. set: function (value) {
  19609. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19615. get: function () {
  19616. return this._buttonX;
  19617. },
  19618. set: function (value) {
  19619. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19620. },
  19621. enumerable: true,
  19622. configurable: true
  19623. });
  19624. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19625. get: function () {
  19626. return this._buttonY;
  19627. },
  19628. set: function (value) {
  19629. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19635. get: function () {
  19636. return this._buttonStart;
  19637. },
  19638. set: function (value) {
  19639. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19640. },
  19641. enumerable: true,
  19642. configurable: true
  19643. });
  19644. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19645. get: function () {
  19646. return this._buttonBack;
  19647. },
  19648. set: function (value) {
  19649. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19655. get: function () {
  19656. return this._buttonLB;
  19657. },
  19658. set: function (value) {
  19659. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19665. get: function () {
  19666. return this._buttonRB;
  19667. },
  19668. set: function (value) {
  19669. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19670. },
  19671. enumerable: true,
  19672. configurable: true
  19673. });
  19674. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19675. get: function () {
  19676. return this._buttonLeftStick;
  19677. },
  19678. set: function (value) {
  19679. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19685. get: function () {
  19686. return this._buttonRightStick;
  19687. },
  19688. set: function (value) {
  19689. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19695. get: function () {
  19696. return this._dPadUp;
  19697. },
  19698. set: function (value) {
  19699. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19700. },
  19701. enumerable: true,
  19702. configurable: true
  19703. });
  19704. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19705. get: function () {
  19706. return this._dPadDown;
  19707. },
  19708. set: function (value) {
  19709. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19715. get: function () {
  19716. return this._dPadLeft;
  19717. },
  19718. set: function (value) {
  19719. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19725. get: function () {
  19726. return this._dPadRight;
  19727. },
  19728. set: function (value) {
  19729. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Xbox360Pad.prototype.update = function () {
  19735. _super.prototype.update.call(this);
  19736. this.buttonA = this.browserGamepad.buttons[0].value;
  19737. this.buttonB = this.browserGamepad.buttons[1].value;
  19738. this.buttonX = this.browserGamepad.buttons[2].value;
  19739. this.buttonY = this.browserGamepad.buttons[3].value;
  19740. this.buttonLB = this.browserGamepad.buttons[4].value;
  19741. this.buttonRB = this.browserGamepad.buttons[5].value;
  19742. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19743. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19744. this.buttonBack = this.browserGamepad.buttons[8].value;
  19745. this.buttonStart = this.browserGamepad.buttons[9].value;
  19746. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19747. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19748. this.dPadUp = this.browserGamepad.buttons[12].value;
  19749. this.dPadDown = this.browserGamepad.buttons[13].value;
  19750. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19751. this.dPadRight = this.browserGamepad.buttons[15].value;
  19752. };
  19753. return Xbox360Pad;
  19754. })(Gamepad);
  19755. BABYLON.Xbox360Pad = Xbox360Pad;
  19756. })(BABYLON || (BABYLON = {}));
  19757. var __extends = this.__extends || function (d, b) {
  19758. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19759. function __() { this.constructor = d; }
  19760. __.prototype = b.prototype;
  19761. d.prototype = new __();
  19762. };
  19763. var BABYLON;
  19764. (function (BABYLON) {
  19765. var GamepadCamera = (function (_super) {
  19766. __extends(GamepadCamera, _super);
  19767. function GamepadCamera(name, position, scene) {
  19768. var _this = this;
  19769. _super.call(this, name, position, scene);
  19770. this.angularSensibility = 200;
  19771. this.moveSensibility = 75;
  19772. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19773. _this._onNewGameConnected(gamepad);
  19774. });
  19775. }
  19776. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19777. if (gamepad.index === 0) {
  19778. this._gamepad = gamepad;
  19779. }
  19780. };
  19781. GamepadCamera.prototype._checkInputs = function () {
  19782. if (!this._gamepad) {
  19783. return;
  19784. }
  19785. var LSValues = this._gamepad.leftStick;
  19786. var normalizedLX = LSValues.x / this.moveSensibility;
  19787. var normalizedLY = LSValues.y / this.moveSensibility;
  19788. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19789. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19790. var RSValues = this._gamepad.rightStick;
  19791. var normalizedRX = RSValues.x / this.angularSensibility;
  19792. var normalizedRY = RSValues.y / this.angularSensibility;
  19793. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19794. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19795. ;
  19796. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19797. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19798. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19799. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19800. };
  19801. GamepadCamera.prototype.dispose = function () {
  19802. this._gamepads.dispose();
  19803. _super.prototype.dispose.call(this);
  19804. };
  19805. return GamepadCamera;
  19806. })(BABYLON.FreeCamera);
  19807. BABYLON.GamepadCamera = GamepadCamera;
  19808. })(BABYLON || (BABYLON = {}));
  19809. var __extends = this.__extends || function (d, b) {
  19810. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19811. function __() { this.constructor = d; }
  19812. __.prototype = b.prototype;
  19813. d.prototype = new __();
  19814. };
  19815. var BABYLON;
  19816. (function (BABYLON) {
  19817. var LinesMesh = (function (_super) {
  19818. __extends(LinesMesh, _super);
  19819. function LinesMesh(name, scene, updatable) {
  19820. if (typeof updatable === "undefined") { updatable = false; }
  19821. _super.call(this, name, scene);
  19822. this.color = new BABYLON.Color3(1, 1, 1);
  19823. this.alpha = 1;
  19824. this._indices = new Array();
  19825. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19826. attributes: ["position"],
  19827. uniforms: ["worldViewProjection", "color"],
  19828. needAlphaBlending: true
  19829. });
  19830. }
  19831. Object.defineProperty(LinesMesh.prototype, "material", {
  19832. get: function () {
  19833. return this._colorShader;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19839. get: function () {
  19840. return false;
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19846. get: function () {
  19847. return false;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19853. var engine = this.getScene().getEngine();
  19854. var indexToBind = this._geometry.getIndexBuffer();
  19855. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19856. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19857. };
  19858. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19859. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19860. return;
  19861. }
  19862. var engine = this.getScene().getEngine();
  19863. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19864. };
  19865. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19866. return null;
  19867. };
  19868. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19869. this._colorShader.dispose();
  19870. _super.prototype.dispose.call(this, doNotRecurse);
  19871. };
  19872. return LinesMesh;
  19873. })(BABYLON.Mesh);
  19874. BABYLON.LinesMesh = LinesMesh;
  19875. })(BABYLON || (BABYLON = {}));
  19876. var BABYLON;
  19877. (function (BABYLON) {
  19878. var OutlineRenderer = (function () {
  19879. function OutlineRenderer(scene) {
  19880. this._scene = scene;
  19881. }
  19882. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19883. var scene = this._scene;
  19884. var engine = this._scene.getEngine();
  19885. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19886. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19887. return;
  19888. }
  19889. var mesh = subMesh.getRenderingMesh();
  19890. var material = subMesh.getMaterial();
  19891. engine.enableEffect(this._effect);
  19892. this._effect.setFloat("offset", mesh.outlineWidth);
  19893. this._effect.setColor3("color", mesh.outlineColor);
  19894. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19895. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19896. if (useBones) {
  19897. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19898. }
  19899. mesh._bind(subMesh, this._effect, false);
  19900. if (material && material.needAlphaTesting()) {
  19901. var alphaTexture = material.getAlphaTestTexture();
  19902. this._effect.setTexture("diffuseSampler", alphaTexture);
  19903. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19904. }
  19905. if (hardwareInstancedRendering) {
  19906. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19907. } else {
  19908. if (batch.renderSelf[subMesh._id]) {
  19909. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19910. mesh._draw(subMesh, true);
  19911. }
  19912. if (batch.visibleInstances[subMesh._id]) {
  19913. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19914. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19915. this._effect.setMatrix("world", instance.getWorldMatrix());
  19916. mesh._draw(subMesh, true);
  19917. }
  19918. }
  19919. }
  19920. };
  19921. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19922. var defines = [];
  19923. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19924. var mesh = subMesh.getMesh();
  19925. var material = subMesh.getMaterial();
  19926. if (material && material.needAlphaTesting()) {
  19927. defines.push("#define ALPHATEST");
  19928. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19929. attribs.push(BABYLON.VertexBuffer.UVKind);
  19930. defines.push("#define UV1");
  19931. }
  19932. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19933. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19934. defines.push("#define UV2");
  19935. }
  19936. }
  19937. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19940. defines.push("#define BONES");
  19941. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19942. }
  19943. if (useInstances) {
  19944. defines.push("#define INSTANCES");
  19945. attribs.push("world0");
  19946. attribs.push("world1");
  19947. attribs.push("world2");
  19948. attribs.push("world3");
  19949. }
  19950. var join = defines.join("\n");
  19951. if (this._cachedDefines != join) {
  19952. this._cachedDefines = join;
  19953. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19954. }
  19955. return this._effect.isReady();
  19956. };
  19957. return OutlineRenderer;
  19958. })();
  19959. BABYLON.OutlineRenderer = OutlineRenderer;
  19960. })(BABYLON || (BABYLON = {}));
  19961. var BABYLON;
  19962. (function (BABYLON) {
  19963. var MeshAssetTask = (function () {
  19964. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19965. this.name = name;
  19966. this.meshesNames = meshesNames;
  19967. this.rootUrl = rootUrl;
  19968. this.sceneFilename = sceneFilename;
  19969. this.isCompleted = false;
  19970. }
  19971. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19972. var _this = this;
  19973. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19974. _this.loadedMeshes = meshes;
  19975. _this.loadedParticleSystems = particleSystems;
  19976. _this.loadedSkeletons = skeletons;
  19977. _this.isCompleted = true;
  19978. if (_this.onSuccess) {
  19979. _this.onSuccess(_this);
  19980. }
  19981. onSuccess();
  19982. }, null, function () {
  19983. if (_this.onError) {
  19984. _this.onError(_this);
  19985. }
  19986. onError();
  19987. });
  19988. };
  19989. return MeshAssetTask;
  19990. })();
  19991. BABYLON.MeshAssetTask = MeshAssetTask;
  19992. var TextFileAssetTask = (function () {
  19993. function TextFileAssetTask(name, url) {
  19994. this.name = name;
  19995. this.url = url;
  19996. this.isCompleted = false;
  19997. }
  19998. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19999. var _this = this;
  20000. BABYLON.Tools.LoadFile(this.url, function (data) {
  20001. _this.text = data;
  20002. _this.isCompleted = true;
  20003. if (_this.onSuccess) {
  20004. _this.onSuccess(_this);
  20005. }
  20006. onSuccess();
  20007. }, null, scene.database, false, function () {
  20008. if (_this.onError) {
  20009. _this.onError(_this);
  20010. }
  20011. onError();
  20012. });
  20013. };
  20014. return TextFileAssetTask;
  20015. })();
  20016. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20017. var BinaryFileAssetTask = (function () {
  20018. function BinaryFileAssetTask(name, url) {
  20019. this.name = name;
  20020. this.url = url;
  20021. this.isCompleted = false;
  20022. }
  20023. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20024. var _this = this;
  20025. BABYLON.Tools.LoadFile(this.url, function (data) {
  20026. _this.data = data;
  20027. _this.isCompleted = true;
  20028. if (_this.onSuccess) {
  20029. _this.onSuccess(_this);
  20030. }
  20031. onSuccess();
  20032. }, null, scene.database, true, function () {
  20033. if (_this.onError) {
  20034. _this.onError(_this);
  20035. }
  20036. onError();
  20037. });
  20038. };
  20039. return BinaryFileAssetTask;
  20040. })();
  20041. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20042. var ImageAssetTask = (function () {
  20043. function ImageAssetTask(name, url) {
  20044. this.name = name;
  20045. this.url = url;
  20046. this.isCompleted = false;
  20047. }
  20048. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20049. var _this = this;
  20050. var img = new Image();
  20051. img.onload = function () {
  20052. _this.image = img;
  20053. _this.isCompleted = true;
  20054. if (_this.onSuccess) {
  20055. _this.onSuccess(_this);
  20056. }
  20057. onSuccess();
  20058. };
  20059. img.onerror = function () {
  20060. if (_this.onError) {
  20061. _this.onError(_this);
  20062. }
  20063. onError();
  20064. };
  20065. img.src = this.url;
  20066. };
  20067. return ImageAssetTask;
  20068. })();
  20069. BABYLON.ImageAssetTask = ImageAssetTask;
  20070. var AssetsManager = (function () {
  20071. function AssetsManager(scene) {
  20072. this._tasks = new Array();
  20073. this._waitingTasksCount = 0;
  20074. this.useDefaultLoadingScreen = true;
  20075. this._scene = scene;
  20076. }
  20077. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20078. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20079. this._tasks.push(task);
  20080. return task;
  20081. };
  20082. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20083. var task = new TextFileAssetTask(taskName, url);
  20084. this._tasks.push(task);
  20085. return task;
  20086. };
  20087. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20088. var task = new BinaryFileAssetTask(taskName, url);
  20089. this._tasks.push(task);
  20090. return task;
  20091. };
  20092. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20093. var task = new ImageAssetTask(taskName, url);
  20094. this._tasks.push(task);
  20095. return task;
  20096. };
  20097. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20098. this._waitingTasksCount--;
  20099. if (this._waitingTasksCount === 0) {
  20100. if (this.onFinish) {
  20101. this.onFinish(this._tasks);
  20102. }
  20103. this._scene.getEngine().hideLoadingUI();
  20104. }
  20105. };
  20106. AssetsManager.prototype._runTask = function (task) {
  20107. var _this = this;
  20108. task.run(this._scene, function () {
  20109. if (_this.onTaskSuccess) {
  20110. _this.onTaskSuccess(task);
  20111. }
  20112. _this._decreaseWaitingTasksCount();
  20113. }, function () {
  20114. if (_this.onTaskError) {
  20115. _this.onTaskError(task);
  20116. }
  20117. _this._decreaseWaitingTasksCount();
  20118. });
  20119. };
  20120. AssetsManager.prototype.reset = function () {
  20121. this._tasks = new Array();
  20122. return this;
  20123. };
  20124. AssetsManager.prototype.load = function () {
  20125. this._waitingTasksCount = this._tasks.length;
  20126. if (this._waitingTasksCount === 0) {
  20127. if (this.onFinish) {
  20128. this.onFinish(this._tasks);
  20129. }
  20130. return this;
  20131. }
  20132. if (this.useDefaultLoadingScreen) {
  20133. this._scene.getEngine().displayLoadingUI();
  20134. }
  20135. for (var index = 0; index < this._tasks.length; index++) {
  20136. var task = this._tasks[index];
  20137. this._runTask(task);
  20138. }
  20139. return this;
  20140. };
  20141. return AssetsManager;
  20142. })();
  20143. BABYLON.AssetsManager = AssetsManager;
  20144. })(BABYLON || (BABYLON = {}));