babylon.1.14-beta-debug.js 1011 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501
  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.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2958. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2959. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2960. var shaderProgram = this._gl.createProgram();
  2961. this._gl.attachShader(shaderProgram, vertexShader);
  2962. this._gl.attachShader(shaderProgram, fragmentShader);
  2963. this._gl.linkProgram(shaderProgram);
  2964. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2965. if (!linked) {
  2966. var error = this._gl.getProgramInfoLog(shaderProgram);
  2967. if (error) {
  2968. throw new Error(error);
  2969. }
  2970. }
  2971. this._gl.deleteShader(vertexShader);
  2972. this._gl.deleteShader(fragmentShader);
  2973. return shaderProgram;
  2974. };
  2975. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2976. var results = [];
  2977. for (var index = 0; index < uniformsNames.length; index++) {
  2978. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2979. }
  2980. return results;
  2981. };
  2982. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  2983. var results = [];
  2984. for (var index = 0; index < attributesNames.length; index++) {
  2985. try {
  2986. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2987. } catch (e) {
  2988. results.push(-1);
  2989. }
  2990. }
  2991. return results;
  2992. };
  2993. Engine.prototype.enableEffect = function (effect) {
  2994. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  2995. return;
  2996. }
  2997. this._vertexAttribArrays = this._vertexAttribArrays || [];
  2998. this._gl.useProgram(effect.getProgram());
  2999. for (var i in this._vertexAttribArrays) {
  3000. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3001. continue;
  3002. }
  3003. this._vertexAttribArrays[i] = false;
  3004. this._gl.disableVertexAttribArray(i);
  3005. }
  3006. var attributesCount = effect.getAttributesCount();
  3007. for (var index = 0; index < attributesCount; index++) {
  3008. var order = effect.getAttributeLocation(index);
  3009. if (order >= 0) {
  3010. this._vertexAttribArrays[order] = true;
  3011. this._gl.enableVertexAttribArray(order);
  3012. }
  3013. }
  3014. this._currentEffect = effect;
  3015. };
  3016. Engine.prototype.setArray = function (uniform, array) {
  3017. if (!uniform)
  3018. return;
  3019. this._gl.uniform1fv(uniform, array);
  3020. };
  3021. Engine.prototype.setMatrices = function (uniform, matrices) {
  3022. if (!uniform)
  3023. return;
  3024. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3025. };
  3026. Engine.prototype.setMatrix = function (uniform, matrix) {
  3027. if (!uniform)
  3028. return;
  3029. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3030. };
  3031. Engine.prototype.setFloat = function (uniform, value) {
  3032. if (!uniform)
  3033. return;
  3034. this._gl.uniform1f(uniform, value);
  3035. };
  3036. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3037. if (!uniform)
  3038. return;
  3039. this._gl.uniform2f(uniform, x, y);
  3040. };
  3041. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3042. if (!uniform)
  3043. return;
  3044. this._gl.uniform3f(uniform, x, y, z);
  3045. };
  3046. Engine.prototype.setBool = function (uniform, bool) {
  3047. if (!uniform)
  3048. return;
  3049. this._gl.uniform1i(uniform, bool);
  3050. };
  3051. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3052. if (!uniform)
  3053. return;
  3054. this._gl.uniform4f(uniform, x, y, z, w);
  3055. };
  3056. Engine.prototype.setColor3 = function (uniform, color3) {
  3057. if (!uniform)
  3058. return;
  3059. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3060. };
  3061. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3062. if (!uniform)
  3063. return;
  3064. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3065. };
  3066. Engine.prototype.setState = function (culling, force) {
  3067. if (this._depthCullingState.cull !== culling || force) {
  3068. if (culling) {
  3069. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3070. this._depthCullingState.cull = true;
  3071. } else {
  3072. this._depthCullingState.cull = false;
  3073. }
  3074. }
  3075. };
  3076. Engine.prototype.setDepthBuffer = function (enable) {
  3077. this._depthCullingState.depthTest = enable;
  3078. };
  3079. Engine.prototype.getDepthWrite = function () {
  3080. return this._depthCullingState.depthMask;
  3081. };
  3082. Engine.prototype.setDepthWrite = function (enable) {
  3083. this._depthCullingState.depthMask = enable;
  3084. };
  3085. Engine.prototype.setColorWrite = function (enable) {
  3086. this._gl.colorMask(enable, enable, enable, enable);
  3087. };
  3088. Engine.prototype.setAlphaMode = function (mode) {
  3089. switch (mode) {
  3090. case BABYLON.Engine.ALPHA_DISABLE:
  3091. this.setDepthWrite(true);
  3092. this._alphaState.alphaBlend = false;
  3093. break;
  3094. case BABYLON.Engine.ALPHA_COMBINE:
  3095. this.setDepthWrite(false);
  3096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3097. this._alphaState.alphaBlend = true;
  3098. break;
  3099. case BABYLON.Engine.ALPHA_ADD:
  3100. this.setDepthWrite(false);
  3101. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3102. this._alphaState.alphaBlend = true;
  3103. break;
  3104. }
  3105. };
  3106. Engine.prototype.setAlphaTesting = function (enable) {
  3107. this._alphaTest = enable;
  3108. };
  3109. Engine.prototype.getAlphaTesting = function () {
  3110. return this._alphaTest;
  3111. };
  3112. Engine.prototype.wipeCaches = function () {
  3113. this._activeTexturesCache = [];
  3114. this._currentEffect = null;
  3115. this._depthCullingState.reset();
  3116. this._alphaState.reset();
  3117. this._cachedVertexBuffers = null;
  3118. this._cachedIndexBuffer = null;
  3119. this._cachedEffectForVertexBuffers = null;
  3120. };
  3121. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3122. var gl = this._gl;
  3123. gl.bindTexture(gl.TEXTURE_2D, texture);
  3124. var magFilter = gl.NEAREST;
  3125. var minFilter = gl.NEAREST;
  3126. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3127. magFilter = gl.LINEAR;
  3128. minFilter = gl.LINEAR;
  3129. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3130. magFilter = gl.LINEAR;
  3131. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3132. }
  3133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3135. gl.bindTexture(gl.TEXTURE_2D, null);
  3136. };
  3137. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  3138. var _this = this;
  3139. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3140. var texture = this._gl.createTexture();
  3141. var extension = url.substr(url.length - 4, 4).toLowerCase();
  3142. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3143. var isTGA = (extension === ".tga");
  3144. scene._addPendingData(texture);
  3145. texture.url = url;
  3146. texture.noMipmap = noMipmap;
  3147. texture.references = 1;
  3148. this._loadedTexturesCache.push(texture);
  3149. if (isTGA) {
  3150. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3151. var data = new Uint8Array(arrayBuffer);
  3152. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3153. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3154. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3155. }, samplingMode);
  3156. }, null, scene.database, true);
  3157. } else if (isDDS) {
  3158. BABYLON.Tools.LoadFile(url, function (data) {
  3159. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3160. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3161. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3162. console.log("loading " + url);
  3163. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3164. }, samplingMode);
  3165. }, null, scene.database, true);
  3166. } else {
  3167. var onload = function (img) {
  3168. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3169. var isPot = (img.width == potWidth && img.height == potHeight);
  3170. if (!isPot) {
  3171. _this._workingCanvas.width = potWidth;
  3172. _this._workingCanvas.height = potHeight;
  3173. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3174. }
  3175. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3176. }, samplingMode);
  3177. };
  3178. var onerror = function () {
  3179. scene._removePendingData(texture);
  3180. };
  3181. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3182. }
  3183. return texture;
  3184. };
  3185. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3186. var texture = this._gl.createTexture();
  3187. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  3188. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  3189. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3190. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3191. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3193. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3194. this._activeTexturesCache = [];
  3195. texture._baseWidth = width;
  3196. texture._baseHeight = height;
  3197. texture._width = width;
  3198. texture._height = height;
  3199. texture.isReady = false;
  3200. texture.generateMipMaps = generateMipMaps;
  3201. texture.references = 1;
  3202. this._loadedTexturesCache.push(texture);
  3203. return texture;
  3204. };
  3205. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3206. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3207. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3208. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3209. if (texture.generateMipMaps) {
  3210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3211. }
  3212. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3213. this._activeTexturesCache = [];
  3214. texture.isReady = true;
  3215. };
  3216. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3217. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3219. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3220. if (!texture._workingCanvas) {
  3221. texture._workingCanvas = document.createElement("canvas");
  3222. texture._workingContext = texture._workingCanvas.getContext("2d");
  3223. texture._workingCanvas.width = texture._width;
  3224. texture._workingCanvas.height = texture._height;
  3225. }
  3226. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3227. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3228. } else {
  3229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3230. }
  3231. if (texture.generateMipMaps) {
  3232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3233. }
  3234. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3235. this._activeTexturesCache = [];
  3236. texture.isReady = true;
  3237. };
  3238. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3239. var generateMipMaps = false;
  3240. var generateDepthBuffer = true;
  3241. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3242. if (options !== undefined) {
  3243. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3244. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3245. if (options.samplingMode !== undefined) {
  3246. samplingMode = options.samplingMode;
  3247. }
  3248. }
  3249. var gl = this._gl;
  3250. var texture = gl.createTexture();
  3251. gl.bindTexture(gl.TEXTURE_2D, texture);
  3252. var width = size.width || size;
  3253. var height = size.height || size;
  3254. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3259. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3260. var depthBuffer;
  3261. if (generateDepthBuffer) {
  3262. depthBuffer = gl.createRenderbuffer();
  3263. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3264. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3265. }
  3266. var framebuffer = gl.createFramebuffer();
  3267. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3268. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3269. if (generateDepthBuffer) {
  3270. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3271. }
  3272. gl.bindTexture(gl.TEXTURE_2D, null);
  3273. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3274. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3275. texture._framebuffer = framebuffer;
  3276. if (generateDepthBuffer) {
  3277. texture._depthBuffer = depthBuffer;
  3278. }
  3279. texture._width = width;
  3280. texture._height = height;
  3281. texture.isReady = true;
  3282. texture.generateMipMaps = generateMipMaps;
  3283. texture.references = 1;
  3284. this._activeTexturesCache = [];
  3285. this._loadedTexturesCache.push(texture);
  3286. return texture;
  3287. };
  3288. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3289. var _this = this;
  3290. var gl = this._gl;
  3291. var texture = gl.createTexture();
  3292. texture.isCube = true;
  3293. texture.url = rootUrl;
  3294. texture.references = 1;
  3295. this._loadedTexturesCache.push(texture);
  3296. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3297. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3298. if (isDDS) {
  3299. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3300. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3301. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3302. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3303. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3304. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3305. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3306. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3307. }
  3308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3309. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3310. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3312. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3313. _this._activeTexturesCache = [];
  3314. texture._width = info.width;
  3315. texture._height = info.height;
  3316. texture.isReady = true;
  3317. }, null, null, true);
  3318. } else {
  3319. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3320. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3321. var height = width;
  3322. _this._workingCanvas.width = width;
  3323. _this._workingCanvas.height = height;
  3324. var faces = [
  3325. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3326. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3327. ];
  3328. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3329. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3330. for (var index = 0; index < faces.length; index++) {
  3331. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3332. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3333. }
  3334. if (!noMipmap) {
  3335. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3336. }
  3337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3339. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3340. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3341. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3342. _this._activeTexturesCache = [];
  3343. texture._width = width;
  3344. texture._height = height;
  3345. texture.isReady = true;
  3346. }, extensions);
  3347. }
  3348. return texture;
  3349. };
  3350. Engine.prototype._releaseTexture = function (texture) {
  3351. var gl = this._gl;
  3352. if (texture._framebuffer) {
  3353. gl.deleteFramebuffer(texture._framebuffer);
  3354. }
  3355. if (texture._depthBuffer) {
  3356. gl.deleteRenderbuffer(texture._depthBuffer);
  3357. }
  3358. gl.deleteTexture(texture);
  3359. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3360. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3361. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3362. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3363. this._activeTexturesCache[channel] = null;
  3364. }
  3365. var index = this._loadedTexturesCache.indexOf(texture);
  3366. if (index !== -1) {
  3367. this._loadedTexturesCache.splice(index, 1);
  3368. }
  3369. };
  3370. Engine.prototype.bindSamplers = function (effect) {
  3371. this._gl.useProgram(effect.getProgram());
  3372. var samplers = effect.getSamplers();
  3373. for (var index = 0; index < samplers.length; index++) {
  3374. var uniform = effect.getUniform(samplers[index]);
  3375. this._gl.uniform1i(uniform, index);
  3376. }
  3377. this._currentEffect = null;
  3378. };
  3379. Engine.prototype._bindTexture = function (channel, texture) {
  3380. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3381. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3382. this._activeTexturesCache[channel] = null;
  3383. };
  3384. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3385. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3386. };
  3387. Engine.prototype.setTexture = function (channel, texture) {
  3388. if (channel < 0) {
  3389. return;
  3390. }
  3391. if (!texture || !texture.isReady()) {
  3392. if (this._activeTexturesCache[channel] != null) {
  3393. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3394. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3395. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3396. this._activeTexturesCache[channel] = null;
  3397. }
  3398. return;
  3399. }
  3400. if (texture instanceof BABYLON.VideoTexture) {
  3401. if (texture.update()) {
  3402. this._activeTexturesCache[channel] = null;
  3403. }
  3404. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3405. texture.delayLoad();
  3406. return;
  3407. }
  3408. if (this._activeTexturesCache[channel] == texture) {
  3409. return;
  3410. }
  3411. this._activeTexturesCache[channel] = texture;
  3412. var internalTexture = texture.getInternalTexture();
  3413. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3414. if (internalTexture.isCube) {
  3415. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3416. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3417. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3418. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3419. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3420. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3421. }
  3422. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3423. } else {
  3424. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3425. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3426. internalTexture._cachedWrapU = texture.wrapU;
  3427. switch (texture.wrapU) {
  3428. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3429. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3430. break;
  3431. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3432. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3433. break;
  3434. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3435. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3436. break;
  3437. }
  3438. }
  3439. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3440. internalTexture._cachedWrapV = texture.wrapV;
  3441. switch (texture.wrapV) {
  3442. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3443. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3444. break;
  3445. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3446. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3447. break;
  3448. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3449. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3450. break;
  3451. }
  3452. }
  3453. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3454. }
  3455. };
  3456. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3457. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3458. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3459. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3460. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3461. }
  3462. };
  3463. Engine.prototype.readPixels = function (x, y, width, height) {
  3464. var data = new Uint8Array(height * width * 4);
  3465. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3466. return data;
  3467. };
  3468. Engine.prototype.dispose = function () {
  3469. this.hideLoadingUI();
  3470. this.stopRenderLoop();
  3471. while (this.scenes.length) {
  3472. this.scenes[0].dispose();
  3473. }
  3474. for (var name in this._compiledEffects) {
  3475. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3476. }
  3477. for (var i in this._vertexAttribArrays) {
  3478. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3479. continue;
  3480. }
  3481. this._gl.disableVertexAttribArray(i);
  3482. }
  3483. window.removeEventListener("blur", this._onBlur);
  3484. window.removeEventListener("focus", this._onFocus);
  3485. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3486. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3487. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3488. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3489. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3490. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3491. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3492. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3493. };
  3494. Engine.prototype.displayLoadingUI = function () {
  3495. var _this = this;
  3496. this._loadingDiv = document.createElement("div");
  3497. this._loadingDiv.style.opacity = "0";
  3498. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3499. this._loadingTextDiv = document.createElement("div");
  3500. this._loadingTextDiv.style.position = "absolute";
  3501. this._loadingTextDiv.style.left = "0";
  3502. this._loadingTextDiv.style.top = "50%";
  3503. this._loadingTextDiv.style.marginTop = "80px";
  3504. this._loadingTextDiv.style.width = "100%";
  3505. this._loadingTextDiv.style.height = "20px";
  3506. this._loadingTextDiv.style.fontFamily = "Arial";
  3507. this._loadingTextDiv.style.fontSize = "14px";
  3508. this._loadingTextDiv.style.color = "white";
  3509. this._loadingTextDiv.style.textAlign = "center";
  3510. this._loadingTextDiv.innerHTML = "Loading";
  3511. this._loadingDiv.appendChild(this._loadingTextDiv);
  3512. var imgBack = new Image();
  3513. 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==";
  3514. imgBack.style.position = "absolute";
  3515. imgBack.style.left = "50%";
  3516. imgBack.style.top = "50%";
  3517. imgBack.style.marginLeft = "-50px";
  3518. imgBack.style.marginTop = "-50px";
  3519. imgBack.style.transition = "transform 1.0s ease";
  3520. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3521. var deg = 360;
  3522. var onTransitionEnd = function () {
  3523. deg += 360;
  3524. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3525. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3526. };
  3527. imgBack.addEventListener("transitionend", onTransitionEnd);
  3528. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3529. this._loadingDiv.appendChild(imgBack);
  3530. var imgFront = new Image();
  3531. 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=";
  3532. imgFront.style.position = "absolute";
  3533. imgFront.style.left = "50%";
  3534. imgFront.style.top = "50%";
  3535. imgFront.style.marginLeft = "-50px";
  3536. imgFront.style.marginTop = "-50px";
  3537. this._loadingDiv.appendChild(imgFront);
  3538. this._resizeLoadingUI = function () {
  3539. var canvasRect = _this.getRenderingCanvasClientRect();
  3540. _this._loadingDiv.style.position = "absolute";
  3541. _this._loadingDiv.style.left = canvasRect.left + "px";
  3542. _this._loadingDiv.style.top = canvasRect.top + "px";
  3543. _this._loadingDiv.style.width = canvasRect.width + "px";
  3544. _this._loadingDiv.style.height = canvasRect.height + "px";
  3545. };
  3546. this._resizeLoadingUI();
  3547. window.addEventListener("resize", this._resizeLoadingUI);
  3548. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3549. document.body.appendChild(this._loadingDiv);
  3550. setTimeout(function () {
  3551. _this._loadingDiv.style.opacity = "1";
  3552. imgBack.style.transform = "rotateZ(360deg)";
  3553. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3554. }, 0);
  3555. };
  3556. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3557. set: function (text) {
  3558. if (!this._loadingDiv) {
  3559. return;
  3560. }
  3561. this._loadingTextDiv.innerHTML = text;
  3562. },
  3563. enumerable: true,
  3564. configurable: true
  3565. });
  3566. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3567. get: function () {
  3568. return this._loadingDivBackgroundColor;
  3569. },
  3570. set: function (color) {
  3571. this._loadingDivBackgroundColor = color;
  3572. if (!this._loadingDiv) {
  3573. return;
  3574. }
  3575. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3576. },
  3577. enumerable: true,
  3578. configurable: true
  3579. });
  3580. Engine.prototype.hideLoadingUI = function () {
  3581. var _this = this;
  3582. if (!this._loadingDiv) {
  3583. return;
  3584. }
  3585. var onTransitionEnd = function () {
  3586. if (!_this._loadingDiv) {
  3587. return;
  3588. }
  3589. document.body.removeChild(_this._loadingDiv);
  3590. window.removeEventListener("resize", _this._resizeLoadingUI);
  3591. _this._loadingDiv = null;
  3592. };
  3593. this._loadingDiv.style.opacity = "0";
  3594. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3595. };
  3596. Engine.isSupported = function () {
  3597. try {
  3598. var tempcanvas = document.createElement("canvas");
  3599. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3600. return gl != null && !!window.WebGLRenderingContext;
  3601. } catch (e) {
  3602. return false;
  3603. }
  3604. };
  3605. Engine._ALPHA_DISABLE = 0;
  3606. Engine._ALPHA_ADD = 1;
  3607. Engine._ALPHA_COMBINE = 2;
  3608. Engine._DELAYLOADSTATE_NONE = 0;
  3609. Engine._DELAYLOADSTATE_LOADED = 1;
  3610. Engine._DELAYLOADSTATE_LOADING = 2;
  3611. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3612. Engine.Epsilon = 0.001;
  3613. Engine.CollisionsEpsilon = 0.001;
  3614. Engine.ShadersRepository = "Babylon/Shaders/";
  3615. return Engine;
  3616. })();
  3617. BABYLON.Engine = Engine;
  3618. })(BABYLON || (BABYLON = {}));
  3619. var BABYLON;
  3620. (function (BABYLON) {
  3621. var Node = (function () {
  3622. function Node(name, scene) {
  3623. this.state = "";
  3624. this.animations = new Array();
  3625. this._childrenFlag = -1;
  3626. this._isEnabled = true;
  3627. this._isReady = true;
  3628. this._currentRenderId = -1;
  3629. this.name = name;
  3630. this.id = name;
  3631. this._scene = scene;
  3632. this._initCache();
  3633. }
  3634. Node.prototype.getScene = function () {
  3635. return this._scene;
  3636. };
  3637. Node.prototype.getEngine = function () {
  3638. return this._scene.getEngine();
  3639. };
  3640. Node.prototype.getWorldMatrix = function () {
  3641. return BABYLON.Matrix.Identity();
  3642. };
  3643. Node.prototype._initCache = function () {
  3644. this._cache = {};
  3645. this._cache.parent = undefined;
  3646. };
  3647. Node.prototype.updateCache = function (force) {
  3648. if (!force && this.isSynchronized())
  3649. return;
  3650. this._cache.parent = this.parent;
  3651. this._updateCache();
  3652. };
  3653. Node.prototype._updateCache = function (ignoreParentClass) {
  3654. };
  3655. Node.prototype._isSynchronized = function () {
  3656. return true;
  3657. };
  3658. Node.prototype.isSynchronizedWithParent = function () {
  3659. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3660. };
  3661. Node.prototype.isSynchronized = function (updateCache) {
  3662. var check = this.hasNewParent();
  3663. check = check || !this.isSynchronizedWithParent();
  3664. check = check || !this._isSynchronized();
  3665. if (updateCache)
  3666. this.updateCache(true);
  3667. return !check;
  3668. };
  3669. Node.prototype.hasNewParent = function (update) {
  3670. if (this._cache.parent === this.parent)
  3671. return false;
  3672. if (update)
  3673. this._cache.parent = this.parent;
  3674. return true;
  3675. };
  3676. Node.prototype.isReady = function () {
  3677. return this._isReady;
  3678. };
  3679. Node.prototype.isEnabled = function () {
  3680. if (!this._isEnabled) {
  3681. return false;
  3682. }
  3683. if (this.parent) {
  3684. return this.parent.isEnabled();
  3685. }
  3686. return true;
  3687. };
  3688. Node.prototype.setEnabled = function (value) {
  3689. this._isEnabled = value;
  3690. };
  3691. Node.prototype.isDescendantOf = function (ancestor) {
  3692. if (this.parent) {
  3693. if (this.parent === ancestor) {
  3694. return true;
  3695. }
  3696. return this.parent.isDescendantOf(ancestor);
  3697. }
  3698. return false;
  3699. };
  3700. Node.prototype._getDescendants = function (list, results) {
  3701. for (var index = 0; index < list.length; index++) {
  3702. var item = list[index];
  3703. if (item.isDescendantOf(this)) {
  3704. results.push(item);
  3705. }
  3706. }
  3707. };
  3708. Node.prototype.getDescendants = function () {
  3709. var results = [];
  3710. this._getDescendants(this._scene.meshes, results);
  3711. this._getDescendants(this._scene.lights, results);
  3712. this._getDescendants(this._scene.cameras, results);
  3713. return results;
  3714. };
  3715. Node.prototype._setReady = function (state) {
  3716. if (state == this._isReady) {
  3717. return;
  3718. }
  3719. if (!state) {
  3720. this._isReady = false;
  3721. return;
  3722. }
  3723. this._isReady = true;
  3724. if (this.onReady) {
  3725. this.onReady(this);
  3726. }
  3727. };
  3728. return Node;
  3729. })();
  3730. BABYLON.Node = Node;
  3731. })(BABYLON || (BABYLON = {}));
  3732. var BABYLON;
  3733. (function (BABYLON) {
  3734. var BoundingSphere = (function () {
  3735. function BoundingSphere(minimum, maximum) {
  3736. this.minimum = minimum;
  3737. this.maximum = maximum;
  3738. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3739. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3740. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3741. this.radius = distance * 0.5;
  3742. this.centerWorld = BABYLON.Vector3.Zero();
  3743. this._update(BABYLON.Matrix.Identity());
  3744. }
  3745. BoundingSphere.prototype._update = function (world) {
  3746. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3747. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3748. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3749. };
  3750. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3751. for (var i = 0; i < 6; i++) {
  3752. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3753. return false;
  3754. }
  3755. return true;
  3756. };
  3757. BoundingSphere.prototype.intersectsPoint = function (point) {
  3758. var x = this.centerWorld.x - point.x;
  3759. var y = this.centerWorld.y - point.y;
  3760. var z = this.centerWorld.z - point.z;
  3761. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3762. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3763. return false;
  3764. return true;
  3765. };
  3766. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3767. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3768. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3769. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3770. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3771. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3772. return false;
  3773. return true;
  3774. };
  3775. return BoundingSphere;
  3776. })();
  3777. BABYLON.BoundingSphere = BoundingSphere;
  3778. })(BABYLON || (BABYLON = {}));
  3779. var BABYLON;
  3780. (function (BABYLON) {
  3781. var BoundingBox = (function () {
  3782. function BoundingBox(minimum, maximum) {
  3783. this.minimum = minimum;
  3784. this.maximum = maximum;
  3785. this.vectors = new Array();
  3786. this.vectorsWorld = new Array();
  3787. this.vectors.push(this.minimum.clone());
  3788. this.vectors.push(this.maximum.clone());
  3789. this.vectors.push(this.minimum.clone());
  3790. this.vectors[2].x = this.maximum.x;
  3791. this.vectors.push(this.minimum.clone());
  3792. this.vectors[3].y = this.maximum.y;
  3793. this.vectors.push(this.minimum.clone());
  3794. this.vectors[4].z = this.maximum.z;
  3795. this.vectors.push(this.maximum.clone());
  3796. this.vectors[5].z = this.minimum.z;
  3797. this.vectors.push(this.maximum.clone());
  3798. this.vectors[6].x = this.minimum.x;
  3799. this.vectors.push(this.maximum.clone());
  3800. this.vectors[7].y = this.minimum.y;
  3801. this.center = this.maximum.add(this.minimum).scale(0.5);
  3802. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3803. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3804. for (var index = 0; index < this.vectors.length; index++) {
  3805. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3806. }
  3807. this.minimumWorld = BABYLON.Vector3.Zero();
  3808. this.maximumWorld = BABYLON.Vector3.Zero();
  3809. this._update(BABYLON.Matrix.Identity());
  3810. }
  3811. BoundingBox.prototype.getWorldMatrix = function () {
  3812. return this._worldMatrix;
  3813. };
  3814. BoundingBox.prototype._update = function (world) {
  3815. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3816. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3817. for (var index = 0; index < this.vectors.length; index++) {
  3818. var v = this.vectorsWorld[index];
  3819. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3820. if (v.x < this.minimumWorld.x)
  3821. this.minimumWorld.x = v.x;
  3822. if (v.y < this.minimumWorld.y)
  3823. this.minimumWorld.y = v.y;
  3824. if (v.z < this.minimumWorld.z)
  3825. this.minimumWorld.z = v.z;
  3826. if (v.x > this.maximumWorld.x)
  3827. this.maximumWorld.x = v.x;
  3828. if (v.y > this.maximumWorld.y)
  3829. this.maximumWorld.y = v.y;
  3830. if (v.z > this.maximumWorld.z)
  3831. this.maximumWorld.z = v.z;
  3832. }
  3833. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3834. this.center.scaleInPlace(0.5);
  3835. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3836. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3837. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3838. this._worldMatrix = world;
  3839. };
  3840. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3841. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3842. };
  3843. BoundingBox.prototype.intersectsPoint = function (point) {
  3844. var delta = BABYLON.Engine.Epsilon;
  3845. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3846. return false;
  3847. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3848. return false;
  3849. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3850. return false;
  3851. return true;
  3852. };
  3853. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3854. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3855. };
  3856. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3857. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3858. return false;
  3859. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3860. return false;
  3861. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3862. return false;
  3863. return true;
  3864. };
  3865. BoundingBox.Intersects = function (box0, box1) {
  3866. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3867. return false;
  3868. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3869. return false;
  3870. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3871. return false;
  3872. return true;
  3873. };
  3874. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3875. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3876. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3877. return (num <= (sphereRadius * sphereRadius));
  3878. };
  3879. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3880. for (var p = 0; p < 6; p++) {
  3881. var inCount = 8;
  3882. for (var i = 0; i < 8; i++) {
  3883. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3884. --inCount;
  3885. } else {
  3886. break;
  3887. }
  3888. }
  3889. if (inCount == 0)
  3890. return false;
  3891. }
  3892. return true;
  3893. };
  3894. return BoundingBox;
  3895. })();
  3896. BABYLON.BoundingBox = BoundingBox;
  3897. })(BABYLON || (BABYLON = {}));
  3898. var BABYLON;
  3899. (function (BABYLON) {
  3900. var computeBoxExtents = function (axis, box) {
  3901. var p = BABYLON.Vector3.Dot(box.center, axis);
  3902. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3903. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3904. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3905. var r = r0 + r1 + r2;
  3906. return {
  3907. min: p - r,
  3908. max: p + r
  3909. };
  3910. };
  3911. var extentsOverlap = function (min0, max0, min1, max1) {
  3912. return !(min0 > max1 || min1 > max0);
  3913. };
  3914. var axisOverlap = function (axis, box0, box1) {
  3915. var result0 = computeBoxExtents(axis, box0);
  3916. var result1 = computeBoxExtents(axis, box1);
  3917. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3918. };
  3919. var BoundingInfo = (function () {
  3920. function BoundingInfo(minimum, maximum) {
  3921. this.minimum = minimum;
  3922. this.maximum = maximum;
  3923. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3924. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3925. }
  3926. BoundingInfo.prototype._update = function (world) {
  3927. this.boundingBox._update(world);
  3928. this.boundingSphere._update(world);
  3929. };
  3930. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3931. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3932. return false;
  3933. return this.boundingBox.isInFrustum(frustumPlanes);
  3934. };
  3935. BoundingInfo.prototype._checkCollision = function (collider) {
  3936. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  3937. };
  3938. BoundingInfo.prototype.intersectsPoint = function (point) {
  3939. if (!this.boundingSphere.centerWorld) {
  3940. return false;
  3941. }
  3942. if (!this.boundingSphere.intersectsPoint(point)) {
  3943. return false;
  3944. }
  3945. if (!this.boundingBox.intersectsPoint(point)) {
  3946. return false;
  3947. }
  3948. return true;
  3949. };
  3950. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  3951. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  3952. return false;
  3953. }
  3954. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  3955. return false;
  3956. }
  3957. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  3958. return false;
  3959. }
  3960. if (!precise) {
  3961. return true;
  3962. }
  3963. var box0 = this.boundingBox;
  3964. var box1 = boundingInfo.boundingBox;
  3965. if (!axisOverlap(box0.directions[0], box0, box1))
  3966. return false;
  3967. if (!axisOverlap(box0.directions[1], box0, box1))
  3968. return false;
  3969. if (!axisOverlap(box0.directions[2], box0, box1))
  3970. return false;
  3971. if (!axisOverlap(box1.directions[0], box0, box1))
  3972. return false;
  3973. if (!axisOverlap(box1.directions[1], box0, box1))
  3974. return false;
  3975. if (!axisOverlap(box1.directions[2], box0, box1))
  3976. return false;
  3977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  3978. return false;
  3979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  3980. return false;
  3981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  3982. return false;
  3983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  3984. return false;
  3985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  3986. return false;
  3987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  3988. return false;
  3989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  3990. return false;
  3991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  3992. return false;
  3993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  3994. return false;
  3995. return true;
  3996. };
  3997. return BoundingInfo;
  3998. })();
  3999. BABYLON.BoundingInfo = BoundingInfo;
  4000. })(BABYLON || (BABYLON = {}));
  4001. var __extends = this.__extends || function (d, b) {
  4002. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4003. function __() { this.constructor = d; }
  4004. __.prototype = b.prototype;
  4005. d.prototype = new __();
  4006. };
  4007. var BABYLON;
  4008. (function (BABYLON) {
  4009. var Light = (function (_super) {
  4010. __extends(Light, _super);
  4011. function Light(name, scene) {
  4012. _super.call(this, name, scene);
  4013. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4014. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4015. this.intensity = 1.0;
  4016. this.range = Number.MAX_VALUE;
  4017. this.includedOnlyMeshes = new Array();
  4018. this.excludedMeshes = new Array();
  4019. this._excludedMeshesIds = new Array();
  4020. this._includedOnlyMeshesIds = new Array();
  4021. scene.lights.push(this);
  4022. }
  4023. Light.prototype.getShadowGenerator = function () {
  4024. return this._shadowGenerator;
  4025. };
  4026. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4027. };
  4028. Light.prototype._getWorldMatrix = function () {
  4029. return BABYLON.Matrix.Identity();
  4030. };
  4031. Light.prototype.canAffectMesh = function (mesh) {
  4032. if (!mesh) {
  4033. return true;
  4034. }
  4035. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4036. return false;
  4037. }
  4038. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4039. return false;
  4040. }
  4041. return true;
  4042. };
  4043. Light.prototype.getWorldMatrix = function () {
  4044. this._currentRenderId = this.getScene().getRenderId();
  4045. var worldMatrix = this._getWorldMatrix();
  4046. if (this.parent && this.parent.getWorldMatrix) {
  4047. if (!this._parentedWorldMatrix) {
  4048. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4049. }
  4050. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4051. return this._parentedWorldMatrix;
  4052. }
  4053. return worldMatrix;
  4054. };
  4055. Light.prototype.dispose = function () {
  4056. if (this._shadowGenerator) {
  4057. this._shadowGenerator.dispose();
  4058. this._shadowGenerator = null;
  4059. }
  4060. var index = this.getScene().lights.indexOf(this);
  4061. this.getScene().lights.splice(index, 1);
  4062. };
  4063. return Light;
  4064. })(BABYLON.Node);
  4065. BABYLON.Light = Light;
  4066. })(BABYLON || (BABYLON = {}));
  4067. var __extends = this.__extends || function (d, b) {
  4068. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4069. function __() { this.constructor = d; }
  4070. __.prototype = b.prototype;
  4071. d.prototype = new __();
  4072. };
  4073. var BABYLON;
  4074. (function (BABYLON) {
  4075. var PointLight = (function (_super) {
  4076. __extends(PointLight, _super);
  4077. function PointLight(name, position, scene) {
  4078. _super.call(this, name, scene);
  4079. this.position = position;
  4080. }
  4081. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4082. if (this.parent && this.parent.getWorldMatrix) {
  4083. if (!this._transformedPosition) {
  4084. this._transformedPosition = BABYLON.Vector3.Zero();
  4085. }
  4086. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4087. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4088. return;
  4089. }
  4090. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4091. };
  4092. PointLight.prototype.getShadowGenerator = function () {
  4093. return null;
  4094. };
  4095. PointLight.prototype._getWorldMatrix = function () {
  4096. if (!this._worldMatrix) {
  4097. this._worldMatrix = BABYLON.Matrix.Identity();
  4098. }
  4099. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4100. return this._worldMatrix;
  4101. };
  4102. return PointLight;
  4103. })(BABYLON.Light);
  4104. BABYLON.PointLight = PointLight;
  4105. })(BABYLON || (BABYLON = {}));
  4106. var __extends = this.__extends || function (d, b) {
  4107. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4108. function __() { this.constructor = d; }
  4109. __.prototype = b.prototype;
  4110. d.prototype = new __();
  4111. };
  4112. var BABYLON;
  4113. (function (BABYLON) {
  4114. var SpotLight = (function (_super) {
  4115. __extends(SpotLight, _super);
  4116. function SpotLight(name, position, direction, angle, exponent, scene) {
  4117. _super.call(this, name, scene);
  4118. this.position = position;
  4119. this.direction = direction;
  4120. this.angle = angle;
  4121. this.exponent = exponent;
  4122. }
  4123. SpotLight.prototype.setDirectionToTarget = function (target) {
  4124. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4125. return this.direction;
  4126. };
  4127. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4128. var normalizeDirection;
  4129. if (this.parent && this.parent.getWorldMatrix) {
  4130. if (!this._transformedDirection) {
  4131. this._transformedDirection = BABYLON.Vector3.Zero();
  4132. }
  4133. if (!this._transformedPosition) {
  4134. this._transformedPosition = BABYLON.Vector3.Zero();
  4135. }
  4136. var parentWorldMatrix = this.parent.getWorldMatrix();
  4137. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4138. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4139. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4140. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4141. } else {
  4142. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4143. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4144. }
  4145. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4146. };
  4147. SpotLight.prototype._getWorldMatrix = function () {
  4148. if (!this._worldMatrix) {
  4149. this._worldMatrix = BABYLON.Matrix.Identity();
  4150. }
  4151. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4152. return this._worldMatrix;
  4153. };
  4154. return SpotLight;
  4155. })(BABYLON.Light);
  4156. BABYLON.SpotLight = SpotLight;
  4157. })(BABYLON || (BABYLON = {}));
  4158. var __extends = this.__extends || function (d, b) {
  4159. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4160. function __() { this.constructor = d; }
  4161. __.prototype = b.prototype;
  4162. d.prototype = new __();
  4163. };
  4164. var BABYLON;
  4165. (function (BABYLON) {
  4166. var DirectionalLight = (function (_super) {
  4167. __extends(DirectionalLight, _super);
  4168. function DirectionalLight(name, direction, scene) {
  4169. _super.call(this, name, scene);
  4170. this.direction = direction;
  4171. this.position = direction.scale(-1);
  4172. }
  4173. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4174. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4175. return this.direction;
  4176. };
  4177. DirectionalLight.prototype._computeTransformedPosition = function () {
  4178. if (this.parent && this.parent.getWorldMatrix) {
  4179. if (!this._transformedPosition) {
  4180. this._transformedPosition = BABYLON.Vector3.Zero();
  4181. }
  4182. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4183. return true;
  4184. }
  4185. return false;
  4186. };
  4187. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4188. if (this.parent && this.parent.getWorldMatrix) {
  4189. if (!this._transformedDirection) {
  4190. this._transformedDirection = BABYLON.Vector3.Zero();
  4191. }
  4192. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4193. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4194. return;
  4195. }
  4196. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4197. };
  4198. DirectionalLight.prototype._getWorldMatrix = function () {
  4199. if (!this._worldMatrix) {
  4200. this._worldMatrix = BABYLON.Matrix.Identity();
  4201. }
  4202. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4203. return this._worldMatrix;
  4204. };
  4205. return DirectionalLight;
  4206. })(BABYLON.Light);
  4207. BABYLON.DirectionalLight = DirectionalLight;
  4208. })(BABYLON || (BABYLON = {}));
  4209. var BABYLON;
  4210. (function (BABYLON) {
  4211. var ShadowGenerator = (function () {
  4212. function ShadowGenerator(mapSize, light) {
  4213. var _this = this;
  4214. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4215. this._darkness = 0;
  4216. this._transparencyShadow = false;
  4217. this._viewMatrix = BABYLON.Matrix.Zero();
  4218. this._projectionMatrix = BABYLON.Matrix.Zero();
  4219. this._transformMatrix = BABYLON.Matrix.Zero();
  4220. this._worldViewProjection = BABYLON.Matrix.Zero();
  4221. this._light = light;
  4222. this._scene = light.getScene();
  4223. light._shadowGenerator = this;
  4224. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4225. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4226. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4227. this._shadowMap.renderParticles = false;
  4228. var renderSubMesh = function (subMesh) {
  4229. var mesh = subMesh.getRenderingMesh();
  4230. var scene = _this._scene;
  4231. var engine = scene.getEngine();
  4232. engine.setState(subMesh.getMaterial().backFaceCulling);
  4233. var batch = mesh._getInstancesRenderList(subMesh._id);
  4234. if (batch.mustReturn) {
  4235. return;
  4236. }
  4237. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4238. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4239. engine.enableEffect(_this._effect);
  4240. mesh._bind(subMesh, _this._effect, false);
  4241. var material = subMesh.getMaterial();
  4242. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4243. if (material && material.needAlphaTesting()) {
  4244. var alphaTexture = material.getAlphaTestTexture();
  4245. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4246. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4247. }
  4248. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4249. if (useBones) {
  4250. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4251. }
  4252. if (hardwareInstancedRendering) {
  4253. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4254. } else {
  4255. if (batch.renderSelf[subMesh._id]) {
  4256. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4257. mesh._draw(subMesh, true);
  4258. }
  4259. if (batch.visibleInstances[subMesh._id]) {
  4260. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4261. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4262. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4263. mesh._draw(subMesh, true);
  4264. }
  4265. }
  4266. }
  4267. } else {
  4268. _this._shadowMap.resetRefreshCounter();
  4269. }
  4270. };
  4271. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4272. var index;
  4273. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4274. renderSubMesh(opaqueSubMeshes.data[index]);
  4275. }
  4276. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4277. renderSubMesh(alphaTestSubMeshes.data[index]);
  4278. }
  4279. if (_this._transparencyShadow) {
  4280. for (index = 0; index < transparentSubMeshes.length; index++) {
  4281. renderSubMesh(transparentSubMeshes.data[index]);
  4282. }
  4283. }
  4284. };
  4285. }
  4286. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4287. get: function () {
  4288. return ShadowGenerator._FILTER_NONE;
  4289. },
  4290. enumerable: true,
  4291. configurable: true
  4292. });
  4293. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4294. get: function () {
  4295. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4296. },
  4297. enumerable: true,
  4298. configurable: true
  4299. });
  4300. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4301. get: function () {
  4302. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4303. },
  4304. enumerable: true,
  4305. configurable: true
  4306. });
  4307. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4308. get: function () {
  4309. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4310. },
  4311. set: function (value) {
  4312. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4313. },
  4314. enumerable: true,
  4315. configurable: true
  4316. });
  4317. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4318. get: function () {
  4319. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4320. },
  4321. set: function (value) {
  4322. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4323. },
  4324. enumerable: true,
  4325. configurable: true
  4326. });
  4327. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4328. var defines = [];
  4329. if (this.useVarianceShadowMap) {
  4330. defines.push("#define VSM");
  4331. }
  4332. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4333. var mesh = subMesh.getMesh();
  4334. var material = subMesh.getMaterial();
  4335. if (material && material.needAlphaTesting()) {
  4336. defines.push("#define ALPHATEST");
  4337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4338. attribs.push(BABYLON.VertexBuffer.UVKind);
  4339. defines.push("#define UV1");
  4340. }
  4341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4343. defines.push("#define UV2");
  4344. }
  4345. }
  4346. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4347. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4348. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4349. defines.push("#define BONES");
  4350. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4351. }
  4352. if (useInstances) {
  4353. defines.push("#define INSTANCES");
  4354. attribs.push("world0");
  4355. attribs.push("world1");
  4356. attribs.push("world2");
  4357. attribs.push("world3");
  4358. }
  4359. var join = defines.join("\n");
  4360. if (this._cachedDefines != join) {
  4361. this._cachedDefines = join;
  4362. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4363. }
  4364. return this._effect.isReady();
  4365. };
  4366. ShadowGenerator.prototype.getShadowMap = function () {
  4367. return this._shadowMap;
  4368. };
  4369. ShadowGenerator.prototype.getLight = function () {
  4370. return this._light;
  4371. };
  4372. ShadowGenerator.prototype.getTransformMatrix = function () {
  4373. var lightPosition = this._light.position;
  4374. var lightDirection = this._light.direction;
  4375. if (this._light._computeTransformedPosition()) {
  4376. lightPosition = this._light._transformedPosition;
  4377. }
  4378. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4379. this._cachedPosition = lightPosition.clone();
  4380. this._cachedDirection = lightDirection.clone();
  4381. var activeCamera = this._scene.activeCamera;
  4382. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4383. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4384. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4385. }
  4386. return this._transformMatrix;
  4387. };
  4388. ShadowGenerator.prototype.getDarkness = function () {
  4389. return this._darkness;
  4390. };
  4391. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4392. if (darkness >= 1.0)
  4393. this._darkness = 1.0;
  4394. else if (darkness <= 0.0)
  4395. this._darkness = 0.0;
  4396. else
  4397. this._darkness = darkness;
  4398. };
  4399. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4400. this._transparencyShadow = hasShadow;
  4401. };
  4402. ShadowGenerator.prototype.dispose = function () {
  4403. this._shadowMap.dispose();
  4404. };
  4405. ShadowGenerator._FILTER_NONE = 0;
  4406. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4407. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4408. return ShadowGenerator;
  4409. })();
  4410. BABYLON.ShadowGenerator = ShadowGenerator;
  4411. })(BABYLON || (BABYLON = {}));
  4412. var __extends = this.__extends || function (d, b) {
  4413. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4414. function __() { this.constructor = d; }
  4415. __.prototype = b.prototype;
  4416. d.prototype = new __();
  4417. };
  4418. var BABYLON;
  4419. (function (BABYLON) {
  4420. var HemisphericLight = (function (_super) {
  4421. __extends(HemisphericLight, _super);
  4422. function HemisphericLight(name, direction, scene) {
  4423. _super.call(this, name, scene);
  4424. this.direction = direction;
  4425. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4426. }
  4427. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4428. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4429. return this.direction;
  4430. };
  4431. HemisphericLight.prototype.getShadowGenerator = function () {
  4432. return null;
  4433. };
  4434. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4435. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4436. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4437. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4438. };
  4439. HemisphericLight.prototype._getWorldMatrix = function () {
  4440. if (!this._worldMatrix) {
  4441. this._worldMatrix = BABYLON.Matrix.Identity();
  4442. }
  4443. return this._worldMatrix;
  4444. };
  4445. return HemisphericLight;
  4446. })(BABYLON.Light);
  4447. BABYLON.HemisphericLight = HemisphericLight;
  4448. })(BABYLON || (BABYLON = {}));
  4449. var BABYLON;
  4450. (function (BABYLON) {
  4451. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4452. if (boxMin.x > sphereCenter.x + sphereRadius)
  4453. return false;
  4454. if (sphereCenter.x - sphereRadius > boxMax.x)
  4455. return false;
  4456. if (boxMin.y > sphereCenter.y + sphereRadius)
  4457. return false;
  4458. if (sphereCenter.y - sphereRadius > boxMax.y)
  4459. return false;
  4460. if (boxMin.z > sphereCenter.z + sphereRadius)
  4461. return false;
  4462. if (sphereCenter.z - sphereRadius > boxMax.z)
  4463. return false;
  4464. return true;
  4465. };
  4466. var getLowestRoot = function (a, b, c, maxR) {
  4467. var determinant = b * b - 4.0 * a * c;
  4468. var result = { root: 0, found: false };
  4469. if (determinant < 0)
  4470. return result;
  4471. var sqrtD = Math.sqrt(determinant);
  4472. var r1 = (-b - sqrtD) / (2.0 * a);
  4473. var r2 = (-b + sqrtD) / (2.0 * a);
  4474. if (r1 > r2) {
  4475. var temp = r2;
  4476. r2 = r1;
  4477. r1 = temp;
  4478. }
  4479. if (r1 > 0 && r1 < maxR) {
  4480. result.root = r1;
  4481. result.found = true;
  4482. return result;
  4483. }
  4484. if (r2 > 0 && r2 < maxR) {
  4485. result.root = r2;
  4486. result.found = true;
  4487. return result;
  4488. }
  4489. return result;
  4490. };
  4491. var Collider = (function () {
  4492. function Collider() {
  4493. this.radius = new BABYLON.Vector3(1, 1, 1);
  4494. this.retry = 0;
  4495. this.basePointWorld = BABYLON.Vector3.Zero();
  4496. this.velocityWorld = BABYLON.Vector3.Zero();
  4497. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4498. this._collisionPoint = BABYLON.Vector3.Zero();
  4499. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4500. this._tempVector = BABYLON.Vector3.Zero();
  4501. this._tempVector2 = BABYLON.Vector3.Zero();
  4502. this._tempVector3 = BABYLON.Vector3.Zero();
  4503. this._tempVector4 = BABYLON.Vector3.Zero();
  4504. this._edge = BABYLON.Vector3.Zero();
  4505. this._baseToVertex = BABYLON.Vector3.Zero();
  4506. this._destinationPoint = BABYLON.Vector3.Zero();
  4507. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4508. this._displacementVector = BABYLON.Vector3.Zero();
  4509. }
  4510. Collider.prototype._initialize = function (source, dir, e) {
  4511. this.velocity = dir;
  4512. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4513. this.basePoint = source;
  4514. source.multiplyToRef(this.radius, this.basePointWorld);
  4515. dir.multiplyToRef(this.radius, this.velocityWorld);
  4516. this.velocityWorldLength = this.velocityWorld.length();
  4517. this.epsilon = e;
  4518. this.collisionFound = false;
  4519. };
  4520. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4521. pa.subtractToRef(point, this._tempVector);
  4522. pb.subtractToRef(point, this._tempVector2);
  4523. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4524. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4525. if (d < 0)
  4526. return false;
  4527. pc.subtractToRef(point, this._tempVector3);
  4528. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4529. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4530. if (d < 0)
  4531. return false;
  4532. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4533. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4534. return d >= 0;
  4535. };
  4536. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4537. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4538. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4539. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4540. return false;
  4541. }
  4542. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4543. return false;
  4544. return true;
  4545. };
  4546. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4547. var t0;
  4548. var embeddedInPlane = false;
  4549. if (!subMesh._trianglePlanes) {
  4550. subMesh._trianglePlanes = [];
  4551. }
  4552. if (!subMesh._trianglePlanes[faceIndex]) {
  4553. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4554. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4555. }
  4556. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4557. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4558. return;
  4559. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4560. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4561. if (normalDotVelocity == 0) {
  4562. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4563. return;
  4564. embeddedInPlane = true;
  4565. t0 = 0;
  4566. } else {
  4567. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4568. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4569. if (t0 > t1) {
  4570. var temp = t1;
  4571. t1 = t0;
  4572. t0 = temp;
  4573. }
  4574. if (t0 > 1.0 || t1 < 0.0)
  4575. return;
  4576. if (t0 < 0)
  4577. t0 = 0;
  4578. if (t0 > 1.0)
  4579. t0 = 1.0;
  4580. }
  4581. this._collisionPoint.copyFromFloats(0, 0, 0);
  4582. var found = false;
  4583. var t = 1.0;
  4584. if (!embeddedInPlane) {
  4585. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4586. this.velocity.scaleToRef(t0, this._tempVector);
  4587. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4588. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4589. found = true;
  4590. t = t0;
  4591. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4592. }
  4593. }
  4594. if (!found) {
  4595. var velocitySquaredLength = this.velocity.lengthSquared();
  4596. var a = velocitySquaredLength;
  4597. this.basePoint.subtractToRef(p1, this._tempVector);
  4598. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4599. var c = this._tempVector.lengthSquared() - 1.0;
  4600. var lowestRoot = getLowestRoot(a, b, c, t);
  4601. if (lowestRoot.found) {
  4602. t = lowestRoot.root;
  4603. found = true;
  4604. this._collisionPoint.copyFrom(p1);
  4605. }
  4606. this.basePoint.subtractToRef(p2, this._tempVector);
  4607. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4608. c = this._tempVector.lengthSquared() - 1.0;
  4609. lowestRoot = getLowestRoot(a, b, c, t);
  4610. if (lowestRoot.found) {
  4611. t = lowestRoot.root;
  4612. found = true;
  4613. this._collisionPoint.copyFrom(p2);
  4614. }
  4615. this.basePoint.subtractToRef(p3, 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(p3);
  4623. }
  4624. p2.subtractToRef(p1, this._edge);
  4625. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4626. var edgeSquaredLength = this._edge.lengthSquared();
  4627. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4628. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4629. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4630. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4631. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4632. lowestRoot = getLowestRoot(a, b, c, t);
  4633. if (lowestRoot.found) {
  4634. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4635. if (f >= 0.0 && f <= 1.0) {
  4636. t = lowestRoot.root;
  4637. found = true;
  4638. this._edge.scaleInPlace(f);
  4639. p1.addToRef(this._edge, this._collisionPoint);
  4640. }
  4641. }
  4642. p3.subtractToRef(p2, this._edge);
  4643. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4644. edgeSquaredLength = this._edge.lengthSquared();
  4645. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4646. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4647. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4648. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4649. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4650. lowestRoot = getLowestRoot(a, b, c, t);
  4651. if (lowestRoot.found) {
  4652. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4653. if (f >= 0.0 && f <= 1.0) {
  4654. t = lowestRoot.root;
  4655. found = true;
  4656. this._edge.scaleInPlace(f);
  4657. p2.addToRef(this._edge, this._collisionPoint);
  4658. }
  4659. }
  4660. p1.subtractToRef(p3, this._edge);
  4661. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4662. edgeSquaredLength = this._edge.lengthSquared();
  4663. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4664. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4665. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4666. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4667. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4668. lowestRoot = getLowestRoot(a, b, c, t);
  4669. if (lowestRoot.found) {
  4670. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4671. if (f >= 0.0 && f <= 1.0) {
  4672. t = lowestRoot.root;
  4673. found = true;
  4674. this._edge.scaleInPlace(f);
  4675. p3.addToRef(this._edge, this._collisionPoint);
  4676. }
  4677. }
  4678. }
  4679. if (found) {
  4680. var distToCollision = t * this.velocity.length();
  4681. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4682. if (!this.intersectionPoint) {
  4683. this.intersectionPoint = this._collisionPoint.clone();
  4684. } else {
  4685. this.intersectionPoint.copyFrom(this._collisionPoint);
  4686. }
  4687. this.nearestDistance = distToCollision;
  4688. this.collisionFound = true;
  4689. this.collidedMesh = subMesh.getMesh();
  4690. }
  4691. }
  4692. };
  4693. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4694. for (var i = indexStart; i < indexEnd; i += 3) {
  4695. var p1 = pts[indices[i] - decal];
  4696. var p2 = pts[indices[i + 1] - decal];
  4697. var p3 = pts[indices[i + 2] - decal];
  4698. this._testTriangle(i, subMesh, p3, p2, p1);
  4699. }
  4700. };
  4701. Collider.prototype._getResponse = function (pos, vel) {
  4702. pos.addToRef(vel, this._destinationPoint);
  4703. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4704. this.basePoint.addToRef(vel, pos);
  4705. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4706. this._slidePlaneNormal.normalize();
  4707. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4708. pos.addInPlace(this._displacementVector);
  4709. this.intersectionPoint.addInPlace(this._displacementVector);
  4710. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4711. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4712. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4713. };
  4714. return Collider;
  4715. })();
  4716. BABYLON.Collider = Collider;
  4717. })(BABYLON || (BABYLON = {}));
  4718. var __extends = this.__extends || function (d, b) {
  4719. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4720. function __() { this.constructor = d; }
  4721. __.prototype = b.prototype;
  4722. d.prototype = new __();
  4723. };
  4724. var BABYLON;
  4725. (function (BABYLON) {
  4726. var Camera = (function (_super) {
  4727. __extends(Camera, _super);
  4728. function Camera(name, position, scene) {
  4729. _super.call(this, name, scene);
  4730. this.position = position;
  4731. this.upVector = BABYLON.Vector3.Up();
  4732. this.orthoLeft = null;
  4733. this.orthoRight = null;
  4734. this.orthoBottom = null;
  4735. this.orthoTop = null;
  4736. this.fov = 0.8;
  4737. this.minZ = 1.0;
  4738. this.maxZ = 10000.0;
  4739. this.inertia = 0.9;
  4740. this.mode = Camera.PERSPECTIVE_CAMERA;
  4741. this.isIntermediate = false;
  4742. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4743. this.subCameras = [];
  4744. this.layerMask = 0xFFFFFFFF;
  4745. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4746. this._projectionMatrix = new BABYLON.Matrix();
  4747. this._postProcesses = new Array();
  4748. this._postProcessesTakenIndices = [];
  4749. scene.cameras.push(this);
  4750. if (!scene.activeCamera) {
  4751. scene.activeCamera = this;
  4752. }
  4753. }
  4754. Camera.prototype._initCache = function () {
  4755. _super.prototype._initCache.call(this);
  4756. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4757. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4758. this._cache.mode = undefined;
  4759. this._cache.minZ = undefined;
  4760. this._cache.maxZ = undefined;
  4761. this._cache.fov = undefined;
  4762. this._cache.aspectRatio = undefined;
  4763. this._cache.orthoLeft = undefined;
  4764. this._cache.orthoRight = undefined;
  4765. this._cache.orthoBottom = undefined;
  4766. this._cache.orthoTop = undefined;
  4767. this._cache.renderWidth = undefined;
  4768. this._cache.renderHeight = undefined;
  4769. };
  4770. Camera.prototype._updateCache = function (ignoreParentClass) {
  4771. if (!ignoreParentClass) {
  4772. _super.prototype._updateCache.call(this);
  4773. }
  4774. var engine = this.getEngine();
  4775. this._cache.position.copyFrom(this.position);
  4776. this._cache.upVector.copyFrom(this.upVector);
  4777. this._cache.mode = this.mode;
  4778. this._cache.minZ = this.minZ;
  4779. this._cache.maxZ = this.maxZ;
  4780. this._cache.fov = this.fov;
  4781. this._cache.aspectRatio = engine.getAspectRatio(this);
  4782. this._cache.orthoLeft = this.orthoLeft;
  4783. this._cache.orthoRight = this.orthoRight;
  4784. this._cache.orthoBottom = this.orthoBottom;
  4785. this._cache.orthoTop = this.orthoTop;
  4786. this._cache.renderWidth = engine.getRenderWidth();
  4787. this._cache.renderHeight = engine.getRenderHeight();
  4788. };
  4789. Camera.prototype._updateFromScene = function () {
  4790. this.updateCache();
  4791. this._update();
  4792. };
  4793. Camera.prototype._isSynchronized = function () {
  4794. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4795. };
  4796. Camera.prototype._isSynchronizedViewMatrix = function () {
  4797. if (!_super.prototype._isSynchronized.call(this))
  4798. return false;
  4799. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4800. };
  4801. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4802. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4803. if (!check) {
  4804. return false;
  4805. }
  4806. var engine = this.getEngine();
  4807. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4808. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4809. } else {
  4810. 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();
  4811. }
  4812. return check;
  4813. };
  4814. Camera.prototype.attachControl = function (element) {
  4815. };
  4816. Camera.prototype.detachControl = function (element) {
  4817. };
  4818. Camera.prototype._update = function () {
  4819. };
  4820. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4821. if (typeof insertAt === "undefined") { insertAt = null; }
  4822. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4823. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4824. return 0;
  4825. }
  4826. if (insertAt == null || insertAt < 0) {
  4827. this._postProcesses.push(postProcess);
  4828. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4829. return this._postProcesses.length - 1;
  4830. }
  4831. var add = 0;
  4832. if (this._postProcesses[insertAt]) {
  4833. var start = this._postProcesses.length - 1;
  4834. for (var i = start; i >= insertAt + 1; --i) {
  4835. this._postProcesses[i + 1] = this._postProcesses[i];
  4836. }
  4837. add = 1;
  4838. }
  4839. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4840. if (this._postProcessesTakenIndices[i] < insertAt) {
  4841. continue;
  4842. }
  4843. start = this._postProcessesTakenIndices.length - 1;
  4844. for (var j = start; j >= i; --j) {
  4845. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4846. }
  4847. this._postProcessesTakenIndices[i] = insertAt;
  4848. break;
  4849. }
  4850. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4851. this._postProcessesTakenIndices.push(insertAt);
  4852. }
  4853. var result = insertAt + add;
  4854. this._postProcesses[result] = postProcess;
  4855. return result;
  4856. };
  4857. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4858. if (typeof atIndices === "undefined") { atIndices = null; }
  4859. var result = [];
  4860. if (!atIndices) {
  4861. var length = this._postProcesses.length;
  4862. for (var i = 0; i < length; i++) {
  4863. if (this._postProcesses[i] !== postProcess) {
  4864. continue;
  4865. }
  4866. delete this._postProcesses[i];
  4867. var index = this._postProcessesTakenIndices.indexOf(i);
  4868. this._postProcessesTakenIndices.splice(index, 1);
  4869. }
  4870. } else {
  4871. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4872. for (i = 0; i < atIndices.length; i++) {
  4873. var foundPostProcess = this._postProcesses[atIndices[i]];
  4874. if (foundPostProcess !== postProcess) {
  4875. result.push(i);
  4876. continue;
  4877. }
  4878. delete this._postProcesses[atIndices[i]];
  4879. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4880. this._postProcessesTakenIndices.splice(index, 1);
  4881. }
  4882. }
  4883. return result;
  4884. };
  4885. Camera.prototype.getWorldMatrix = function () {
  4886. if (!this._worldMatrix) {
  4887. this._worldMatrix = BABYLON.Matrix.Identity();
  4888. }
  4889. var viewMatrix = this.getViewMatrix();
  4890. viewMatrix.invertToRef(this._worldMatrix);
  4891. return this._worldMatrix;
  4892. };
  4893. Camera.prototype._getViewMatrix = function () {
  4894. return BABYLON.Matrix.Identity();
  4895. };
  4896. Camera.prototype.getViewMatrix = function () {
  4897. this._computedViewMatrix = this._computeViewMatrix();
  4898. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4899. return this._computedViewMatrix;
  4900. }
  4901. if (!this._worldMatrix) {
  4902. this._worldMatrix = BABYLON.Matrix.Identity();
  4903. }
  4904. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4905. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4906. this._computedViewMatrix.invert();
  4907. this._currentRenderId = this.getScene().getRenderId();
  4908. return this._computedViewMatrix;
  4909. };
  4910. Camera.prototype._computeViewMatrix = function (force) {
  4911. if (!force && this._isSynchronizedViewMatrix()) {
  4912. return this._computedViewMatrix;
  4913. }
  4914. this._computedViewMatrix = this._getViewMatrix();
  4915. if (!this.parent || !this.parent.getWorldMatrix) {
  4916. this._currentRenderId = this.getScene().getRenderId();
  4917. }
  4918. return this._computedViewMatrix;
  4919. };
  4920. Camera.prototype.getProjectionMatrix = function (force) {
  4921. if (!force && this._isSynchronizedProjectionMatrix()) {
  4922. return this._projectionMatrix;
  4923. }
  4924. var engine = this.getEngine();
  4925. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4926. if (this.minZ <= 0) {
  4927. this.minZ = 0.1;
  4928. }
  4929. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4930. return this._projectionMatrix;
  4931. }
  4932. var halfWidth = engine.getRenderWidth() / 2.0;
  4933. var halfHeight = engine.getRenderHeight() / 2.0;
  4934. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4935. return this._projectionMatrix;
  4936. };
  4937. Camera.prototype.dispose = function () {
  4938. var index = this.getScene().cameras.indexOf(this);
  4939. this.getScene().cameras.splice(index, 1);
  4940. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4941. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  4942. }
  4943. };
  4944. Camera.PERSPECTIVE_CAMERA = 0;
  4945. Camera.ORTHOGRAPHIC_CAMERA = 1;
  4946. return Camera;
  4947. })(BABYLON.Node);
  4948. BABYLON.Camera = Camera;
  4949. })(BABYLON || (BABYLON = {}));
  4950. var __extends = this.__extends || function (d, b) {
  4951. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4952. function __() { this.constructor = d; }
  4953. __.prototype = b.prototype;
  4954. d.prototype = new __();
  4955. };
  4956. var BABYLON;
  4957. (function (BABYLON) {
  4958. var TargetCamera = (function (_super) {
  4959. __extends(TargetCamera, _super);
  4960. function TargetCamera(name, position, scene) {
  4961. _super.call(this, name, position, scene);
  4962. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  4963. this.cameraRotation = new BABYLON.Vector2(0, 0);
  4964. this.rotation = new BABYLON.Vector3(0, 0, 0);
  4965. this.speed = 2.0;
  4966. this.noRotationConstraint = false;
  4967. this.lockedTarget = null;
  4968. this._currentTarget = BABYLON.Vector3.Zero();
  4969. this._viewMatrix = BABYLON.Matrix.Zero();
  4970. this._camMatrix = BABYLON.Matrix.Zero();
  4971. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  4972. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  4973. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  4974. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  4975. this._lookAtTemp = BABYLON.Matrix.Zero();
  4976. this._tempMatrix = BABYLON.Matrix.Zero();
  4977. }
  4978. TargetCamera.prototype._getLockedTargetPosition = function () {
  4979. if (!this.lockedTarget) {
  4980. return null;
  4981. }
  4982. return this.lockedTarget.position || this.lockedTarget;
  4983. };
  4984. TargetCamera.prototype._initCache = function () {
  4985. _super.prototype._initCache.call(this);
  4986. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4987. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4988. };
  4989. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  4990. if (!ignoreParentClass) {
  4991. _super.prototype._updateCache.call(this);
  4992. }
  4993. var lockedTargetPosition = this._getLockedTargetPosition();
  4994. if (!lockedTargetPosition) {
  4995. this._cache.lockedTarget = null;
  4996. } else {
  4997. if (!this._cache.lockedTarget) {
  4998. this._cache.lockedTarget = lockedTargetPosition.clone();
  4999. } else {
  5000. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5001. }
  5002. }
  5003. this._cache.rotation.copyFrom(this.rotation);
  5004. };
  5005. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5006. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5007. return false;
  5008. }
  5009. var lockedTargetPosition = this._getLockedTargetPosition();
  5010. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5011. };
  5012. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5013. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5014. };
  5015. TargetCamera.prototype.setTarget = function (target) {
  5016. this.upVector.normalize();
  5017. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5018. this._camMatrix.invert();
  5019. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5020. var vDir = target.subtract(this.position);
  5021. if (vDir.x >= 0.0) {
  5022. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5023. } else {
  5024. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5025. }
  5026. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5027. if (isNaN(this.rotation.x)) {
  5028. this.rotation.x = 0;
  5029. }
  5030. if (isNaN(this.rotation.y)) {
  5031. this.rotation.y = 0;
  5032. }
  5033. if (isNaN(this.rotation.z)) {
  5034. this.rotation.z = 0;
  5035. }
  5036. };
  5037. TargetCamera.prototype.getTarget = function () {
  5038. return this._currentTarget;
  5039. };
  5040. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5041. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5042. };
  5043. TargetCamera.prototype._updatePosition = function () {
  5044. this.position.addInPlace(this.cameraDirection);
  5045. };
  5046. TargetCamera.prototype._update = function () {
  5047. var needToMove = this._decideIfNeedsToMove();
  5048. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5049. if (needToMove) {
  5050. this._updatePosition();
  5051. }
  5052. if (needToRotate) {
  5053. this.rotation.x += this.cameraRotation.x;
  5054. this.rotation.y += this.cameraRotation.y;
  5055. if (!this.noRotationConstraint) {
  5056. var limit = (Math.PI / 2) * 0.95;
  5057. if (this.rotation.x > limit)
  5058. this.rotation.x = limit;
  5059. if (this.rotation.x < -limit)
  5060. this.rotation.x = -limit;
  5061. }
  5062. }
  5063. if (needToMove) {
  5064. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5065. this.cameraDirection.x = 0;
  5066. }
  5067. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5068. this.cameraDirection.y = 0;
  5069. }
  5070. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5071. this.cameraDirection.z = 0;
  5072. }
  5073. this.cameraDirection.scaleInPlace(this.inertia);
  5074. }
  5075. if (needToRotate) {
  5076. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5077. this.cameraRotation.x = 0;
  5078. }
  5079. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5080. this.cameraRotation.y = 0;
  5081. }
  5082. this.cameraRotation.scaleInPlace(this.inertia);
  5083. }
  5084. };
  5085. TargetCamera.prototype._getViewMatrix = function () {
  5086. if (!this.lockedTarget) {
  5087. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5088. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5089. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5090. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5091. this._lookAtTemp.invert();
  5092. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5093. } else {
  5094. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5095. }
  5096. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5097. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5098. } else {
  5099. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5100. }
  5101. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5102. return this._viewMatrix;
  5103. };
  5104. return TargetCamera;
  5105. })(BABYLON.Camera);
  5106. BABYLON.TargetCamera = TargetCamera;
  5107. })(BABYLON || (BABYLON = {}));
  5108. var __extends = this.__extends || function (d, b) {
  5109. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5110. function __() { this.constructor = d; }
  5111. __.prototype = b.prototype;
  5112. d.prototype = new __();
  5113. };
  5114. var BABYLON;
  5115. (function (BABYLON) {
  5116. var FollowCamera = (function (_super) {
  5117. __extends(FollowCamera, _super);
  5118. function FollowCamera(name, position, scene) {
  5119. _super.call(this, name, position, scene);
  5120. this.radius = 12;
  5121. this.rotationOffset = 0;
  5122. this.heightOffset = 4;
  5123. this.cameraAcceleration = 0.05;
  5124. this.maxCameraSpeed = 20;
  5125. }
  5126. FollowCamera.prototype.getRadians = function (degrees) {
  5127. return degrees * Math.PI / 180;
  5128. };
  5129. FollowCamera.prototype.follow = function (cameraTarget) {
  5130. if (!cameraTarget)
  5131. return;
  5132. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5133. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5134. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5135. var dx = targetX - this.position.x;
  5136. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5137. var dz = (targetZ) - this.position.z;
  5138. var vx = dx * this.cameraAcceleration * 2;
  5139. var vy = dy * this.cameraAcceleration;
  5140. var vz = dz * this.cameraAcceleration * 2;
  5141. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5142. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5143. }
  5144. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5145. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5146. }
  5147. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5148. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5149. }
  5150. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5151. this.setTarget(cameraTarget.position);
  5152. };
  5153. FollowCamera.prototype._update = function () {
  5154. _super.prototype._update.call(this);
  5155. this.follow(this.target);
  5156. };
  5157. return FollowCamera;
  5158. })(BABYLON.TargetCamera);
  5159. BABYLON.FollowCamera = FollowCamera;
  5160. })(BABYLON || (BABYLON = {}));
  5161. var __extends = this.__extends || function (d, b) {
  5162. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5163. function __() { this.constructor = d; }
  5164. __.prototype = b.prototype;
  5165. d.prototype = new __();
  5166. };
  5167. var BABYLON;
  5168. (function (BABYLON) {
  5169. var FreeCamera = (function (_super) {
  5170. __extends(FreeCamera, _super);
  5171. function FreeCamera(name, position, scene) {
  5172. _super.call(this, name, position, scene);
  5173. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5174. this.keysUp = [38];
  5175. this.keysDown = [40];
  5176. this.keysLeft = [37];
  5177. this.keysRight = [39];
  5178. this.checkCollisions = false;
  5179. this.applyGravity = false;
  5180. this.angularSensibility = 2000.0;
  5181. this._keys = [];
  5182. this._collider = new BABYLON.Collider();
  5183. this._needMoveForGravity = true;
  5184. this._oldPosition = BABYLON.Vector3.Zero();
  5185. this._diffPosition = BABYLON.Vector3.Zero();
  5186. this._newPosition = BABYLON.Vector3.Zero();
  5187. }
  5188. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5189. var _this = this;
  5190. var previousPosition;
  5191. var engine = this.getEngine();
  5192. if (this._attachedElement) {
  5193. return;
  5194. }
  5195. this._attachedElement = element;
  5196. if (this._onMouseDown === undefined) {
  5197. this._onMouseDown = function (evt) {
  5198. previousPosition = {
  5199. x: evt.clientX,
  5200. y: evt.clientY
  5201. };
  5202. if (!noPreventDefault) {
  5203. evt.preventDefault();
  5204. }
  5205. };
  5206. this._onMouseUp = function (evt) {
  5207. previousPosition = null;
  5208. if (!noPreventDefault) {
  5209. evt.preventDefault();
  5210. }
  5211. };
  5212. this._onMouseOut = function (evt) {
  5213. previousPosition = null;
  5214. _this._keys = [];
  5215. if (!noPreventDefault) {
  5216. evt.preventDefault();
  5217. }
  5218. };
  5219. this._onMouseMove = function (evt) {
  5220. if (!previousPosition && !engine.isPointerLock) {
  5221. return;
  5222. }
  5223. var offsetX;
  5224. var offsetY;
  5225. if (!engine.isPointerLock) {
  5226. offsetX = evt.clientX - previousPosition.x;
  5227. offsetY = evt.clientY - previousPosition.y;
  5228. } else {
  5229. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5230. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5231. }
  5232. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5233. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5234. previousPosition = {
  5235. x: evt.clientX,
  5236. y: evt.clientY
  5237. };
  5238. if (!noPreventDefault) {
  5239. evt.preventDefault();
  5240. }
  5241. };
  5242. this._onKeyDown = function (evt) {
  5243. 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) {
  5244. var index = _this._keys.indexOf(evt.keyCode);
  5245. if (index === -1) {
  5246. _this._keys.push(evt.keyCode);
  5247. }
  5248. if (!noPreventDefault) {
  5249. evt.preventDefault();
  5250. }
  5251. }
  5252. };
  5253. this._onKeyUp = function (evt) {
  5254. 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) {
  5255. var index = _this._keys.indexOf(evt.keyCode);
  5256. if (index >= 0) {
  5257. _this._keys.splice(index, 1);
  5258. }
  5259. if (!noPreventDefault) {
  5260. evt.preventDefault();
  5261. }
  5262. }
  5263. };
  5264. this._onLostFocus = function () {
  5265. _this._keys = [];
  5266. };
  5267. this._reset = function () {
  5268. _this._keys = [];
  5269. previousPosition = null;
  5270. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5271. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5272. };
  5273. }
  5274. element.addEventListener("mousedown", this._onMouseDown, false);
  5275. element.addEventListener("mouseup", this._onMouseUp, false);
  5276. element.addEventListener("mouseout", this._onMouseOut, false);
  5277. element.addEventListener("mousemove", this._onMouseMove, false);
  5278. BABYLON.Tools.RegisterTopRootEvents([
  5279. { name: "keydown", handler: this._onKeyDown },
  5280. { name: "keyup", handler: this._onKeyUp },
  5281. { name: "blur", handler: this._onLostFocus }
  5282. ]);
  5283. };
  5284. FreeCamera.prototype.detachControl = function (element) {
  5285. if (this._attachedElement != element) {
  5286. return;
  5287. }
  5288. element.removeEventListener("mousedown", this._onMouseDown);
  5289. element.removeEventListener("mouseup", this._onMouseUp);
  5290. element.removeEventListener("mouseout", this._onMouseOut);
  5291. element.removeEventListener("mousemove", this._onMouseMove);
  5292. BABYLON.Tools.UnregisterTopRootEvents([
  5293. { name: "keydown", handler: this._onKeyDown },
  5294. { name: "keyup", handler: this._onKeyUp },
  5295. { name: "blur", handler: this._onLostFocus }
  5296. ]);
  5297. this._attachedElement = null;
  5298. if (this._reset) {
  5299. this._reset();
  5300. }
  5301. };
  5302. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5303. var globalPosition;
  5304. if (this.parent) {
  5305. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5306. } else {
  5307. globalPosition = this.position;
  5308. }
  5309. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5310. this._collider.radius = this.ellipsoid;
  5311. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5312. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5313. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5314. this.position.addInPlace(this._diffPosition);
  5315. if (this.onCollide) {
  5316. this.onCollide(this._collider.collidedMesh);
  5317. }
  5318. }
  5319. };
  5320. FreeCamera.prototype._checkInputs = function () {
  5321. if (!this._localDirection) {
  5322. this._localDirection = BABYLON.Vector3.Zero();
  5323. this._transformedDirection = BABYLON.Vector3.Zero();
  5324. }
  5325. for (var index = 0; index < this._keys.length; index++) {
  5326. var keyCode = this._keys[index];
  5327. var speed = this._computeLocalCameraSpeed();
  5328. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5329. this._localDirection.copyFromFloats(-speed, 0, 0);
  5330. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5331. this._localDirection.copyFromFloats(0, 0, speed);
  5332. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5333. this._localDirection.copyFromFloats(speed, 0, 0);
  5334. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5335. this._localDirection.copyFromFloats(0, 0, -speed);
  5336. }
  5337. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5338. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5339. this.cameraDirection.addInPlace(this._transformedDirection);
  5340. }
  5341. };
  5342. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5343. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5344. };
  5345. FreeCamera.prototype._updatePosition = function () {
  5346. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5347. this._collideWithWorld(this.cameraDirection);
  5348. if (this.applyGravity) {
  5349. var oldPosition = this.position;
  5350. this._collideWithWorld(this.getScene().gravity);
  5351. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5352. }
  5353. } else {
  5354. this.position.addInPlace(this.cameraDirection);
  5355. }
  5356. };
  5357. FreeCamera.prototype._update = function () {
  5358. this._checkInputs();
  5359. _super.prototype._update.call(this);
  5360. };
  5361. return FreeCamera;
  5362. })(BABYLON.TargetCamera);
  5363. BABYLON.FreeCamera = FreeCamera;
  5364. })(BABYLON || (BABYLON = {}));
  5365. var __extends = this.__extends || function (d, b) {
  5366. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5367. function __() { this.constructor = d; }
  5368. __.prototype = b.prototype;
  5369. d.prototype = new __();
  5370. };
  5371. var BABYLON;
  5372. (function (BABYLON) {
  5373. var TouchCamera = (function (_super) {
  5374. __extends(TouchCamera, _super);
  5375. function TouchCamera(name, position, scene) {
  5376. _super.call(this, name, position, scene);
  5377. this._offsetX = null;
  5378. this._offsetY = null;
  5379. this._pointerCount = 0;
  5380. this._pointerPressed = [];
  5381. this.angularSensibility = 200000.0;
  5382. this.moveSensibility = 500.0;
  5383. }
  5384. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5385. var _this = this;
  5386. var previousPosition;
  5387. if (this._attachedCanvas) {
  5388. return;
  5389. }
  5390. this._attachedCanvas = canvas;
  5391. if (this._onPointerDown === undefined) {
  5392. this._onPointerDown = function (evt) {
  5393. if (!noPreventDefault) {
  5394. evt.preventDefault();
  5395. }
  5396. _this._pointerPressed.push(evt.pointerId);
  5397. if (_this._pointerPressed.length !== 1) {
  5398. return;
  5399. }
  5400. previousPosition = {
  5401. x: evt.clientX,
  5402. y: evt.clientY
  5403. };
  5404. };
  5405. this._onPointerUp = function (evt) {
  5406. if (!noPreventDefault) {
  5407. evt.preventDefault();
  5408. }
  5409. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5410. if (index === -1) {
  5411. return;
  5412. }
  5413. _this._pointerPressed.splice(index, 1);
  5414. if (index != 0) {
  5415. return;
  5416. }
  5417. previousPosition = null;
  5418. _this._offsetX = null;
  5419. _this._offsetY = null;
  5420. };
  5421. this._onPointerMove = function (evt) {
  5422. if (!noPreventDefault) {
  5423. evt.preventDefault();
  5424. }
  5425. if (!previousPosition) {
  5426. return;
  5427. }
  5428. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5429. if (index != 0) {
  5430. return;
  5431. }
  5432. _this._offsetX = evt.clientX - previousPosition.x;
  5433. _this._offsetY = -(evt.clientY - previousPosition.y);
  5434. };
  5435. this._onLostFocus = function () {
  5436. _this._offsetX = null;
  5437. _this._offsetY = null;
  5438. };
  5439. }
  5440. canvas.addEventListener("pointerdown", this._onPointerDown);
  5441. canvas.addEventListener("pointerup", this._onPointerUp);
  5442. canvas.addEventListener("pointerout", this._onPointerUp);
  5443. canvas.addEventListener("pointermove", this._onPointerMove);
  5444. BABYLON.Tools.RegisterTopRootEvents([
  5445. { name: "blur", handler: this._onLostFocus }
  5446. ]);
  5447. };
  5448. TouchCamera.prototype.detachControl = function (canvas) {
  5449. if (this._attachedCanvas != canvas) {
  5450. return;
  5451. }
  5452. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5453. canvas.removeEventListener("pointerup", this._onPointerUp);
  5454. canvas.removeEventListener("pointerout", this._onPointerUp);
  5455. canvas.removeEventListener("pointermove", this._onPointerMove);
  5456. BABYLON.Tools.UnregisterTopRootEvents([
  5457. { name: "blur", handler: this._onLostFocus }
  5458. ]);
  5459. this._attachedCanvas = null;
  5460. };
  5461. TouchCamera.prototype._checkInputs = function () {
  5462. if (!this._offsetX) {
  5463. return;
  5464. }
  5465. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5466. if (this._pointerPressed.length > 1) {
  5467. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5468. } else {
  5469. var speed = this._computeLocalCameraSpeed();
  5470. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5471. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5472. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5473. }
  5474. };
  5475. return TouchCamera;
  5476. })(BABYLON.FreeCamera);
  5477. BABYLON.TouchCamera = TouchCamera;
  5478. })(BABYLON || (BABYLON = {}));
  5479. var __extends = this.__extends || function (d, b) {
  5480. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5481. function __() { this.constructor = d; }
  5482. __.prototype = b.prototype;
  5483. d.prototype = new __();
  5484. };
  5485. var BABYLON;
  5486. (function (BABYLON) {
  5487. var DeviceOrientationCamera = (function (_super) {
  5488. __extends(DeviceOrientationCamera, _super);
  5489. function DeviceOrientationCamera(name, position, scene) {
  5490. var _this = this;
  5491. _super.call(this, name, position, scene);
  5492. this._offsetX = null;
  5493. this._offsetY = null;
  5494. this._orientationGamma = 0;
  5495. this._orientationBeta = 0;
  5496. this._initialOrientationGamma = 0;
  5497. this._initialOrientationBeta = 0;
  5498. this.angularSensibility = 10000.0;
  5499. this.moveSensibility = 50.0;
  5500. window.addEventListener("resize", function () {
  5501. _this._initialOrientationGamma = null;
  5502. }, false);
  5503. }
  5504. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5505. var _this = this;
  5506. if (this._attachedCanvas) {
  5507. return;
  5508. }
  5509. this._attachedCanvas = canvas;
  5510. if (!this._orientationChanged) {
  5511. this._orientationChanged = function (evt) {
  5512. if (!_this._initialOrientationGamma) {
  5513. _this._initialOrientationGamma = evt.gamma;
  5514. _this._initialOrientationBeta = evt.beta;
  5515. }
  5516. _this._orientationGamma = evt.gamma;
  5517. _this._orientationBeta = evt.beta;
  5518. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5519. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5520. };
  5521. }
  5522. window.addEventListener("deviceorientation", this._orientationChanged);
  5523. };
  5524. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5525. if (this._attachedCanvas != canvas) {
  5526. return;
  5527. }
  5528. window.removeEventListener("deviceorientation", this._orientationChanged);
  5529. this._attachedCanvas = null;
  5530. this._orientationGamma = 0;
  5531. this._orientationBeta = 0;
  5532. this._initialOrientationGamma = 0;
  5533. this._initialOrientationBeta = 0;
  5534. };
  5535. DeviceOrientationCamera.prototype._checkInputs = function () {
  5536. if (!this._offsetX) {
  5537. return;
  5538. }
  5539. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5540. var speed = this._computeLocalCameraSpeed();
  5541. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5542. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5543. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5544. };
  5545. return DeviceOrientationCamera;
  5546. })(BABYLON.FreeCamera);
  5547. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5548. })(BABYLON || (BABYLON = {}));
  5549. var __extends = this.__extends || function (d, b) {
  5550. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5551. function __() { this.constructor = d; }
  5552. __.prototype = b.prototype;
  5553. d.prototype = new __();
  5554. };
  5555. var BABYLON;
  5556. (function (BABYLON) {
  5557. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5558. var ArcRotateCamera = (function (_super) {
  5559. __extends(ArcRotateCamera, _super);
  5560. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5561. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5562. this.alpha = alpha;
  5563. this.beta = beta;
  5564. this.radius = radius;
  5565. this.target = target;
  5566. this.inertialAlphaOffset = 0;
  5567. this.inertialBetaOffset = 0;
  5568. this.inertialRadiusOffset = 0;
  5569. this.lowerAlphaLimit = null;
  5570. this.upperAlphaLimit = null;
  5571. this.lowerBetaLimit = 0.01;
  5572. this.upperBetaLimit = Math.PI;
  5573. this.lowerRadiusLimit = null;
  5574. this.upperRadiusLimit = null;
  5575. this.angularSensibility = 1000.0;
  5576. this.wheelPrecision = 3.0;
  5577. this.keysUp = [38];
  5578. this.keysDown = [40];
  5579. this.keysLeft = [37];
  5580. this.keysRight = [39];
  5581. this.zoomOnFactor = 1;
  5582. this._keys = [];
  5583. this._viewMatrix = new BABYLON.Matrix();
  5584. this.checkCollisions = false;
  5585. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5586. this._collider = new BABYLON.Collider();
  5587. this._previousPosition = BABYLON.Vector3.Zero();
  5588. this._collisionVelocity = BABYLON.Vector3.Zero();
  5589. this._newPosition = BABYLON.Vector3.Zero();
  5590. this.getViewMatrix();
  5591. }
  5592. ArcRotateCamera.prototype._getTargetPosition = function () {
  5593. return this.target.position || this.target;
  5594. };
  5595. ArcRotateCamera.prototype._initCache = function () {
  5596. _super.prototype._initCache.call(this);
  5597. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5598. this._cache.alpha = undefined;
  5599. this._cache.beta = undefined;
  5600. this._cache.radius = undefined;
  5601. };
  5602. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5603. if (!ignoreParentClass) {
  5604. _super.prototype._updateCache.call(this);
  5605. }
  5606. this._cache.target.copyFrom(this._getTargetPosition());
  5607. this._cache.alpha = this.alpha;
  5608. this._cache.beta = this.beta;
  5609. this._cache.radius = this.radius;
  5610. };
  5611. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5612. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5613. return false;
  5614. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5615. };
  5616. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5617. var _this = this;
  5618. var previousPosition;
  5619. var pointerId;
  5620. if (this._attachedElement) {
  5621. return;
  5622. }
  5623. this._attachedElement = element;
  5624. var engine = this.getEngine();
  5625. if (this._onPointerDown === undefined) {
  5626. this._onPointerDown = function (evt) {
  5627. if (pointerId) {
  5628. return;
  5629. }
  5630. pointerId = evt.pointerId;
  5631. previousPosition = {
  5632. x: evt.clientX,
  5633. y: evt.clientY
  5634. };
  5635. if (!noPreventDefault) {
  5636. evt.preventDefault();
  5637. }
  5638. };
  5639. this._onPointerUp = function (evt) {
  5640. previousPosition = null;
  5641. pointerId = null;
  5642. if (!noPreventDefault) {
  5643. evt.preventDefault();
  5644. }
  5645. };
  5646. this._onPointerMove = function (evt) {
  5647. if (!previousPosition) {
  5648. return;
  5649. }
  5650. if (pointerId !== evt.pointerId) {
  5651. return;
  5652. }
  5653. var offsetX = evt.clientX - previousPosition.x;
  5654. var offsetY = evt.clientY - previousPosition.y;
  5655. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5656. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5657. previousPosition = {
  5658. x: evt.clientX,
  5659. y: evt.clientY
  5660. };
  5661. if (!noPreventDefault) {
  5662. evt.preventDefault();
  5663. }
  5664. };
  5665. this._onMouseMove = function (evt) {
  5666. if (!engine.isPointerLock) {
  5667. return;
  5668. }
  5669. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5670. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5671. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5672. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5673. if (!noPreventDefault) {
  5674. evt.preventDefault();
  5675. }
  5676. };
  5677. this._wheel = function (event) {
  5678. var delta = 0;
  5679. if (event.wheelDelta) {
  5680. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5681. } else if (event.detail) {
  5682. delta = -event.detail / _this.wheelPrecision;
  5683. }
  5684. if (delta)
  5685. _this.inertialRadiusOffset += delta;
  5686. if (event.preventDefault) {
  5687. if (!noPreventDefault) {
  5688. event.preventDefault();
  5689. }
  5690. }
  5691. };
  5692. this._onKeyDown = function (evt) {
  5693. 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) {
  5694. var index = _this._keys.indexOf(evt.keyCode);
  5695. if (index === -1) {
  5696. _this._keys.push(evt.keyCode);
  5697. }
  5698. if (evt.preventDefault) {
  5699. if (!noPreventDefault) {
  5700. evt.preventDefault();
  5701. }
  5702. }
  5703. }
  5704. };
  5705. this._onKeyUp = function (evt) {
  5706. 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) {
  5707. var index = _this._keys.indexOf(evt.keyCode);
  5708. if (index >= 0) {
  5709. _this._keys.splice(index, 1);
  5710. }
  5711. if (evt.preventDefault) {
  5712. if (!noPreventDefault) {
  5713. evt.preventDefault();
  5714. }
  5715. }
  5716. }
  5717. };
  5718. this._onLostFocus = function () {
  5719. _this._keys = [];
  5720. pointerId = null;
  5721. };
  5722. this._onGestureStart = function (e) {
  5723. if (window.MSGesture === undefined) {
  5724. return;
  5725. }
  5726. if (!_this._MSGestureHandler) {
  5727. _this._MSGestureHandler = new MSGesture();
  5728. _this._MSGestureHandler.target = element;
  5729. }
  5730. _this._MSGestureHandler.addPointer(e.pointerId);
  5731. };
  5732. this._onGesture = function (e) {
  5733. _this.radius *= e.scale;
  5734. if (e.preventDefault) {
  5735. if (!noPreventDefault) {
  5736. e.stopPropagation();
  5737. e.preventDefault();
  5738. }
  5739. }
  5740. };
  5741. this._reset = function () {
  5742. _this._keys = [];
  5743. _this.inertialAlphaOffset = 0;
  5744. _this.inertialBetaOffset = 0;
  5745. _this.inertialRadiusOffset = 0;
  5746. previousPosition = null;
  5747. pointerId = null;
  5748. };
  5749. }
  5750. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5751. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5752. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5753. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5754. element.addEventListener("mousemove", this._onMouseMove, false);
  5755. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5756. element.addEventListener("MSGestureChange", this._onGesture, false);
  5757. element.addEventListener('mousewheel', this._wheel, false);
  5758. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5759. BABYLON.Tools.RegisterTopRootEvents([
  5760. { name: "keydown", handler: this._onKeyDown },
  5761. { name: "keyup", handler: this._onKeyUp },
  5762. { name: "blur", handler: this._onLostFocus }
  5763. ]);
  5764. };
  5765. ArcRotateCamera.prototype.detachControl = function (element) {
  5766. if (this._attachedElement != element) {
  5767. return;
  5768. }
  5769. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5770. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5771. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5772. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5773. element.removeEventListener("mousemove", this._onMouseMove);
  5774. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5775. element.removeEventListener("MSGestureChange", this._onGesture);
  5776. element.removeEventListener('mousewheel', this._wheel);
  5777. element.removeEventListener('DOMMouseScroll', this._wheel);
  5778. BABYLON.Tools.UnregisterTopRootEvents([
  5779. { name: "keydown", handler: this._onKeyDown },
  5780. { name: "keyup", handler: this._onKeyUp },
  5781. { name: "blur", handler: this._onLostFocus }
  5782. ]);
  5783. this._MSGestureHandler = null;
  5784. this._attachedElement = null;
  5785. if (this._reset) {
  5786. this._reset();
  5787. }
  5788. };
  5789. ArcRotateCamera.prototype._update = function () {
  5790. for (var index = 0; index < this._keys.length; index++) {
  5791. var keyCode = this._keys[index];
  5792. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5793. this.inertialAlphaOffset -= 0.01;
  5794. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5795. this.inertialBetaOffset -= 0.01;
  5796. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5797. this.inertialAlphaOffset += 0.01;
  5798. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5799. this.inertialBetaOffset += 0.01;
  5800. }
  5801. }
  5802. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5803. this.alpha += this.inertialAlphaOffset;
  5804. this.beta += this.inertialBetaOffset;
  5805. this.radius -= this.inertialRadiusOffset;
  5806. this.inertialAlphaOffset *= this.inertia;
  5807. this.inertialBetaOffset *= this.inertia;
  5808. this.inertialRadiusOffset *= this.inertia;
  5809. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5810. this.inertialAlphaOffset = 0;
  5811. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5812. this.inertialBetaOffset = 0;
  5813. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5814. this.inertialRadiusOffset = 0;
  5815. }
  5816. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5817. this.alpha = this.lowerAlphaLimit;
  5818. }
  5819. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5820. this.alpha = this.upperAlphaLimit;
  5821. }
  5822. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5823. this.beta = this.lowerBetaLimit;
  5824. }
  5825. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5826. this.beta = this.upperBetaLimit;
  5827. }
  5828. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5829. this.radius = this.lowerRadiusLimit;
  5830. }
  5831. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5832. this.radius = this.upperRadiusLimit;
  5833. }
  5834. };
  5835. ArcRotateCamera.prototype.setPosition = function (position) {
  5836. var radiusv3 = position.subtract(this._getTargetPosition());
  5837. this.radius = radiusv3.length();
  5838. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5839. if (radiusv3.z < 0) {
  5840. this.alpha = 2 * Math.PI - this.alpha;
  5841. }
  5842. this.beta = Math.acos(radiusv3.y / this.radius);
  5843. };
  5844. ArcRotateCamera.prototype._getViewMatrix = function () {
  5845. var cosa = Math.cos(this.alpha);
  5846. var sina = Math.sin(this.alpha);
  5847. var cosb = Math.cos(this.beta);
  5848. var sinb = Math.sin(this.beta);
  5849. var target = this._getTargetPosition();
  5850. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5851. if (this.checkCollisions) {
  5852. this._collider.radius = this.collisionRadius;
  5853. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5854. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5855. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5856. this.position.copyFrom(this._previousPosition);
  5857. this.alpha = this._previousAlpha;
  5858. this.beta = this._previousBeta;
  5859. this.radius = this._previousRadius;
  5860. if (this.onCollide) {
  5861. this.onCollide(this._collider.collidedMesh);
  5862. }
  5863. }
  5864. }
  5865. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5866. this._previousAlpha = this.alpha;
  5867. this._previousBeta = this.beta;
  5868. this._previousRadius = this.radius;
  5869. this._previousPosition.copyFrom(this.position);
  5870. return this._viewMatrix;
  5871. };
  5872. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5873. meshes = meshes || this.getScene().meshes;
  5874. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5875. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5876. this.radius = distance * this.zoomOnFactor;
  5877. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5878. };
  5879. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5880. var meshesOrMinMaxVector;
  5881. var distance;
  5882. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  5883. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  5884. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  5885. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  5886. } else {
  5887. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  5888. distance = meshesOrMinMaxVectorAndDistance.distance;
  5889. }
  5890. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  5891. this.maxZ = distance * 2;
  5892. };
  5893. return ArcRotateCamera;
  5894. })(BABYLON.Camera);
  5895. BABYLON.ArcRotateCamera = ArcRotateCamera;
  5896. })(BABYLON || (BABYLON = {}));
  5897. var BABYLON;
  5898. (function (BABYLON) {
  5899. var Scene = (function () {
  5900. function Scene(engine) {
  5901. this.autoClear = true;
  5902. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5903. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  5904. this.forceWireframe = false;
  5905. this.cameraToUseForPointers = null;
  5906. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  5907. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  5908. this.fogDensity = 0.1;
  5909. this.fogStart = 0;
  5910. this.fogEnd = 1000.0;
  5911. this.lightsEnabled = true;
  5912. this.lights = new Array();
  5913. this.cameras = new Array();
  5914. this.activeCameras = new Array();
  5915. this.meshes = new Array();
  5916. this._geometries = new Array();
  5917. this.materials = new Array();
  5918. this.multiMaterials = new Array();
  5919. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  5920. this.texturesEnabled = true;
  5921. this.textures = new Array();
  5922. this.particlesEnabled = true;
  5923. this.particleSystems = new Array();
  5924. this.spriteManagers = new Array();
  5925. this.layers = new Array();
  5926. this.skeletons = new Array();
  5927. this.lensFlareSystems = new Array();
  5928. this.collisionsEnabled = true;
  5929. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  5930. this.postProcessesEnabled = true;
  5931. this.renderTargetsEnabled = true;
  5932. this.customRenderTargets = new Array();
  5933. this.importedMeshesFiles = new Array();
  5934. this._actionManagers = new Array();
  5935. this._meshesForIntersections = new BABYLON.SmartArray(256);
  5936. this._totalVertices = 0;
  5937. this._activeVertices = 0;
  5938. this._activeParticles = 0;
  5939. this._lastFrameDuration = 0;
  5940. this._evaluateActiveMeshesDuration = 0;
  5941. this._renderTargetsDuration = 0;
  5942. this._particlesDuration = 0;
  5943. this._renderDuration = 0;
  5944. this._spritesDuration = 0;
  5945. this._animationRatio = 0;
  5946. this._renderId = 0;
  5947. this._executeWhenReadyTimeoutId = -1;
  5948. this._toBeDisposed = new BABYLON.SmartArray(256);
  5949. this._onReadyCallbacks = new Array();
  5950. this._pendingData = [];
  5951. this._onBeforeRenderCallbacks = new Array();
  5952. this._activeMeshes = new BABYLON.SmartArray(256);
  5953. this._processedMaterials = new BABYLON.SmartArray(256);
  5954. this._renderTargets = new BABYLON.SmartArray(256);
  5955. this._activeParticleSystems = new BABYLON.SmartArray(256);
  5956. this._activeSkeletons = new BABYLON.SmartArray(32);
  5957. this._activeAnimatables = new Array();
  5958. this._transformMatrix = BABYLON.Matrix.Zero();
  5959. this._scaledPosition = BABYLON.Vector3.Zero();
  5960. this._scaledVelocity = BABYLON.Vector3.Zero();
  5961. this._engine = engine;
  5962. engine.scenes.push(this);
  5963. this._renderingManager = new BABYLON.RenderingManager(this);
  5964. this.postProcessManager = new BABYLON.PostProcessManager(this);
  5965. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  5966. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  5967. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  5968. this.attachControl();
  5969. }
  5970. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  5971. get: function () {
  5972. return this._meshUnderPointer;
  5973. },
  5974. enumerable: true,
  5975. configurable: true
  5976. });
  5977. Object.defineProperty(Scene.prototype, "pointerX", {
  5978. get: function () {
  5979. return this._pointerX;
  5980. },
  5981. enumerable: true,
  5982. configurable: true
  5983. });
  5984. Object.defineProperty(Scene.prototype, "pointerY", {
  5985. get: function () {
  5986. return this._pointerY;
  5987. },
  5988. enumerable: true,
  5989. configurable: true
  5990. });
  5991. Scene.prototype.getBoundingBoxRenderer = function () {
  5992. return this._boundingBoxRenderer;
  5993. };
  5994. Scene.prototype.getOutlineRenderer = function () {
  5995. return this._outlineRenderer;
  5996. };
  5997. Scene.prototype.getEngine = function () {
  5998. return this._engine;
  5999. };
  6000. Scene.prototype.getTotalVertices = function () {
  6001. return this._totalVertices;
  6002. };
  6003. Scene.prototype.getActiveVertices = function () {
  6004. return this._activeVertices;
  6005. };
  6006. Scene.prototype.getActiveParticles = function () {
  6007. return this._activeParticles;
  6008. };
  6009. Scene.prototype.getLastFrameDuration = function () {
  6010. return this._lastFrameDuration;
  6011. };
  6012. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6013. return this._evaluateActiveMeshesDuration;
  6014. };
  6015. Scene.prototype.getActiveMeshes = function () {
  6016. return this._activeMeshes;
  6017. };
  6018. Scene.prototype.getRenderTargetsDuration = function () {
  6019. return this._renderTargetsDuration;
  6020. };
  6021. Scene.prototype.getRenderDuration = function () {
  6022. return this._renderDuration;
  6023. };
  6024. Scene.prototype.getParticlesDuration = function () {
  6025. return this._particlesDuration;
  6026. };
  6027. Scene.prototype.getSpritesDuration = function () {
  6028. return this._spritesDuration;
  6029. };
  6030. Scene.prototype.getAnimationRatio = function () {
  6031. return this._animationRatio;
  6032. };
  6033. Scene.prototype.getRenderId = function () {
  6034. return this._renderId;
  6035. };
  6036. Scene.prototype._updatePointerPosition = function (evt) {
  6037. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6038. this._pointerX = evt.clientX - canvasRect.left;
  6039. this._pointerY = evt.clientY - canvasRect.top;
  6040. if (this.cameraToUseForPointers) {
  6041. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6042. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6043. }
  6044. };
  6045. Scene.prototype.attachControl = function () {
  6046. var _this = this;
  6047. this._onPointerMove = function (evt) {
  6048. var canvas = _this._engine.getRenderingCanvas();
  6049. _this._updatePointerPosition(evt);
  6050. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6051. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6052. }, false, _this.cameraToUseForPointers);
  6053. if (pickResult.hit) {
  6054. _this._meshUnderPointer = pickResult.pickedMesh;
  6055. _this.setPointerOverMesh(pickResult.pickedMesh);
  6056. canvas.style.cursor = "pointer";
  6057. } else {
  6058. _this.setPointerOverMesh(null);
  6059. canvas.style.cursor = "";
  6060. _this._meshUnderPointer = null;
  6061. }
  6062. };
  6063. this._onPointerDown = function (evt) {
  6064. var predicate = null;
  6065. if (!_this.onPointerDown) {
  6066. predicate = function (mesh) {
  6067. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6068. };
  6069. }
  6070. _this._updatePointerPosition(evt);
  6071. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6072. if (pickResult.hit) {
  6073. if (pickResult.pickedMesh.actionManager) {
  6074. switch (evt.button) {
  6075. case 0:
  6076. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6077. break;
  6078. case 1:
  6079. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6080. break;
  6081. case 2:
  6082. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6083. break;
  6084. }
  6085. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6086. }
  6087. }
  6088. if (_this.onPointerDown) {
  6089. _this.onPointerDown(evt, pickResult);
  6090. }
  6091. };
  6092. this._onKeyDown = function (evt) {
  6093. if (_this.actionManager) {
  6094. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6095. }
  6096. };
  6097. this._onKeyUp = function (evt) {
  6098. if (_this.actionManager) {
  6099. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6100. }
  6101. };
  6102. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6103. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6104. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6105. window.addEventListener("keydown", this._onKeyDown, false);
  6106. window.addEventListener("keyup", this._onKeyUp, false);
  6107. };
  6108. Scene.prototype.detachControl = function () {
  6109. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6110. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6111. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6112. window.removeEventListener("keydown", this._onKeyDown);
  6113. window.removeEventListener("keyup", this._onKeyUp);
  6114. };
  6115. Scene.prototype.isReady = function () {
  6116. if (this._pendingData.length > 0) {
  6117. return false;
  6118. }
  6119. for (var index = 0; index < this._geometries.length; index++) {
  6120. var geometry = this._geometries[index];
  6121. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6122. return false;
  6123. }
  6124. }
  6125. for (index = 0; index < this.meshes.length; index++) {
  6126. var mesh = this.meshes[index];
  6127. if (!mesh.isReady()) {
  6128. return false;
  6129. }
  6130. var mat = mesh.material;
  6131. if (mat) {
  6132. if (!mat.isReady(mesh)) {
  6133. return false;
  6134. }
  6135. }
  6136. }
  6137. return true;
  6138. };
  6139. Scene.prototype.registerBeforeRender = function (func) {
  6140. this._onBeforeRenderCallbacks.push(func);
  6141. };
  6142. Scene.prototype.unregisterBeforeRender = function (func) {
  6143. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6144. if (index > -1) {
  6145. this._onBeforeRenderCallbacks.splice(index, 1);
  6146. }
  6147. };
  6148. Scene.prototype._addPendingData = function (data) {
  6149. this._pendingData.push(data);
  6150. };
  6151. Scene.prototype._removePendingData = function (data) {
  6152. var index = this._pendingData.indexOf(data);
  6153. if (index !== -1) {
  6154. this._pendingData.splice(index, 1);
  6155. }
  6156. };
  6157. Scene.prototype.getWaitingItemsCount = function () {
  6158. return this._pendingData.length;
  6159. };
  6160. Scene.prototype.executeWhenReady = function (func) {
  6161. var _this = this;
  6162. this._onReadyCallbacks.push(func);
  6163. if (this._executeWhenReadyTimeoutId !== -1) {
  6164. return;
  6165. }
  6166. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6167. _this._checkIsReady();
  6168. }, 150);
  6169. };
  6170. Scene.prototype._checkIsReady = function () {
  6171. var _this = this;
  6172. if (this.isReady()) {
  6173. this._onReadyCallbacks.forEach(function (func) {
  6174. func();
  6175. });
  6176. this._onReadyCallbacks = [];
  6177. this._executeWhenReadyTimeoutId = -1;
  6178. return;
  6179. }
  6180. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6181. _this._checkIsReady();
  6182. }, 150);
  6183. };
  6184. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6185. if (speedRatio === undefined) {
  6186. speedRatio = 1.0;
  6187. }
  6188. this.stopAnimation(target);
  6189. if (!animatable) {
  6190. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6191. }
  6192. if (target.animations) {
  6193. animatable.appendAnimations(target, target.animations);
  6194. }
  6195. if (target.getAnimatables) {
  6196. var animatables = target.getAnimatables();
  6197. for (var index = 0; index < animatables.length; index++) {
  6198. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6199. }
  6200. }
  6201. return animatable;
  6202. };
  6203. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6204. if (speedRatio === undefined) {
  6205. speedRatio = 1.0;
  6206. }
  6207. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6208. return animatable;
  6209. };
  6210. Scene.prototype.getAnimatableByTarget = function (target) {
  6211. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6212. if (this._activeAnimatables[index].target === target) {
  6213. return this._activeAnimatables[index];
  6214. }
  6215. }
  6216. return null;
  6217. };
  6218. Scene.prototype.stopAnimation = function (target) {
  6219. var animatable = this.getAnimatableByTarget(target);
  6220. if (animatable) {
  6221. animatable.stop();
  6222. }
  6223. };
  6224. Scene.prototype._animate = function () {
  6225. if (!this._animationStartDate) {
  6226. this._animationStartDate = new Date().getTime();
  6227. }
  6228. var now = new Date().getTime();
  6229. var delay = now - this._animationStartDate;
  6230. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6231. if (!this._activeAnimatables[index]._animate(delay)) {
  6232. this._activeAnimatables.splice(index, 1);
  6233. index--;
  6234. }
  6235. }
  6236. };
  6237. Scene.prototype.getViewMatrix = function () {
  6238. return this._viewMatrix;
  6239. };
  6240. Scene.prototype.getProjectionMatrix = function () {
  6241. return this._projectionMatrix;
  6242. };
  6243. Scene.prototype.getTransformMatrix = function () {
  6244. return this._transformMatrix;
  6245. };
  6246. Scene.prototype.setTransformMatrix = function (view, projection) {
  6247. this._viewMatrix = view;
  6248. this._projectionMatrix = projection;
  6249. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6250. };
  6251. Scene.prototype.setActiveCameraByID = function (id) {
  6252. var camera = this.getCameraByID(id);
  6253. if (camera) {
  6254. this.activeCamera = camera;
  6255. return camera;
  6256. }
  6257. return null;
  6258. };
  6259. Scene.prototype.setActiveCameraByName = function (name) {
  6260. var camera = this.getCameraByName(name);
  6261. if (camera) {
  6262. this.activeCamera = camera;
  6263. return camera;
  6264. }
  6265. return null;
  6266. };
  6267. Scene.prototype.getMaterialByID = function (id) {
  6268. for (var index = 0; index < this.materials.length; index++) {
  6269. if (this.materials[index].id === id) {
  6270. return this.materials[index];
  6271. }
  6272. }
  6273. return null;
  6274. };
  6275. Scene.prototype.getMaterialByName = function (name) {
  6276. for (var index = 0; index < this.materials.length; index++) {
  6277. if (this.materials[index].name === name) {
  6278. return this.materials[index];
  6279. }
  6280. }
  6281. return null;
  6282. };
  6283. Scene.prototype.getCameraByID = function (id) {
  6284. for (var index = 0; index < this.cameras.length; index++) {
  6285. if (this.cameras[index].id === id) {
  6286. return this.cameras[index];
  6287. }
  6288. }
  6289. return null;
  6290. };
  6291. Scene.prototype.getCameraByName = function (name) {
  6292. for (var index = 0; index < this.cameras.length; index++) {
  6293. if (this.cameras[index].name === name) {
  6294. return this.cameras[index];
  6295. }
  6296. }
  6297. return null;
  6298. };
  6299. Scene.prototype.getLightByName = function (name) {
  6300. for (var index = 0; index < this.lights.length; index++) {
  6301. if (this.lights[index].name === name) {
  6302. return this.lights[index];
  6303. }
  6304. }
  6305. return null;
  6306. };
  6307. Scene.prototype.getLightByID = function (id) {
  6308. for (var index = 0; index < this.lights.length; index++) {
  6309. if (this.lights[index].id === id) {
  6310. return this.lights[index];
  6311. }
  6312. }
  6313. return null;
  6314. };
  6315. Scene.prototype.getGeometryByID = function (id) {
  6316. for (var index = 0; index < this._geometries.length; index++) {
  6317. if (this._geometries[index].id === id) {
  6318. return this._geometries[index];
  6319. }
  6320. }
  6321. return null;
  6322. };
  6323. Scene.prototype.pushGeometry = function (geometry, force) {
  6324. if (!force && this.getGeometryByID(geometry.id)) {
  6325. return false;
  6326. }
  6327. this._geometries.push(geometry);
  6328. return true;
  6329. };
  6330. Scene.prototype.getGeometries = function () {
  6331. return this._geometries;
  6332. };
  6333. Scene.prototype.getMeshByID = function (id) {
  6334. for (var index = 0; index < this.meshes.length; index++) {
  6335. if (this.meshes[index].id === id) {
  6336. return this.meshes[index];
  6337. }
  6338. }
  6339. return null;
  6340. };
  6341. Scene.prototype.getLastMeshByID = function (id) {
  6342. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6343. if (this.meshes[index].id === id) {
  6344. return this.meshes[index];
  6345. }
  6346. }
  6347. return null;
  6348. };
  6349. Scene.prototype.getLastEntryByID = function (id) {
  6350. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6351. if (this.meshes[index].id === id) {
  6352. return this.meshes[index];
  6353. }
  6354. }
  6355. for (index = this.cameras.length - 1; index >= 0; index--) {
  6356. if (this.cameras[index].id === id) {
  6357. return this.cameras[index];
  6358. }
  6359. }
  6360. for (index = this.lights.length - 1; index >= 0; index--) {
  6361. if (this.lights[index].id === id) {
  6362. return this.lights[index];
  6363. }
  6364. }
  6365. return null;
  6366. };
  6367. Scene.prototype.getMeshByName = function (name) {
  6368. for (var index = 0; index < this.meshes.length; index++) {
  6369. if (this.meshes[index].name === name) {
  6370. return this.meshes[index];
  6371. }
  6372. }
  6373. return null;
  6374. };
  6375. Scene.prototype.getLastSkeletonByID = function (id) {
  6376. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6377. if (this.skeletons[index].id === id) {
  6378. return this.skeletons[index];
  6379. }
  6380. }
  6381. return null;
  6382. };
  6383. Scene.prototype.getSkeletonById = function (id) {
  6384. for (var index = 0; index < this.skeletons.length; index++) {
  6385. if (this.skeletons[index].id === id) {
  6386. return this.skeletons[index];
  6387. }
  6388. }
  6389. return null;
  6390. };
  6391. Scene.prototype.getSkeletonByName = function (name) {
  6392. for (var index = 0; index < this.skeletons.length; index++) {
  6393. if (this.skeletons[index].name === name) {
  6394. return this.skeletons[index];
  6395. }
  6396. }
  6397. return null;
  6398. };
  6399. Scene.prototype.isActiveMesh = function (mesh) {
  6400. return (this._activeMeshes.indexOf(mesh) !== -1);
  6401. };
  6402. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6403. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6404. var material = subMesh.getMaterial();
  6405. if (mesh.showSubMeshesBoundingBox) {
  6406. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6407. }
  6408. if (material) {
  6409. if (material.getRenderTargetTextures) {
  6410. if (this._processedMaterials.indexOf(material) === -1) {
  6411. this._processedMaterials.push(material);
  6412. this._renderTargets.concat(material.getRenderTargetTextures());
  6413. }
  6414. }
  6415. this._activeVertices += subMesh.verticesCount;
  6416. this._renderingManager.dispatch(subMesh);
  6417. }
  6418. }
  6419. };
  6420. Scene.prototype._evaluateActiveMeshes = function () {
  6421. this._activeMeshes.reset();
  6422. this._renderingManager.reset();
  6423. this._processedMaterials.reset();
  6424. this._activeParticleSystems.reset();
  6425. this._activeSkeletons.reset();
  6426. this._boundingBoxRenderer.reset();
  6427. if (!this._frustumPlanes) {
  6428. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6429. } else {
  6430. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6431. }
  6432. var meshes;
  6433. var len;
  6434. if (this._selectionOctree) {
  6435. var selection = this._selectionOctree.select(this._frustumPlanes);
  6436. meshes = selection.data;
  6437. len = selection.length;
  6438. } else {
  6439. len = this.meshes.length;
  6440. meshes = this.meshes;
  6441. }
  6442. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6443. var mesh = meshes[meshIndex];
  6444. this._totalVertices += mesh.getTotalVertices();
  6445. if (!mesh.isReady()) {
  6446. continue;
  6447. }
  6448. mesh.computeWorldMatrix();
  6449. mesh._preActivate();
  6450. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6451. this._meshesForIntersections.pushNoDuplicate(mesh);
  6452. }
  6453. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6454. this._activeMeshes.push(mesh);
  6455. mesh._activate(this._renderId);
  6456. this._activeMesh(mesh);
  6457. }
  6458. }
  6459. var beforeParticlesDate = new Date().getTime();
  6460. if (this.particlesEnabled) {
  6461. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6462. var particleSystem = this.particleSystems[particleIndex];
  6463. if (!particleSystem.isStarted()) {
  6464. continue;
  6465. }
  6466. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6467. this._activeParticleSystems.push(particleSystem);
  6468. particleSystem.animate();
  6469. }
  6470. }
  6471. }
  6472. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6473. };
  6474. Scene.prototype._activeMesh = function (mesh) {
  6475. if (mesh.skeleton) {
  6476. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6477. }
  6478. if (mesh.showBoundingBox) {
  6479. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6480. }
  6481. if (mesh.subMeshes) {
  6482. var len;
  6483. var subMeshes;
  6484. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6485. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6486. len = intersections.length;
  6487. subMeshes = intersections.data;
  6488. } else {
  6489. subMeshes = mesh.subMeshes;
  6490. len = subMeshes.length;
  6491. }
  6492. for (var subIndex = 0; subIndex < len; subIndex++) {
  6493. var subMesh = subMeshes[subIndex];
  6494. this._evaluateSubMesh(subMesh, mesh);
  6495. }
  6496. }
  6497. };
  6498. Scene.prototype.updateTransformMatrix = function (force) {
  6499. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6500. };
  6501. Scene.prototype._renderForCamera = function (camera) {
  6502. var engine = this._engine;
  6503. this.activeCamera = camera;
  6504. if (!this.activeCamera)
  6505. throw new Error("Active camera not set");
  6506. engine.setViewport(this.activeCamera.viewport);
  6507. this._renderId++;
  6508. this.updateTransformMatrix();
  6509. if (this.beforeCameraRender) {
  6510. this.beforeCameraRender(this.activeCamera);
  6511. }
  6512. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6513. this._evaluateActiveMeshes();
  6514. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6515. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6516. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6517. skeleton.prepare();
  6518. }
  6519. var beforeRenderTargetDate = new Date().getTime();
  6520. if (this.renderTargetsEnabled) {
  6521. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6522. var renderTarget = this._renderTargets.data[renderIndex];
  6523. if (renderTarget._shouldRender()) {
  6524. this._renderId++;
  6525. renderTarget.render();
  6526. }
  6527. }
  6528. this._renderId++;
  6529. }
  6530. if (this._renderTargets.length > 0) {
  6531. engine.restoreDefaultFramebuffer();
  6532. }
  6533. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6534. this.postProcessManager._prepareFrame();
  6535. var beforeRenderDate = new Date().getTime();
  6536. if (this.layers.length) {
  6537. engine.setDepthBuffer(false);
  6538. var layerIndex;
  6539. var layer;
  6540. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6541. layer = this.layers[layerIndex];
  6542. if (layer.isBackground) {
  6543. layer.render();
  6544. }
  6545. }
  6546. engine.setDepthBuffer(true);
  6547. }
  6548. this._renderingManager.render(null, null, true, true);
  6549. this._boundingBoxRenderer.render();
  6550. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6551. this.lensFlareSystems[lensFlareSystemIndex].render();
  6552. }
  6553. if (this.layers.length) {
  6554. engine.setDepthBuffer(false);
  6555. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6556. layer = this.layers[layerIndex];
  6557. if (!layer.isBackground) {
  6558. layer.render();
  6559. }
  6560. }
  6561. engine.setDepthBuffer(true);
  6562. }
  6563. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6564. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6565. this.activeCamera._updateFromScene();
  6566. this._renderTargets.reset();
  6567. if (this.afterCameraRender) {
  6568. this.afterCameraRender(this.activeCamera);
  6569. }
  6570. };
  6571. Scene.prototype._processSubCameras = function (camera) {
  6572. if (camera.subCameras.length == 0) {
  6573. this._renderForCamera(camera);
  6574. return;
  6575. }
  6576. for (var index = 0; index < camera.subCameras.length; index++) {
  6577. this._renderForCamera(camera.subCameras[index]);
  6578. }
  6579. this.activeCamera = camera;
  6580. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6581. this.activeCamera._updateFromScene();
  6582. };
  6583. Scene.prototype._checkIntersections = function () {
  6584. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6585. var sourceMesh = this._meshesForIntersections.data[index];
  6586. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6587. var action = sourceMesh.actionManager.actions[actionIndex];
  6588. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6589. var otherMesh = action.getTriggerParameter();
  6590. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6591. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6592. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6593. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6594. sourceMesh._intersectionsInProgress.push(otherMesh);
  6595. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6596. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6597. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6598. if (indexOfOther > -1) {
  6599. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6600. }
  6601. }
  6602. }
  6603. }
  6604. }
  6605. };
  6606. Scene.prototype.render = function () {
  6607. var startDate = new Date().getTime();
  6608. this._particlesDuration = 0;
  6609. this._spritesDuration = 0;
  6610. this._activeParticles = 0;
  6611. this._renderDuration = 0;
  6612. this._evaluateActiveMeshesDuration = 0;
  6613. this._totalVertices = 0;
  6614. this._activeVertices = 0;
  6615. this._meshesForIntersections.reset();
  6616. if (this.actionManager) {
  6617. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6618. }
  6619. if (this.beforeRender) {
  6620. this.beforeRender();
  6621. }
  6622. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6623. this._onBeforeRenderCallbacks[callbackIndex]();
  6624. }
  6625. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6626. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6627. this._animate();
  6628. if (this._physicsEngine) {
  6629. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6630. }
  6631. var beforeRenderTargetDate = new Date().getTime();
  6632. var engine = this.getEngine();
  6633. if (this.renderTargetsEnabled) {
  6634. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6635. var renderTarget = this.customRenderTargets[customIndex];
  6636. if (renderTarget._shouldRender()) {
  6637. this._renderId++;
  6638. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6639. if (!this.activeCamera)
  6640. throw new Error("Active camera not set");
  6641. engine.setViewport(this.activeCamera.viewport);
  6642. this.updateTransformMatrix();
  6643. renderTarget.render();
  6644. }
  6645. }
  6646. this._renderId++;
  6647. }
  6648. if (this.customRenderTargets.length > 0) {
  6649. engine.restoreDefaultFramebuffer();
  6650. }
  6651. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6652. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6653. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6654. var light = this.lights[lightIndex];
  6655. var shadowGenerator = light.getShadowGenerator();
  6656. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6657. this._renderTargets.push(shadowGenerator.getShadowMap());
  6658. }
  6659. }
  6660. this.postProcessRenderPipelineManager.update();
  6661. if (this.activeCameras.length > 0) {
  6662. var currentRenderId = this._renderId;
  6663. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6664. this._renderId = currentRenderId;
  6665. this._processSubCameras(this.activeCameras[cameraIndex]);
  6666. }
  6667. } else {
  6668. if (!this.activeCamera) {
  6669. throw new Error("No camera defined");
  6670. }
  6671. this._processSubCameras(this.activeCamera);
  6672. }
  6673. this._checkIntersections();
  6674. if (this.afterRender) {
  6675. this.afterRender();
  6676. }
  6677. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6678. this._toBeDisposed.data[index].dispose();
  6679. this._toBeDisposed[index] = null;
  6680. }
  6681. this._toBeDisposed.reset();
  6682. this._lastFrameDuration = new Date().getTime() - startDate;
  6683. };
  6684. Scene.prototype.dispose = function () {
  6685. this.beforeRender = null;
  6686. this.afterRender = null;
  6687. this.skeletons = [];
  6688. this._boundingBoxRenderer.dispose();
  6689. if (this.onDispose) {
  6690. this.onDispose();
  6691. }
  6692. this.detachControl();
  6693. var canvas = this._engine.getRenderingCanvas();
  6694. var index;
  6695. for (index = 0; index < this.cameras.length; index++) {
  6696. this.cameras[index].detachControl(canvas);
  6697. }
  6698. while (this.lights.length) {
  6699. this.lights[0].dispose();
  6700. }
  6701. while (this.meshes.length) {
  6702. this.meshes[0].dispose(true);
  6703. }
  6704. while (this.cameras.length) {
  6705. this.cameras[0].dispose();
  6706. }
  6707. while (this.materials.length) {
  6708. this.materials[0].dispose();
  6709. }
  6710. while (this.particleSystems.length) {
  6711. this.particleSystems[0].dispose();
  6712. }
  6713. while (this.spriteManagers.length) {
  6714. this.spriteManagers[0].dispose();
  6715. }
  6716. while (this.layers.length) {
  6717. this.layers[0].dispose();
  6718. }
  6719. while (this.textures.length) {
  6720. this.textures[0].dispose();
  6721. }
  6722. this.postProcessManager.dispose();
  6723. if (this._physicsEngine) {
  6724. this.disablePhysicsEngine();
  6725. }
  6726. index = this._engine.scenes.indexOf(this);
  6727. if (index > -1) {
  6728. this._engine.scenes.splice(index, 1);
  6729. }
  6730. this._engine.wipeCaches();
  6731. };
  6732. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6733. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6734. position.divideToRef(collider.radius, this._scaledPosition);
  6735. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6736. collider.retry = 0;
  6737. collider.initialVelocity = this._scaledVelocity;
  6738. collider.initialPosition = this._scaledPosition;
  6739. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6740. finalPosition.multiplyInPlace(collider.radius);
  6741. };
  6742. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6743. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6744. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6745. if (collider.retry >= maximumRetry) {
  6746. finalPosition.copyFrom(position);
  6747. return;
  6748. }
  6749. collider._initialize(position, velocity, closeDistance);
  6750. for (var index = 0; index < this.meshes.length; index++) {
  6751. var mesh = this.meshes[index];
  6752. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6753. mesh._checkCollision(collider);
  6754. }
  6755. }
  6756. if (!collider.collisionFound) {
  6757. position.addToRef(velocity, finalPosition);
  6758. return;
  6759. }
  6760. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6761. collider._getResponse(position, velocity);
  6762. }
  6763. if (velocity.length() <= closeDistance) {
  6764. finalPosition.copyFrom(position);
  6765. return;
  6766. }
  6767. collider.retry++;
  6768. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6769. };
  6770. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6771. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6772. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6773. if (!this._selectionOctree) {
  6774. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6775. }
  6776. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6777. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6778. for (var index = 0; index < this.meshes.length; index++) {
  6779. var mesh = this.meshes[index];
  6780. mesh.computeWorldMatrix(true);
  6781. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6782. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6783. BABYLON.Tools.CheckExtends(minBox, min, max);
  6784. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6785. }
  6786. this._selectionOctree.update(min, max, this.meshes);
  6787. return this._selectionOctree;
  6788. };
  6789. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6790. var engine = this._engine;
  6791. if (!camera) {
  6792. if (!this.activeCamera)
  6793. throw new Error("Active camera not set");
  6794. camera = this.activeCamera;
  6795. }
  6796. var cameraViewport = camera.viewport;
  6797. var viewport = cameraViewport.toGlobal(engine);
  6798. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6799. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6800. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6801. };
  6802. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6803. var pickingInfo = null;
  6804. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6805. var mesh = this.meshes[meshIndex];
  6806. if (predicate) {
  6807. if (!predicate(mesh)) {
  6808. continue;
  6809. }
  6810. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6811. continue;
  6812. }
  6813. var world = mesh.getWorldMatrix();
  6814. var ray = rayFunction(world);
  6815. var result = mesh.intersects(ray, fastCheck);
  6816. if (!result || !result.hit)
  6817. continue;
  6818. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6819. continue;
  6820. pickingInfo = result;
  6821. if (fastCheck) {
  6822. break;
  6823. }
  6824. }
  6825. return pickingInfo || new BABYLON.PickingInfo();
  6826. };
  6827. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6828. var _this = this;
  6829. return this._internalPick(function (world) {
  6830. return _this.createPickingRay(x, y, world, camera);
  6831. }, predicate, fastCheck);
  6832. };
  6833. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6834. var _this = this;
  6835. return this._internalPick(function (world) {
  6836. if (!_this._pickWithRayInverseMatrix) {
  6837. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6838. }
  6839. world.invertToRef(_this._pickWithRayInverseMatrix);
  6840. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6841. }, predicate, fastCheck);
  6842. };
  6843. Scene.prototype.setPointerOverMesh = function (mesh) {
  6844. if (this._pointerOverMesh === mesh) {
  6845. return;
  6846. }
  6847. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6848. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6849. }
  6850. this._pointerOverMesh = mesh;
  6851. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6852. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6853. }
  6854. };
  6855. Scene.prototype.getPointerOverMesh = function () {
  6856. return this._pointerOverMesh;
  6857. };
  6858. Scene.prototype.getPhysicsEngine = function () {
  6859. return this._physicsEngine;
  6860. };
  6861. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6862. if (this._physicsEngine) {
  6863. return true;
  6864. }
  6865. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6866. if (!this._physicsEngine.isSupported()) {
  6867. this._physicsEngine = null;
  6868. return false;
  6869. }
  6870. this._physicsEngine._initialize(gravity);
  6871. return true;
  6872. };
  6873. Scene.prototype.disablePhysicsEngine = function () {
  6874. if (!this._physicsEngine) {
  6875. return;
  6876. }
  6877. this._physicsEngine.dispose();
  6878. this._physicsEngine = undefined;
  6879. };
  6880. Scene.prototype.isPhysicsEnabled = function () {
  6881. return this._physicsEngine !== undefined;
  6882. };
  6883. Scene.prototype.setGravity = function (gravity) {
  6884. if (!this._physicsEngine) {
  6885. return;
  6886. }
  6887. this._physicsEngine._setGravity(gravity);
  6888. };
  6889. Scene.prototype.createCompoundImpostor = function (parts, options) {
  6890. if (parts.parts) {
  6891. options = parts;
  6892. parts = parts.parts;
  6893. }
  6894. if (!this._physicsEngine) {
  6895. return null;
  6896. }
  6897. for (var index = 0; index < parts.length; index++) {
  6898. var mesh = parts[index].mesh;
  6899. mesh._physicImpostor = parts[index].impostor;
  6900. mesh._physicsMass = options.mass / parts.length;
  6901. mesh._physicsFriction = options.friction;
  6902. mesh._physicRestitution = options.restitution;
  6903. }
  6904. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  6905. };
  6906. Scene.prototype.deleteCompoundImpostor = function (compound) {
  6907. for (var index = 0; index < compound.parts.length; index++) {
  6908. var mesh = compound.parts[index].mesh;
  6909. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  6910. this._physicsEngine._unregisterMesh(mesh);
  6911. }
  6912. };
  6913. Scene.prototype._getByTags = function (list, tagsQuery) {
  6914. if (tagsQuery === undefined) {
  6915. return list;
  6916. }
  6917. var listByTags = [];
  6918. for (var i in list) {
  6919. var item = list[i];
  6920. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  6921. listByTags.push(item);
  6922. }
  6923. }
  6924. return listByTags;
  6925. };
  6926. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  6927. return this._getByTags(this.meshes, tagsQuery);
  6928. };
  6929. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  6930. return this._getByTags(this.cameras, tagsQuery);
  6931. };
  6932. Scene.prototype.getLightsByTags = function (tagsQuery) {
  6933. return this._getByTags(this.lights, tagsQuery);
  6934. };
  6935. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  6936. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  6937. };
  6938. Scene.FOGMODE_NONE = 0;
  6939. Scene.FOGMODE_EXP = 1;
  6940. Scene.FOGMODE_EXP2 = 2;
  6941. Scene.FOGMODE_LINEAR = 3;
  6942. Scene.MinDeltaTime = 1.0;
  6943. Scene.MaxDeltaTime = 1000.0;
  6944. return Scene;
  6945. })();
  6946. BABYLON.Scene = Scene;
  6947. })(BABYLON || (BABYLON = {}));
  6948. var BABYLON;
  6949. (function (BABYLON) {
  6950. var VertexBuffer = (function () {
  6951. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  6952. if (engine instanceof BABYLON.Mesh) {
  6953. this._engine = engine.getScene().getEngine();
  6954. } else {
  6955. this._engine = engine;
  6956. }
  6957. this._updatable = updatable;
  6958. this._data = data;
  6959. if (!postponeInternalCreation) {
  6960. this.create();
  6961. }
  6962. this._kind = kind;
  6963. switch (kind) {
  6964. case VertexBuffer.PositionKind:
  6965. this._strideSize = 3;
  6966. break;
  6967. case VertexBuffer.NormalKind:
  6968. this._strideSize = 3;
  6969. break;
  6970. case VertexBuffer.UVKind:
  6971. this._strideSize = 2;
  6972. break;
  6973. case VertexBuffer.UV2Kind:
  6974. this._strideSize = 2;
  6975. break;
  6976. case VertexBuffer.ColorKind:
  6977. this._strideSize = 3;
  6978. break;
  6979. case VertexBuffer.MatricesIndicesKind:
  6980. this._strideSize = 4;
  6981. break;
  6982. case VertexBuffer.MatricesWeightsKind:
  6983. this._strideSize = 4;
  6984. break;
  6985. }
  6986. }
  6987. VertexBuffer.prototype.isUpdatable = function () {
  6988. return this._updatable;
  6989. };
  6990. VertexBuffer.prototype.getData = function () {
  6991. return this._data;
  6992. };
  6993. VertexBuffer.prototype.getBuffer = function () {
  6994. return this._buffer;
  6995. };
  6996. VertexBuffer.prototype.getStrideSize = function () {
  6997. return this._strideSize;
  6998. };
  6999. VertexBuffer.prototype.create = function (data) {
  7000. if (!data && this._buffer) {
  7001. return;
  7002. }
  7003. data = data || this._data;
  7004. if (!this._buffer) {
  7005. if (this._updatable) {
  7006. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7007. } else {
  7008. this._buffer = this._engine.createVertexBuffer(data);
  7009. }
  7010. }
  7011. if (this._updatable) {
  7012. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7013. this._data = data;
  7014. }
  7015. };
  7016. VertexBuffer.prototype.update = function (data) {
  7017. this.create(data);
  7018. };
  7019. VertexBuffer.prototype.dispose = function () {
  7020. if (!this._buffer) {
  7021. return;
  7022. }
  7023. if (this._engine._releaseBuffer(this._buffer)) {
  7024. this._buffer = null;
  7025. }
  7026. };
  7027. Object.defineProperty(VertexBuffer, "PositionKind", {
  7028. get: function () {
  7029. return VertexBuffer._PositionKind;
  7030. },
  7031. enumerable: true,
  7032. configurable: true
  7033. });
  7034. Object.defineProperty(VertexBuffer, "NormalKind", {
  7035. get: function () {
  7036. return VertexBuffer._NormalKind;
  7037. },
  7038. enumerable: true,
  7039. configurable: true
  7040. });
  7041. Object.defineProperty(VertexBuffer, "UVKind", {
  7042. get: function () {
  7043. return VertexBuffer._UVKind;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7049. get: function () {
  7050. return VertexBuffer._UV2Kind;
  7051. },
  7052. enumerable: true,
  7053. configurable: true
  7054. });
  7055. Object.defineProperty(VertexBuffer, "ColorKind", {
  7056. get: function () {
  7057. return VertexBuffer._ColorKind;
  7058. },
  7059. enumerable: true,
  7060. configurable: true
  7061. });
  7062. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7063. get: function () {
  7064. return VertexBuffer._MatricesIndicesKind;
  7065. },
  7066. enumerable: true,
  7067. configurable: true
  7068. });
  7069. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7070. get: function () {
  7071. return VertexBuffer._MatricesWeightsKind;
  7072. },
  7073. enumerable: true,
  7074. configurable: true
  7075. });
  7076. VertexBuffer._PositionKind = "position";
  7077. VertexBuffer._NormalKind = "normal";
  7078. VertexBuffer._UVKind = "uv";
  7079. VertexBuffer._UV2Kind = "uv2";
  7080. VertexBuffer._ColorKind = "color";
  7081. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7082. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7083. return VertexBuffer;
  7084. })();
  7085. BABYLON.VertexBuffer = VertexBuffer;
  7086. })(BABYLON || (BABYLON = {}));
  7087. var __extends = this.__extends || function (d, b) {
  7088. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7089. function __() { this.constructor = d; }
  7090. __.prototype = b.prototype;
  7091. d.prototype = new __();
  7092. };
  7093. var BABYLON;
  7094. (function (BABYLON) {
  7095. var AbstractMesh = (function (_super) {
  7096. __extends(AbstractMesh, _super);
  7097. function AbstractMesh(name, scene) {
  7098. _super.call(this, name, scene);
  7099. this.position = new BABYLON.Vector3(0, 0, 0);
  7100. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7101. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7102. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7103. this.visibility = 1.0;
  7104. this.infiniteDistance = false;
  7105. this.isVisible = true;
  7106. this.isPickable = true;
  7107. this.showBoundingBox = false;
  7108. this.showSubMeshesBoundingBox = false;
  7109. this.onDispose = null;
  7110. this.checkCollisions = false;
  7111. this.isBlocker = false;
  7112. this.renderingGroupId = 0;
  7113. this.receiveShadows = false;
  7114. this.renderOutline = false;
  7115. this.outlineColor = BABYLON.Color3.Red();
  7116. this.outlineWidth = 0.02;
  7117. this.useOctreeForRenderingSelection = true;
  7118. this.useOctreeForPicking = true;
  7119. this.useOctreeForCollisions = true;
  7120. this.layerMask = 0xFFFFFFFF;
  7121. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7122. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7123. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7124. this._collider = new BABYLON.Collider();
  7125. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7126. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7127. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7128. this._localScaling = BABYLON.Matrix.Zero();
  7129. this._localRotation = BABYLON.Matrix.Zero();
  7130. this._localTranslation = BABYLON.Matrix.Zero();
  7131. this._localBillboard = BABYLON.Matrix.Zero();
  7132. this._localPivotScaling = BABYLON.Matrix.Zero();
  7133. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7134. this._localWorld = BABYLON.Matrix.Zero();
  7135. this._worldMatrix = BABYLON.Matrix.Zero();
  7136. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7137. this._absolutePosition = BABYLON.Vector3.Zero();
  7138. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7139. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7140. this._isDirty = false;
  7141. this._pivotMatrix = BABYLON.Matrix.Identity();
  7142. this._isDisposed = false;
  7143. this._renderId = 0;
  7144. this._intersectionsInProgress = new Array();
  7145. scene.meshes.push(this);
  7146. }
  7147. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7148. get: function () {
  7149. return AbstractMesh._BILLBOARDMODE_NONE;
  7150. },
  7151. enumerable: true,
  7152. configurable: true
  7153. });
  7154. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7155. get: function () {
  7156. return AbstractMesh._BILLBOARDMODE_X;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7162. get: function () {
  7163. return AbstractMesh._BILLBOARDMODE_Y;
  7164. },
  7165. enumerable: true,
  7166. configurable: true
  7167. });
  7168. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7169. get: function () {
  7170. return AbstractMesh._BILLBOARDMODE_Z;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7176. get: function () {
  7177. return AbstractMesh._BILLBOARDMODE_ALL;
  7178. },
  7179. enumerable: true,
  7180. configurable: true
  7181. });
  7182. AbstractMesh.prototype.getTotalVertices = function () {
  7183. return 0;
  7184. };
  7185. AbstractMesh.prototype.getIndices = function () {
  7186. return null;
  7187. };
  7188. AbstractMesh.prototype.getVerticesData = function (kind) {
  7189. return null;
  7190. };
  7191. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7192. return false;
  7193. };
  7194. AbstractMesh.prototype.getBoundingInfo = function () {
  7195. if (!this._boundingInfo) {
  7196. this._updateBoundingInfo();
  7197. }
  7198. return this._boundingInfo;
  7199. };
  7200. AbstractMesh.prototype._preActivate = function () {
  7201. };
  7202. AbstractMesh.prototype._activate = function (renderId) {
  7203. this._renderId = renderId;
  7204. };
  7205. AbstractMesh.prototype.getWorldMatrix = function () {
  7206. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7207. this.computeWorldMatrix();
  7208. }
  7209. return this._worldMatrix;
  7210. };
  7211. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7212. get: function () {
  7213. return this._worldMatrix;
  7214. },
  7215. enumerable: true,
  7216. configurable: true
  7217. });
  7218. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7219. get: function () {
  7220. return this._absolutePosition;
  7221. },
  7222. enumerable: true,
  7223. configurable: true
  7224. });
  7225. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7226. if (!this.rotationQuaternion) {
  7227. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7228. this.rotation = BABYLON.Vector3.Zero();
  7229. }
  7230. if (!space || space == 0 /* LOCAL */) {
  7231. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7232. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7233. } else {
  7234. if (this.parent) {
  7235. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7236. invertParentWorldMatrix.invert();
  7237. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7238. }
  7239. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7240. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7241. }
  7242. };
  7243. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7244. var displacementVector = axis.scale(distance);
  7245. if (!space || space == 0 /* LOCAL */) {
  7246. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7247. this.setPositionWithLocalVector(tempV3);
  7248. } else {
  7249. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7250. }
  7251. };
  7252. AbstractMesh.prototype.getAbsolutePosition = function () {
  7253. this.computeWorldMatrix();
  7254. return this._absolutePosition;
  7255. };
  7256. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7257. if (!absolutePosition) {
  7258. return;
  7259. }
  7260. var absolutePositionX;
  7261. var absolutePositionY;
  7262. var absolutePositionZ;
  7263. if (absolutePosition.x === undefined) {
  7264. if (arguments.length < 3) {
  7265. return;
  7266. }
  7267. absolutePositionX = arguments[0];
  7268. absolutePositionY = arguments[1];
  7269. absolutePositionZ = arguments[2];
  7270. } else {
  7271. absolutePositionX = absolutePosition.x;
  7272. absolutePositionY = absolutePosition.y;
  7273. absolutePositionZ = absolutePosition.z;
  7274. }
  7275. if (this.parent) {
  7276. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7277. invertParentWorldMatrix.invert();
  7278. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7279. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7280. } else {
  7281. this.position.x = absolutePositionX;
  7282. this.position.y = absolutePositionY;
  7283. this.position.z = absolutePositionZ;
  7284. }
  7285. };
  7286. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7287. this._pivotMatrix = matrix;
  7288. this._cache.pivotMatrixUpdated = true;
  7289. };
  7290. AbstractMesh.prototype.getPivotMatrix = function () {
  7291. return this._pivotMatrix;
  7292. };
  7293. AbstractMesh.prototype._isSynchronized = function () {
  7294. if (this._isDirty) {
  7295. return false;
  7296. }
  7297. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7298. return false;
  7299. if (this._cache.pivotMatrixUpdated) {
  7300. return false;
  7301. }
  7302. if (this.infiniteDistance) {
  7303. return false;
  7304. }
  7305. if (!this._cache.position.equals(this.position))
  7306. return false;
  7307. if (this.rotationQuaternion) {
  7308. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7309. return false;
  7310. } else {
  7311. if (!this._cache.rotation.equals(this.rotation))
  7312. return false;
  7313. }
  7314. if (!this._cache.scaling.equals(this.scaling))
  7315. return false;
  7316. return true;
  7317. };
  7318. AbstractMesh.prototype._initCache = function () {
  7319. _super.prototype._initCache.call(this);
  7320. this._cache.localMatrixUpdated = false;
  7321. this._cache.position = BABYLON.Vector3.Zero();
  7322. this._cache.scaling = BABYLON.Vector3.Zero();
  7323. this._cache.rotation = BABYLON.Vector3.Zero();
  7324. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7325. };
  7326. AbstractMesh.prototype.markAsDirty = function (property) {
  7327. if (property === "rotation") {
  7328. this.rotationQuaternion = null;
  7329. }
  7330. this._currentRenderId = Number.MAX_VALUE;
  7331. this._isDirty = true;
  7332. };
  7333. AbstractMesh.prototype._updateBoundingInfo = function () {
  7334. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7335. this._boundingInfo._update(this.worldMatrixFromCache);
  7336. if (!this.subMeshes) {
  7337. return;
  7338. }
  7339. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7340. var subMesh = this.subMeshes[subIndex];
  7341. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7342. }
  7343. };
  7344. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7345. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7346. return this._worldMatrix;
  7347. }
  7348. this._cache.position.copyFrom(this.position);
  7349. this._cache.scaling.copyFrom(this.scaling);
  7350. this._cache.pivotMatrixUpdated = false;
  7351. this._currentRenderId = this.getScene().getRenderId();
  7352. this._isDirty = false;
  7353. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7354. if (this.rotationQuaternion) {
  7355. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7356. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7357. } else {
  7358. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7359. this._cache.rotation.copyFrom(this.rotation);
  7360. }
  7361. if (this.infiniteDistance && !this.parent) {
  7362. var camera = this.getScene().activeCamera;
  7363. var cameraWorldMatrix = camera.getWorldMatrix();
  7364. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7365. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7366. } else {
  7367. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7368. }
  7369. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7370. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7371. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  7372. var localPosition = this.position.clone();
  7373. var zero = this.getScene().activeCamera.position.clone();
  7374. if (this.parent && this.parent.position) {
  7375. localPosition.addInPlace(this.parent.position);
  7376. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7377. }
  7378. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7379. zero = this.getScene().activeCamera.position;
  7380. } else {
  7381. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7382. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7383. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7384. zero.y = localPosition.y + 0.001;
  7385. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7386. zero.z = localPosition.z + 0.001;
  7387. }
  7388. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7389. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7390. this._localBillboard.invert();
  7391. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7392. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7393. }
  7394. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7395. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7396. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7397. } else {
  7398. this._worldMatrix.copyFrom(this._localWorld);
  7399. }
  7400. this._updateBoundingInfo();
  7401. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7402. return this._worldMatrix;
  7403. };
  7404. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7405. this.computeWorldMatrix();
  7406. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7407. };
  7408. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7409. this.computeWorldMatrix();
  7410. var invLocalWorldMatrix = this._localWorld.clone();
  7411. invLocalWorldMatrix.invert();
  7412. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7413. };
  7414. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7415. this.computeWorldMatrix();
  7416. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7417. };
  7418. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7419. yawCor = yawCor || 0;
  7420. pitchCor = pitchCor || 0;
  7421. rollCor = rollCor || 0;
  7422. var dv = targetPoint.subtract(this.position);
  7423. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7424. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7425. var pitch = Math.atan2(dv.y, len);
  7426. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7427. };
  7428. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7429. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7430. return false;
  7431. }
  7432. return true;
  7433. };
  7434. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7435. if (!this._boundingInfo || !mesh._boundingInfo) {
  7436. return false;
  7437. }
  7438. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7439. };
  7440. AbstractMesh.prototype.intersectsPoint = function (point) {
  7441. if (!this._boundingInfo) {
  7442. return false;
  7443. }
  7444. return this._boundingInfo.intersectsPoint(point);
  7445. };
  7446. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7447. var physicsEngine = this.getScene().getPhysicsEngine();
  7448. if (!physicsEngine) {
  7449. return;
  7450. }
  7451. if (impostor.impostor) {
  7452. options = impostor;
  7453. impostor = impostor.impostor;
  7454. }
  7455. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7456. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7457. physicsEngine._unregisterMesh(this);
  7458. return;
  7459. }
  7460. options.mass = options.mass || 0;
  7461. options.friction = options.friction || 0.2;
  7462. options.restitution = options.restitution || 0.9;
  7463. this._physicImpostor = impostor;
  7464. this._physicsMass = options.mass;
  7465. this._physicsFriction = options.friction;
  7466. this._physicRestitution = options.restitution;
  7467. physicsEngine._registerMesh(this, impostor, options);
  7468. };
  7469. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7470. if (!this._physicImpostor) {
  7471. return BABYLON.PhysicsEngine.NoImpostor;
  7472. }
  7473. return this._physicImpostor;
  7474. };
  7475. AbstractMesh.prototype.getPhysicsMass = function () {
  7476. if (!this._physicsMass) {
  7477. return 0;
  7478. }
  7479. return this._physicsMass;
  7480. };
  7481. AbstractMesh.prototype.getPhysicsFriction = function () {
  7482. if (!this._physicsFriction) {
  7483. return 0;
  7484. }
  7485. return this._physicsFriction;
  7486. };
  7487. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7488. if (!this._physicRestitution) {
  7489. return 0;
  7490. }
  7491. return this._physicRestitution;
  7492. };
  7493. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7494. if (!this._physicImpostor) {
  7495. return;
  7496. }
  7497. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7498. };
  7499. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7500. if (!this._physicImpostor) {
  7501. return;
  7502. }
  7503. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7504. };
  7505. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7506. if (!this._physicImpostor) {
  7507. return;
  7508. }
  7509. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7510. };
  7511. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7512. var globalPosition = this.getAbsolutePosition();
  7513. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7514. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7515. this._collider.radius = this.ellipsoid;
  7516. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7517. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7518. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7519. this.position.addInPlace(this._diffPositionForCollisions);
  7520. }
  7521. };
  7522. /**
  7523. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7524. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7525. */
  7526. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7527. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7528. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7529. if (!this._submeshesOctree) {
  7530. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7531. }
  7532. this.computeWorldMatrix(true);
  7533. var bbox = this.getBoundingInfo().boundingBox;
  7534. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7535. return this._submeshesOctree;
  7536. };
  7537. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7538. this._generatePointsArray();
  7539. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7540. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7541. subMesh._lastColliderWorldVertices = [];
  7542. subMesh._trianglePlanes = [];
  7543. var start = subMesh.verticesStart;
  7544. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7545. for (var i = start; i < end; i++) {
  7546. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7547. }
  7548. }
  7549. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7550. };
  7551. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7552. var subMeshes;
  7553. var len;
  7554. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7555. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7556. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7557. len = intersections.length;
  7558. subMeshes = intersections.data;
  7559. } else {
  7560. subMeshes = this.subMeshes;
  7561. len = subMeshes.length;
  7562. }
  7563. for (var index = 0; index < len; index++) {
  7564. var subMesh = subMeshes[index];
  7565. if (len > 1 && !subMesh._checkCollision(collider))
  7566. continue;
  7567. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7568. }
  7569. };
  7570. AbstractMesh.prototype._checkCollision = function (collider) {
  7571. if (!this._boundingInfo._checkCollision(collider))
  7572. return;
  7573. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7574. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7575. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7576. };
  7577. AbstractMesh.prototype._generatePointsArray = function () {
  7578. return false;
  7579. };
  7580. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7581. var pickingInfo = new BABYLON.PickingInfo();
  7582. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7583. return pickingInfo;
  7584. }
  7585. if (!this._generatePointsArray()) {
  7586. return pickingInfo;
  7587. }
  7588. var intersectInfo = null;
  7589. var subMeshes;
  7590. var len;
  7591. if (this._submeshesOctree && this.useOctreeForPicking) {
  7592. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7593. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7594. len = intersections.length;
  7595. subMeshes = intersections.data;
  7596. } else {
  7597. subMeshes = this.subMeshes;
  7598. len = subMeshes.length;
  7599. }
  7600. for (var index = 0; index < len; index++) {
  7601. var subMesh = subMeshes[index];
  7602. if (len > 1 && !subMesh.canIntersects(ray))
  7603. continue;
  7604. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7605. if (currentIntersectInfo) {
  7606. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7607. intersectInfo = currentIntersectInfo;
  7608. if (fastCheck) {
  7609. break;
  7610. }
  7611. }
  7612. }
  7613. }
  7614. if (intersectInfo) {
  7615. var world = this.getWorldMatrix();
  7616. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7617. var direction = ray.direction.clone();
  7618. direction.normalize();
  7619. direction = direction.scale(intersectInfo.distance);
  7620. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7621. var pickedPoint = worldOrigin.add(worldDirection);
  7622. pickingInfo.hit = true;
  7623. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7624. pickingInfo.pickedPoint = pickedPoint;
  7625. pickingInfo.pickedMesh = this;
  7626. pickingInfo.bu = intersectInfo.bu;
  7627. pickingInfo.bv = intersectInfo.bv;
  7628. pickingInfo.faceId = intersectInfo.faceId;
  7629. return pickingInfo;
  7630. }
  7631. return pickingInfo;
  7632. };
  7633. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7634. return null;
  7635. };
  7636. AbstractMesh.prototype.releaseSubMeshes = function () {
  7637. if (this.subMeshes) {
  7638. while (this.subMeshes.length) {
  7639. this.subMeshes[0].dispose();
  7640. }
  7641. } else {
  7642. this.subMeshes = new Array();
  7643. }
  7644. };
  7645. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7646. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7647. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7648. }
  7649. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7650. var other = this._intersectionsInProgress[index];
  7651. var pos = other._intersectionsInProgress.indexOf(this);
  7652. other._intersectionsInProgress.splice(pos, 1);
  7653. }
  7654. this._intersectionsInProgress = [];
  7655. this.releaseSubMeshes();
  7656. var index = this.getScene().meshes.indexOf(this);
  7657. if (index != -1) {
  7658. this.getScene().meshes.splice(index, 1);
  7659. }
  7660. if (!doNotRecurse) {
  7661. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7662. if (this.getScene().particleSystems[index].emitter == this) {
  7663. this.getScene().particleSystems[index].dispose();
  7664. index--;
  7665. }
  7666. }
  7667. var objects = this.getScene().meshes.slice(0);
  7668. for (index = 0; index < objects.length; index++) {
  7669. if (objects[index].parent == this) {
  7670. objects[index].dispose();
  7671. }
  7672. }
  7673. } else {
  7674. for (index = 0; index < this.getScene().meshes.length; index++) {
  7675. var obj = this.getScene().meshes[index];
  7676. if (obj.parent === this) {
  7677. obj.parent = null;
  7678. obj.computeWorldMatrix(true);
  7679. }
  7680. }
  7681. }
  7682. this._isDisposed = true;
  7683. if (this.onDispose) {
  7684. this.onDispose();
  7685. }
  7686. };
  7687. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7688. AbstractMesh._BILLBOARDMODE_X = 1;
  7689. AbstractMesh._BILLBOARDMODE_Y = 2;
  7690. AbstractMesh._BILLBOARDMODE_Z = 4;
  7691. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7692. return AbstractMesh;
  7693. })(BABYLON.Node);
  7694. BABYLON.AbstractMesh = AbstractMesh;
  7695. })(BABYLON || (BABYLON = {}));
  7696. var __extends = this.__extends || function (d, b) {
  7697. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7698. function __() { this.constructor = d; }
  7699. __.prototype = b.prototype;
  7700. d.prototype = new __();
  7701. };
  7702. var BABYLON;
  7703. (function (BABYLON) {
  7704. var _InstancesBatch = (function () {
  7705. function _InstancesBatch() {
  7706. this.mustReturn = false;
  7707. this.visibleInstances = new Array();
  7708. this.renderSelf = new Array();
  7709. }
  7710. return _InstancesBatch;
  7711. })();
  7712. BABYLON._InstancesBatch = _InstancesBatch;
  7713. var Mesh = (function (_super) {
  7714. __extends(Mesh, _super);
  7715. function Mesh(name, scene) {
  7716. _super.call(this, name, scene);
  7717. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7718. this.instances = new Array();
  7719. this._onBeforeRenderCallbacks = new Array();
  7720. this._onAfterRenderCallbacks = new Array();
  7721. this._visibleInstances = {};
  7722. this._renderIdForInstances = new Array();
  7723. this._batchCache = new _InstancesBatch();
  7724. this._instancesBufferSize = 32 * 16 * 4;
  7725. }
  7726. Mesh.prototype.getTotalVertices = function () {
  7727. if (!this._geometry) {
  7728. return 0;
  7729. }
  7730. return this._geometry.getTotalVertices();
  7731. };
  7732. Mesh.prototype.getVerticesData = function (kind) {
  7733. if (!this._geometry) {
  7734. return null;
  7735. }
  7736. return this._geometry.getVerticesData(kind);
  7737. };
  7738. Mesh.prototype.getVertexBuffer = function (kind) {
  7739. if (!this._geometry) {
  7740. return undefined;
  7741. }
  7742. return this._geometry.getVertexBuffer(kind);
  7743. };
  7744. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7745. if (!this._geometry) {
  7746. if (this._delayInfo) {
  7747. return this._delayInfo.indexOf(kind) !== -1;
  7748. }
  7749. return false;
  7750. }
  7751. return this._geometry.isVerticesDataPresent(kind);
  7752. };
  7753. Mesh.prototype.getVerticesDataKinds = function () {
  7754. if (!this._geometry) {
  7755. var result = [];
  7756. if (this._delayInfo) {
  7757. for (var kind in this._delayInfo) {
  7758. result.push(kind);
  7759. }
  7760. }
  7761. return result;
  7762. }
  7763. return this._geometry.getVerticesDataKinds();
  7764. };
  7765. Mesh.prototype.getTotalIndices = function () {
  7766. if (!this._geometry) {
  7767. return 0;
  7768. }
  7769. return this._geometry.getTotalIndices();
  7770. };
  7771. Mesh.prototype.getIndices = function () {
  7772. if (!this._geometry) {
  7773. return [];
  7774. }
  7775. return this._geometry.getIndices();
  7776. };
  7777. Mesh.prototype.isReady = function () {
  7778. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7779. return false;
  7780. }
  7781. return _super.prototype.isReady.call(this);
  7782. };
  7783. Mesh.prototype.isDisposed = function () {
  7784. return this._isDisposed;
  7785. };
  7786. Mesh.prototype._preActivate = function () {
  7787. var sceneRenderId = this.getScene().getRenderId();
  7788. if (this._preActivateId == sceneRenderId) {
  7789. return;
  7790. }
  7791. this._preActivateId = sceneRenderId;
  7792. this._visibleInstances = null;
  7793. };
  7794. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7795. if (!this._visibleInstances) {
  7796. this._visibleInstances = {};
  7797. this._visibleInstances.defaultRenderId = renderId;
  7798. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7799. }
  7800. if (!this._visibleInstances[renderId]) {
  7801. this._visibleInstances[renderId] = new Array();
  7802. }
  7803. this._visibleInstances[renderId].push(instance);
  7804. };
  7805. Mesh.prototype.refreshBoundingInfo = function () {
  7806. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7807. if (data) {
  7808. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7809. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7810. }
  7811. if (this.subMeshes) {
  7812. for (var index = 0; index < this.subMeshes.length; index++) {
  7813. this.subMeshes[index].refreshBoundingInfo();
  7814. }
  7815. }
  7816. this._updateBoundingInfo();
  7817. };
  7818. Mesh.prototype._createGlobalSubMesh = function () {
  7819. var totalVertices = this.getTotalVertices();
  7820. if (!totalVertices || !this.getIndices()) {
  7821. return null;
  7822. }
  7823. this.releaseSubMeshes();
  7824. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7825. };
  7826. Mesh.prototype.subdivide = function (count) {
  7827. if (count < 1) {
  7828. return;
  7829. }
  7830. var totalIndices = this.getTotalIndices();
  7831. var subdivisionSize = (totalIndices / count) | 0;
  7832. var offset = 0;
  7833. while (subdivisionSize % 3 != 0) {
  7834. subdivisionSize++;
  7835. }
  7836. this.releaseSubMeshes();
  7837. for (var index = 0; index < count; index++) {
  7838. if (offset >= totalIndices) {
  7839. break;
  7840. }
  7841. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7842. offset += subdivisionSize;
  7843. }
  7844. this.synchronizeInstances();
  7845. };
  7846. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7847. if (kind instanceof Array) {
  7848. var temp = data;
  7849. data = kind;
  7850. kind = temp;
  7851. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7852. }
  7853. if (!this._geometry) {
  7854. var vertexData = new BABYLON.VertexData();
  7855. vertexData.set(data, kind);
  7856. var scene = this.getScene();
  7857. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7858. } else {
  7859. this._geometry.setVerticesData(kind, data, updatable);
  7860. }
  7861. };
  7862. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7863. if (!this._geometry) {
  7864. return;
  7865. }
  7866. if (!makeItUnique) {
  7867. this._geometry.updateVerticesData(kind, data, updateExtends);
  7868. } else {
  7869. this.makeGeometryUnique();
  7870. this.updateVerticesData(kind, data, updateExtends, false);
  7871. }
  7872. };
  7873. Mesh.prototype.makeGeometryUnique = function () {
  7874. if (!this._geometry) {
  7875. return;
  7876. }
  7877. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  7878. geometry.applyToMesh(this);
  7879. };
  7880. Mesh.prototype.setIndices = function (indices) {
  7881. if (!this._geometry) {
  7882. var vertexData = new BABYLON.VertexData();
  7883. vertexData.indices = indices;
  7884. var scene = this.getScene();
  7885. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  7886. } else {
  7887. this._geometry.setIndices(indices);
  7888. }
  7889. };
  7890. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  7891. var engine = this.getScene().getEngine();
  7892. var indexToBind = this._geometry.getIndexBuffer();
  7893. if (wireframe) {
  7894. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  7895. }
  7896. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  7897. };
  7898. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  7899. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7900. return;
  7901. }
  7902. var engine = this.getScene().getEngine();
  7903. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7904. };
  7905. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  7906. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  7907. return;
  7908. }
  7909. var engine = this.getScene().getEngine();
  7910. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  7911. };
  7912. Mesh.prototype.registerBeforeRender = function (func) {
  7913. this._onBeforeRenderCallbacks.push(func);
  7914. };
  7915. Mesh.prototype.unregisterBeforeRender = function (func) {
  7916. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7917. if (index > -1) {
  7918. this._onBeforeRenderCallbacks.splice(index, 1);
  7919. }
  7920. };
  7921. Mesh.prototype.registerAfterRender = function (func) {
  7922. this._onAfterRenderCallbacks.push(func);
  7923. };
  7924. Mesh.prototype.unregisterAfterRender = function (func) {
  7925. var index = this._onAfterRenderCallbacks.indexOf(func);
  7926. if (index > -1) {
  7927. this._onAfterRenderCallbacks.splice(index, 1);
  7928. }
  7929. };
  7930. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  7931. var scene = this.getScene();
  7932. this._batchCache.mustReturn = false;
  7933. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  7934. this._batchCache.visibleInstances[subMeshId] = null;
  7935. if (this._visibleInstances) {
  7936. var currentRenderId = scene.getRenderId();
  7937. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  7938. var selfRenderId = this._renderId;
  7939. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  7940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  7941. currentRenderId = this._visibleInstances.defaultRenderId;
  7942. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  7943. }
  7944. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  7945. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  7946. this._batchCache.mustReturn = true;
  7947. return this._batchCache;
  7948. }
  7949. if (currentRenderId !== selfRenderId) {
  7950. this._batchCache.renderSelf[subMeshId] = false;
  7951. }
  7952. }
  7953. this._renderIdForInstances[subMeshId] = currentRenderId;
  7954. }
  7955. return this._batchCache;
  7956. };
  7957. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  7958. var matricesCount = this.instances.length + 1;
  7959. var bufferSize = matricesCount * 16 * 4;
  7960. while (this._instancesBufferSize < bufferSize) {
  7961. this._instancesBufferSize *= 2;
  7962. }
  7963. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  7964. if (this._worldMatricesInstancesBuffer) {
  7965. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  7966. }
  7967. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  7968. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  7969. }
  7970. var offset = 0;
  7971. var instancesCount = 0;
  7972. var world = this.getWorldMatrix();
  7973. if (batch.renderSelf[subMesh._id]) {
  7974. world.copyToArray(this._worldMatricesInstancesArray, offset);
  7975. offset += 16;
  7976. instancesCount++;
  7977. }
  7978. var visibleInstances = batch.visibleInstances[subMesh._id];
  7979. if (visibleInstances) {
  7980. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  7981. var instance = visibleInstances[instanceIndex];
  7982. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  7983. offset += 16;
  7984. instancesCount++;
  7985. }
  7986. }
  7987. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  7988. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  7989. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  7990. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  7991. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  7992. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  7993. this._draw(subMesh, !wireFrame, instancesCount);
  7994. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  7995. };
  7996. Mesh.prototype.render = function (subMesh) {
  7997. var scene = this.getScene();
  7998. var batch = this._getInstancesRenderList(subMesh._id);
  7999. if (batch.mustReturn) {
  8000. return;
  8001. }
  8002. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8003. return;
  8004. }
  8005. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8006. this._onBeforeRenderCallbacks[callbackIndex]();
  8007. }
  8008. var engine = scene.getEngine();
  8009. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8010. var effectiveMaterial = subMesh.getMaterial();
  8011. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8012. return;
  8013. }
  8014. var savedDepthWrite = engine.getDepthWrite();
  8015. if (this.renderOutline) {
  8016. engine.setDepthWrite(false);
  8017. scene.getOutlineRenderer().render(subMesh, batch);
  8018. }
  8019. effectiveMaterial._preBind();
  8020. var effect = effectiveMaterial.getEffect();
  8021. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8022. this._bind(subMesh, effect, wireFrame);
  8023. var world = this.getWorldMatrix();
  8024. effectiveMaterial.bind(world, this);
  8025. if (hardwareInstancedRendering) {
  8026. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8027. } else {
  8028. if (batch.renderSelf[subMesh._id]) {
  8029. this._draw(subMesh, !wireFrame);
  8030. }
  8031. if (batch.visibleInstances[subMesh._id]) {
  8032. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8033. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8034. world = instance.getWorldMatrix();
  8035. effectiveMaterial.bindOnlyWorldMatrix(world);
  8036. this._draw(subMesh, !wireFrame);
  8037. }
  8038. }
  8039. }
  8040. effectiveMaterial.unbind();
  8041. if (this.renderOutline && savedDepthWrite) {
  8042. engine.setDepthWrite(true);
  8043. engine.setColorWrite(false);
  8044. scene.getOutlineRenderer().render(subMesh, batch);
  8045. engine.setColorWrite(true);
  8046. }
  8047. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8048. this._onAfterRenderCallbacks[callbackIndex]();
  8049. }
  8050. };
  8051. Mesh.prototype.getEmittedParticleSystems = function () {
  8052. var results = new Array();
  8053. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8054. var particleSystem = this.getScene().particleSystems[index];
  8055. if (particleSystem.emitter === this) {
  8056. results.push(particleSystem);
  8057. }
  8058. }
  8059. return results;
  8060. };
  8061. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8062. var results = new Array();
  8063. var descendants = this.getDescendants();
  8064. descendants.push(this);
  8065. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8066. var particleSystem = this.getScene().particleSystems[index];
  8067. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8068. results.push(particleSystem);
  8069. }
  8070. }
  8071. return results;
  8072. };
  8073. Mesh.prototype.getChildren = function () {
  8074. var results = [];
  8075. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8076. var mesh = this.getScene().meshes[index];
  8077. if (mesh.parent == this) {
  8078. results.push(mesh);
  8079. }
  8080. }
  8081. return results;
  8082. };
  8083. Mesh.prototype._checkDelayState = function () {
  8084. var _this = this;
  8085. var that = this;
  8086. var scene = this.getScene();
  8087. if (this._geometry) {
  8088. this._geometry.load(scene);
  8089. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8090. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8091. scene._addPendingData(that);
  8092. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8093. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8094. if (data instanceof ArrayBuffer) {
  8095. _this._delayLoadingFunction(data, _this);
  8096. } else {
  8097. _this._delayLoadingFunction(JSON.parse(data), _this);
  8098. }
  8099. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8100. scene._removePendingData(_this);
  8101. }, function () {
  8102. }, scene.database, getBinaryData);
  8103. }
  8104. };
  8105. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8106. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8107. return false;
  8108. }
  8109. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8110. return false;
  8111. }
  8112. this._checkDelayState();
  8113. return true;
  8114. };
  8115. Mesh.prototype.setMaterialByID = function (id) {
  8116. var materials = this.getScene().materials;
  8117. for (var index = 0; index < materials.length; index++) {
  8118. if (materials[index].id == id) {
  8119. this.material = materials[index];
  8120. return;
  8121. }
  8122. }
  8123. var multiMaterials = this.getScene().multiMaterials;
  8124. for (index = 0; index < multiMaterials.length; index++) {
  8125. if (multiMaterials[index].id == id) {
  8126. this.material = multiMaterials[index];
  8127. return;
  8128. }
  8129. }
  8130. };
  8131. Mesh.prototype.getAnimatables = function () {
  8132. var results = [];
  8133. if (this.material) {
  8134. results.push(this.material);
  8135. }
  8136. return results;
  8137. };
  8138. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8139. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8140. return;
  8141. }
  8142. this._resetPointsArrayCache();
  8143. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8144. var temp = [];
  8145. for (var index = 0; index < data.length; index += 3) {
  8146. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8147. }
  8148. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8149. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8150. return;
  8151. }
  8152. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8153. for (index = 0; index < data.length; index += 3) {
  8154. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8155. }
  8156. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8157. };
  8158. Mesh.prototype._resetPointsArrayCache = function () {
  8159. this._positions = null;
  8160. };
  8161. Mesh.prototype._generatePointsArray = function () {
  8162. if (this._positions)
  8163. return true;
  8164. this._positions = [];
  8165. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8166. if (!data) {
  8167. return false;
  8168. }
  8169. for (var index = 0; index < data.length; index += 3) {
  8170. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8171. }
  8172. return true;
  8173. };
  8174. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8175. var result = new BABYLON.Mesh(name, this.getScene());
  8176. this._geometry.applyToMesh(result);
  8177. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8178. result.material = this.material;
  8179. if (newParent) {
  8180. result.parent = newParent;
  8181. }
  8182. if (!doNotCloneChildren) {
  8183. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8184. var mesh = this.getScene().meshes[index];
  8185. if (mesh.parent == this) {
  8186. mesh.clone(mesh.name, result);
  8187. }
  8188. }
  8189. }
  8190. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8191. var system = this.getScene().particleSystems[index];
  8192. if (system.emitter == this) {
  8193. system.clone(system.name, result);
  8194. }
  8195. }
  8196. result.computeWorldMatrix(true);
  8197. return result;
  8198. };
  8199. Mesh.prototype.dispose = function (doNotRecurse) {
  8200. if (this._geometry) {
  8201. this._geometry.releaseForMesh(this, true);
  8202. }
  8203. if (this._worldMatricesInstancesBuffer) {
  8204. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8205. this._worldMatricesInstancesBuffer = null;
  8206. }
  8207. while (this.instances.length) {
  8208. this.instances[0].dispose();
  8209. }
  8210. _super.prototype.dispose.call(this, doNotRecurse);
  8211. };
  8212. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8213. var _this = this;
  8214. var scene = this.getScene();
  8215. var onload = function (img) {
  8216. var canvas = document.createElement("canvas");
  8217. var context = canvas.getContext("2d");
  8218. var heightMapWidth = img.width;
  8219. var heightMapHeight = img.height;
  8220. canvas.width = heightMapWidth;
  8221. canvas.height = heightMapHeight;
  8222. context.drawImage(img, 0, 0);
  8223. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8224. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8225. };
  8226. BABYLON.Tools.LoadImage(url, onload, function () {
  8227. }, scene.database);
  8228. };
  8229. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8230. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8231. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8232. return;
  8233. }
  8234. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8235. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8236. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8237. var position = BABYLON.Vector3.Zero();
  8238. var normal = BABYLON.Vector3.Zero();
  8239. var uv = BABYLON.Vector2.Zero();
  8240. for (var index = 0; index < positions.length; index += 3) {
  8241. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8242. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8243. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8244. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8245. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8246. var pos = (u + v * heightMapWidth) * 4;
  8247. var r = buffer[pos] / 255.0;
  8248. var g = buffer[pos + 1] / 255.0;
  8249. var b = buffer[pos + 2] / 255.0;
  8250. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8251. normal.normalize();
  8252. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8253. position = position.add(normal);
  8254. position.toArray(positions, index);
  8255. }
  8256. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8257. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8258. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8259. };
  8260. Mesh.prototype.convertToFlatShadedMesh = function () {
  8261. var kinds = this.getVerticesDataKinds();
  8262. var vbs = [];
  8263. var data = [];
  8264. var newdata = [];
  8265. var updatableNormals = false;
  8266. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8267. var kind = kinds[kindIndex];
  8268. var vertexBuffer = this.getVertexBuffer(kind);
  8269. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8270. updatableNormals = vertexBuffer.isUpdatable();
  8271. kinds.splice(kindIndex, 1);
  8272. kindIndex--;
  8273. continue;
  8274. }
  8275. vbs[kind] = vertexBuffer;
  8276. data[kind] = vbs[kind].getData();
  8277. newdata[kind] = [];
  8278. }
  8279. var previousSubmeshes = this.subMeshes.slice(0);
  8280. var indices = this.getIndices();
  8281. var totalIndices = this.getTotalIndices();
  8282. for (index = 0; index < totalIndices; index++) {
  8283. var vertexIndex = indices[index];
  8284. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8285. kind = kinds[kindIndex];
  8286. var stride = vbs[kind].getStrideSize();
  8287. for (var offset = 0; offset < stride; offset++) {
  8288. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8289. }
  8290. }
  8291. }
  8292. var normals = [];
  8293. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8294. for (var index = 0; index < totalIndices; index += 3) {
  8295. indices[index] = index;
  8296. indices[index + 1] = index + 1;
  8297. indices[index + 2] = index + 2;
  8298. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8299. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8300. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8301. var p1p2 = p1.subtract(p2);
  8302. var p3p2 = p3.subtract(p2);
  8303. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8304. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8305. normals.push(normal.x);
  8306. normals.push(normal.y);
  8307. normals.push(normal.z);
  8308. }
  8309. }
  8310. this.setIndices(indices);
  8311. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8312. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8313. kind = kinds[kindIndex];
  8314. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8315. }
  8316. this.releaseSubMeshes();
  8317. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8318. var previousOne = previousSubmeshes[submeshIndex];
  8319. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8320. }
  8321. this.synchronizeInstances();
  8322. };
  8323. Mesh.prototype.createInstance = function (name) {
  8324. return new BABYLON.InstancedMesh(name, this);
  8325. };
  8326. Mesh.prototype.synchronizeInstances = function () {
  8327. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8328. var instance = this.instances[instanceIndex];
  8329. instance._syncSubMeshes();
  8330. }
  8331. };
  8332. Mesh.CreateBox = function (name, size, scene, updatable) {
  8333. var box = new BABYLON.Mesh(name, scene);
  8334. var vertexData = BABYLON.VertexData.CreateBox(size);
  8335. vertexData.applyToMesh(box, updatable);
  8336. return box;
  8337. };
  8338. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8339. var sphere = new BABYLON.Mesh(name, scene);
  8340. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8341. vertexData.applyToMesh(sphere, updatable);
  8342. return sphere;
  8343. };
  8344. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8345. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8346. if (scene !== undefined) {
  8347. updatable = scene;
  8348. }
  8349. scene = subdivisions;
  8350. subdivisions = 1;
  8351. }
  8352. var cylinder = new BABYLON.Mesh(name, scene);
  8353. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8354. vertexData.applyToMesh(cylinder, updatable);
  8355. return cylinder;
  8356. };
  8357. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8358. var torus = new BABYLON.Mesh(name, scene);
  8359. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8360. vertexData.applyToMesh(torus, updatable);
  8361. return torus;
  8362. };
  8363. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8364. var torusKnot = new BABYLON.Mesh(name, scene);
  8365. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8366. vertexData.applyToMesh(torusKnot, updatable);
  8367. return torusKnot;
  8368. };
  8369. Mesh.CreateLines = function (name, points, scene, updatable) {
  8370. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8371. var vertexData = BABYLON.VertexData.CreateLines(points);
  8372. vertexData.applyToMesh(lines, updatable);
  8373. return lines;
  8374. };
  8375. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8376. var plane = new BABYLON.Mesh(name, scene);
  8377. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8378. vertexData.applyToMesh(plane, updatable);
  8379. return plane;
  8380. };
  8381. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8382. var ground = new BABYLON.GroundMesh(name, scene);
  8383. ground._setReady(false);
  8384. ground._subdivisions = subdivisions;
  8385. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8386. vertexData.applyToMesh(ground, updatable);
  8387. ground._setReady(true);
  8388. return ground;
  8389. };
  8390. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8391. var tiledGround = new BABYLON.Mesh(name, scene);
  8392. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8393. vertexData.applyToMesh(tiledGround, updatable);
  8394. return tiledGround;
  8395. };
  8396. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8397. var ground = new BABYLON.GroundMesh(name, scene);
  8398. ground._subdivisions = subdivisions;
  8399. ground._setReady(false);
  8400. var onload = function (img) {
  8401. var canvas = document.createElement("canvas");
  8402. var context = canvas.getContext("2d");
  8403. var heightMapWidth = img.width;
  8404. var heightMapHeight = img.height;
  8405. canvas.width = heightMapWidth;
  8406. canvas.height = heightMapHeight;
  8407. context.drawImage(img, 0, 0);
  8408. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8409. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8410. vertexData.applyToMesh(ground, updatable);
  8411. ground._setReady(true);
  8412. };
  8413. BABYLON.Tools.LoadImage(url, onload, function () {
  8414. }, scene.database);
  8415. return ground;
  8416. };
  8417. Mesh.MinMax = function (meshes) {
  8418. var minVector = null;
  8419. var maxVector = null;
  8420. for (var i in meshes) {
  8421. var mesh = meshes[i];
  8422. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8423. if (!minVector) {
  8424. minVector = boundingBox.minimumWorld;
  8425. maxVector = boundingBox.maximumWorld;
  8426. continue;
  8427. }
  8428. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8429. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8430. }
  8431. return {
  8432. min: minVector,
  8433. max: maxVector
  8434. };
  8435. };
  8436. Mesh.Center = function (meshesOrMinMaxVector) {
  8437. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8438. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8439. };
  8440. return Mesh;
  8441. })(BABYLON.AbstractMesh);
  8442. BABYLON.Mesh = Mesh;
  8443. })(BABYLON || (BABYLON = {}));
  8444. var __extends = this.__extends || function (d, b) {
  8445. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8446. function __() { this.constructor = d; }
  8447. __.prototype = b.prototype;
  8448. d.prototype = new __();
  8449. };
  8450. var BABYLON;
  8451. (function (BABYLON) {
  8452. var GroundMesh = (function (_super) {
  8453. __extends(GroundMesh, _super);
  8454. function GroundMesh(name, scene) {
  8455. _super.call(this, name, scene);
  8456. this.generateOctree = false;
  8457. this._worldInverse = new BABYLON.Matrix();
  8458. }
  8459. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8460. get: function () {
  8461. return this._subdivisions;
  8462. },
  8463. enumerable: true,
  8464. configurable: true
  8465. });
  8466. GroundMesh.prototype.optimize = function (chunksCount) {
  8467. this.subdivide(this._subdivisions);
  8468. this.createOrUpdateSubmeshesOctree(32);
  8469. };
  8470. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8471. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8472. this.getWorldMatrix().invertToRef(this._worldInverse);
  8473. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8474. var pickInfo = this.intersects(ray);
  8475. if (pickInfo.hit) {
  8476. return pickInfo.pickedPoint.y;
  8477. }
  8478. return 0;
  8479. };
  8480. return GroundMesh;
  8481. })(BABYLON.Mesh);
  8482. BABYLON.GroundMesh = GroundMesh;
  8483. })(BABYLON || (BABYLON = {}));
  8484. var __extends = this.__extends || function (d, b) {
  8485. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8486. function __() { this.constructor = d; }
  8487. __.prototype = b.prototype;
  8488. d.prototype = new __();
  8489. };
  8490. var BABYLON;
  8491. (function (BABYLON) {
  8492. var InstancedMesh = (function (_super) {
  8493. __extends(InstancedMesh, _super);
  8494. function InstancedMesh(name, source) {
  8495. _super.call(this, name, source.getScene());
  8496. source.instances.push(this);
  8497. this._sourceMesh = source;
  8498. this.position.copyFrom(source.position);
  8499. this.rotation.copyFrom(source.rotation);
  8500. this.scaling.copyFrom(source.scaling);
  8501. if (source.rotationQuaternion) {
  8502. this.rotationQuaternion = source.rotationQuaternion.clone();
  8503. }
  8504. this.infiniteDistance = source.infiniteDistance;
  8505. this.setPivotMatrix(source.getPivotMatrix());
  8506. this.refreshBoundingInfo();
  8507. this._syncSubMeshes();
  8508. }
  8509. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8510. get: function () {
  8511. return this._sourceMesh.receiveShadows;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. Object.defineProperty(InstancedMesh.prototype, "material", {
  8517. get: function () {
  8518. return this._sourceMesh.material;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8524. get: function () {
  8525. return this._sourceMesh.visibility;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8531. get: function () {
  8532. return this._sourceMesh.skeleton;
  8533. },
  8534. enumerable: true,
  8535. configurable: true
  8536. });
  8537. InstancedMesh.prototype.getTotalVertices = function () {
  8538. return this._sourceMesh.getTotalVertices();
  8539. };
  8540. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8541. get: function () {
  8542. return this._sourceMesh;
  8543. },
  8544. enumerable: true,
  8545. configurable: true
  8546. });
  8547. InstancedMesh.prototype.getVerticesData = function (kind) {
  8548. return this._sourceMesh.getVerticesData(kind);
  8549. };
  8550. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8551. return this._sourceMesh.isVerticesDataPresent(kind);
  8552. };
  8553. InstancedMesh.prototype.getIndices = function () {
  8554. return this._sourceMesh.getIndices();
  8555. };
  8556. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8557. get: function () {
  8558. return this._sourceMesh._positions;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8564. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8565. if (data) {
  8566. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8567. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8568. }
  8569. this._updateBoundingInfo();
  8570. };
  8571. InstancedMesh.prototype._preActivate = function () {
  8572. this.sourceMesh._preActivate();
  8573. };
  8574. InstancedMesh.prototype._activate = function (renderId) {
  8575. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8576. };
  8577. InstancedMesh.prototype._syncSubMeshes = function () {
  8578. this.releaseSubMeshes();
  8579. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8580. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8581. }
  8582. };
  8583. InstancedMesh.prototype._generatePointsArray = function () {
  8584. return this._sourceMesh._generatePointsArray();
  8585. };
  8586. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8587. var result = this._sourceMesh.createInstance(name);
  8588. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8589. this.refreshBoundingInfo();
  8590. if (newParent) {
  8591. result.parent = newParent;
  8592. }
  8593. if (!doNotCloneChildren) {
  8594. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8595. var mesh = this.getScene().meshes[index];
  8596. if (mesh.parent == this) {
  8597. mesh.clone(mesh.name, result);
  8598. }
  8599. }
  8600. }
  8601. result.computeWorldMatrix(true);
  8602. return result;
  8603. };
  8604. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8605. var index = this._sourceMesh.instances.indexOf(this);
  8606. this._sourceMesh.instances.splice(index, 1);
  8607. _super.prototype.dispose.call(this, doNotRecurse);
  8608. };
  8609. return InstancedMesh;
  8610. })(BABYLON.AbstractMesh);
  8611. BABYLON.InstancedMesh = InstancedMesh;
  8612. })(BABYLON || (BABYLON = {}));
  8613. var BABYLON;
  8614. (function (BABYLON) {
  8615. var SubMesh = (function () {
  8616. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8617. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8618. this.materialIndex = materialIndex;
  8619. this.verticesStart = verticesStart;
  8620. this.verticesCount = verticesCount;
  8621. this.indexStart = indexStart;
  8622. this.indexCount = indexCount;
  8623. this._renderId = 0;
  8624. this._mesh = mesh;
  8625. this._renderingMesh = renderingMesh || mesh;
  8626. mesh.subMeshes.push(this);
  8627. this._id = mesh.subMeshes.length - 1;
  8628. if (createBoundingBox) {
  8629. this.refreshBoundingInfo();
  8630. }
  8631. }
  8632. SubMesh.prototype.getBoundingInfo = function () {
  8633. return this._boundingInfo;
  8634. };
  8635. SubMesh.prototype.getMesh = function () {
  8636. return this._mesh;
  8637. };
  8638. SubMesh.prototype.getRenderingMesh = function () {
  8639. return this._renderingMesh;
  8640. };
  8641. SubMesh.prototype.getMaterial = function () {
  8642. var rootMaterial = this._renderingMesh.material;
  8643. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8644. var multiMaterial = rootMaterial;
  8645. return multiMaterial.getSubMaterial(this.materialIndex);
  8646. }
  8647. if (!rootMaterial) {
  8648. return this._mesh.getScene().defaultMaterial;
  8649. }
  8650. return rootMaterial;
  8651. };
  8652. SubMesh.prototype.refreshBoundingInfo = function () {
  8653. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8654. if (!data) {
  8655. this._boundingInfo = this._mesh._boundingInfo;
  8656. return;
  8657. }
  8658. var indices = this._renderingMesh.getIndices();
  8659. var extend;
  8660. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8661. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8662. } else {
  8663. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8664. }
  8665. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8666. };
  8667. SubMesh.prototype._checkCollision = function (collider) {
  8668. return this._boundingInfo._checkCollision(collider);
  8669. };
  8670. SubMesh.prototype.updateBoundingInfo = function (world) {
  8671. if (!this._boundingInfo) {
  8672. this.refreshBoundingInfo();
  8673. }
  8674. this._boundingInfo._update(world);
  8675. };
  8676. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8677. return this._boundingInfo.isInFrustum(frustumPlanes);
  8678. };
  8679. SubMesh.prototype.render = function () {
  8680. this._renderingMesh.render(this);
  8681. };
  8682. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8683. if (!this._linesIndexBuffer) {
  8684. var linesIndices = [];
  8685. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8686. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8687. }
  8688. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8689. this.linesIndexCount = linesIndices.length;
  8690. }
  8691. return this._linesIndexBuffer;
  8692. };
  8693. SubMesh.prototype.canIntersects = function (ray) {
  8694. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8695. };
  8696. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8697. var intersectInfo = null;
  8698. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8699. var p0 = positions[indices[index]];
  8700. var p1 = positions[indices[index + 1]];
  8701. var p2 = positions[indices[index + 2]];
  8702. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8703. if (currentIntersectInfo) {
  8704. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8705. intersectInfo = currentIntersectInfo;
  8706. intersectInfo.faceId = index / 3;
  8707. if (fastCheck) {
  8708. break;
  8709. }
  8710. }
  8711. }
  8712. }
  8713. return intersectInfo;
  8714. };
  8715. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8716. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8717. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8718. return result;
  8719. };
  8720. SubMesh.prototype.dispose = function () {
  8721. if (this._linesIndexBuffer) {
  8722. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8723. this._linesIndexBuffer = null;
  8724. }
  8725. var index = this._mesh.subMeshes.indexOf(this);
  8726. this._mesh.subMeshes.splice(index, 1);
  8727. };
  8728. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8729. var minVertexIndex = Number.MAX_VALUE;
  8730. var maxVertexIndex = -Number.MAX_VALUE;
  8731. renderingMesh = renderingMesh || mesh;
  8732. var indices = renderingMesh.getIndices();
  8733. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8734. var vertexIndex = indices[index];
  8735. if (vertexIndex < minVertexIndex)
  8736. minVertexIndex = vertexIndex;
  8737. if (vertexIndex > maxVertexIndex)
  8738. maxVertexIndex = vertexIndex;
  8739. }
  8740. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8741. };
  8742. return SubMesh;
  8743. })();
  8744. BABYLON.SubMesh = SubMesh;
  8745. })(BABYLON || (BABYLON = {}));
  8746. var BABYLON;
  8747. (function (BABYLON) {
  8748. var BaseTexture = (function () {
  8749. function BaseTexture(scene) {
  8750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8751. this.hasAlpha = false;
  8752. this.getAlphaFromRGB = false;
  8753. this.level = 1;
  8754. this.isCube = false;
  8755. this.isRenderTarget = false;
  8756. this.animations = new Array();
  8757. this.coordinatesIndex = 0;
  8758. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8759. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8760. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8761. this.anisotropicFilteringLevel = 4;
  8762. this._scene = scene;
  8763. this._scene.textures.push(this);
  8764. }
  8765. BaseTexture.prototype.getScene = function () {
  8766. return this._scene;
  8767. };
  8768. BaseTexture.prototype.getTextureMatrix = function () {
  8769. return null;
  8770. };
  8771. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8772. return null;
  8773. };
  8774. BaseTexture.prototype.getInternalTexture = function () {
  8775. return this._texture;
  8776. };
  8777. BaseTexture.prototype.isReady = function () {
  8778. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8779. return true;
  8780. }
  8781. if (this._texture) {
  8782. return this._texture.isReady;
  8783. }
  8784. return false;
  8785. };
  8786. BaseTexture.prototype.getSize = function () {
  8787. if (this._texture._width) {
  8788. return { width: this._texture._width, height: this._texture._height };
  8789. }
  8790. if (this._texture._size) {
  8791. return { width: this._texture._size, height: this._texture._size };
  8792. }
  8793. return { width: 0, height: 0 };
  8794. };
  8795. BaseTexture.prototype.getBaseSize = function () {
  8796. if (!this.isReady())
  8797. return { width: 0, height: 0 };
  8798. if (this._texture._size) {
  8799. return { width: this._texture._size, height: this._texture._size };
  8800. }
  8801. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8802. };
  8803. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8804. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8805. for (var index = 0; index < texturesCache.length; index++) {
  8806. var texturesCacheEntry = texturesCache[index];
  8807. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8808. texturesCacheEntry.references++;
  8809. return texturesCacheEntry;
  8810. }
  8811. }
  8812. return null;
  8813. };
  8814. BaseTexture.prototype.delayLoad = function () {
  8815. };
  8816. BaseTexture.prototype.releaseInternalTexture = function () {
  8817. if (!this._texture) {
  8818. return;
  8819. }
  8820. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8821. this._texture.references--;
  8822. if (this._texture.references == 0) {
  8823. var index = texturesCache.indexOf(this._texture);
  8824. texturesCache.splice(index, 1);
  8825. this._scene.getEngine()._releaseTexture(this._texture);
  8826. delete this._texture;
  8827. }
  8828. };
  8829. BaseTexture.prototype.clone = function () {
  8830. return null;
  8831. };
  8832. BaseTexture.prototype.dispose = function () {
  8833. var index = this._scene.textures.indexOf(this);
  8834. if (index >= 0) {
  8835. this._scene.textures.splice(index, 1);
  8836. }
  8837. if (this._texture === undefined) {
  8838. return;
  8839. }
  8840. this.releaseInternalTexture();
  8841. if (this.onDispose) {
  8842. this.onDispose();
  8843. }
  8844. };
  8845. return BaseTexture;
  8846. })();
  8847. BABYLON.BaseTexture = BaseTexture;
  8848. })(BABYLON || (BABYLON = {}));
  8849. var BABYLON;
  8850. (function (BABYLON) {
  8851. var RenderingGroup = (function () {
  8852. function RenderingGroup(index, scene) {
  8853. this.index = index;
  8854. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8855. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8856. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8857. this._scene = scene;
  8858. }
  8859. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  8860. if (customRenderFunction) {
  8861. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  8862. return true;
  8863. }
  8864. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  8865. return false;
  8866. }
  8867. var engine = this._scene.getEngine();
  8868. var subIndex;
  8869. var submesh;
  8870. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  8871. submesh = this._opaqueSubMeshes.data[subIndex];
  8872. this._activeVertices += submesh.verticesCount;
  8873. submesh.render();
  8874. }
  8875. engine.setAlphaTesting(true);
  8876. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  8877. submesh = this._alphaTestSubMeshes.data[subIndex];
  8878. this._activeVertices += submesh.verticesCount;
  8879. submesh.render();
  8880. }
  8881. engine.setAlphaTesting(false);
  8882. if (beforeTransparents) {
  8883. beforeTransparents();
  8884. }
  8885. if (this._transparentSubMeshes.length) {
  8886. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  8887. submesh = this._transparentSubMeshes.data[subIndex];
  8888. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  8889. }
  8890. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  8891. sortedArray.sort(function (a, b) {
  8892. if (a._distanceToCamera < b._distanceToCamera) {
  8893. return 1;
  8894. }
  8895. if (a._distanceToCamera > b._distanceToCamera) {
  8896. return -1;
  8897. }
  8898. return 0;
  8899. });
  8900. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8901. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  8902. submesh = sortedArray[subIndex];
  8903. this._activeVertices += submesh.verticesCount;
  8904. submesh.render();
  8905. }
  8906. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  8907. }
  8908. return true;
  8909. };
  8910. RenderingGroup.prototype.prepare = function () {
  8911. this._opaqueSubMeshes.reset();
  8912. this._transparentSubMeshes.reset();
  8913. this._alphaTestSubMeshes.reset();
  8914. };
  8915. RenderingGroup.prototype.dispatch = function (subMesh) {
  8916. var material = subMesh.getMaterial();
  8917. var mesh = subMesh.getMesh();
  8918. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  8919. if (material.alpha > 0 || mesh.visibility < 1.0) {
  8920. this._transparentSubMeshes.push(subMesh);
  8921. }
  8922. } else if (material.needAlphaTesting()) {
  8923. this._alphaTestSubMeshes.push(subMesh);
  8924. } else {
  8925. this._opaqueSubMeshes.push(subMesh);
  8926. }
  8927. };
  8928. return RenderingGroup;
  8929. })();
  8930. BABYLON.RenderingGroup = RenderingGroup;
  8931. })(BABYLON || (BABYLON = {}));
  8932. var BABYLON;
  8933. (function (BABYLON) {
  8934. var RenderingManager = (function () {
  8935. function RenderingManager(scene) {
  8936. this._renderingGroups = new Array();
  8937. this._scene = scene;
  8938. }
  8939. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  8940. if (this._scene._activeParticleSystems.length === 0) {
  8941. return;
  8942. }
  8943. var beforeParticlesDate = new Date().getTime();
  8944. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  8945. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  8946. if (particleSystem.renderingGroupId !== index) {
  8947. continue;
  8948. }
  8949. this._clearDepthBuffer();
  8950. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  8951. this._scene._activeParticles += particleSystem.render();
  8952. }
  8953. }
  8954. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  8955. };
  8956. RenderingManager.prototype._renderSprites = function (index) {
  8957. if (this._scene.spriteManagers.length === 0) {
  8958. return;
  8959. }
  8960. var beforeSpritessDate = new Date().getTime();
  8961. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  8962. var spriteManager = this._scene.spriteManagers[id];
  8963. if (spriteManager.renderingGroupId === index) {
  8964. this._clearDepthBuffer();
  8965. spriteManager.render();
  8966. }
  8967. }
  8968. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  8969. };
  8970. RenderingManager.prototype._clearDepthBuffer = function () {
  8971. if (this._depthBufferAlreadyCleaned) {
  8972. return;
  8973. }
  8974. this._scene.getEngine().clear(0, false, true);
  8975. this._depthBufferAlreadyCleaned = true;
  8976. };
  8977. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  8978. var _this = this;
  8979. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  8980. this._depthBufferAlreadyCleaned = false;
  8981. var renderingGroup = this._renderingGroups[index];
  8982. if (renderingGroup) {
  8983. this._clearDepthBuffer();
  8984. if (!renderingGroup.render(customRenderFunction, function () {
  8985. if (renderSprites) {
  8986. _this._renderSprites(index);
  8987. }
  8988. })) {
  8989. this._renderingGroups.splice(index, 1);
  8990. }
  8991. } else if (renderSprites) {
  8992. this._renderSprites(index);
  8993. }
  8994. if (renderParticles) {
  8995. this._renderParticles(index, activeMeshes);
  8996. }
  8997. }
  8998. };
  8999. RenderingManager.prototype.reset = function () {
  9000. for (var index in this._renderingGroups) {
  9001. var renderingGroup = this._renderingGroups[index];
  9002. renderingGroup.prepare();
  9003. }
  9004. };
  9005. RenderingManager.prototype.dispatch = function (subMesh) {
  9006. var mesh = subMesh.getMesh();
  9007. var renderingGroupId = mesh.renderingGroupId || 0;
  9008. if (!this._renderingGroups[renderingGroupId]) {
  9009. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9010. }
  9011. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9012. };
  9013. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9014. return RenderingManager;
  9015. })();
  9016. BABYLON.RenderingManager = RenderingManager;
  9017. })(BABYLON || (BABYLON = {}));
  9018. var __extends = this.__extends || function (d, b) {
  9019. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9020. function __() { this.constructor = d; }
  9021. __.prototype = b.prototype;
  9022. d.prototype = new __();
  9023. };
  9024. var BABYLON;
  9025. (function (BABYLON) {
  9026. var Texture = (function (_super) {
  9027. __extends(Texture, _super);
  9028. function Texture(url, scene, noMipmap, invertY, samplingMode) {
  9029. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9030. _super.call(this, scene);
  9031. this.uOffset = 0;
  9032. this.vOffset = 0;
  9033. this.uScale = 1.0;
  9034. this.vScale = 1.0;
  9035. this.uAng = 0;
  9036. this.vAng = 0;
  9037. this.wAng = 0;
  9038. this.name = url;
  9039. this.url = url;
  9040. this._noMipmap = noMipmap;
  9041. this._invertY = invertY;
  9042. this._samplingMode = samplingMode;
  9043. if (!url) {
  9044. return;
  9045. }
  9046. this._texture = this._getFromCache(url, noMipmap);
  9047. if (!this._texture) {
  9048. if (!scene.useDelayedTextureLoading) {
  9049. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode);
  9050. } else {
  9051. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9052. }
  9053. }
  9054. }
  9055. Texture.prototype.delayLoad = function () {
  9056. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9057. return;
  9058. }
  9059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9060. this._texture = this._getFromCache(this.url, this._noMipmap);
  9061. if (!this._texture) {
  9062. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode);
  9063. }
  9064. };
  9065. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9066. x -= this.uOffset + 0.5;
  9067. y -= this.vOffset + 0.5;
  9068. z -= 0.5;
  9069. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9070. t.x *= this.uScale;
  9071. t.y *= this.vScale;
  9072. t.x += 0.5;
  9073. t.y += 0.5;
  9074. t.z += 0.5;
  9075. };
  9076. Texture.prototype.getTextureMatrix = function () {
  9077. 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) {
  9078. return this._cachedTextureMatrix;
  9079. }
  9080. this._cachedUOffset = this.uOffset;
  9081. this._cachedVOffset = this.vOffset;
  9082. this._cachedUScale = this.uScale;
  9083. this._cachedVScale = this.vScale;
  9084. this._cachedUAng = this.uAng;
  9085. this._cachedVAng = this.vAng;
  9086. this._cachedWAng = this.wAng;
  9087. if (!this._cachedTextureMatrix) {
  9088. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9089. this._rowGenerationMatrix = new BABYLON.Matrix();
  9090. this._t0 = BABYLON.Vector3.Zero();
  9091. this._t1 = BABYLON.Vector3.Zero();
  9092. this._t2 = BABYLON.Vector3.Zero();
  9093. }
  9094. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9095. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9096. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9097. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9098. this._t1.subtractInPlace(this._t0);
  9099. this._t2.subtractInPlace(this._t0);
  9100. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9101. this._cachedTextureMatrix.m[0] = this._t1.x;
  9102. this._cachedTextureMatrix.m[1] = this._t1.y;
  9103. this._cachedTextureMatrix.m[2] = this._t1.z;
  9104. this._cachedTextureMatrix.m[4] = this._t2.x;
  9105. this._cachedTextureMatrix.m[5] = this._t2.y;
  9106. this._cachedTextureMatrix.m[6] = this._t2.z;
  9107. this._cachedTextureMatrix.m[8] = this._t0.x;
  9108. this._cachedTextureMatrix.m[9] = this._t0.y;
  9109. this._cachedTextureMatrix.m[10] = this._t0.z;
  9110. return this._cachedTextureMatrix;
  9111. };
  9112. Texture.prototype.getReflectionTextureMatrix = function () {
  9113. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9114. return this._cachedTextureMatrix;
  9115. }
  9116. if (!this._cachedTextureMatrix) {
  9117. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9118. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9119. }
  9120. switch (this.coordinatesMode) {
  9121. case BABYLON.Texture.SPHERICAL_MODE:
  9122. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9123. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9124. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9125. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9126. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9127. break;
  9128. case BABYLON.Texture.PLANAR_MODE:
  9129. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9130. this._cachedTextureMatrix[0] = this.uScale;
  9131. this._cachedTextureMatrix[5] = this.vScale;
  9132. this._cachedTextureMatrix[12] = this.uOffset;
  9133. this._cachedTextureMatrix[13] = this.vOffset;
  9134. break;
  9135. case BABYLON.Texture.PROJECTION_MODE:
  9136. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9137. this._projectionModeMatrix.m[0] = 0.5;
  9138. this._projectionModeMatrix.m[5] = -0.5;
  9139. this._projectionModeMatrix.m[10] = 0.0;
  9140. this._projectionModeMatrix.m[12] = 0.5;
  9141. this._projectionModeMatrix.m[13] = 0.5;
  9142. this._projectionModeMatrix.m[14] = 1.0;
  9143. this._projectionModeMatrix.m[15] = 1.0;
  9144. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9145. break;
  9146. default:
  9147. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9148. break;
  9149. }
  9150. return this._cachedTextureMatrix;
  9151. };
  9152. Texture.prototype.clone = function () {
  9153. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9154. newTexture.hasAlpha = this.hasAlpha;
  9155. newTexture.level = this.level;
  9156. newTexture.wrapU = this.wrapU;
  9157. newTexture.wrapV = this.wrapV;
  9158. newTexture.coordinatesIndex = this.coordinatesIndex;
  9159. newTexture.coordinatesMode = this.coordinatesMode;
  9160. newTexture.uOffset = this.uOffset;
  9161. newTexture.vOffset = this.vOffset;
  9162. newTexture.uScale = this.uScale;
  9163. newTexture.vScale = this.vScale;
  9164. newTexture.uAng = this.uAng;
  9165. newTexture.vAng = this.vAng;
  9166. newTexture.wAng = this.wAng;
  9167. return newTexture;
  9168. };
  9169. Texture.NEAREST_SAMPLINGMODE = 1;
  9170. Texture.BILINEAR_SAMPLINGMODE = 2;
  9171. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9172. Texture.EXPLICIT_MODE = 0;
  9173. Texture.SPHERICAL_MODE = 1;
  9174. Texture.PLANAR_MODE = 2;
  9175. Texture.CUBIC_MODE = 3;
  9176. Texture.PROJECTION_MODE = 4;
  9177. Texture.SKYBOX_MODE = 5;
  9178. Texture.CLAMP_ADDRESSMODE = 0;
  9179. Texture.WRAP_ADDRESSMODE = 1;
  9180. Texture.MIRROR_ADDRESSMODE = 2;
  9181. return Texture;
  9182. })(BABYLON.BaseTexture);
  9183. BABYLON.Texture = Texture;
  9184. })(BABYLON || (BABYLON = {}));
  9185. var __extends = this.__extends || function (d, b) {
  9186. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9187. function __() { this.constructor = d; }
  9188. __.prototype = b.prototype;
  9189. d.prototype = new __();
  9190. };
  9191. var BABYLON;
  9192. (function (BABYLON) {
  9193. var CubeTexture = (function (_super) {
  9194. __extends(CubeTexture, _super);
  9195. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9196. _super.call(this, scene);
  9197. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9198. this.name = rootUrl;
  9199. this.url = rootUrl;
  9200. this._noMipmap = noMipmap;
  9201. this.hasAlpha = false;
  9202. this._texture = this._getFromCache(rootUrl, noMipmap);
  9203. if (!extensions) {
  9204. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9205. }
  9206. this._extensions = extensions;
  9207. if (!this._texture) {
  9208. if (!scene.useDelayedTextureLoading) {
  9209. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9210. } else {
  9211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9212. }
  9213. }
  9214. this.isCube = true;
  9215. this._textureMatrix = BABYLON.Matrix.Identity();
  9216. }
  9217. CubeTexture.prototype.clone = function () {
  9218. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9219. newTexture.level = this.level;
  9220. newTexture.wrapU = this.wrapU;
  9221. newTexture.wrapV = this.wrapV;
  9222. newTexture.coordinatesIndex = this.coordinatesIndex;
  9223. newTexture.coordinatesMode = this.coordinatesMode;
  9224. return newTexture;
  9225. };
  9226. CubeTexture.prototype.delayLoad = function () {
  9227. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9228. return;
  9229. }
  9230. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9231. this._texture = this._getFromCache(this.url, this._noMipmap);
  9232. if (!this._texture) {
  9233. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9234. }
  9235. };
  9236. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9237. return this._textureMatrix;
  9238. };
  9239. return CubeTexture;
  9240. })(BABYLON.BaseTexture);
  9241. BABYLON.CubeTexture = CubeTexture;
  9242. })(BABYLON || (BABYLON = {}));
  9243. var __extends = this.__extends || function (d, b) {
  9244. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9245. function __() { this.constructor = d; }
  9246. __.prototype = b.prototype;
  9247. d.prototype = new __();
  9248. };
  9249. var BABYLON;
  9250. (function (BABYLON) {
  9251. var RenderTargetTexture = (function (_super) {
  9252. __extends(RenderTargetTexture, _super);
  9253. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9254. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9255. _super.call(this, null, scene, !generateMipMaps);
  9256. this.renderList = new Array();
  9257. this.renderParticles = true;
  9258. this.renderSprites = false;
  9259. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9260. this._currentRefreshId = -1;
  9261. this._refreshRate = 1;
  9262. this.name = name;
  9263. this.isRenderTarget = true;
  9264. this._size = size;
  9265. this._generateMipMaps = generateMipMaps;
  9266. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9267. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9268. this._renderingManager = new BABYLON.RenderingManager(scene);
  9269. }
  9270. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9271. this._currentRefreshId = -1;
  9272. };
  9273. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9274. get: function () {
  9275. return this._refreshRate;
  9276. },
  9277. set: function (value) {
  9278. this._refreshRate = value;
  9279. this.resetRefreshCounter();
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. RenderTargetTexture.prototype._shouldRender = function () {
  9285. if (this._currentRefreshId === -1) {
  9286. this._currentRefreshId = 1;
  9287. return true;
  9288. }
  9289. if (this.refreshRate == this._currentRefreshId) {
  9290. this._currentRefreshId = 1;
  9291. return true;
  9292. }
  9293. this._currentRefreshId++;
  9294. return false;
  9295. };
  9296. RenderTargetTexture.prototype.getRenderSize = function () {
  9297. return this._size;
  9298. };
  9299. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9300. this.releaseInternalTexture();
  9301. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9302. };
  9303. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9304. var scene = this.getScene();
  9305. var engine = scene.getEngine();
  9306. if (this._waitingRenderList) {
  9307. this.renderList = [];
  9308. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9309. var id = this._waitingRenderList[index];
  9310. this.renderList.push(scene.getMeshByID(id));
  9311. }
  9312. delete this._waitingRenderList;
  9313. }
  9314. if (!this.renderList) {
  9315. return;
  9316. }
  9317. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9318. engine.bindFramebuffer(this._texture);
  9319. }
  9320. engine.clear(scene.clearColor, true, true);
  9321. this._renderingManager.reset();
  9322. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9323. var mesh = this.renderList[meshIndex];
  9324. if (mesh) {
  9325. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9326. this.resetRefreshCounter();
  9327. continue;
  9328. }
  9329. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9330. mesh._activate(scene.getRenderId());
  9331. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9332. var subMesh = mesh.subMeshes[subIndex];
  9333. scene._activeVertices += subMesh.verticesCount;
  9334. this._renderingManager.dispatch(subMesh);
  9335. }
  9336. }
  9337. }
  9338. }
  9339. if (!this._doNotChangeAspectRatio) {
  9340. scene.updateTransformMatrix(true);
  9341. }
  9342. if (this.onBeforeRender) {
  9343. this.onBeforeRender();
  9344. }
  9345. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9346. if (useCameraPostProcess) {
  9347. scene.postProcessManager._finalizeFrame(false, this._texture);
  9348. }
  9349. if (this.onAfterRender) {
  9350. this.onAfterRender();
  9351. }
  9352. engine.unBindFramebuffer(this._texture);
  9353. if (!this._doNotChangeAspectRatio) {
  9354. scene.updateTransformMatrix(true);
  9355. }
  9356. };
  9357. RenderTargetTexture.prototype.clone = function () {
  9358. var textureSize = this.getSize();
  9359. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9360. newTexture.hasAlpha = this.hasAlpha;
  9361. newTexture.level = this.level;
  9362. newTexture.coordinatesMode = this.coordinatesMode;
  9363. newTexture.renderList = this.renderList.slice(0);
  9364. return newTexture;
  9365. };
  9366. return RenderTargetTexture;
  9367. })(BABYLON.Texture);
  9368. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9369. })(BABYLON || (BABYLON = {}));
  9370. var __extends = this.__extends || function (d, b) {
  9371. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9372. function __() { this.constructor = d; }
  9373. __.prototype = b.prototype;
  9374. d.prototype = new __();
  9375. };
  9376. var BABYLON;
  9377. (function (BABYLON) {
  9378. var MirrorTexture = (function (_super) {
  9379. __extends(MirrorTexture, _super);
  9380. function MirrorTexture(name, size, scene, generateMipMaps) {
  9381. var _this = this;
  9382. _super.call(this, name, size, scene, generateMipMaps, true);
  9383. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9384. this._transformMatrix = BABYLON.Matrix.Zero();
  9385. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9386. this.onBeforeRender = function () {
  9387. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9388. _this._savedViewMatrix = scene.getViewMatrix();
  9389. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9390. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9391. scene.clipPlane = _this.mirrorPlane;
  9392. scene.getEngine().cullBackFaces = false;
  9393. };
  9394. this.onAfterRender = function () {
  9395. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9396. scene.getEngine().cullBackFaces = true;
  9397. delete scene.clipPlane;
  9398. };
  9399. }
  9400. MirrorTexture.prototype.clone = function () {
  9401. var textureSize = this.getSize();
  9402. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9403. newTexture.hasAlpha = this.hasAlpha;
  9404. newTexture.level = this.level;
  9405. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9406. newTexture.renderList = this.renderList.slice(0);
  9407. return newTexture;
  9408. };
  9409. return MirrorTexture;
  9410. })(BABYLON.RenderTargetTexture);
  9411. BABYLON.MirrorTexture = MirrorTexture;
  9412. })(BABYLON || (BABYLON = {}));
  9413. var __extends = this.__extends || function (d, b) {
  9414. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9415. function __() { this.constructor = d; }
  9416. __.prototype = b.prototype;
  9417. d.prototype = new __();
  9418. };
  9419. var BABYLON;
  9420. (function (BABYLON) {
  9421. var DynamicTexture = (function (_super) {
  9422. __extends(DynamicTexture, _super);
  9423. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9424. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9425. _super.call(this, null, scene, !generateMipMaps);
  9426. this.name = name;
  9427. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9428. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9429. this._generateMipMaps = generateMipMaps;
  9430. if (options.getContext) {
  9431. this._canvas = options;
  9432. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9433. } else {
  9434. this._canvas = document.createElement("canvas");
  9435. if (options.width) {
  9436. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9437. } else {
  9438. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9439. }
  9440. }
  9441. var textureSize = this.getSize();
  9442. this._canvas.width = textureSize.width;
  9443. this._canvas.height = textureSize.height;
  9444. this._context = this._canvas.getContext("2d");
  9445. }
  9446. DynamicTexture.prototype.getContext = function () {
  9447. return this._context;
  9448. };
  9449. DynamicTexture.prototype.update = function (invertY) {
  9450. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9451. };
  9452. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9453. var size = this.getSize();
  9454. if (clearColor) {
  9455. this._context.fillStyle = clearColor;
  9456. this._context.fillRect(0, 0, size.width, size.height);
  9457. }
  9458. this._context.font = font;
  9459. if (x === null) {
  9460. var textSize = this._context.measureText(text);
  9461. x = (size.width - textSize.width) / 2;
  9462. }
  9463. this._context.fillStyle = color;
  9464. this._context.fillText(text, x, y);
  9465. this.update(invertY);
  9466. };
  9467. DynamicTexture.prototype.clone = function () {
  9468. var textureSize = this.getSize();
  9469. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9470. newTexture.hasAlpha = this.hasAlpha;
  9471. newTexture.level = this.level;
  9472. newTexture.wrapU = this.wrapU;
  9473. newTexture.wrapV = this.wrapV;
  9474. return newTexture;
  9475. };
  9476. return DynamicTexture;
  9477. })(BABYLON.Texture);
  9478. BABYLON.DynamicTexture = DynamicTexture;
  9479. })(BABYLON || (BABYLON = {}));
  9480. var __extends = this.__extends || function (d, b) {
  9481. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9482. function __() { this.constructor = d; }
  9483. __.prototype = b.prototype;
  9484. d.prototype = new __();
  9485. };
  9486. var BABYLON;
  9487. (function (BABYLON) {
  9488. var VideoTexture = (function (_super) {
  9489. __extends(VideoTexture, _super);
  9490. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9491. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9492. var _this = this;
  9493. _super.call(this, null, scene, !generateMipMaps, invertY);
  9494. this._autoLaunch = true;
  9495. this.name = name;
  9496. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9497. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9498. var requiredWidth = size.width || size;
  9499. var requiredHeight = size.height || size;
  9500. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9501. var textureSize = this.getSize();
  9502. this.video = document.createElement("video");
  9503. this.video.width = textureSize.width;
  9504. this.video.height = textureSize.height;
  9505. this.video.autoplay = false;
  9506. this.video.loop = true;
  9507. this.video.addEventListener("canplaythrough", function () {
  9508. if (_this._texture) {
  9509. _this._texture.isReady = true;
  9510. }
  9511. });
  9512. urls.forEach(function (url) {
  9513. var source = document.createElement("source");
  9514. source.src = url;
  9515. _this.video.appendChild(source);
  9516. });
  9517. this._lastUpdate = new Date().getTime();
  9518. }
  9519. VideoTexture.prototype.update = function () {
  9520. if (this._autoLaunch) {
  9521. this._autoLaunch = false;
  9522. this.video.play();
  9523. }
  9524. var now = new Date().getTime();
  9525. if (now - this._lastUpdate < 15) {
  9526. return false;
  9527. }
  9528. this._lastUpdate = now;
  9529. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9530. return true;
  9531. };
  9532. return VideoTexture;
  9533. })(BABYLON.Texture);
  9534. BABYLON.VideoTexture = VideoTexture;
  9535. })(BABYLON || (BABYLON = {}));
  9536. var BABYLON;
  9537. (function (BABYLON) {
  9538. var EffectFallbacks = (function () {
  9539. function EffectFallbacks() {
  9540. this._defines = {};
  9541. this._currentRank = 32;
  9542. this._maxRank = -1;
  9543. }
  9544. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9545. if (!this._defines[rank]) {
  9546. if (rank < this._currentRank) {
  9547. this._currentRank = rank;
  9548. }
  9549. if (rank > this._maxRank) {
  9550. this._maxRank = rank;
  9551. }
  9552. this._defines[rank] = new Array();
  9553. }
  9554. this._defines[rank].push(define);
  9555. };
  9556. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9557. get: function () {
  9558. return this._currentRank <= this._maxRank;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9564. var currentFallbacks = this._defines[this._currentRank];
  9565. for (var index = 0; index < currentFallbacks.length; index++) {
  9566. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9567. }
  9568. this._currentRank++;
  9569. return currentDefines;
  9570. };
  9571. return EffectFallbacks;
  9572. })();
  9573. BABYLON.EffectFallbacks = EffectFallbacks;
  9574. var Effect = (function () {
  9575. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9576. var _this = this;
  9577. this._isReady = false;
  9578. this._compilationError = "";
  9579. this._valueCache = [];
  9580. this._engine = engine;
  9581. this.name = baseName;
  9582. this.defines = defines;
  9583. this._uniformsNames = uniformsNames.concat(samplers);
  9584. this._samplers = samplers;
  9585. this._attributesNames = attributesNames;
  9586. this.onError = onError;
  9587. this.onCompiled = onCompiled;
  9588. var vertexSource;
  9589. var fragmentSource;
  9590. if (baseName.vertexElement) {
  9591. vertexSource = document.getElementById(baseName.vertexElement);
  9592. } else {
  9593. vertexSource = baseName.vertex || baseName;
  9594. }
  9595. if (baseName.fragmentElement) {
  9596. fragmentSource = document.getElementById(baseName.fragmentElement);
  9597. } else {
  9598. fragmentSource = baseName.fragment || baseName;
  9599. }
  9600. this._loadVertexShader(vertexSource, function (vertexCode) {
  9601. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9602. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9603. });
  9604. });
  9605. }
  9606. Effect.prototype.isReady = function () {
  9607. return this._isReady;
  9608. };
  9609. Effect.prototype.getProgram = function () {
  9610. return this._program;
  9611. };
  9612. Effect.prototype.getAttributesNames = function () {
  9613. return this._attributesNames;
  9614. };
  9615. Effect.prototype.getAttributeLocation = function (index) {
  9616. return this._attributes[index];
  9617. };
  9618. Effect.prototype.getAttributeLocationByName = function (name) {
  9619. var index = this._attributesNames.indexOf(name);
  9620. return this._attributes[index];
  9621. };
  9622. Effect.prototype.getAttributesCount = function () {
  9623. return this._attributes.length;
  9624. };
  9625. Effect.prototype.getUniformIndex = function (uniformName) {
  9626. return this._uniformsNames.indexOf(uniformName);
  9627. };
  9628. Effect.prototype.getUniform = function (uniformName) {
  9629. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9630. };
  9631. Effect.prototype.getSamplers = function () {
  9632. return this._samplers;
  9633. };
  9634. Effect.prototype.getCompilationError = function () {
  9635. return this._compilationError;
  9636. };
  9637. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9638. if (vertex instanceof HTMLElement) {
  9639. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9640. callback(vertexCode);
  9641. return;
  9642. }
  9643. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9644. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9645. return;
  9646. }
  9647. var vertexShaderUrl;
  9648. if (vertex[0] === ".") {
  9649. vertexShaderUrl = vertex;
  9650. } else {
  9651. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9652. }
  9653. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9654. };
  9655. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9656. if (fragment instanceof HTMLElement) {
  9657. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9658. callback(fragmentCode);
  9659. return;
  9660. }
  9661. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9662. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9663. return;
  9664. }
  9665. var fragmentShaderUrl;
  9666. if (fragment[0] === ".") {
  9667. fragmentShaderUrl = fragment;
  9668. } else {
  9669. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9670. }
  9671. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9672. };
  9673. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9674. try {
  9675. var engine = this._engine;
  9676. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9677. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9678. this._attributes = engine.getAttributes(this._program, attributesNames);
  9679. for (var index = 0; index < this._samplers.length; index++) {
  9680. var sampler = this.getUniform(this._samplers[index]);
  9681. if (sampler == null) {
  9682. this._samplers.splice(index, 1);
  9683. index--;
  9684. }
  9685. }
  9686. engine.bindSamplers(this);
  9687. this._isReady = true;
  9688. if (this.onCompiled) {
  9689. this.onCompiled(this);
  9690. }
  9691. } catch (e) {
  9692. if (fallbacks && fallbacks.isMoreFallbacks) {
  9693. defines = fallbacks.reduce(defines);
  9694. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9695. } else {
  9696. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9697. BABYLON.Tools.Error("Defines: " + defines);
  9698. BABYLON.Tools.Error("Error: " + e.message);
  9699. this._compilationError = e.message;
  9700. if (this.onError) {
  9701. this.onError(this, this._compilationError);
  9702. }
  9703. }
  9704. }
  9705. };
  9706. Effect.prototype._bindTexture = function (channel, texture) {
  9707. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9708. };
  9709. Effect.prototype.setTexture = function (channel, texture) {
  9710. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9711. };
  9712. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9713. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9714. };
  9715. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9716. if (!this._valueCache[uniformName]) {
  9717. this._valueCache[uniformName] = [x, y];
  9718. return;
  9719. }
  9720. this._valueCache[uniformName][0] = x;
  9721. this._valueCache[uniformName][1] = y;
  9722. };
  9723. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9724. if (!this._valueCache[uniformName]) {
  9725. this._valueCache[uniformName] = [x, y, z];
  9726. return;
  9727. }
  9728. this._valueCache[uniformName][0] = x;
  9729. this._valueCache[uniformName][1] = y;
  9730. this._valueCache[uniformName][2] = z;
  9731. };
  9732. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9733. if (!this._valueCache[uniformName]) {
  9734. this._valueCache[uniformName] = [x, y, z, w];
  9735. return;
  9736. }
  9737. this._valueCache[uniformName][0] = x;
  9738. this._valueCache[uniformName][1] = y;
  9739. this._valueCache[uniformName][2] = z;
  9740. this._valueCache[uniformName][3] = w;
  9741. };
  9742. Effect.prototype.setArray = function (uniformName, array) {
  9743. this._engine.setArray(this.getUniform(uniformName), array);
  9744. return this;
  9745. };
  9746. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9747. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9748. return this;
  9749. };
  9750. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9751. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9752. return this;
  9753. };
  9754. Effect.prototype.setFloat = function (uniformName, value) {
  9755. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9756. return this;
  9757. this._valueCache[uniformName] = value;
  9758. this._engine.setFloat(this.getUniform(uniformName), value);
  9759. return this;
  9760. };
  9761. Effect.prototype.setBool = function (uniformName, bool) {
  9762. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9763. return this;
  9764. this._valueCache[uniformName] = bool;
  9765. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9766. return this;
  9767. };
  9768. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9769. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9770. return this;
  9771. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9772. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9773. return this;
  9774. };
  9775. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9776. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9777. return this;
  9778. this._cacheFloat2(uniformName, x, y);
  9779. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9780. return this;
  9781. };
  9782. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9783. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9784. return this;
  9785. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9786. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9787. return this;
  9788. };
  9789. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9790. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9791. return this;
  9792. this._cacheFloat3(uniformName, x, y, z);
  9793. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9794. return this;
  9795. };
  9796. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9797. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9798. return this;
  9799. this._cacheFloat4(uniformName, x, y, z, w);
  9800. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9801. return this;
  9802. };
  9803. Effect.prototype.setColor3 = function (uniformName, color3) {
  9804. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9805. return this;
  9806. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9807. this._engine.setColor3(this.getUniform(uniformName), color3);
  9808. return this;
  9809. };
  9810. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9811. 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)
  9812. return this;
  9813. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9814. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9815. return this;
  9816. };
  9817. 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}",
  9818. 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}",
  9819. 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}",
  9820. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9821. 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}",
  9822. 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}",
  9823. 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}",
  9824. 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}",
  9825. 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}",
  9826. 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}",
  9827. 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}",
  9828. 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}",
  9829. 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}",
  9830. 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}",
  9831. 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}",
  9832. 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}",
  9833. 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}",
  9834. 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}",
  9835. 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}",
  9836. 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}",
  9837. 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}",
  9838. 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}",
  9839. 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}",
  9840. 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}",
  9841. 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}",
  9842. 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}",
  9843. 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}",
  9844. 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}",
  9845. 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}",
  9846. };
  9847. return Effect;
  9848. })();
  9849. BABYLON.Effect = Effect;
  9850. })(BABYLON || (BABYLON = {}));
  9851. var BABYLON;
  9852. (function (BABYLON) {
  9853. var Material = (function () {
  9854. function Material(name, scene, doNotAdd) {
  9855. this.name = name;
  9856. this.checkReadyOnEveryCall = true;
  9857. this.checkReadyOnlyOnce = false;
  9858. this.state = "";
  9859. this.alpha = 1.0;
  9860. this.wireframe = false;
  9861. this.backFaceCulling = true;
  9862. this._wasPreviouslyReady = false;
  9863. this.id = name;
  9864. this._scene = scene;
  9865. if (!doNotAdd) {
  9866. scene.materials.push(this);
  9867. }
  9868. }
  9869. Material.prototype.isReady = function (mesh, useInstances) {
  9870. return true;
  9871. };
  9872. Material.prototype.getEffect = function () {
  9873. return this._effect;
  9874. };
  9875. Material.prototype.getScene = function () {
  9876. return this._scene;
  9877. };
  9878. Material.prototype.needAlphaBlending = function () {
  9879. return (this.alpha < 1.0);
  9880. };
  9881. Material.prototype.needAlphaTesting = function () {
  9882. return false;
  9883. };
  9884. Material.prototype.getAlphaTestTexture = function () {
  9885. return null;
  9886. };
  9887. Material.prototype.trackCreation = function (onCompiled, onError) {
  9888. };
  9889. Material.prototype._preBind = function () {
  9890. var engine = this._scene.getEngine();
  9891. engine.enableEffect(this._effect);
  9892. engine.setState(this.backFaceCulling);
  9893. };
  9894. Material.prototype.bind = function (world, mesh) {
  9895. };
  9896. Material.prototype.bindOnlyWorldMatrix = function (world) {
  9897. };
  9898. Material.prototype.unbind = function () {
  9899. };
  9900. Material.prototype.dispose = function (forceDisposeEffect) {
  9901. var index = this._scene.materials.indexOf(this);
  9902. this._scene.materials.splice(index, 1);
  9903. if (forceDisposeEffect && this._effect) {
  9904. this._scene.getEngine()._releaseEffect(this._effect);
  9905. this._effect = null;
  9906. }
  9907. if (this.onDispose) {
  9908. this.onDispose();
  9909. }
  9910. };
  9911. return Material;
  9912. })();
  9913. BABYLON.Material = Material;
  9914. })(BABYLON || (BABYLON = {}));
  9915. var __extends = this.__extends || function (d, b) {
  9916. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9917. function __() { this.constructor = d; }
  9918. __.prototype = b.prototype;
  9919. d.prototype = new __();
  9920. };
  9921. var BABYLON;
  9922. (function (BABYLON) {
  9923. var maxSimultaneousLights = 4;
  9924. var FresnelParameters = (function () {
  9925. function FresnelParameters() {
  9926. this.isEnabled = true;
  9927. this.leftColor = BABYLON.Color3.White();
  9928. this.rightColor = BABYLON.Color3.Black();
  9929. this.bias = 0;
  9930. this.power = 1;
  9931. }
  9932. return FresnelParameters;
  9933. })();
  9934. BABYLON.FresnelParameters = FresnelParameters;
  9935. var StandardMaterial = (function (_super) {
  9936. __extends(StandardMaterial, _super);
  9937. function StandardMaterial(name, scene) {
  9938. var _this = this;
  9939. _super.call(this, name, scene);
  9940. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9941. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  9942. this.specularColor = new BABYLON.Color3(1, 1, 1);
  9943. this.specularPower = 64;
  9944. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  9945. this.useAlphaFromDiffuseTexture = false;
  9946. this.useSpecularOverAlpha = true;
  9947. this._cachedDefines = null;
  9948. this._renderTargets = new BABYLON.SmartArray(16);
  9949. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  9950. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  9951. this._scaledDiffuse = new BABYLON.Color3();
  9952. this._scaledSpecular = new BABYLON.Color3();
  9953. this.getRenderTargetTextures = function () {
  9954. _this._renderTargets.reset();
  9955. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  9956. _this._renderTargets.push(_this.reflectionTexture);
  9957. }
  9958. return _this._renderTargets;
  9959. };
  9960. }
  9961. StandardMaterial.prototype.needAlphaBlending = function () {
  9962. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  9963. };
  9964. StandardMaterial.prototype.needAlphaTesting = function () {
  9965. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  9966. };
  9967. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  9968. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  9969. };
  9970. StandardMaterial.prototype.getAlphaTestTexture = function () {
  9971. return this.diffuseTexture;
  9972. };
  9973. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  9974. if (this.checkReadyOnlyOnce) {
  9975. if (this._wasPreviouslyReady) {
  9976. return true;
  9977. }
  9978. }
  9979. var scene = this.getScene();
  9980. if (!this.checkReadyOnEveryCall) {
  9981. if (this._renderId === scene.getRenderId()) {
  9982. return true;
  9983. }
  9984. }
  9985. var engine = scene.getEngine();
  9986. var defines = [];
  9987. var fallbacks = new BABYLON.EffectFallbacks();
  9988. if (scene.texturesEnabled) {
  9989. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  9990. if (!this.diffuseTexture.isReady()) {
  9991. return false;
  9992. } else {
  9993. defines.push("#define DIFFUSE");
  9994. }
  9995. }
  9996. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  9997. if (!this.ambientTexture.isReady()) {
  9998. return false;
  9999. } else {
  10000. defines.push("#define AMBIENT");
  10001. }
  10002. }
  10003. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10004. if (!this.opacityTexture.isReady()) {
  10005. return false;
  10006. } else {
  10007. defines.push("#define OPACITY");
  10008. if (this.opacityTexture.getAlphaFromRGB) {
  10009. defines.push("#define OPACITYRGB");
  10010. }
  10011. }
  10012. }
  10013. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10014. if (!this.reflectionTexture.isReady()) {
  10015. return false;
  10016. } else {
  10017. defines.push("#define REFLECTION");
  10018. fallbacks.addFallback(0, "REFLECTION");
  10019. }
  10020. }
  10021. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10022. if (!this.emissiveTexture.isReady()) {
  10023. return false;
  10024. } else {
  10025. defines.push("#define EMISSIVE");
  10026. }
  10027. }
  10028. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10029. if (!this.specularTexture.isReady()) {
  10030. return false;
  10031. } else {
  10032. defines.push("#define SPECULAR");
  10033. fallbacks.addFallback(0, "SPECULAR");
  10034. }
  10035. }
  10036. }
  10037. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10038. if (!this.bumpTexture.isReady()) {
  10039. return false;
  10040. } else {
  10041. defines.push("#define BUMP");
  10042. fallbacks.addFallback(0, "BUMP");
  10043. }
  10044. }
  10045. if (this.useSpecularOverAlpha) {
  10046. defines.push("#define SPECULAROVERALPHA");
  10047. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10048. }
  10049. if (scene.clipPlane) {
  10050. defines.push("#define CLIPPLANE");
  10051. }
  10052. if (engine.getAlphaTesting()) {
  10053. defines.push("#define ALPHATEST");
  10054. }
  10055. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10056. defines.push("#define ALPHAFROMDIFFUSE");
  10057. }
  10058. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10059. defines.push("#define FOG");
  10060. fallbacks.addFallback(1, "FOG");
  10061. }
  10062. var shadowsActivated = false;
  10063. var lightIndex = 0;
  10064. if (scene.lightsEnabled) {
  10065. for (var index = 0; index < scene.lights.length; index++) {
  10066. var light = scene.lights[index];
  10067. if (!light.isEnabled()) {
  10068. continue;
  10069. }
  10070. if (light._excludedMeshesIds.length > 0) {
  10071. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10072. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10073. if (excludedMesh) {
  10074. light.excludedMeshes.push(excludedMesh);
  10075. }
  10076. }
  10077. light._excludedMeshesIds = [];
  10078. }
  10079. if (light._includedOnlyMeshesIds.length > 0) {
  10080. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10081. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10082. if (includedOnlyMesh) {
  10083. light.includedOnlyMeshes.push(includedOnlyMesh);
  10084. }
  10085. }
  10086. light._includedOnlyMeshesIds = [];
  10087. }
  10088. if (!light.canAffectMesh(mesh)) {
  10089. continue;
  10090. }
  10091. defines.push("#define LIGHT" + lightIndex);
  10092. if (lightIndex > 0) {
  10093. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10094. }
  10095. var type;
  10096. if (light instanceof BABYLON.SpotLight) {
  10097. type = "#define SPOTLIGHT" + lightIndex;
  10098. } else if (light instanceof BABYLON.HemisphericLight) {
  10099. type = "#define HEMILIGHT" + lightIndex;
  10100. } else {
  10101. type = "#define POINTDIRLIGHT" + lightIndex;
  10102. }
  10103. defines.push(type);
  10104. if (lightIndex > 0) {
  10105. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10106. }
  10107. var shadowGenerator = light.getShadowGenerator();
  10108. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10109. defines.push("#define SHADOW" + lightIndex);
  10110. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10111. if (!shadowsActivated) {
  10112. defines.push("#define SHADOWS");
  10113. shadowsActivated = true;
  10114. }
  10115. if (shadowGenerator.useVarianceShadowMap) {
  10116. defines.push("#define SHADOWVSM" + lightIndex);
  10117. if (lightIndex > 0) {
  10118. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10119. }
  10120. }
  10121. if (shadowGenerator.usePoissonSampling) {
  10122. defines.push("#define SHADOWPCF" + lightIndex);
  10123. if (lightIndex > 0) {
  10124. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10125. }
  10126. }
  10127. }
  10128. lightIndex++;
  10129. if (lightIndex == maxSimultaneousLights)
  10130. break;
  10131. }
  10132. }
  10133. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10134. var fresnelRank = 1;
  10135. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10136. defines.push("#define DIFFUSEFRESNEL");
  10137. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10138. fresnelRank++;
  10139. }
  10140. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10141. defines.push("#define OPACITYFRESNEL");
  10142. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10143. fresnelRank++;
  10144. }
  10145. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10146. defines.push("#define REFLECTIONFRESNEL");
  10147. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10148. fresnelRank++;
  10149. }
  10150. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10151. defines.push("#define EMISSIVEFRESNEL");
  10152. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10153. fresnelRank++;
  10154. }
  10155. defines.push("#define FRESNEL");
  10156. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10157. }
  10158. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10159. if (mesh) {
  10160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10161. attribs.push(BABYLON.VertexBuffer.UVKind);
  10162. defines.push("#define UV1");
  10163. }
  10164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10165. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10166. defines.push("#define UV2");
  10167. }
  10168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10169. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10170. defines.push("#define VERTEXCOLOR");
  10171. }
  10172. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10173. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10174. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10175. defines.push("#define BONES");
  10176. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10177. defines.push("#define BONES4");
  10178. fallbacks.addFallback(0, "BONES4");
  10179. }
  10180. if (useInstances) {
  10181. defines.push("#define INSTANCES");
  10182. attribs.push("world0");
  10183. attribs.push("world1");
  10184. attribs.push("world2");
  10185. attribs.push("world3");
  10186. }
  10187. }
  10188. var join = defines.join("\n");
  10189. if (this._cachedDefines != join) {
  10190. this._cachedDefines = join;
  10191. var shaderName = "default";
  10192. if (!scene.getEngine().getCaps().standardDerivatives) {
  10193. shaderName = "legacydefault";
  10194. }
  10195. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10196. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10197. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10198. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10199. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10200. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10201. "vFogInfos", "vFogColor",
  10202. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10203. "mBones",
  10204. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10205. "darkness0", "darkness1", "darkness2", "darkness3",
  10206. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10207. ], [
  10208. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10209. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10210. ], join, fallbacks, this.onCompiled, this.onError);
  10211. }
  10212. if (!this._effect.isReady()) {
  10213. return false;
  10214. }
  10215. this._renderId = scene.getRenderId();
  10216. this._wasPreviouslyReady = true;
  10217. return true;
  10218. };
  10219. StandardMaterial.prototype.unbind = function () {
  10220. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10221. this._effect.setTexture("reflection2DSampler", null);
  10222. }
  10223. };
  10224. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10225. this._effect.setMatrix("world", world);
  10226. };
  10227. StandardMaterial.prototype.bind = function (world, mesh) {
  10228. var scene = this.getScene();
  10229. this.bindOnlyWorldMatrix(world);
  10230. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10231. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10232. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10233. }
  10234. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10235. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10236. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10237. }
  10238. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10239. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10240. }
  10241. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10242. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10243. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10244. }
  10245. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10246. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10247. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10248. }
  10249. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10250. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10251. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10252. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10253. }
  10254. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10255. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10256. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10257. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10258. }
  10259. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10260. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10261. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10262. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10263. }
  10264. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10265. if (this.reflectionTexture.isCube) {
  10266. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10267. } else {
  10268. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10269. }
  10270. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10271. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10272. }
  10273. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10274. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10275. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10276. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10277. }
  10278. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10279. this._effect.setTexture("specularSampler", this.specularTexture);
  10280. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10281. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10282. }
  10283. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10284. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10285. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10286. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10287. }
  10288. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10289. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10290. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10291. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10292. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10293. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10294. if (scene.lightsEnabled) {
  10295. var lightIndex = 0;
  10296. for (var index = 0; index < scene.lights.length; index++) {
  10297. var light = scene.lights[index];
  10298. if (!light.isEnabled()) {
  10299. continue;
  10300. }
  10301. if (!light.canAffectMesh(mesh)) {
  10302. continue;
  10303. }
  10304. if (light instanceof BABYLON.PointLight) {
  10305. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10306. } else if (light instanceof BABYLON.DirectionalLight) {
  10307. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10308. } else if (light instanceof BABYLON.SpotLight) {
  10309. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10310. } else if (light instanceof BABYLON.HemisphericLight) {
  10311. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10312. }
  10313. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10314. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10315. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10316. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10317. var shadowGenerator = light.getShadowGenerator();
  10318. if (mesh.receiveShadows && shadowGenerator) {
  10319. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10320. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10321. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10322. }
  10323. lightIndex++;
  10324. if (lightIndex == maxSimultaneousLights)
  10325. break;
  10326. }
  10327. }
  10328. if (scene.clipPlane) {
  10329. var clipPlane = scene.clipPlane;
  10330. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10331. }
  10332. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10333. this._effect.setMatrix("view", scene.getViewMatrix());
  10334. }
  10335. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10336. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10337. this._effect.setColor3("vFogColor", scene.fogColor);
  10338. }
  10339. };
  10340. StandardMaterial.prototype.getAnimatables = function () {
  10341. var results = [];
  10342. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10343. results.push(this.diffuseTexture);
  10344. }
  10345. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10346. results.push(this.ambientTexture);
  10347. }
  10348. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10349. results.push(this.opacityTexture);
  10350. }
  10351. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10352. results.push(this.reflectionTexture);
  10353. }
  10354. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10355. results.push(this.emissiveTexture);
  10356. }
  10357. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10358. results.push(this.specularTexture);
  10359. }
  10360. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10361. results.push(this.bumpTexture);
  10362. }
  10363. return results;
  10364. };
  10365. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10366. if (this.diffuseTexture) {
  10367. this.diffuseTexture.dispose();
  10368. }
  10369. if (this.ambientTexture) {
  10370. this.ambientTexture.dispose();
  10371. }
  10372. if (this.opacityTexture) {
  10373. this.opacityTexture.dispose();
  10374. }
  10375. if (this.reflectionTexture) {
  10376. this.reflectionTexture.dispose();
  10377. }
  10378. if (this.emissiveTexture) {
  10379. this.emissiveTexture.dispose();
  10380. }
  10381. if (this.specularTexture) {
  10382. this.specularTexture.dispose();
  10383. }
  10384. if (this.bumpTexture) {
  10385. this.bumpTexture.dispose();
  10386. }
  10387. _super.prototype.dispose.call(this, forceDisposeEffect);
  10388. };
  10389. StandardMaterial.prototype.clone = function (name) {
  10390. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10391. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10392. newStandardMaterial.alpha = this.alpha;
  10393. newStandardMaterial.wireframe = this.wireframe;
  10394. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10395. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10396. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10397. }
  10398. if (this.ambientTexture && this.ambientTexture.clone) {
  10399. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10400. }
  10401. if (this.opacityTexture && this.opacityTexture.clone) {
  10402. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10403. }
  10404. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10405. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10406. }
  10407. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10408. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10409. }
  10410. if (this.specularTexture && this.specularTexture.clone) {
  10411. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10412. }
  10413. if (this.bumpTexture && this.bumpTexture.clone) {
  10414. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10415. }
  10416. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10417. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10418. newStandardMaterial.specularColor = this.specularColor.clone();
  10419. newStandardMaterial.specularPower = this.specularPower;
  10420. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10421. return newStandardMaterial;
  10422. };
  10423. StandardMaterial.DiffuseTextureEnabled = true;
  10424. StandardMaterial.AmbientTextureEnabled = true;
  10425. StandardMaterial.OpacityTextureEnabled = true;
  10426. StandardMaterial.ReflectionTextureEnabled = true;
  10427. StandardMaterial.EmissiveTextureEnabled = true;
  10428. StandardMaterial.SpecularTextureEnabled = true;
  10429. StandardMaterial.BumpTextureEnabled = true;
  10430. return StandardMaterial;
  10431. })(BABYLON.Material);
  10432. BABYLON.StandardMaterial = StandardMaterial;
  10433. })(BABYLON || (BABYLON = {}));
  10434. var __extends = this.__extends || function (d, b) {
  10435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10436. function __() { this.constructor = d; }
  10437. __.prototype = b.prototype;
  10438. d.prototype = new __();
  10439. };
  10440. var BABYLON;
  10441. (function (BABYLON) {
  10442. var MultiMaterial = (function (_super) {
  10443. __extends(MultiMaterial, _super);
  10444. function MultiMaterial(name, scene) {
  10445. _super.call(this, name, scene, true);
  10446. this.subMaterials = new Array();
  10447. scene.multiMaterials.push(this);
  10448. }
  10449. MultiMaterial.prototype.getSubMaterial = function (index) {
  10450. if (index < 0 || index >= this.subMaterials.length) {
  10451. return this.getScene().defaultMaterial;
  10452. }
  10453. return this.subMaterials[index];
  10454. };
  10455. MultiMaterial.prototype.isReady = function (mesh) {
  10456. for (var index = 0; index < this.subMaterials.length; index++) {
  10457. var subMaterial = this.subMaterials[index];
  10458. if (subMaterial) {
  10459. if (!this.subMaterials[index].isReady(mesh)) {
  10460. return false;
  10461. }
  10462. }
  10463. }
  10464. return true;
  10465. };
  10466. return MultiMaterial;
  10467. })(BABYLON.Material);
  10468. BABYLON.MultiMaterial = MultiMaterial;
  10469. })(BABYLON || (BABYLON = {}));
  10470. var BABYLON;
  10471. (function (BABYLON) {
  10472. var Database = (function () {
  10473. function Database(urlToScene, callbackManifestChecked) {
  10474. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10475. this.callbackManifestChecked = callbackManifestChecked;
  10476. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10477. this.db = null;
  10478. this.enableSceneOffline = false;
  10479. this.enableTexturesOffline = false;
  10480. this.manifestVersionFound = 0;
  10481. this.mustUpdateRessources = false;
  10482. this.hasReachedQuota = false;
  10483. this.checkManifestFile();
  10484. }
  10485. Database.prototype.checkManifestFile = function () {
  10486. var _this = this;
  10487. function noManifestFile() {
  10488. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10489. that.enableSceneOffline = false;
  10490. that.enableTexturesOffline = false;
  10491. that.callbackManifestChecked(false);
  10492. }
  10493. var that = this;
  10494. var manifestURL = this.currentSceneUrl + ".manifest";
  10495. var xhr = new XMLHttpRequest();
  10496. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10497. xhr.open("GET", manifestURLTimeStamped, true);
  10498. xhr.addEventListener("load", function () {
  10499. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10500. try {
  10501. var manifestFile = JSON.parse(xhr.response);
  10502. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10503. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10504. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10505. _this.manifestVersionFound = manifestFile.version;
  10506. }
  10507. if (_this.callbackManifestChecked) {
  10508. _this.callbackManifestChecked(true);
  10509. }
  10510. } catch (ex) {
  10511. noManifestFile();
  10512. }
  10513. } else {
  10514. noManifestFile();
  10515. }
  10516. }, false);
  10517. xhr.addEventListener("error", function (event) {
  10518. noManifestFile();
  10519. }, false);
  10520. try {
  10521. xhr.send();
  10522. } catch (ex) {
  10523. BABYLON.Tools.Error("Error on XHR send request.");
  10524. that.callbackManifestChecked(false);
  10525. }
  10526. };
  10527. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10528. var _this = this;
  10529. function handleError() {
  10530. that.isSupported = false;
  10531. if (errorCallback)
  10532. errorCallback();
  10533. }
  10534. var that = this;
  10535. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10536. this.isSupported = false;
  10537. if (errorCallback)
  10538. errorCallback();
  10539. } else {
  10540. if (!this.db) {
  10541. this.hasReachedQuota = false;
  10542. this.isSupported = true;
  10543. var request = this.idbFactory.open("babylonjs", 1);
  10544. request.onerror = function (event) {
  10545. handleError();
  10546. };
  10547. request.onblocked = function (event) {
  10548. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10549. handleError();
  10550. };
  10551. request.onsuccess = function (event) {
  10552. _this.db = request.result;
  10553. successCallback();
  10554. };
  10555. request.onupgradeneeded = function (event) {
  10556. _this.db = (event.target).result;
  10557. try {
  10558. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10559. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10560. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10561. } catch (ex) {
  10562. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10563. handleError();
  10564. }
  10565. };
  10566. } else {
  10567. if (successCallback)
  10568. successCallback();
  10569. }
  10570. }
  10571. };
  10572. Database.prototype.loadImageFromDB = function (url, image) {
  10573. var _this = this;
  10574. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10575. var saveAndLoadImage = function () {
  10576. if (!_this.hasReachedQuota && _this.db !== null) {
  10577. _this._saveImageIntoDBAsync(completeURL, image);
  10578. } else {
  10579. image.src = url;
  10580. }
  10581. };
  10582. if (!this.mustUpdateRessources) {
  10583. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10584. } else {
  10585. saveAndLoadImage();
  10586. }
  10587. };
  10588. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10589. if (this.isSupported && this.db !== null) {
  10590. var texture;
  10591. var transaction = this.db.transaction(["textures"]);
  10592. transaction.onabort = function (event) {
  10593. image.src = url;
  10594. };
  10595. transaction.oncomplete = function (event) {
  10596. var blobTextureURL;
  10597. if (texture) {
  10598. var URL = window.URL || window.webkitURL;
  10599. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10600. image.onerror = function () {
  10601. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10602. image.src = url;
  10603. };
  10604. image.src = blobTextureURL;
  10605. } else {
  10606. notInDBCallback();
  10607. }
  10608. };
  10609. var getRequest = transaction.objectStore("textures").get(url);
  10610. getRequest.onsuccess = function (event) {
  10611. texture = (event.target).result;
  10612. };
  10613. getRequest.onerror = function (event) {
  10614. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10615. image.src = url;
  10616. };
  10617. } else {
  10618. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10619. image.src = url;
  10620. }
  10621. };
  10622. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10623. var _this = this;
  10624. if (this.isSupported) {
  10625. var generateBlobUrl = function () {
  10626. var blobTextureURL;
  10627. if (blob) {
  10628. var URL = window.URL || window.webkitURL;
  10629. try {
  10630. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10631. } catch (ex) {
  10632. blobTextureURL = URL.createObjectURL(blob);
  10633. }
  10634. }
  10635. image.src = blobTextureURL;
  10636. };
  10637. if (BABYLON.Database.isUASupportingBlobStorage) {
  10638. var xhr = new XMLHttpRequest(), blob;
  10639. xhr.open("GET", url, true);
  10640. xhr.responseType = "blob";
  10641. xhr.addEventListener("load", function () {
  10642. if (xhr.status === 200) {
  10643. blob = xhr.response;
  10644. var transaction = _this.db.transaction(["textures"], "readwrite");
  10645. transaction.onabort = function (event) {
  10646. try {
  10647. if (event.srcElement.error.name === "QuotaExceededError") {
  10648. this.hasReachedQuota = true;
  10649. }
  10650. } catch (ex) {
  10651. }
  10652. generateBlobUrl();
  10653. };
  10654. transaction.oncomplete = function (event) {
  10655. generateBlobUrl();
  10656. };
  10657. var newTexture = { textureUrl: url, data: blob };
  10658. try {
  10659. var addRequest = transaction.objectStore("textures").put(newTexture);
  10660. addRequest.onsuccess = function (event) {
  10661. };
  10662. addRequest.onerror = function (event) {
  10663. generateBlobUrl();
  10664. };
  10665. } catch (ex) {
  10666. if (ex.code === 25) {
  10667. BABYLON.Database.isUASupportingBlobStorage = false;
  10668. }
  10669. image.src = url;
  10670. }
  10671. } else {
  10672. image.src = url;
  10673. }
  10674. }, false);
  10675. xhr.addEventListener("error", function (event) {
  10676. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10677. image.src = url;
  10678. }, false);
  10679. xhr.send();
  10680. } else {
  10681. image.src = url;
  10682. }
  10683. } else {
  10684. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10685. image.src = url;
  10686. }
  10687. };
  10688. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10689. var _this = this;
  10690. var updateVersion = function (event) {
  10691. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10692. };
  10693. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10694. };
  10695. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10696. var _this = this;
  10697. if (this.isSupported) {
  10698. var version;
  10699. try {
  10700. var transaction = this.db.transaction(["versions"]);
  10701. transaction.oncomplete = function (event) {
  10702. if (version) {
  10703. if (_this.manifestVersionFound > version.data) {
  10704. _this.mustUpdateRessources = true;
  10705. updateInDBCallback();
  10706. } else {
  10707. callback(version.data);
  10708. }
  10709. } else {
  10710. _this.mustUpdateRessources = true;
  10711. updateInDBCallback();
  10712. }
  10713. };
  10714. transaction.onabort = function (event) {
  10715. callback(-1);
  10716. };
  10717. var getRequest = transaction.objectStore("versions").get(url);
  10718. getRequest.onsuccess = function (event) {
  10719. version = (event.target).result;
  10720. };
  10721. getRequest.onerror = function (event) {
  10722. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10723. callback(-1);
  10724. };
  10725. } catch (ex) {
  10726. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10727. callback(-1);
  10728. }
  10729. } else {
  10730. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10731. callback(-1);
  10732. }
  10733. };
  10734. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10735. var _this = this;
  10736. if (this.isSupported && !this.hasReachedQuota) {
  10737. try {
  10738. var transaction = this.db.transaction(["versions"], "readwrite");
  10739. transaction.onabort = function (event) {
  10740. try {
  10741. if (event.srcElement.error.name === "QuotaExceededError") {
  10742. _this.hasReachedQuota = true;
  10743. }
  10744. } catch (ex) {
  10745. }
  10746. callback(-1);
  10747. };
  10748. transaction.oncomplete = function (event) {
  10749. callback(_this.manifestVersionFound);
  10750. };
  10751. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10752. var addRequest = transaction.objectStore("versions").put(newVersion);
  10753. addRequest.onsuccess = function (event) {
  10754. };
  10755. addRequest.onerror = function (event) {
  10756. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10757. };
  10758. } catch (ex) {
  10759. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10760. callback(-1);
  10761. }
  10762. } else {
  10763. callback(-1);
  10764. }
  10765. };
  10766. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10767. var _this = this;
  10768. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10769. var saveAndLoadFile = function (event) {
  10770. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10771. };
  10772. this._checkVersionFromDB(completeUrl, function (version) {
  10773. if (version !== -1) {
  10774. if (!_this.mustUpdateRessources) {
  10775. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10776. } else {
  10777. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10778. }
  10779. } else {
  10780. errorCallback();
  10781. }
  10782. });
  10783. };
  10784. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10785. if (this.isSupported) {
  10786. var targetStore;
  10787. if (url.indexOf(".babylon") !== -1) {
  10788. targetStore = "scenes";
  10789. } else {
  10790. targetStore = "textures";
  10791. }
  10792. var file;
  10793. var transaction = this.db.transaction([targetStore]);
  10794. transaction.oncomplete = function (event) {
  10795. if (file) {
  10796. callback(file.data);
  10797. } else {
  10798. notInDBCallback();
  10799. }
  10800. };
  10801. transaction.onabort = function (event) {
  10802. notInDBCallback();
  10803. };
  10804. var getRequest = transaction.objectStore(targetStore).get(url);
  10805. getRequest.onsuccess = function (event) {
  10806. file = (event.target).result;
  10807. };
  10808. getRequest.onerror = function (event) {
  10809. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10810. notInDBCallback();
  10811. };
  10812. } else {
  10813. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10814. callback();
  10815. }
  10816. };
  10817. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10818. var _this = this;
  10819. if (this.isSupported) {
  10820. var targetStore;
  10821. if (url.indexOf(".babylon") !== -1) {
  10822. targetStore = "scenes";
  10823. } else {
  10824. targetStore = "textures";
  10825. }
  10826. var xhr = new XMLHttpRequest(), fileData;
  10827. xhr.open("GET", url, true);
  10828. if (useArrayBuffer) {
  10829. xhr.responseType = "arraybuffer";
  10830. }
  10831. xhr.onprogress = progressCallback;
  10832. xhr.addEventListener("load", function () {
  10833. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10834. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10835. if (!_this.hasReachedQuota) {
  10836. var transaction = _this.db.transaction([targetStore], "readwrite");
  10837. transaction.onabort = function (event) {
  10838. try {
  10839. if (event.srcElement.error.name === "QuotaExceededError") {
  10840. this.hasReachedQuota = true;
  10841. }
  10842. } catch (ex) {
  10843. }
  10844. callback(fileData);
  10845. };
  10846. transaction.oncomplete = function (event) {
  10847. callback(fileData);
  10848. };
  10849. var newFile;
  10850. if (targetStore === "scenes") {
  10851. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  10852. } else {
  10853. newFile = { textureUrl: url, data: fileData };
  10854. }
  10855. try {
  10856. var addRequest = transaction.objectStore(targetStore).put(newFile);
  10857. addRequest.onsuccess = function (event) {
  10858. };
  10859. addRequest.onerror = function (event) {
  10860. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  10861. };
  10862. } catch (ex) {
  10863. callback(fileData);
  10864. }
  10865. } else {
  10866. callback(fileData);
  10867. }
  10868. } else {
  10869. callback();
  10870. }
  10871. }, false);
  10872. xhr.addEventListener("error", function (event) {
  10873. BABYLON.Tools.Error("error on XHR request.");
  10874. callback();
  10875. }, false);
  10876. xhr.send();
  10877. } else {
  10878. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10879. callback();
  10880. }
  10881. };
  10882. Database.isUASupportingBlobStorage = true;
  10883. Database.parseURL = function (url) {
  10884. var a = document.createElement('a');
  10885. a.href = url;
  10886. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  10887. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  10888. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  10889. return absLocation;
  10890. };
  10891. Database.ReturnFullUrlLocation = function (url) {
  10892. if (url.indexOf("http:/") === -1) {
  10893. return (BABYLON.Database.parseURL(window.location.href) + url);
  10894. } else {
  10895. return url;
  10896. }
  10897. };
  10898. return Database;
  10899. })();
  10900. BABYLON.Database = Database;
  10901. })(BABYLON || (BABYLON = {}));
  10902. var BABYLON;
  10903. (function (BABYLON) {
  10904. var SpriteManager = (function () {
  10905. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  10906. this.name = name;
  10907. this.cellSize = cellSize;
  10908. this.sprites = new Array();
  10909. this.renderingGroupId = 0;
  10910. this._vertexDeclaration = [3, 4, 4, 4];
  10911. this._vertexStrideSize = 15 * 4;
  10912. this._capacity = capacity;
  10913. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  10914. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10915. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10916. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  10917. this._scene = scene;
  10918. this._scene.spriteManagers.push(this);
  10919. this._vertexDeclaration = [3, 4, 4, 4];
  10920. this._vertexStrideSize = 15 * 4;
  10921. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  10922. var indices = [];
  10923. var index = 0;
  10924. for (var count = 0; count < capacity; count++) {
  10925. indices.push(index);
  10926. indices.push(index + 1);
  10927. indices.push(index + 2);
  10928. indices.push(index);
  10929. indices.push(index + 2);
  10930. indices.push(index + 3);
  10931. index += 4;
  10932. }
  10933. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10934. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  10935. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  10936. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  10937. }
  10938. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  10939. var arrayOffset = index * 15;
  10940. if (offsetX == 0)
  10941. offsetX = this._epsilon;
  10942. else if (offsetX == 1)
  10943. offsetX = 1 - this._epsilon;
  10944. if (offsetY == 0)
  10945. offsetY = this._epsilon;
  10946. else if (offsetY == 1)
  10947. offsetY = 1 - this._epsilon;
  10948. this._vertices[arrayOffset] = sprite.position.x;
  10949. this._vertices[arrayOffset + 1] = sprite.position.y;
  10950. this._vertices[arrayOffset + 2] = sprite.position.z;
  10951. this._vertices[arrayOffset + 3] = sprite.angle;
  10952. this._vertices[arrayOffset + 4] = sprite.size;
  10953. this._vertices[arrayOffset + 5] = offsetX;
  10954. this._vertices[arrayOffset + 6] = offsetY;
  10955. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  10956. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  10957. var offset = (sprite.cellIndex / rowSize) >> 0;
  10958. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  10959. this._vertices[arrayOffset + 10] = offset;
  10960. this._vertices[arrayOffset + 11] = sprite.color.r;
  10961. this._vertices[arrayOffset + 12] = sprite.color.g;
  10962. this._vertices[arrayOffset + 13] = sprite.color.b;
  10963. this._vertices[arrayOffset + 14] = sprite.color.a;
  10964. };
  10965. SpriteManager.prototype.render = function () {
  10966. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  10967. return;
  10968. var engine = this._scene.getEngine();
  10969. var baseSize = this._spriteTexture.getBaseSize();
  10970. var deltaTime = BABYLON.Tools.GetDeltaTime();
  10971. var max = Math.min(this._capacity, this.sprites.length);
  10972. var rowSize = baseSize.width / this.cellSize;
  10973. var offset = 0;
  10974. for (var index = 0; index < max; index++) {
  10975. var sprite = this.sprites[index];
  10976. if (!sprite) {
  10977. continue;
  10978. }
  10979. sprite._animate(deltaTime);
  10980. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  10981. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  10982. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  10983. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  10984. }
  10985. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  10986. var effect = this._effectBase;
  10987. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10988. effect = this._effectFog;
  10989. }
  10990. engine.enableEffect(effect);
  10991. var viewMatrix = this._scene.getViewMatrix();
  10992. effect.setTexture("diffuseSampler", this._spriteTexture);
  10993. effect.setMatrix("view", viewMatrix);
  10994. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  10995. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  10996. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10997. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  10998. effect.setColor3("vFogColor", this._scene.fogColor);
  10999. }
  11000. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11001. effect.setBool("alphaTest", true);
  11002. engine.setColorWrite(false);
  11003. engine.draw(true, 0, max * 6);
  11004. engine.setColorWrite(true);
  11005. effect.setBool("alphaTest", false);
  11006. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11007. engine.draw(true, 0, max * 6);
  11008. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11009. };
  11010. SpriteManager.prototype.dispose = function () {
  11011. if (this._vertexBuffer) {
  11012. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11013. this._vertexBuffer = null;
  11014. }
  11015. if (this._indexBuffer) {
  11016. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11017. this._indexBuffer = null;
  11018. }
  11019. if (this._spriteTexture) {
  11020. this._spriteTexture.dispose();
  11021. this._spriteTexture = null;
  11022. }
  11023. var index = this._scene.spriteManagers.indexOf(this);
  11024. this._scene.spriteManagers.splice(index, 1);
  11025. if (this.onDispose) {
  11026. this.onDispose();
  11027. }
  11028. };
  11029. return SpriteManager;
  11030. })();
  11031. BABYLON.SpriteManager = SpriteManager;
  11032. })(BABYLON || (BABYLON = {}));
  11033. var BABYLON;
  11034. (function (BABYLON) {
  11035. var Sprite = (function () {
  11036. function Sprite(name, manager) {
  11037. this.name = name;
  11038. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11039. this.size = 1.0;
  11040. this.angle = 0;
  11041. this.cellIndex = 0;
  11042. this.invertU = 0;
  11043. this.invertV = 0;
  11044. this.animations = new Array();
  11045. this._animationStarted = false;
  11046. this._loopAnimation = false;
  11047. this._fromIndex = 0;
  11048. this._toIndex = 0;
  11049. this._delay = 0;
  11050. this._direction = 1;
  11051. this._frameCount = 0;
  11052. this._time = 0;
  11053. this._manager = manager;
  11054. this._manager.sprites.push(this);
  11055. this.position = BABYLON.Vector3.Zero();
  11056. }
  11057. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11058. this._fromIndex = from;
  11059. this._toIndex = to;
  11060. this._loopAnimation = loop;
  11061. this._delay = delay;
  11062. this._animationStarted = true;
  11063. this._direction = from < to ? 1 : -1;
  11064. this.cellIndex = from;
  11065. this._time = 0;
  11066. };
  11067. Sprite.prototype.stopAnimation = function () {
  11068. this._animationStarted = false;
  11069. };
  11070. Sprite.prototype._animate = function (deltaTime) {
  11071. if (!this._animationStarted)
  11072. return;
  11073. this._time += deltaTime;
  11074. if (this._time > this._delay) {
  11075. this._time = this._time % this._delay;
  11076. this.cellIndex += this._direction;
  11077. if (this.cellIndex == this._toIndex) {
  11078. if (this._loopAnimation) {
  11079. this.cellIndex = this._fromIndex;
  11080. } else {
  11081. this._animationStarted = false;
  11082. if (this.disposeWhenFinishedAnimating) {
  11083. this.dispose();
  11084. }
  11085. }
  11086. }
  11087. }
  11088. };
  11089. Sprite.prototype.dispose = function () {
  11090. for (var i = 0; i < this._manager.sprites.length; i++) {
  11091. if (this._manager.sprites[i] == this) {
  11092. this._manager.sprites.splice(i, 1);
  11093. }
  11094. }
  11095. };
  11096. return Sprite;
  11097. })();
  11098. BABYLON.Sprite = Sprite;
  11099. })(BABYLON || (BABYLON = {}));
  11100. var BABYLON;
  11101. (function (BABYLON) {
  11102. var Layer = (function () {
  11103. function Layer(name, imgUrl, scene, isBackground, color) {
  11104. this.name = name;
  11105. this._vertexDeclaration = [2];
  11106. this._vertexStrideSize = 2 * 4;
  11107. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11108. this.isBackground = isBackground === undefined ? true : isBackground;
  11109. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11110. this._scene = scene;
  11111. this._scene.layers.push(this);
  11112. var vertices = [];
  11113. vertices.push(1, 1);
  11114. vertices.push(-1, 1);
  11115. vertices.push(-1, -1);
  11116. vertices.push(1, -1);
  11117. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11118. var indices = [];
  11119. indices.push(0);
  11120. indices.push(1);
  11121. indices.push(2);
  11122. indices.push(0);
  11123. indices.push(2);
  11124. indices.push(3);
  11125. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11126. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11127. }
  11128. Layer.prototype.render = function () {
  11129. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11130. return;
  11131. var engine = this._scene.getEngine();
  11132. engine.enableEffect(this._effect);
  11133. engine.setState(false);
  11134. this._effect.setTexture("textureSampler", this.texture);
  11135. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11136. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11137. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11138. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11139. engine.draw(true, 0, 6);
  11140. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11141. };
  11142. Layer.prototype.dispose = function () {
  11143. if (this._vertexBuffer) {
  11144. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11145. this._vertexBuffer = null;
  11146. }
  11147. if (this._indexBuffer) {
  11148. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11149. this._indexBuffer = null;
  11150. }
  11151. if (this.texture) {
  11152. this.texture.dispose();
  11153. this.texture = null;
  11154. }
  11155. var index = this._scene.layers.indexOf(this);
  11156. this._scene.layers.splice(index, 1);
  11157. if (this.onDispose) {
  11158. this.onDispose();
  11159. }
  11160. };
  11161. return Layer;
  11162. })();
  11163. BABYLON.Layer = Layer;
  11164. })(BABYLON || (BABYLON = {}));
  11165. var BABYLON;
  11166. (function (BABYLON) {
  11167. var Particle = (function () {
  11168. function Particle() {
  11169. this.position = BABYLON.Vector3.Zero();
  11170. this.direction = BABYLON.Vector3.Zero();
  11171. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11172. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11173. this.lifeTime = 1.0;
  11174. this.age = 0;
  11175. this.size = 0;
  11176. this.angle = 0;
  11177. this.angularSpeed = 0;
  11178. }
  11179. return Particle;
  11180. })();
  11181. BABYLON.Particle = Particle;
  11182. })(BABYLON || (BABYLON = {}));
  11183. var BABYLON;
  11184. (function (BABYLON) {
  11185. var randomNumber = function (min, max) {
  11186. if (min == max) {
  11187. return (min);
  11188. }
  11189. var random = Math.random();
  11190. return ((random * (max - min)) + min);
  11191. };
  11192. var ParticleSystem = (function () {
  11193. function ParticleSystem(name, capacity, scene, fragmentElement) {
  11194. var _this = this;
  11195. this.name = name;
  11196. this.fragmentElement = fragmentElement;
  11197. this.renderingGroupId = 0;
  11198. this.emitter = null;
  11199. this.emitRate = 10;
  11200. this.manualEmitCount = -1;
  11201. this.updateSpeed = 0.01;
  11202. this.targetStopDuration = 0;
  11203. this.disposeOnStop = false;
  11204. this.minEmitPower = 1;
  11205. this.maxEmitPower = 1;
  11206. this.minLifeTime = 1;
  11207. this.maxLifeTime = 1;
  11208. this.minSize = 1;
  11209. this.maxSize = 1;
  11210. this.minAngularSpeed = 0;
  11211. this.maxAngularSpeed = 0;
  11212. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11213. this.forceDepthWrite = false;
  11214. this.gravity = BABYLON.Vector3.Zero();
  11215. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11216. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11217. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11218. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11219. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11220. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11221. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11222. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11223. this.particles = new Array();
  11224. this._vertexDeclaration = [3, 4, 4];
  11225. this._vertexStrideSize = 11 * 4;
  11226. this._stockParticles = new Array();
  11227. this._newPartsExcess = 0;
  11228. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11229. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11230. this._scaledDirection = BABYLON.Vector3.Zero();
  11231. this._scaledGravity = BABYLON.Vector3.Zero();
  11232. this._currentRenderId = -1;
  11233. this._started = false;
  11234. this._stopped = false;
  11235. this._actualFrame = 0;
  11236. this.id = name;
  11237. this._capacity = capacity;
  11238. this._scene = scene;
  11239. scene.particleSystems.push(this);
  11240. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11241. var indices = [];
  11242. var index = 0;
  11243. for (var count = 0; count < capacity; count++) {
  11244. indices.push(index);
  11245. indices.push(index + 1);
  11246. indices.push(index + 2);
  11247. indices.push(index);
  11248. indices.push(index + 2);
  11249. indices.push(index + 3);
  11250. index += 4;
  11251. }
  11252. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11253. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11254. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11255. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11256. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11257. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11258. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11259. };
  11260. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11261. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11262. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11263. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11264. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11265. };
  11266. }
  11267. ParticleSystem.prototype.getCapacity = function () {
  11268. return this._capacity;
  11269. };
  11270. ParticleSystem.prototype.isAlive = function () {
  11271. return this._alive;
  11272. };
  11273. ParticleSystem.prototype.isStarted = function () {
  11274. return this._started;
  11275. };
  11276. ParticleSystem.prototype.start = function () {
  11277. this._started = true;
  11278. this._stopped = false;
  11279. this._actualFrame = 0;
  11280. };
  11281. ParticleSystem.prototype.stop = function () {
  11282. this._stopped = true;
  11283. };
  11284. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11285. var offset = index * 11;
  11286. this._vertices[offset] = particle.position.x;
  11287. this._vertices[offset + 1] = particle.position.y;
  11288. this._vertices[offset + 2] = particle.position.z;
  11289. this._vertices[offset + 3] = particle.color.r;
  11290. this._vertices[offset + 4] = particle.color.g;
  11291. this._vertices[offset + 5] = particle.color.b;
  11292. this._vertices[offset + 6] = particle.color.a;
  11293. this._vertices[offset + 7] = particle.angle;
  11294. this._vertices[offset + 8] = particle.size;
  11295. this._vertices[offset + 9] = offsetX;
  11296. this._vertices[offset + 10] = offsetY;
  11297. };
  11298. ParticleSystem.prototype._update = function (newParticles) {
  11299. this._alive = this.particles.length > 0;
  11300. for (var index = 0; index < this.particles.length; index++) {
  11301. var particle = this.particles[index];
  11302. particle.age += this._scaledUpdateSpeed;
  11303. if (particle.age >= particle.lifeTime) {
  11304. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11305. index--;
  11306. continue;
  11307. } else {
  11308. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11309. particle.color.addInPlace(this._scaledColorStep);
  11310. if (particle.color.a < 0)
  11311. particle.color.a = 0;
  11312. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11313. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11314. particle.position.addInPlace(this._scaledDirection);
  11315. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11316. particle.direction.addInPlace(this._scaledGravity);
  11317. }
  11318. }
  11319. var worldMatrix;
  11320. if (this.emitter.position) {
  11321. worldMatrix = this.emitter.getWorldMatrix();
  11322. } else {
  11323. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11324. }
  11325. for (index = 0; index < newParticles; index++) {
  11326. if (this.particles.length == this._capacity) {
  11327. break;
  11328. }
  11329. if (this._stockParticles.length !== 0) {
  11330. particle = this._stockParticles.pop();
  11331. particle.age = 0;
  11332. } else {
  11333. particle = new BABYLON.Particle();
  11334. }
  11335. this.particles.push(particle);
  11336. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11337. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11338. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11339. particle.size = randomNumber(this.minSize, this.maxSize);
  11340. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11341. this.startPositionFunction(worldMatrix, particle.position);
  11342. var step = randomNumber(0, 1.0);
  11343. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11344. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11345. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11346. }
  11347. };
  11348. ParticleSystem.prototype._getEffect = function () {
  11349. var defines = [];
  11350. if (this._scene.clipPlane) {
  11351. defines.push("#define CLIPPLANE");
  11352. }
  11353. var join = defines.join("\n");
  11354. if (this._cachedDefines != join) {
  11355. this._cachedDefines = join;
  11356. var baseName;
  11357. if (this.fragmentElement) {
  11358. baseName = {
  11359. vertex: "particles",
  11360. fragmentElement: this.fragmentElement
  11361. };
  11362. } else {
  11363. baseName = "particles";
  11364. }
  11365. this._effect = this._scene.getEngine().createEffect(baseName, ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11366. }
  11367. return this._effect;
  11368. };
  11369. ParticleSystem.prototype.animate = function () {
  11370. if (!this._started)
  11371. return;
  11372. var effect = this._getEffect();
  11373. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11374. return;
  11375. if (this._currentRenderId === this._scene.getRenderId()) {
  11376. return;
  11377. }
  11378. this._currentRenderId = this._scene.getRenderId();
  11379. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11380. var emitCout;
  11381. if (this.manualEmitCount > -1) {
  11382. emitCout = this.manualEmitCount;
  11383. this.manualEmitCount = 0;
  11384. } else {
  11385. emitCout = this.emitRate;
  11386. }
  11387. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11388. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11389. if (this._newPartsExcess > 1.0) {
  11390. newParticles += this._newPartsExcess >> 0;
  11391. this._newPartsExcess -= this._newPartsExcess >> 0;
  11392. }
  11393. this._alive = false;
  11394. if (!this._stopped) {
  11395. this._actualFrame += this._scaledUpdateSpeed;
  11396. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11397. this.stop();
  11398. } else {
  11399. newParticles = 0;
  11400. }
  11401. this._update(newParticles);
  11402. if (this._stopped) {
  11403. if (!this._alive) {
  11404. this._started = false;
  11405. if (this.disposeOnStop) {
  11406. this._scene._toBeDisposed.push(this);
  11407. }
  11408. }
  11409. }
  11410. var offset = 0;
  11411. for (var index = 0; index < this.particles.length; index++) {
  11412. var particle = this.particles[index];
  11413. this._appendParticleVertex(offset++, particle, 0, 0);
  11414. this._appendParticleVertex(offset++, particle, 1, 0);
  11415. this._appendParticleVertex(offset++, particle, 1, 1);
  11416. this._appendParticleVertex(offset++, particle, 0, 1);
  11417. }
  11418. var engine = this._scene.getEngine();
  11419. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11420. };
  11421. ParticleSystem.prototype.render = function () {
  11422. var effect = this._getEffect();
  11423. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11424. return 0;
  11425. var engine = this._scene.getEngine();
  11426. engine.enableEffect(effect);
  11427. var viewMatrix = this._scene.getViewMatrix();
  11428. effect.setTexture("diffuseSampler", this.particleTexture);
  11429. effect.setMatrix("view", viewMatrix);
  11430. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11431. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11432. if (this._scene.clipPlane) {
  11433. var clipPlane = this._scene.clipPlane;
  11434. var invView = viewMatrix.clone();
  11435. invView.invert();
  11436. effect.setMatrix("invView", invView);
  11437. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11438. }
  11439. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11440. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11441. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11442. } else {
  11443. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11444. }
  11445. if (this.forceDepthWrite) {
  11446. engine.setDepthWrite(true);
  11447. }
  11448. engine.draw(true, 0, this.particles.length * 6);
  11449. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11450. return this.particles.length;
  11451. };
  11452. ParticleSystem.prototype.dispose = function () {
  11453. if (this._vertexBuffer) {
  11454. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11455. this._vertexBuffer = null;
  11456. }
  11457. if (this._indexBuffer) {
  11458. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11459. this._indexBuffer = null;
  11460. }
  11461. if (this.particleTexture) {
  11462. this.particleTexture.dispose();
  11463. this.particleTexture = null;
  11464. }
  11465. var index = this._scene.particleSystems.indexOf(this);
  11466. this._scene.particleSystems.splice(index, 1);
  11467. if (this.onDispose) {
  11468. this.onDispose();
  11469. }
  11470. };
  11471. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11472. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11473. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11474. if (newEmitter === undefined) {
  11475. newEmitter = this.emitter;
  11476. }
  11477. result.emitter = newEmitter;
  11478. if (this.particleTexture) {
  11479. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11480. }
  11481. result.start();
  11482. return result;
  11483. };
  11484. ParticleSystem.BLENDMODE_ONEONE = 0;
  11485. ParticleSystem.BLENDMODE_STANDARD = 1;
  11486. return ParticleSystem;
  11487. })();
  11488. BABYLON.ParticleSystem = ParticleSystem;
  11489. })(BABYLON || (BABYLON = {}));
  11490. var BABYLON;
  11491. (function (BABYLON) {
  11492. var Animation = (function () {
  11493. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11494. this.name = name;
  11495. this.targetProperty = targetProperty;
  11496. this.framePerSecond = framePerSecond;
  11497. this.dataType = dataType;
  11498. this.loopMode = loopMode;
  11499. this._offsetsCache = {};
  11500. this._highLimitsCache = {};
  11501. this._stopped = false;
  11502. this.targetPropertyPath = targetProperty.split(".");
  11503. this.dataType = dataType;
  11504. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11505. }
  11506. Animation.prototype.isStopped = function () {
  11507. return this._stopped;
  11508. };
  11509. Animation.prototype.getKeys = function () {
  11510. return this._keys;
  11511. };
  11512. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11513. return startValue + (endValue - startValue) * gradient;
  11514. };
  11515. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11516. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11517. };
  11518. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11519. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11520. };
  11521. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11522. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11523. };
  11524. Animation.prototype.clone = function () {
  11525. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11526. clone.setKeys(this._keys);
  11527. return clone;
  11528. };
  11529. Animation.prototype.setKeys = function (values) {
  11530. this._keys = values.slice(0);
  11531. this._offsetsCache = {};
  11532. this._highLimitsCache = {};
  11533. };
  11534. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11535. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11536. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11537. }
  11538. this.currentFrame = currentFrame;
  11539. for (var key = 0; key < this._keys.length; key++) {
  11540. if (this._keys[key + 1].frame >= currentFrame) {
  11541. var startValue = this._keys[key].value;
  11542. var endValue = this._keys[key + 1].value;
  11543. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11544. switch (this.dataType) {
  11545. case Animation.ANIMATIONTYPE_FLOAT:
  11546. switch (loopMode) {
  11547. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11548. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11549. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11550. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11551. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11552. }
  11553. break;
  11554. case Animation.ANIMATIONTYPE_QUATERNION:
  11555. var quaternion = null;
  11556. switch (loopMode) {
  11557. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11558. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11559. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11560. break;
  11561. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11562. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11563. break;
  11564. }
  11565. return quaternion;
  11566. case Animation.ANIMATIONTYPE_VECTOR3:
  11567. switch (loopMode) {
  11568. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11569. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11570. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11571. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11572. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11573. }
  11574. case Animation.ANIMATIONTYPE_COLOR3:
  11575. switch (loopMode) {
  11576. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11577. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11578. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11579. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11580. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11581. }
  11582. case Animation.ANIMATIONTYPE_MATRIX:
  11583. switch (loopMode) {
  11584. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11585. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11586. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11587. return startValue;
  11588. }
  11589. default:
  11590. break;
  11591. }
  11592. break;
  11593. }
  11594. }
  11595. return this._keys[this._keys.length - 1].value;
  11596. };
  11597. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11598. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11599. this._stopped = true;
  11600. return false;
  11601. }
  11602. var returnValue = true;
  11603. if (this._keys[0].frame != 0) {
  11604. var newKey = {
  11605. frame: 0,
  11606. value: this._keys[0].value
  11607. };
  11608. this._keys.splice(0, 0, newKey);
  11609. }
  11610. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11611. from = this._keys[0].frame;
  11612. }
  11613. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11614. to = this._keys[this._keys.length - 1].frame;
  11615. }
  11616. var range = to - from;
  11617. var offsetValue;
  11618. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11619. if (ratio > range && !loop) {
  11620. returnValue = false;
  11621. highLimitValue = this._keys[this._keys.length - 1].value;
  11622. } else {
  11623. var highLimitValue = 0;
  11624. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11625. var keyOffset = to.toString() + from.toString();
  11626. if (!this._offsetsCache[keyOffset]) {
  11627. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11628. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11629. switch (this.dataType) {
  11630. case Animation.ANIMATIONTYPE_FLOAT:
  11631. this._offsetsCache[keyOffset] = toValue - fromValue;
  11632. break;
  11633. case Animation.ANIMATIONTYPE_QUATERNION:
  11634. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11635. break;
  11636. case Animation.ANIMATIONTYPE_VECTOR3:
  11637. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11638. case Animation.ANIMATIONTYPE_COLOR3:
  11639. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11640. default:
  11641. break;
  11642. }
  11643. this._highLimitsCache[keyOffset] = toValue;
  11644. }
  11645. highLimitValue = this._highLimitsCache[keyOffset];
  11646. offsetValue = this._offsetsCache[keyOffset];
  11647. }
  11648. }
  11649. if (offsetValue === undefined) {
  11650. switch (this.dataType) {
  11651. case Animation.ANIMATIONTYPE_FLOAT:
  11652. offsetValue = 0;
  11653. break;
  11654. case Animation.ANIMATIONTYPE_QUATERNION:
  11655. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11656. break;
  11657. case Animation.ANIMATIONTYPE_VECTOR3:
  11658. offsetValue = BABYLON.Vector3.Zero();
  11659. break;
  11660. case Animation.ANIMATIONTYPE_COLOR3:
  11661. offsetValue = BABYLON.Color3.Black();
  11662. }
  11663. }
  11664. var repeatCount = (ratio / range) >> 0;
  11665. var currentFrame = returnValue ? from + ratio % range : to;
  11666. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11667. if (this.targetPropertyPath.length > 1) {
  11668. var property = this._target[this.targetPropertyPath[0]];
  11669. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11670. property = property[this.targetPropertyPath[index]];
  11671. }
  11672. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11673. } else {
  11674. this._target[this.targetPropertyPath[0]] = currentValue;
  11675. }
  11676. if (this._target.markAsDirty) {
  11677. this._target.markAsDirty(this.targetProperty);
  11678. }
  11679. if (!returnValue) {
  11680. this._stopped = true;
  11681. }
  11682. return returnValue;
  11683. };
  11684. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11685. get: function () {
  11686. return Animation._ANIMATIONTYPE_FLOAT;
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11692. get: function () {
  11693. return Animation._ANIMATIONTYPE_VECTOR3;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11699. get: function () {
  11700. return Animation._ANIMATIONTYPE_QUATERNION;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11706. get: function () {
  11707. return Animation._ANIMATIONTYPE_MATRIX;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11713. get: function () {
  11714. return Animation._ANIMATIONTYPE_COLOR3;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11720. get: function () {
  11721. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11727. get: function () {
  11728. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11734. get: function () {
  11735. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Animation._ANIMATIONTYPE_FLOAT = 0;
  11741. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11742. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11743. Animation._ANIMATIONTYPE_MATRIX = 3;
  11744. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11745. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11746. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11747. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11748. return Animation;
  11749. })();
  11750. BABYLON.Animation = Animation;
  11751. })(BABYLON || (BABYLON = {}));
  11752. var BABYLON;
  11753. (function (BABYLON) {
  11754. var Animatable = (function () {
  11755. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11756. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11757. if (typeof toFrame === "undefined") { toFrame = 100; }
  11758. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11759. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11760. this.target = target;
  11761. this.fromFrame = fromFrame;
  11762. this.toFrame = toFrame;
  11763. this.loopAnimation = loopAnimation;
  11764. this.speedRatio = speedRatio;
  11765. this.onAnimationEnd = onAnimationEnd;
  11766. this._animations = new Array();
  11767. this._paused = false;
  11768. this.animationStarted = false;
  11769. if (animations) {
  11770. this.appendAnimations(target, animations);
  11771. }
  11772. this._scene = scene;
  11773. scene._activeAnimatables.push(this);
  11774. }
  11775. Animatable.prototype.appendAnimations = function (target, animations) {
  11776. for (var index = 0; index < animations.length; index++) {
  11777. var animation = animations[index];
  11778. animation._target = target;
  11779. this._animations.push(animation);
  11780. }
  11781. };
  11782. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11783. var animations = this._animations;
  11784. for (var index = 0; index < animations.length; index++) {
  11785. if (animations[index].targetProperty === property) {
  11786. return animations[index];
  11787. }
  11788. }
  11789. return null;
  11790. };
  11791. Animatable.prototype.pause = function () {
  11792. this._paused = true;
  11793. };
  11794. Animatable.prototype.restart = function () {
  11795. this._paused = false;
  11796. };
  11797. Animatable.prototype.stop = function () {
  11798. var index = this._scene._activeAnimatables.indexOf(this);
  11799. if (index > -1) {
  11800. this._scene._activeAnimatables.splice(index, 1);
  11801. }
  11802. if (this.onAnimationEnd) {
  11803. this.onAnimationEnd();
  11804. }
  11805. };
  11806. Animatable.prototype._animate = function (delay) {
  11807. if (this._paused) {
  11808. return true;
  11809. }
  11810. if (!this._localDelayOffset) {
  11811. this._localDelayOffset = delay;
  11812. }
  11813. var running = false;
  11814. var animations = this._animations;
  11815. for (var index = 0; index < animations.length; index++) {
  11816. var animation = animations[index];
  11817. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11818. running = running || isRunning;
  11819. }
  11820. if (!running && this.onAnimationEnd) {
  11821. this.onAnimationEnd();
  11822. }
  11823. return running;
  11824. };
  11825. return Animatable;
  11826. })();
  11827. BABYLON.Animatable = Animatable;
  11828. })(BABYLON || (BABYLON = {}));
  11829. var BABYLON;
  11830. (function (BABYLON) {
  11831. var Octree = (function () {
  11832. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11833. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11834. this.maxDepth = maxDepth;
  11835. this.dynamicContent = new Array();
  11836. this._maxBlockCapacity = maxBlockCapacity || 64;
  11837. this._selectionContent = new BABYLON.SmartArray(1024);
  11838. this._creationFunc = creationFunc;
  11839. }
  11840. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11841. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  11842. };
  11843. Octree.prototype.addMesh = function (entry) {
  11844. for (var index = 0; index < this.blocks.length; index++) {
  11845. var block = this.blocks[index];
  11846. block.addEntry(entry);
  11847. }
  11848. };
  11849. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  11850. this._selectionContent.reset();
  11851. for (var index = 0; index < this.blocks.length; index++) {
  11852. var block = this.blocks[index];
  11853. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  11854. }
  11855. if (allowDuplicate) {
  11856. this._selectionContent.concat(this.dynamicContent);
  11857. } else {
  11858. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11859. }
  11860. return this._selectionContent;
  11861. };
  11862. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  11863. this._selectionContent.reset();
  11864. for (var index = 0; index < this.blocks.length; index++) {
  11865. var block = this.blocks[index];
  11866. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  11867. }
  11868. if (allowDuplicate) {
  11869. this._selectionContent.concat(this.dynamicContent);
  11870. } else {
  11871. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11872. }
  11873. return this._selectionContent;
  11874. };
  11875. Octree.prototype.intersectsRay = function (ray) {
  11876. this._selectionContent.reset();
  11877. for (var index = 0; index < this.blocks.length; index++) {
  11878. var block = this.blocks[index];
  11879. block.intersectsRay(ray, this._selectionContent);
  11880. }
  11881. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  11882. return this._selectionContent;
  11883. };
  11884. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  11885. target.blocks = new Array();
  11886. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  11887. for (var x = 0; x < 2; x++) {
  11888. for (var y = 0; y < 2; y++) {
  11889. for (var z = 0; z < 2; z++) {
  11890. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  11891. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  11892. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  11893. block.addEntries(entries);
  11894. target.blocks.push(block);
  11895. }
  11896. }
  11897. }
  11898. };
  11899. Octree.CreationFuncForMeshes = function (entry, block) {
  11900. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11901. block.entries.push(entry);
  11902. }
  11903. };
  11904. Octree.CreationFuncForSubMeshes = function (entry, block) {
  11905. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  11906. block.entries.push(entry);
  11907. }
  11908. };
  11909. return Octree;
  11910. })();
  11911. BABYLON.Octree = Octree;
  11912. })(BABYLON || (BABYLON = {}));
  11913. var BABYLON;
  11914. (function (BABYLON) {
  11915. var OctreeBlock = (function () {
  11916. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  11917. this.entries = new Array();
  11918. this._boundingVectors = new Array();
  11919. this._capacity = capacity;
  11920. this._depth = depth;
  11921. this._maxDepth = maxDepth;
  11922. this._creationFunc = creationFunc;
  11923. this._minPoint = minPoint;
  11924. this._maxPoint = maxPoint;
  11925. this._boundingVectors.push(minPoint.clone());
  11926. this._boundingVectors.push(maxPoint.clone());
  11927. this._boundingVectors.push(minPoint.clone());
  11928. this._boundingVectors[2].x = maxPoint.x;
  11929. this._boundingVectors.push(minPoint.clone());
  11930. this._boundingVectors[3].y = maxPoint.y;
  11931. this._boundingVectors.push(minPoint.clone());
  11932. this._boundingVectors[4].z = maxPoint.z;
  11933. this._boundingVectors.push(maxPoint.clone());
  11934. this._boundingVectors[5].z = minPoint.z;
  11935. this._boundingVectors.push(maxPoint.clone());
  11936. this._boundingVectors[6].x = minPoint.x;
  11937. this._boundingVectors.push(maxPoint.clone());
  11938. this._boundingVectors[7].y = minPoint.y;
  11939. }
  11940. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  11941. get: function () {
  11942. return this._capacity;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  11948. get: function () {
  11949. return this._minPoint;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  11955. get: function () {
  11956. return this._maxPoint;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. OctreeBlock.prototype.addEntry = function (entry) {
  11962. if (this.blocks) {
  11963. for (var index = 0; index < this.blocks.length; index++) {
  11964. var block = this.blocks[index];
  11965. block.addEntry(entry);
  11966. }
  11967. return;
  11968. }
  11969. this._creationFunc(entry, this);
  11970. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  11971. this.createInnerBlocks();
  11972. }
  11973. };
  11974. OctreeBlock.prototype.addEntries = function (entries) {
  11975. for (var index = 0; index < entries.length; index++) {
  11976. var mesh = entries[index];
  11977. this.addEntry(mesh);
  11978. }
  11979. };
  11980. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  11981. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  11982. if (this.blocks) {
  11983. for (var index = 0; index < this.blocks.length; index++) {
  11984. var block = this.blocks[index];
  11985. block.select(frustumPlanes, selection, allowDuplicate);
  11986. }
  11987. return;
  11988. }
  11989. if (allowDuplicate) {
  11990. selection.concat(this.entries);
  11991. } else {
  11992. selection.concatWithNoDuplicate(this.entries);
  11993. }
  11994. }
  11995. };
  11996. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  11997. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  11998. if (this.blocks) {
  11999. for (var index = 0; index < this.blocks.length; index++) {
  12000. var block = this.blocks[index];
  12001. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12002. }
  12003. return;
  12004. }
  12005. if (allowDuplicate) {
  12006. selection.concat(this.entries);
  12007. } else {
  12008. selection.concatWithNoDuplicate(this.entries);
  12009. }
  12010. }
  12011. };
  12012. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12013. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12014. if (this.blocks) {
  12015. for (var index = 0; index < this.blocks.length; index++) {
  12016. var block = this.blocks[index];
  12017. block.intersectsRay(ray, selection);
  12018. }
  12019. return;
  12020. }
  12021. selection.concatWithNoDuplicate(this.entries);
  12022. }
  12023. };
  12024. OctreeBlock.prototype.createInnerBlocks = function () {
  12025. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12026. };
  12027. return OctreeBlock;
  12028. })();
  12029. BABYLON.OctreeBlock = OctreeBlock;
  12030. })(BABYLON || (BABYLON = {}));
  12031. var BABYLON;
  12032. (function (BABYLON) {
  12033. var Bone = (function () {
  12034. function Bone(name, skeleton, parentBone, matrix) {
  12035. this.name = name;
  12036. this.children = new Array();
  12037. this.animations = new Array();
  12038. this._worldTransform = new BABYLON.Matrix();
  12039. this._absoluteTransform = new BABYLON.Matrix();
  12040. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12041. this._skeleton = skeleton;
  12042. this._matrix = matrix;
  12043. this._baseMatrix = matrix;
  12044. skeleton.bones.push(this);
  12045. if (parentBone) {
  12046. this._parent = parentBone;
  12047. parentBone.children.push(this);
  12048. } else {
  12049. this._parent = null;
  12050. }
  12051. this._updateDifferenceMatrix();
  12052. }
  12053. Bone.prototype.getParent = function () {
  12054. return this._parent;
  12055. };
  12056. Bone.prototype.getLocalMatrix = function () {
  12057. return this._matrix;
  12058. };
  12059. Bone.prototype.getBaseMatrix = function () {
  12060. return this._baseMatrix;
  12061. };
  12062. Bone.prototype.getWorldMatrix = function () {
  12063. return this._worldTransform;
  12064. };
  12065. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12066. return this._invertedAbsoluteTransform;
  12067. };
  12068. Bone.prototype.getAbsoluteMatrix = function () {
  12069. var matrix = this._matrix.clone();
  12070. var parent = this._parent;
  12071. while (parent) {
  12072. matrix = matrix.multiply(parent.getLocalMatrix());
  12073. parent = parent.getParent();
  12074. }
  12075. return matrix;
  12076. };
  12077. Bone.prototype.updateMatrix = function (matrix) {
  12078. this._matrix = matrix;
  12079. this._skeleton._markAsDirty();
  12080. this._updateDifferenceMatrix();
  12081. };
  12082. Bone.prototype._updateDifferenceMatrix = function () {
  12083. if (this._parent) {
  12084. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12085. } else {
  12086. this._absoluteTransform.copyFrom(this._matrix);
  12087. }
  12088. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12089. for (var index = 0; index < this.children.length; index++) {
  12090. this.children[index]._updateDifferenceMatrix();
  12091. }
  12092. };
  12093. Bone.prototype.markAsDirty = function () {
  12094. this._skeleton._markAsDirty();
  12095. };
  12096. return Bone;
  12097. })();
  12098. BABYLON.Bone = Bone;
  12099. })(BABYLON || (BABYLON = {}));
  12100. var BABYLON;
  12101. (function (BABYLON) {
  12102. var Skeleton = (function () {
  12103. function Skeleton(name, id, scene) {
  12104. this.name = name;
  12105. this.id = id;
  12106. this.bones = new Array();
  12107. this._isDirty = true;
  12108. this._identity = BABYLON.Matrix.Identity();
  12109. this.bones = [];
  12110. this._scene = scene;
  12111. scene.skeletons.push(this);
  12112. }
  12113. Skeleton.prototype.getTransformMatrices = function () {
  12114. return this._transformMatrices;
  12115. };
  12116. Skeleton.prototype._markAsDirty = function () {
  12117. this._isDirty = true;
  12118. };
  12119. Skeleton.prototype.prepare = function () {
  12120. if (!this._isDirty) {
  12121. return;
  12122. }
  12123. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12124. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12125. }
  12126. for (var index = 0; index < this.bones.length; index++) {
  12127. var bone = this.bones[index];
  12128. var parentBone = bone.getParent();
  12129. if (parentBone) {
  12130. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12131. } else {
  12132. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12133. }
  12134. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12135. }
  12136. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12137. this._isDirty = false;
  12138. };
  12139. Skeleton.prototype.getAnimatables = function () {
  12140. if (!this._animatables || this._animatables.length != this.bones.length) {
  12141. this._animatables = [];
  12142. for (var index = 0; index < this.bones.length; index++) {
  12143. this._animatables.push(this.bones[index]);
  12144. }
  12145. }
  12146. return this._animatables;
  12147. };
  12148. Skeleton.prototype.clone = function (name, id) {
  12149. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12150. for (var index = 0; index < this.bones.length; index++) {
  12151. var source = this.bones[index];
  12152. var parentBone = null;
  12153. if (source.getParent()) {
  12154. var parentIndex = this.bones.indexOf(source.getParent());
  12155. parentBone = result.bones[parentIndex];
  12156. }
  12157. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12158. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12159. }
  12160. return result;
  12161. };
  12162. return Skeleton;
  12163. })();
  12164. BABYLON.Skeleton = Skeleton;
  12165. })(BABYLON || (BABYLON = {}));
  12166. var BABYLON;
  12167. (function (BABYLON) {
  12168. var PostProcess = (function () {
  12169. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12170. this.name = name;
  12171. this.width = -1;
  12172. this.height = -1;
  12173. this._reusable = false;
  12174. this._textures = new BABYLON.SmartArray(2);
  12175. this._currentRenderTextureInd = 0;
  12176. if (camera != null) {
  12177. this._camera = camera;
  12178. this._scene = camera.getScene();
  12179. camera.attachPostProcess(this);
  12180. this._engine = this._scene.getEngine();
  12181. } else {
  12182. this._engine = engine;
  12183. }
  12184. this._renderRatio = ratio;
  12185. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12186. this._reusable = reusable || false;
  12187. samplers = samplers || [];
  12188. samplers.push("textureSampler");
  12189. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12190. }
  12191. PostProcess.prototype.isReusable = function () {
  12192. return this._reusable;
  12193. };
  12194. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12195. camera = camera || this._camera;
  12196. var scene = camera.getScene();
  12197. var desiredWidth = (sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio;
  12198. var desiredHeight = (sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio;
  12199. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12200. if (this._textures.length > 0) {
  12201. for (var i = 0; i < this._textures.length; i++) {
  12202. this._engine._releaseTexture(this._textures.data[i]);
  12203. }
  12204. this._textures.reset();
  12205. }
  12206. this.width = desiredWidth;
  12207. this.height = desiredHeight;
  12208. 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 }));
  12209. if (this._reusable) {
  12210. 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 }));
  12211. }
  12212. if (this.onSizeChanged) {
  12213. this.onSizeChanged();
  12214. }
  12215. }
  12216. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12217. if (this.onActivate) {
  12218. this.onActivate(camera);
  12219. }
  12220. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12221. if (this._reusable) {
  12222. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12223. }
  12224. };
  12225. PostProcess.prototype.apply = function () {
  12226. if (!this._effect.isReady())
  12227. return null;
  12228. this._engine.enableEffect(this._effect);
  12229. this._engine.setState(false);
  12230. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12231. this._engine.setDepthBuffer(false);
  12232. this._engine.setDepthWrite(false);
  12233. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12234. if (this.onApply) {
  12235. this.onApply(this._effect);
  12236. }
  12237. return this._effect;
  12238. };
  12239. PostProcess.prototype.dispose = function (camera) {
  12240. camera = camera || this._camera;
  12241. if (this._textures.length > 0) {
  12242. for (var i = 0; i < this._textures.length; i++) {
  12243. this._engine._releaseTexture(this._textures.data[i]);
  12244. }
  12245. this._textures.reset();
  12246. }
  12247. camera.detachPostProcess(this);
  12248. var index = camera._postProcesses.indexOf(this);
  12249. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12250. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12251. }
  12252. };
  12253. return PostProcess;
  12254. })();
  12255. BABYLON.PostProcess = PostProcess;
  12256. })(BABYLON || (BABYLON = {}));
  12257. var BABYLON;
  12258. (function (BABYLON) {
  12259. var PostProcessManager = (function () {
  12260. function PostProcessManager(scene) {
  12261. this._vertexDeclaration = [2];
  12262. this._vertexStrideSize = 2 * 4;
  12263. this._scene = scene;
  12264. var vertices = [];
  12265. vertices.push(1, 1);
  12266. vertices.push(-1, 1);
  12267. vertices.push(-1, -1);
  12268. vertices.push(1, -1);
  12269. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12270. var indices = [];
  12271. indices.push(0);
  12272. indices.push(1);
  12273. indices.push(2);
  12274. indices.push(0);
  12275. indices.push(2);
  12276. indices.push(3);
  12277. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12278. }
  12279. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12280. var postProcesses = this._scene.activeCamera._postProcesses;
  12281. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12282. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12283. return false;
  12284. }
  12285. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12286. return true;
  12287. };
  12288. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12289. var postProcesses = this._scene.activeCamera._postProcesses;
  12290. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12291. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12292. return;
  12293. }
  12294. var engine = this._scene.getEngine();
  12295. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12296. if (index < postProcessesTakenIndices.length - 1) {
  12297. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12298. } else {
  12299. if (targetTexture) {
  12300. engine.bindFramebuffer(targetTexture);
  12301. } else {
  12302. engine.restoreDefaultFramebuffer();
  12303. }
  12304. }
  12305. if (doNotPresent) {
  12306. break;
  12307. }
  12308. var effect = postProcesses[postProcessesTakenIndices[index]].apply();
  12309. if (effect) {
  12310. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12311. engine.draw(true, 0, 6);
  12312. }
  12313. }
  12314. engine.setDepthBuffer(true);
  12315. engine.setDepthWrite(true);
  12316. };
  12317. PostProcessManager.prototype.dispose = function () {
  12318. if (this._vertexBuffer) {
  12319. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12320. this._vertexBuffer = null;
  12321. }
  12322. if (this._indexBuffer) {
  12323. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12324. this._indexBuffer = null;
  12325. }
  12326. };
  12327. return PostProcessManager;
  12328. })();
  12329. BABYLON.PostProcessManager = PostProcessManager;
  12330. })(BABYLON || (BABYLON = {}));
  12331. var __extends = this.__extends || function (d, b) {
  12332. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12333. function __() { this.constructor = d; }
  12334. __.prototype = b.prototype;
  12335. d.prototype = new __();
  12336. };
  12337. var BABYLON;
  12338. (function (BABYLON) {
  12339. var PassPostProcess = (function (_super) {
  12340. __extends(PassPostProcess, _super);
  12341. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12342. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12343. }
  12344. return PassPostProcess;
  12345. })(BABYLON.PostProcess);
  12346. BABYLON.PassPostProcess = PassPostProcess;
  12347. })(BABYLON || (BABYLON = {}));
  12348. var __extends = this.__extends || function (d, b) {
  12349. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12350. function __() { this.constructor = d; }
  12351. __.prototype = b.prototype;
  12352. d.prototype = new __();
  12353. };
  12354. var BABYLON;
  12355. (function (BABYLON) {
  12356. var BlurPostProcess = (function (_super) {
  12357. __extends(BlurPostProcess, _super);
  12358. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12359. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12360. var _this = this;
  12361. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12362. this.direction = direction;
  12363. this.blurWidth = blurWidth;
  12364. this.onApply = function (effect) {
  12365. effect.setFloat2("screenSize", _this.width, _this.height);
  12366. effect.setVector2("direction", _this.direction);
  12367. effect.setFloat("blurWidth", _this.blurWidth);
  12368. };
  12369. }
  12370. return BlurPostProcess;
  12371. })(BABYLON.PostProcess);
  12372. BABYLON.BlurPostProcess = BlurPostProcess;
  12373. })(BABYLON || (BABYLON = {}));
  12374. var __extends = this.__extends || function (d, b) {
  12375. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12376. function __() { this.constructor = d; }
  12377. __.prototype = b.prototype;
  12378. d.prototype = new __();
  12379. };
  12380. var BABYLON;
  12381. (function (BABYLON) {
  12382. var FilterPostProcess = (function (_super) {
  12383. __extends(FilterPostProcess, _super);
  12384. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12385. var _this = this;
  12386. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12387. this.kernelMatrix = kernelMatrix;
  12388. this.onApply = function (effect) {
  12389. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12390. };
  12391. }
  12392. return FilterPostProcess;
  12393. })(BABYLON.PostProcess);
  12394. BABYLON.FilterPostProcess = FilterPostProcess;
  12395. })(BABYLON || (BABYLON = {}));
  12396. var __extends = this.__extends || function (d, b) {
  12397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12398. function __() { this.constructor = d; }
  12399. __.prototype = b.prototype;
  12400. d.prototype = new __();
  12401. };
  12402. var BABYLON;
  12403. (function (BABYLON) {
  12404. var RefractionPostProcess = (function (_super) {
  12405. __extends(RefractionPostProcess, _super);
  12406. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12407. var _this = this;
  12408. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12409. this.color = color;
  12410. this.depth = depth;
  12411. this.colorLevel = colorLevel;
  12412. this.onActivate = function (cam) {
  12413. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12414. };
  12415. this.onApply = function (effect) {
  12416. effect.setColor3("baseColor", _this.color);
  12417. effect.setFloat("depth", _this.depth);
  12418. effect.setFloat("colorLevel", _this.colorLevel);
  12419. effect.setTexture("refractionSampler", _this._refRexture);
  12420. };
  12421. }
  12422. RefractionPostProcess.prototype.dispose = function (camera) {
  12423. if (this._refRexture) {
  12424. this._refRexture.dispose();
  12425. }
  12426. _super.prototype.dispose.call(this, camera);
  12427. };
  12428. return RefractionPostProcess;
  12429. })(BABYLON.PostProcess);
  12430. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12431. })(BABYLON || (BABYLON = {}));
  12432. var __extends = this.__extends || function (d, b) {
  12433. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12434. function __() { this.constructor = d; }
  12435. __.prototype = b.prototype;
  12436. d.prototype = new __();
  12437. };
  12438. var BABYLON;
  12439. (function (BABYLON) {
  12440. var BlackAndWhitePostProcess = (function (_super) {
  12441. __extends(BlackAndWhitePostProcess, _super);
  12442. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12443. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12444. }
  12445. return BlackAndWhitePostProcess;
  12446. })(BABYLON.PostProcess);
  12447. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12448. })(BABYLON || (BABYLON = {}));
  12449. var __extends = this.__extends || function (d, b) {
  12450. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12451. function __() { this.constructor = d; }
  12452. __.prototype = b.prototype;
  12453. d.prototype = new __();
  12454. };
  12455. var BABYLON;
  12456. (function (BABYLON) {
  12457. var ConvolutionPostProcess = (function (_super) {
  12458. __extends(ConvolutionPostProcess, _super);
  12459. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12460. var _this = this;
  12461. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12462. this.kernel = kernel;
  12463. this.onApply = function (effect) {
  12464. effect.setFloat2("screenSize", _this.width, _this.height);
  12465. effect.setArray("kernel", _this.kernel);
  12466. };
  12467. }
  12468. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12469. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12470. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12471. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12472. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12473. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12474. return ConvolutionPostProcess;
  12475. })(BABYLON.PostProcess);
  12476. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12477. })(BABYLON || (BABYLON = {}));
  12478. var __extends = this.__extends || function (d, b) {
  12479. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12480. function __() { this.constructor = d; }
  12481. __.prototype = b.prototype;
  12482. d.prototype = new __();
  12483. };
  12484. var BABYLON;
  12485. (function (BABYLON) {
  12486. var FxaaPostProcess = (function (_super) {
  12487. __extends(FxaaPostProcess, _super);
  12488. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12489. var _this = this;
  12490. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12491. this.onSizeChanged = function () {
  12492. _this.texelWidth = 1.0 / _this.width;
  12493. _this.texelHeight = 1.0 / _this.height;
  12494. };
  12495. this.onApply = function (effect) {
  12496. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12497. };
  12498. }
  12499. return FxaaPostProcess;
  12500. })(BABYLON.PostProcess);
  12501. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12502. })(BABYLON || (BABYLON = {}));
  12503. var BABYLON;
  12504. (function (BABYLON) {
  12505. var LensFlare = (function () {
  12506. function LensFlare(size, position, color, imgUrl, system) {
  12507. this.size = size;
  12508. this.position = position;
  12509. this.dispose = function () {
  12510. if (this.texture) {
  12511. this.texture.dispose();
  12512. }
  12513. var index = this._system.lensFlares.indexOf(this);
  12514. this._system.lensFlares.splice(index, 1);
  12515. };
  12516. this.color = color || new BABYLON.Color3(1, 1, 1);
  12517. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12518. this._system = system;
  12519. system.lensFlares.push(this);
  12520. }
  12521. return LensFlare;
  12522. })();
  12523. BABYLON.LensFlare = LensFlare;
  12524. })(BABYLON || (BABYLON = {}));
  12525. var BABYLON;
  12526. (function (BABYLON) {
  12527. var LensFlareSystem = (function () {
  12528. function LensFlareSystem(name, emitter, scene) {
  12529. this.name = name;
  12530. this.lensFlares = new Array();
  12531. this.borderLimit = 300;
  12532. this._vertexDeclaration = [2];
  12533. this._vertexStrideSize = 2 * 4;
  12534. this._isEnabled = true;
  12535. this._scene = scene;
  12536. this._emitter = emitter;
  12537. scene.lensFlareSystems.push(this);
  12538. this.meshesSelectionPredicate = function (m) {
  12539. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12540. };
  12541. var vertices = [];
  12542. vertices.push(1, 1);
  12543. vertices.push(-1, 1);
  12544. vertices.push(-1, -1);
  12545. vertices.push(1, -1);
  12546. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12547. var indices = [];
  12548. indices.push(0);
  12549. indices.push(1);
  12550. indices.push(2);
  12551. indices.push(0);
  12552. indices.push(2);
  12553. indices.push(3);
  12554. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12555. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12556. }
  12557. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12558. get: function () {
  12559. return this._isEnabled;
  12560. },
  12561. set: function (value) {
  12562. this._isEnabled = value;
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. LensFlareSystem.prototype.getScene = function () {
  12568. return this._scene;
  12569. };
  12570. LensFlareSystem.prototype.getEmitter = function () {
  12571. return this._emitter;
  12572. };
  12573. LensFlareSystem.prototype.getEmitterPosition = function () {
  12574. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12575. };
  12576. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12577. var position = this.getEmitterPosition();
  12578. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12579. this._positionX = position.x;
  12580. this._positionY = position.y;
  12581. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12582. if (position.z > 0) {
  12583. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12584. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12585. return true;
  12586. }
  12587. }
  12588. return false;
  12589. };
  12590. LensFlareSystem.prototype._isVisible = function () {
  12591. if (!this._isEnabled) {
  12592. return false;
  12593. }
  12594. var emitterPosition = this.getEmitterPosition();
  12595. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12596. var distance = direction.length();
  12597. direction.normalize();
  12598. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12599. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12600. return !pickInfo.hit || pickInfo.distance > distance;
  12601. };
  12602. LensFlareSystem.prototype.render = function () {
  12603. if (!this._effect.isReady())
  12604. return false;
  12605. var engine = this._scene.getEngine();
  12606. var viewport = this._scene.activeCamera.viewport;
  12607. var globalViewport = viewport.toGlobal(engine);
  12608. if (!this.computeEffectivePosition(globalViewport)) {
  12609. return false;
  12610. }
  12611. if (!this._isVisible()) {
  12612. return false;
  12613. }
  12614. var awayX;
  12615. var awayY;
  12616. if (this._positionX < this.borderLimit + globalViewport.x) {
  12617. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12618. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12619. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12620. } else {
  12621. awayX = 0;
  12622. }
  12623. if (this._positionY < this.borderLimit + globalViewport.y) {
  12624. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12625. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12626. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12627. } else {
  12628. awayY = 0;
  12629. }
  12630. var away = (awayX > awayY) ? awayX : awayY;
  12631. if (away > this.borderLimit) {
  12632. away = this.borderLimit;
  12633. }
  12634. var intensity = 1.0 - (away / this.borderLimit);
  12635. if (intensity < 0) {
  12636. return false;
  12637. }
  12638. if (intensity > 1.0) {
  12639. intensity = 1.0;
  12640. }
  12641. var centerX = globalViewport.x + globalViewport.width / 2;
  12642. var centerY = globalViewport.y + globalViewport.height / 2;
  12643. var distX = centerX - this._positionX;
  12644. var distY = centerY - this._positionY;
  12645. engine.enableEffect(this._effect);
  12646. engine.setState(false);
  12647. engine.setDepthBuffer(false);
  12648. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12649. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12650. for (var index = 0; index < this.lensFlares.length; index++) {
  12651. var flare = this.lensFlares[index];
  12652. var x = centerX - (distX * flare.position);
  12653. var y = centerY - (distY * flare.position);
  12654. var cw = flare.size;
  12655. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12656. var cx = 2 * (x / globalViewport.width) - 1.0;
  12657. var cy = 1.0 - 2 * (y / globalViewport.height);
  12658. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12659. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12660. this._effect.setTexture("textureSampler", flare.texture);
  12661. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12662. engine.draw(true, 0, 6);
  12663. }
  12664. engine.setDepthBuffer(true);
  12665. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12666. return true;
  12667. };
  12668. LensFlareSystem.prototype.dispose = function () {
  12669. if (this._vertexBuffer) {
  12670. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12671. this._vertexBuffer = null;
  12672. }
  12673. if (this._indexBuffer) {
  12674. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12675. this._indexBuffer = null;
  12676. }
  12677. while (this.lensFlares.length) {
  12678. this.lensFlares[0].dispose();
  12679. }
  12680. var index = this._scene.lensFlareSystems.indexOf(this);
  12681. this._scene.lensFlareSystems.splice(index, 1);
  12682. };
  12683. return LensFlareSystem;
  12684. })();
  12685. BABYLON.LensFlareSystem = LensFlareSystem;
  12686. })(BABYLON || (BABYLON = {}));
  12687. var BABYLON;
  12688. (function (BABYLON) {
  12689. var IntersectionInfo = (function () {
  12690. function IntersectionInfo(bu, bv, distance) {
  12691. this.bu = bu;
  12692. this.bv = bv;
  12693. this.distance = distance;
  12694. this.faceId = 0;
  12695. }
  12696. return IntersectionInfo;
  12697. })();
  12698. BABYLON.IntersectionInfo = IntersectionInfo;
  12699. var PickingInfo = (function () {
  12700. function PickingInfo() {
  12701. this.hit = false;
  12702. this.distance = 0;
  12703. this.pickedPoint = null;
  12704. this.pickedMesh = null;
  12705. this.bu = 0;
  12706. this.bv = 0;
  12707. this.faceId = -1;
  12708. }
  12709. PickingInfo.prototype.getNormal = function () {
  12710. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12711. return null;
  12712. }
  12713. var indices = this.pickedMesh.getIndices();
  12714. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12715. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12716. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12717. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12718. normal0 = normal0.scale(this.bu);
  12719. normal1 = normal1.scale(this.bv);
  12720. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12721. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12722. };
  12723. PickingInfo.prototype.getTextureCoordinates = function () {
  12724. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12725. return null;
  12726. }
  12727. var indices = this.pickedMesh.getIndices();
  12728. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12729. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12730. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12731. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12732. uv0 = uv0.scale(this.bu);
  12733. uv1 = uv1.scale(this.bv);
  12734. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12735. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12736. };
  12737. return PickingInfo;
  12738. })();
  12739. BABYLON.PickingInfo = PickingInfo;
  12740. })(BABYLON || (BABYLON = {}));
  12741. var BABYLON;
  12742. (function (BABYLON) {
  12743. var FilesInput = (function () {
  12744. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12745. this.engine = p_engine;
  12746. this.canvas = p_canvas;
  12747. this.currentScene = p_scene;
  12748. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12749. this.progressCallback = p_progressCallback;
  12750. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12751. this.textureLoadingCallback = p_textureLoadingCallback;
  12752. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12753. }
  12754. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12755. var _this = this;
  12756. if (p_elementToMonitor) {
  12757. this.elementToMonitor = p_elementToMonitor;
  12758. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12759. _this.drag(e);
  12760. }, false);
  12761. this.elementToMonitor.addEventListener("dragover", function (e) {
  12762. _this.drag(e);
  12763. }, false);
  12764. this.elementToMonitor.addEventListener("drop", function (e) {
  12765. _this.drop(e);
  12766. }, false);
  12767. }
  12768. };
  12769. FilesInput.prototype.renderFunction = function () {
  12770. if (this.additionnalRenderLoopLogicCallback) {
  12771. this.additionnalRenderLoopLogicCallback();
  12772. }
  12773. if (this.currentScene) {
  12774. if (this.textureLoadingCallback) {
  12775. var remaining = this.currentScene.getWaitingItemsCount();
  12776. if (remaining > 0) {
  12777. this.textureLoadingCallback(remaining);
  12778. }
  12779. }
  12780. this.currentScene.render();
  12781. }
  12782. };
  12783. FilesInput.prototype.drag = function (e) {
  12784. e.stopPropagation();
  12785. e.preventDefault();
  12786. };
  12787. FilesInput.prototype.drop = function (eventDrop) {
  12788. eventDrop.stopPropagation();
  12789. eventDrop.preventDefault();
  12790. this.loadFiles(eventDrop);
  12791. };
  12792. FilesInput.prototype.loadFiles = function (event) {
  12793. var _this = this;
  12794. var that = this;
  12795. if (this.startingProcessingFilesCallback)
  12796. this.startingProcessingFilesCallback();
  12797. var sceneFileToLoad;
  12798. var filesToLoad;
  12799. if (event && event.dataTransfer && event.dataTransfer.files) {
  12800. filesToLoad = event.dataTransfer.files;
  12801. }
  12802. if (event && event.target && event.target.files) {
  12803. filesToLoad = event.target.files;
  12804. }
  12805. if (filesToLoad && filesToLoad.length > 0) {
  12806. for (var i = 0; i < filesToLoad.length; i++) {
  12807. switch (filesToLoad[i].type) {
  12808. case "image/jpeg":
  12809. case "image/png":
  12810. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12811. break;
  12812. case "image/targa":
  12813. case "image/vnd.ms-dds":
  12814. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12815. break;
  12816. default:
  12817. 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) {
  12818. sceneFileToLoad = filesToLoad[i];
  12819. }
  12820. break;
  12821. }
  12822. }
  12823. if (sceneFileToLoad) {
  12824. if (this.currentScene) {
  12825. this.engine.stopRenderLoop();
  12826. this.currentScene.dispose();
  12827. }
  12828. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12829. that.currentScene = newScene;
  12830. that.currentScene.executeWhenReady(function () {
  12831. if (that.currentScene.activeCamera) {
  12832. that.currentScene.activeCamera.attachControl(that.canvas);
  12833. }
  12834. if (that.sceneLoadedCallback) {
  12835. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  12836. }
  12837. that.engine.runRenderLoop(function () {
  12838. that.renderFunction();
  12839. });
  12840. });
  12841. }, function (progress) {
  12842. if (_this.progressCallback) {
  12843. _this.progressCallback(progress);
  12844. }
  12845. });
  12846. } else {
  12847. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  12848. }
  12849. }
  12850. };
  12851. FilesInput.FilesTextures = new Array();
  12852. FilesInput.FilesToLoad = new Array();
  12853. return FilesInput;
  12854. })();
  12855. BABYLON.FilesInput = FilesInput;
  12856. })(BABYLON || (BABYLON = {}));
  12857. var BABYLON;
  12858. (function (BABYLON) {
  12859. var OimoJSPlugin = (function () {
  12860. function OimoJSPlugin() {
  12861. this._registeredMeshes = [];
  12862. /**
  12863. * Update the body position according to the mesh position
  12864. * @param mesh
  12865. */
  12866. this.updateBodyPosition = function (mesh) {
  12867. for (var index = 0; index < this._registeredMeshes.length; index++) {
  12868. var registeredMesh = this._registeredMeshes[index];
  12869. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  12870. var body = registeredMesh.body.body;
  12871. var center = mesh.getBoundingInfo().boundingBox.center;
  12872. body.setPosition(center.x, center.y, center.z);
  12873. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  12874. return;
  12875. }
  12876. if (registeredMesh.mesh.parent === mesh) {
  12877. mesh.computeWorldMatrix(true);
  12878. registeredMesh.mesh.computeWorldMatrix(true);
  12879. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  12880. var absoluteRotation = mesh.rotation;
  12881. body = registeredMesh.body.body;
  12882. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  12883. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  12884. return;
  12885. }
  12886. }
  12887. };
  12888. }
  12889. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  12890. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  12891. };
  12892. OimoJSPlugin.prototype.initialize = function (iterations) {
  12893. this._world = new OIMO.World();
  12894. this._world.clear();
  12895. };
  12896. OimoJSPlugin.prototype.setGravity = function (gravity) {
  12897. this._world.gravity = gravity;
  12898. };
  12899. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  12900. var body = null;
  12901. this.unregisterMesh(mesh);
  12902. mesh.computeWorldMatrix(true);
  12903. switch (impostor) {
  12904. case BABYLON.PhysicsEngine.SphereImpostor:
  12905. var bbox = mesh.getBoundingInfo().boundingBox;
  12906. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12907. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12908. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12909. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12910. var deltaPosition = mesh.position.subtract(bbox.center);
  12911. body = new OIMO.Body({
  12912. type: 'sphere',
  12913. size: [size],
  12914. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12915. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12916. move: options.mass != 0,
  12917. config: [options.mass, options.friction, options.restitution],
  12918. world: this._world
  12919. });
  12920. this._registeredMeshes.push({
  12921. mesh: mesh,
  12922. body: body,
  12923. delta: deltaPosition
  12924. });
  12925. break;
  12926. case BABYLON.PhysicsEngine.PlaneImpostor:
  12927. case BABYLON.PhysicsEngine.BoxImpostor:
  12928. bbox = mesh.getBoundingInfo().boundingBox;
  12929. var min = bbox.minimumWorld;
  12930. var max = bbox.maximumWorld;
  12931. var box = max.subtract(min);
  12932. var sizeX = this._checkWithEpsilon(box.x);
  12933. var sizeY = this._checkWithEpsilon(box.y);
  12934. var sizeZ = this._checkWithEpsilon(box.z);
  12935. var deltaPosition = mesh.position.subtract(bbox.center);
  12936. body = new OIMO.Body({
  12937. type: 'box',
  12938. size: [sizeX, sizeY, sizeZ],
  12939. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  12940. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  12941. move: options.mass != 0,
  12942. config: [options.mass, options.friction, options.restitution],
  12943. world: this._world
  12944. });
  12945. this._registeredMeshes.push({
  12946. mesh: mesh,
  12947. body: body,
  12948. delta: deltaPosition
  12949. });
  12950. break;
  12951. }
  12952. return body;
  12953. };
  12954. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  12955. var types = [], sizes = [], positions = [], rotations = [];
  12956. var initialMesh = parts[0].mesh;
  12957. for (var index = 0; index < parts.length; index++) {
  12958. var part = parts[index];
  12959. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  12960. types.push(bodyParameters.type);
  12961. sizes.push.apply(sizes, bodyParameters.size);
  12962. positions.push.apply(positions, bodyParameters.pos);
  12963. rotations.push.apply(rotations, bodyParameters.rot);
  12964. }
  12965. var body = new OIMO.Body({
  12966. type: types,
  12967. size: sizes,
  12968. pos: positions,
  12969. rot: rotations,
  12970. move: options.mass != 0,
  12971. config: [options.mass, options.friction, options.restitution],
  12972. world: this._world
  12973. });
  12974. this._registeredMeshes.push({
  12975. mesh: initialMesh,
  12976. body: body
  12977. });
  12978. return body;
  12979. };
  12980. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  12981. var bodyParameters = null;
  12982. var mesh = part.mesh;
  12983. switch (part.impostor) {
  12984. case BABYLON.PhysicsEngine.SphereImpostor:
  12985. var bbox = mesh.getBoundingInfo().boundingBox;
  12986. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  12987. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  12988. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  12989. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  12990. bodyParameters = {
  12991. type: 'sphere',
  12992. /* bug with oimo : sphere needs 3 sizes in this case */
  12993. size: [size, -1, -1],
  12994. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  12995. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  12996. };
  12997. break;
  12998. case BABYLON.PhysicsEngine.PlaneImpostor:
  12999. case BABYLON.PhysicsEngine.BoxImpostor:
  13000. bbox = mesh.getBoundingInfo().boundingBox;
  13001. var min = bbox.minimumWorld;
  13002. var max = bbox.maximumWorld;
  13003. var box = max.subtract(min);
  13004. var sizeX = this._checkWithEpsilon(box.x);
  13005. var sizeY = this._checkWithEpsilon(box.y);
  13006. var sizeZ = this._checkWithEpsilon(box.z);
  13007. var relativePosition = mesh.position;
  13008. bodyParameters = {
  13009. type: 'box',
  13010. size: [sizeX, sizeY, sizeZ],
  13011. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13012. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13013. };
  13014. break;
  13015. }
  13016. return bodyParameters;
  13017. };
  13018. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13019. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13020. var registeredMesh = this._registeredMeshes[index];
  13021. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13022. if (registeredMesh.body) {
  13023. this._world.removeRigidBody(registeredMesh.body.body);
  13024. this._unbindBody(registeredMesh.body);
  13025. }
  13026. this._registeredMeshes.splice(index, 1);
  13027. return;
  13028. }
  13029. }
  13030. };
  13031. OimoJSPlugin.prototype._unbindBody = function (body) {
  13032. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13033. var registeredMesh = this._registeredMeshes[index];
  13034. if (registeredMesh.body === body) {
  13035. registeredMesh.body = null;
  13036. }
  13037. }
  13038. };
  13039. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13040. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13041. var registeredMesh = this._registeredMeshes[index];
  13042. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13043. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE));
  13044. return;
  13045. }
  13046. }
  13047. };
  13048. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13049. var body1 = null, body2 = null;
  13050. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13051. var registeredMesh = this._registeredMeshes[index];
  13052. if (registeredMesh.mesh === mesh1) {
  13053. body1 = registeredMesh.body.body;
  13054. } else if (registeredMesh.mesh === mesh2) {
  13055. body2 = registeredMesh.body.body;
  13056. }
  13057. }
  13058. if (!body1 || !body2) {
  13059. return false;
  13060. }
  13061. if (!options) {
  13062. options = {};
  13063. }
  13064. new OIMO.Link({
  13065. type: options.type,
  13066. body1: body1,
  13067. body2: body2,
  13068. min: options.min,
  13069. max: options.max,
  13070. axe1: options.axe1,
  13071. axe2: options.axe2,
  13072. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13073. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13074. collision: options.collision,
  13075. spring: options.spring,
  13076. world: this._world
  13077. });
  13078. return true;
  13079. };
  13080. OimoJSPlugin.prototype.dispose = function () {
  13081. this._world.clear();
  13082. while (this._registeredMeshes.length) {
  13083. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13084. }
  13085. };
  13086. OimoJSPlugin.prototype.isSupported = function () {
  13087. return OIMO !== undefined;
  13088. };
  13089. OimoJSPlugin.prototype._getLastShape = function (body) {
  13090. var lastShape = body.shapes;
  13091. while (lastShape.next) {
  13092. lastShape = lastShape.next;
  13093. }
  13094. return lastShape;
  13095. };
  13096. OimoJSPlugin.prototype.runOneStep = function (time) {
  13097. this._world.step();
  13098. var i = this._registeredMeshes.length;
  13099. var m;
  13100. while (i--) {
  13101. var body = this._registeredMeshes[i].body.body;
  13102. var mesh = this._registeredMeshes[i].mesh;
  13103. var delta = this._registeredMeshes[i].delta;
  13104. if (!body.sleeping) {
  13105. if (body.shapes.next) {
  13106. var parentShape = this._getLastShape(body);
  13107. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13108. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13109. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13110. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13111. if (!mesh.rotationQuaternion) {
  13112. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13113. }
  13114. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13115. } else {
  13116. m = body.getMatrix();
  13117. mtx = BABYLON.Matrix.FromArray(m);
  13118. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13119. if (!delta) {
  13120. mesh.position.x = bodyX;
  13121. mesh.position.y = bodyY;
  13122. mesh.position.z = bodyZ;
  13123. } else {
  13124. mesh.position.x = bodyX + delta.x;
  13125. mesh.position.y = bodyY + delta.y;
  13126. mesh.position.z = bodyZ + delta.z;
  13127. }
  13128. if (!mesh.rotationQuaternion) {
  13129. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13130. }
  13131. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13132. }
  13133. }
  13134. }
  13135. };
  13136. return OimoJSPlugin;
  13137. })();
  13138. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13139. })(BABYLON || (BABYLON = {}));
  13140. var BABYLON;
  13141. (function (BABYLON) {
  13142. var PhysicsEngine = (function () {
  13143. function PhysicsEngine(plugin) {
  13144. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13145. }
  13146. PhysicsEngine.prototype._initialize = function (gravity) {
  13147. this._currentPlugin.initialize();
  13148. this._setGravity(gravity);
  13149. };
  13150. PhysicsEngine.prototype._runOneStep = function (delta) {
  13151. if (delta > 0.1) {
  13152. delta = 0.1;
  13153. } else if (delta <= 0) {
  13154. delta = 1.0 / 60.0;
  13155. }
  13156. this._currentPlugin.runOneStep(delta);
  13157. };
  13158. PhysicsEngine.prototype._setGravity = function (gravity) {
  13159. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13160. this._currentPlugin.setGravity(this.gravity);
  13161. };
  13162. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13163. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13164. };
  13165. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13166. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13167. };
  13168. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13169. this._currentPlugin.unregisterMesh(mesh);
  13170. };
  13171. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13172. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13173. };
  13174. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13175. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13176. };
  13177. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13178. this._currentPlugin.updateBodyPosition(mesh);
  13179. };
  13180. PhysicsEngine.prototype.dispose = function () {
  13181. this._currentPlugin.dispose();
  13182. };
  13183. PhysicsEngine.prototype.isSupported = function () {
  13184. return this._currentPlugin.isSupported();
  13185. };
  13186. PhysicsEngine.NoImpostor = 0;
  13187. PhysicsEngine.SphereImpostor = 1;
  13188. PhysicsEngine.BoxImpostor = 2;
  13189. PhysicsEngine.PlaneImpostor = 3;
  13190. PhysicsEngine.CompoundImpostor = 4;
  13191. PhysicsEngine.MeshImpostor = 4;
  13192. PhysicsEngine.CapsuleImpostor = 5;
  13193. PhysicsEngine.ConeImpostor = 6;
  13194. PhysicsEngine.CylinderImpostor = 7;
  13195. PhysicsEngine.ConvexHullImpostor = 8;
  13196. PhysicsEngine.Epsilon = 0.001;
  13197. return PhysicsEngine;
  13198. })();
  13199. BABYLON.PhysicsEngine = PhysicsEngine;
  13200. })(BABYLON || (BABYLON = {}));
  13201. var BABYLON;
  13202. (function (BABYLON) {
  13203. var serializeLight = function (light) {
  13204. var serializationObject = {};
  13205. serializationObject.name = light.name;
  13206. serializationObject.id = light.id;
  13207. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13208. if (light instanceof BABYLON.PointLight) {
  13209. serializationObject.type = 0;
  13210. serializationObject.position = light.position.asArray();
  13211. } else if (light instanceof BABYLON.DirectionalLight) {
  13212. serializationObject.type = 1;
  13213. var directionalLight = light;
  13214. serializationObject.position = directionalLight.position.asArray();
  13215. serializationObject.direction = directionalLight.direction.asArray();
  13216. } else if (light instanceof BABYLON.SpotLight) {
  13217. serializationObject.type = 2;
  13218. var spotLight = light;
  13219. serializationObject.position = spotLight.position.asArray();
  13220. serializationObject.direction = spotLight.position.asArray();
  13221. serializationObject.angle = spotLight.angle;
  13222. serializationObject.exponent = spotLight.exponent;
  13223. } else if (light instanceof BABYLON.HemisphericLight) {
  13224. serializationObject.type = 3;
  13225. var hemisphericLight = light;
  13226. serializationObject.direction = hemisphericLight.direction.asArray();
  13227. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13228. }
  13229. if (light.intensity) {
  13230. serializationObject.intensity = light.intensity;
  13231. }
  13232. serializationObject.range = light.range;
  13233. serializationObject.diffuse = light.diffuse.asArray();
  13234. serializationObject.specular = light.specular.asArray();
  13235. return serializationObject;
  13236. };
  13237. var serializeFresnelParameter = function (fresnelParameter) {
  13238. var serializationObject = {};
  13239. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13240. serializationObject.leftColor = fresnelParameter.leftColor;
  13241. serializationObject.rightColor = fresnelParameter.rightColor;
  13242. serializationObject.bias = fresnelParameter.bias;
  13243. serializationObject.power = fresnelParameter.power;
  13244. return serializationObject;
  13245. };
  13246. var serializeCamera = function (camera) {
  13247. var serializationObject = {};
  13248. serializationObject.name = camera.name;
  13249. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13250. serializationObject.id = camera.id;
  13251. serializationObject.position = camera.position.asArray();
  13252. if (camera.parent) {
  13253. serializationObject.parentId = camera.parent.id;
  13254. }
  13255. serializationObject.rotation = camera.rotation.asArray();
  13256. if (camera.lockedTarget && camera.lockedTarget.id) {
  13257. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13258. }
  13259. serializationObject.fov = camera.fov;
  13260. serializationObject.minZ = camera.minZ;
  13261. serializationObject.maxZ = camera.maxZ;
  13262. serializationObject.speed = camera.speed;
  13263. serializationObject.inertia = camera.inertia;
  13264. serializationObject.checkCollisions = camera.checkCollisions;
  13265. serializationObject.applyGravity = camera.applyGravity;
  13266. if (camera.ellipsoid) {
  13267. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13268. }
  13269. appendAnimations(camera, serializationObject);
  13270. serializationObject.layerMask = camera.layerMask;
  13271. return serializationObject;
  13272. };
  13273. var appendAnimations = function (source, destination) {
  13274. if (source.animations) {
  13275. destination.animations = [];
  13276. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13277. var animation = source.animations[animationIndex];
  13278. destination.animations.push(serializeAnimation(animation));
  13279. }
  13280. }
  13281. };
  13282. var serializeAnimation = function (animation) {
  13283. var serializationObject = {};
  13284. serializationObject.name = animation.name;
  13285. serializationObject.property = animation.targetProperty;
  13286. serializationObject.framePerSecond = animation.framePerSecond;
  13287. serializationObject.dataType = animation.dataType;
  13288. serializationObject.loopBehavior = animation.loopMode;
  13289. var dataType = animation.dataType;
  13290. serializationObject.keys = [];
  13291. var keys = animation.getKeys();
  13292. for (var index = 0; index < keys.length; index++) {
  13293. var animationKey = keys[index];
  13294. var key = {};
  13295. key.frame = animationKey.frame;
  13296. switch (dataType) {
  13297. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13298. key.values = [animationKey.value];
  13299. break;
  13300. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13301. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13302. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13303. key.values = animationKey.value.asArray();
  13304. break;
  13305. }
  13306. serializationObject.keys.push(key);
  13307. }
  13308. return serializationObject;
  13309. };
  13310. var serializeMultiMaterial = function (material) {
  13311. var serializationObject = {};
  13312. serializationObject.name = material.name;
  13313. serializationObject.id = material.id;
  13314. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13315. serializationObject.materials = [];
  13316. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13317. var subMat = material.subMaterials[matIndex];
  13318. if (subMat) {
  13319. serializationObject.materials.push(subMat.id);
  13320. } else {
  13321. serializationObject.materials.push(null);
  13322. }
  13323. }
  13324. return serializationObject;
  13325. };
  13326. var serializeMaterial = function (material) {
  13327. var serializationObject = {};
  13328. serializationObject.name = material.name;
  13329. serializationObject.ambient = material.ambientColor.asArray();
  13330. serializationObject.diffuse = material.diffuseColor.asArray();
  13331. serializationObject.specular = material.specularColor.asArray();
  13332. serializationObject.specularPower = material.specularPower;
  13333. serializationObject.emissive = material.emissiveColor.asArray();
  13334. serializationObject.alpha = material.alpha;
  13335. serializationObject.id = material.id;
  13336. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13337. serializationObject.backFaceCulling = material.backFaceCulling;
  13338. if (material.diffuseTexture) {
  13339. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13340. }
  13341. if (material.diffuseFresnelParameters) {
  13342. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13343. }
  13344. if (material.ambientTexture) {
  13345. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13346. }
  13347. if (material.opacityTexture) {
  13348. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13349. }
  13350. if (material.opacityFresnelParameters) {
  13351. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13352. }
  13353. if (material.reflectionTexture) {
  13354. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13355. }
  13356. if (material.reflectionFresnelParameters) {
  13357. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13358. }
  13359. if (material.emissiveTexture) {
  13360. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13361. }
  13362. if (material.emissiveFresnelParameters) {
  13363. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13364. }
  13365. if (material.specularTexture) {
  13366. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13367. }
  13368. if (material.bumpTexture) {
  13369. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13370. }
  13371. return serializationObject;
  13372. };
  13373. var serializeTexture = function (texture) {
  13374. var serializationObject = {};
  13375. if (!texture.name) {
  13376. return null;
  13377. }
  13378. if (texture instanceof BABYLON.CubeTexture) {
  13379. serializationObject.name = texture.name;
  13380. serializationObject.hasAlpha = texture.hasAlpha;
  13381. serializationObject.level = texture.level;
  13382. serializationObject.coordinatesMode = texture.coordinatesMode;
  13383. return serializationObject;
  13384. }
  13385. if (texture instanceof BABYLON.MirrorTexture) {
  13386. var mirrorTexture = texture;
  13387. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13388. serializationObject.renderList = [];
  13389. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13390. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13391. }
  13392. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13393. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13394. var renderTargetTexture = texture;
  13395. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13396. serializationObject.renderList = [];
  13397. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13398. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13399. }
  13400. }
  13401. var regularTexture = texture;
  13402. serializationObject.name = texture.name;
  13403. serializationObject.hasAlpha = texture.hasAlpha;
  13404. serializationObject.level = texture.level;
  13405. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13406. serializationObject.coordinatesMode = texture.coordinatesMode;
  13407. serializationObject.uOffset = regularTexture.uOffset;
  13408. serializationObject.vOffset = regularTexture.vOffset;
  13409. serializationObject.uScale = regularTexture.uScale;
  13410. serializationObject.vScale = regularTexture.vScale;
  13411. serializationObject.uAng = regularTexture.uAng;
  13412. serializationObject.vAng = regularTexture.vAng;
  13413. serializationObject.wAng = regularTexture.wAng;
  13414. serializationObject.wrapU = texture.wrapU;
  13415. serializationObject.wrapV = texture.wrapV;
  13416. appendAnimations(texture, serializationObject);
  13417. return serializationObject;
  13418. };
  13419. var serializeSkeleton = function (skeleton) {
  13420. var serializationObject = {};
  13421. serializationObject.name = skeleton.name;
  13422. serializationObject.id = skeleton.id;
  13423. serializationObject.bones = [];
  13424. for (var index = 0; index < skeleton.bones.length; index++) {
  13425. var bone = skeleton.bones[index];
  13426. var serializedBone = {
  13427. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13428. name: bone.name,
  13429. matrix: bone.getLocalMatrix().toArray()
  13430. };
  13431. serializationObject.bones.push(serializedBone);
  13432. if (bone.animations && bone.animations.length > 0) {
  13433. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13434. }
  13435. }
  13436. return serializationObject;
  13437. };
  13438. var serializeParticleSystem = function (particleSystem) {
  13439. var serializationObject = {};
  13440. serializationObject.emitterId = particleSystem.emitter.id;
  13441. serializationObject.capacity = particleSystem.getCapacity();
  13442. if (particleSystem.particleTexture) {
  13443. serializationObject.textureName = particleSystem.particleTexture.name;
  13444. }
  13445. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13446. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13447. serializationObject.minSize = particleSystem.minSize;
  13448. serializationObject.maxSize = particleSystem.maxSize;
  13449. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13450. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13451. serializationObject.emitRate = particleSystem.emitRate;
  13452. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13453. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13454. serializationObject.gravity = particleSystem.gravity.asArray();
  13455. serializationObject.direction1 = particleSystem.direction1.asArray();
  13456. serializationObject.direction2 = particleSystem.direction2.asArray();
  13457. serializationObject.color1 = particleSystem.color1.asArray();
  13458. serializationObject.color2 = particleSystem.color2.asArray();
  13459. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13460. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13461. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13462. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13463. serializationObject.blendMode = particleSystem.blendMode;
  13464. return serializationObject;
  13465. };
  13466. var serializeLensFlareSystem = function (lensFlareSystem) {
  13467. var serializationObject = {};
  13468. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13469. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13470. serializationObject.flares = [];
  13471. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13472. var flare = lensFlareSystem.lensFlares[index];
  13473. serializationObject.flares.push({
  13474. size: flare.size,
  13475. position: flare.position,
  13476. color: flare.color.asArray(),
  13477. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13478. });
  13479. }
  13480. return serializationObject;
  13481. };
  13482. var serializeShadowGenerator = function (light) {
  13483. var serializationObject = {};
  13484. var shadowGenerator = light.getShadowGenerator();
  13485. serializationObject.lightId = light.id;
  13486. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13487. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13488. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13489. serializationObject.renderList = [];
  13490. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13491. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13492. serializationObject.renderList.push(mesh.id);
  13493. }
  13494. return serializationObject;
  13495. };
  13496. var serializedGeometries = [];
  13497. var serializeGeometry = function (geometry, serializationGeometries) {
  13498. if (serializedGeometries[geometry.id]) {
  13499. return;
  13500. }
  13501. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13502. serializationGeometries.boxes.push(serializeBox(geometry));
  13503. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13504. serializationGeometries.spheres.push(serializeSphere(geometry));
  13505. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13506. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13507. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13508. serializationGeometries.toruses.push(serializeTorus(geometry));
  13509. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13510. serializationGeometries.grounds.push(serializeGround(geometry));
  13511. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13512. serializationGeometries.planes.push(serializePlane(geometry));
  13513. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13514. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13515. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13516. throw new Error("Unknow primitive type");
  13517. } else {
  13518. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13519. }
  13520. serializedGeometries[geometry.id] = true;
  13521. };
  13522. var serializeGeometryBase = function (geometry) {
  13523. var serializationObject = {};
  13524. serializationObject.id = geometry.id;
  13525. if (BABYLON.Tags.HasTags(geometry)) {
  13526. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13527. }
  13528. return serializationObject;
  13529. };
  13530. var serializeVertexData = function (vertexData) {
  13531. var serializationObject = serializeGeometryBase(vertexData);
  13532. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13533. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13534. }
  13535. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13536. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13537. }
  13538. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13539. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13540. }
  13541. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13542. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13543. }
  13544. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13545. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13546. }
  13547. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13548. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13549. serializationObject.matricesIndices._isExpanded = true;
  13550. }
  13551. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13552. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13553. }
  13554. serializationObject.indices = vertexData.getIndices();
  13555. return serializationObject;
  13556. };
  13557. var serializePrimitive = function (primitive) {
  13558. var serializationObject = serializeGeometryBase(primitive);
  13559. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13560. return serializationObject;
  13561. };
  13562. var serializeBox = function (box) {
  13563. var serializationObject = serializePrimitive(box);
  13564. serializationObject.size = box.size;
  13565. return serializationObject;
  13566. };
  13567. var serializeSphere = function (sphere) {
  13568. var serializationObject = serializePrimitive(sphere);
  13569. serializationObject.segments = sphere.segments;
  13570. serializationObject.diameter = sphere.diameter;
  13571. return serializationObject;
  13572. };
  13573. var serializeCylinder = function (cylinder) {
  13574. var serializationObject = serializePrimitive(cylinder);
  13575. serializationObject.height = cylinder.height;
  13576. serializationObject.diameterTop = cylinder.diameterTop;
  13577. serializationObject.diameterBottom = cylinder.diameterBottom;
  13578. serializationObject.tessellation = cylinder.tessellation;
  13579. return serializationObject;
  13580. };
  13581. var serializeTorus = function (torus) {
  13582. var serializationObject = serializePrimitive(torus);
  13583. serializationObject.diameter = torus.diameter;
  13584. serializationObject.thickness = torus.thickness;
  13585. serializationObject.tessellation = torus.tessellation;
  13586. return serializationObject;
  13587. };
  13588. var serializeGround = function (ground) {
  13589. var serializationObject = serializePrimitive(ground);
  13590. serializationObject.width = ground.width;
  13591. serializationObject.height = ground.height;
  13592. serializationObject.subdivisions = ground.subdivisions;
  13593. return serializationObject;
  13594. };
  13595. var serializePlane = function (plane) {
  13596. var serializationObject = serializePrimitive(plane);
  13597. serializationObject.size = plane.size;
  13598. return serializationObject;
  13599. };
  13600. var serializeTorusKnot = function (torusKnot) {
  13601. var serializationObject = serializePrimitive(torusKnot);
  13602. serializationObject.radius = torusKnot.radius;
  13603. serializationObject.tube = torusKnot.tube;
  13604. serializationObject.radialSegments = torusKnot.radialSegments;
  13605. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13606. serializationObject.p = torusKnot.p;
  13607. serializationObject.q = torusKnot.q;
  13608. return serializationObject;
  13609. };
  13610. var serializeMesh = function (mesh, serializationScene) {
  13611. var serializationObject = {};
  13612. serializationObject.name = mesh.name;
  13613. serializationObject.id = mesh.id;
  13614. if (BABYLON.Tags.HasTags(mesh)) {
  13615. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13616. }
  13617. serializationObject.position = mesh.position.asArray();
  13618. if (mesh.rotationQuaternion) {
  13619. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13620. } else if (mesh.rotation) {
  13621. serializationObject.rotation = mesh.rotation.asArray();
  13622. }
  13623. serializationObject.scaling = mesh.scaling.asArray();
  13624. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13625. serializationObject.isEnabled = mesh.isEnabled();
  13626. serializationObject.isVisible = mesh.isVisible;
  13627. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13628. serializationObject.pickable = mesh.isPickable;
  13629. serializationObject.receiveShadows = mesh.receiveShadows;
  13630. serializationObject.billboardMode = mesh.billboardMode;
  13631. serializationObject.visibility = mesh.visibility;
  13632. serializationObject.checkCollisions = mesh.checkCollisions;
  13633. if (mesh.parent) {
  13634. serializationObject.parentId = mesh.parent.id;
  13635. }
  13636. var geometry = mesh._geometry;
  13637. if (geometry) {
  13638. var geometryId = geometry.id;
  13639. serializationObject.geometryId = geometryId;
  13640. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13641. serializeGeometry(geometry, serializationScene.geometries);
  13642. }
  13643. serializationObject.subMeshes = [];
  13644. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13645. var subMesh = mesh.subMeshes[subIndex];
  13646. serializationObject.subMeshes.push({
  13647. materialIndex: subMesh.materialIndex,
  13648. verticesStart: subMesh.verticesStart,
  13649. verticesCount: subMesh.verticesCount,
  13650. indexStart: subMesh.indexStart,
  13651. indexCount: subMesh.indexCount
  13652. });
  13653. }
  13654. }
  13655. if (mesh.material) {
  13656. serializationObject.materialId = mesh.material.id;
  13657. } else {
  13658. mesh.material = null;
  13659. }
  13660. if (mesh.skeleton) {
  13661. serializationObject.skeletonId = mesh.skeleton.id;
  13662. }
  13663. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13664. serializationObject.physicsMass = mesh.getPhysicsMass();
  13665. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13666. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13667. switch (mesh.getPhysicsImpostor()) {
  13668. case BABYLON.PhysicsEngine.BoxImpostor:
  13669. serializationObject.physicsImpostor = 1;
  13670. break;
  13671. case BABYLON.PhysicsEngine.SphereImpostor:
  13672. serializationObject.physicsImpostor = 2;
  13673. break;
  13674. }
  13675. }
  13676. serializationObject.instances = [];
  13677. for (var index = 0; index < mesh.instances.length; index++) {
  13678. var instance = mesh.instances[index];
  13679. var serializationInstance = {
  13680. name: instance.name,
  13681. position: instance.position,
  13682. rotation: instance.rotation,
  13683. rotationQuaternion: instance.rotationQuaternion,
  13684. scaling: instance.scaling
  13685. };
  13686. serializationObject.instances.push(serializationInstance);
  13687. appendAnimations(instance, serializationInstance);
  13688. }
  13689. appendAnimations(mesh, serializationObject);
  13690. serializationObject.layerMask = mesh.layerMask;
  13691. return serializationObject;
  13692. };
  13693. var SceneSerializer = (function () {
  13694. function SceneSerializer() {
  13695. }
  13696. SceneSerializer.Serialize = function (scene) {
  13697. var serializationObject = {};
  13698. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13699. serializationObject.autoClear = scene.autoClear;
  13700. serializationObject.clearColor = scene.clearColor.asArray();
  13701. serializationObject.ambientColor = scene.ambientColor.asArray();
  13702. serializationObject.gravity = scene.gravity.asArray();
  13703. if (scene.fogMode && scene.fogMode !== 0) {
  13704. serializationObject.fogMode = scene.fogMode;
  13705. serializationObject.fogColor = scene.fogColor.asArray();
  13706. serializationObject.fogStart = scene.fogStart;
  13707. serializationObject.fogEnd = scene.fogEnd;
  13708. serializationObject.fogDensity = scene.fogDensity;
  13709. }
  13710. serializationObject.lights = [];
  13711. for (var index = 0; index < scene.lights.length; index++) {
  13712. var light = scene.lights[index];
  13713. serializationObject.lights.push(serializeLight(light));
  13714. }
  13715. serializationObject.cameras = [];
  13716. for (index = 0; index < scene.cameras.length; index++) {
  13717. var camera = scene.cameras[index];
  13718. if (camera instanceof BABYLON.FreeCamera) {
  13719. serializationObject.cameras.push(serializeCamera(camera));
  13720. }
  13721. }
  13722. if (scene.activeCamera) {
  13723. serializationObject.activeCameraID = scene.activeCamera.id;
  13724. }
  13725. serializationObject.materials = [];
  13726. serializationObject.multiMaterials = [];
  13727. for (index = 0; index < scene.materials.length; index++) {
  13728. var material = scene.materials[index];
  13729. if (material instanceof BABYLON.StandardMaterial) {
  13730. serializationObject.materials.push(serializeMaterial(material));
  13731. } else if (material instanceof BABYLON.MultiMaterial) {
  13732. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13733. }
  13734. }
  13735. serializationObject.skeletons = [];
  13736. for (index = 0; index < scene.skeletons.length; index++) {
  13737. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13738. }
  13739. serializationObject.geometries = {};
  13740. serializationObject.geometries.boxes = [];
  13741. serializationObject.geometries.spheres = [];
  13742. serializationObject.geometries.cylinders = [];
  13743. serializationObject.geometries.toruses = [];
  13744. serializationObject.geometries.grounds = [];
  13745. serializationObject.geometries.planes = [];
  13746. serializationObject.geometries.torusKnots = [];
  13747. serializationObject.geometries.vertexData = [];
  13748. serializedGeometries = [];
  13749. var geometries = scene.getGeometries();
  13750. for (var index = 0; index < geometries.length; index++) {
  13751. var geometry = geometries[index];
  13752. if (geometry.isReady()) {
  13753. serializeGeometry(geometry, serializationObject.geometries);
  13754. }
  13755. }
  13756. serializationObject.meshes = [];
  13757. for (index = 0; index < scene.meshes.length; index++) {
  13758. var abstractMesh = scene.meshes[index];
  13759. if (abstractMesh instanceof BABYLON.Mesh) {
  13760. var mesh = abstractMesh;
  13761. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13762. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13763. }
  13764. }
  13765. }
  13766. serializationObject.particleSystems = [];
  13767. for (index = 0; index < scene.particleSystems.length; index++) {
  13768. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13769. }
  13770. serializationObject.lensFlareSystems = [];
  13771. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13772. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13773. }
  13774. serializationObject.shadowGenerators = [];
  13775. for (index = 0; index < scene.lights.length; index++) {
  13776. light = scene.lights[index];
  13777. if (light.getShadowGenerator()) {
  13778. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13779. }
  13780. }
  13781. return serializationObject;
  13782. };
  13783. return SceneSerializer;
  13784. })();
  13785. BABYLON.SceneSerializer = SceneSerializer;
  13786. })(BABYLON || (BABYLON = {}));
  13787. var BABYLON;
  13788. (function (BABYLON) {
  13789. var SceneLoader = (function () {
  13790. function SceneLoader() {
  13791. }
  13792. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13793. get: function () {
  13794. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13795. },
  13796. set: function (value) {
  13797. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13798. },
  13799. enumerable: true,
  13800. configurable: true
  13801. });
  13802. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13803. get: function () {
  13804. return SceneLoader._ShowLoadingScreen;
  13805. },
  13806. set: function (value) {
  13807. SceneLoader._ShowLoadingScreen = value;
  13808. },
  13809. enumerable: true,
  13810. configurable: true
  13811. });
  13812. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13813. var dotPosition = sceneFilename.lastIndexOf(".");
  13814. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13815. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13816. var plugin = this._registeredPlugins[index];
  13817. if (plugin.extensions.indexOf(extension) !== -1) {
  13818. return plugin;
  13819. }
  13820. }
  13821. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13822. };
  13823. SceneLoader.RegisterPlugin = function (plugin) {
  13824. plugin.extensions = plugin.extensions.toLowerCase();
  13825. SceneLoader._registeredPlugins.push(plugin);
  13826. };
  13827. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13828. var _this = this;
  13829. var manifestChecked = function (success) {
  13830. scene.database = database;
  13831. var plugin = _this._getPluginForFilename(sceneFilename);
  13832. var importMeshFromData = function (data) {
  13833. var meshes = [];
  13834. var particleSystems = [];
  13835. var skeletons = [];
  13836. try {
  13837. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  13838. if (onerror) {
  13839. onerror(scene);
  13840. }
  13841. return;
  13842. }
  13843. } catch (e) {
  13844. if (onerror) {
  13845. onerror(scene);
  13846. }
  13847. return;
  13848. }
  13849. if (onsuccess) {
  13850. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  13851. onsuccess(meshes, particleSystems, skeletons);
  13852. }
  13853. };
  13854. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13855. importMeshFromData(sceneFilename.substr(5));
  13856. return;
  13857. }
  13858. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  13859. importMeshFromData(data);
  13860. }, progressCallBack, database);
  13861. };
  13862. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13863. };
  13864. /**
  13865. * Load a scene
  13866. * @param rootUrl a string that defines the root url for scene and resources
  13867. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13868. * @param engine is the instance of BABYLON.Engine to use to create the scene
  13869. */
  13870. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  13871. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  13872. };
  13873. /**
  13874. * Append a scene
  13875. * @param rootUrl a string that defines the root url for scene and resources
  13876. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  13877. * @param scene is the instance of BABYLON.Scene to append to
  13878. */
  13879. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13880. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  13881. var database;
  13882. if (SceneLoader.ShowLoadingScreen) {
  13883. scene.getEngine().displayLoadingUI();
  13884. }
  13885. var loadSceneFromData = function (data) {
  13886. scene.database = database;
  13887. if (!plugin.load(scene, data, rootUrl)) {
  13888. if (onerror) {
  13889. onerror(scene);
  13890. }
  13891. scene.getEngine().hideLoadingUI();
  13892. return;
  13893. }
  13894. if (onsuccess) {
  13895. onsuccess(scene);
  13896. }
  13897. if (SceneLoader.ShowLoadingScreen) {
  13898. scene.executeWhenReady(function () {
  13899. scene.getEngine().hideLoadingUI();
  13900. });
  13901. }
  13902. };
  13903. var manifestChecked = function (success) {
  13904. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  13905. };
  13906. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  13907. loadSceneFromData(sceneFilename.substr(5));
  13908. return;
  13909. }
  13910. if (rootUrl.indexOf("file:") === -1) {
  13911. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  13912. } else {
  13913. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  13914. }
  13915. };
  13916. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  13917. SceneLoader._ShowLoadingScreen = true;
  13918. SceneLoader._registeredPlugins = new Array();
  13919. return SceneLoader;
  13920. })();
  13921. BABYLON.SceneLoader = SceneLoader;
  13922. ;
  13923. })(BABYLON || (BABYLON = {}));
  13924. var BABYLON;
  13925. (function (BABYLON) {
  13926. (function (Internals) {
  13927. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  13928. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  13929. texture.name = parsedTexture.name;
  13930. texture.hasAlpha = parsedTexture.hasAlpha;
  13931. texture.level = parsedTexture.level;
  13932. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13933. return texture;
  13934. };
  13935. var loadTexture = function (rootUrl, parsedTexture, scene) {
  13936. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  13937. return null;
  13938. }
  13939. if (parsedTexture.isCube) {
  13940. return loadCubeTexture(rootUrl, parsedTexture, scene);
  13941. }
  13942. var texture;
  13943. if (parsedTexture.mirrorPlane) {
  13944. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13945. texture._waitingRenderList = parsedTexture.renderList;
  13946. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  13947. } else if (parsedTexture.isRenderTarget) {
  13948. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  13949. texture._waitingRenderList = parsedTexture.renderList;
  13950. } else {
  13951. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  13952. }
  13953. texture.name = parsedTexture.name;
  13954. texture.hasAlpha = parsedTexture.hasAlpha;
  13955. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  13956. texture.level = parsedTexture.level;
  13957. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  13958. texture.coordinatesMode = parsedTexture.coordinatesMode;
  13959. texture.uOffset = parsedTexture.uOffset;
  13960. texture.vOffset = parsedTexture.vOffset;
  13961. texture.uScale = parsedTexture.uScale;
  13962. texture.vScale = parsedTexture.vScale;
  13963. texture.uAng = parsedTexture.uAng;
  13964. texture.vAng = parsedTexture.vAng;
  13965. texture.wAng = parsedTexture.wAng;
  13966. texture.wrapU = parsedTexture.wrapU;
  13967. texture.wrapV = parsedTexture.wrapV;
  13968. if (parsedTexture.animations) {
  13969. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  13970. var parsedAnimation = parsedTexture.animations[animationIndex];
  13971. texture.animations.push(parseAnimation(parsedAnimation));
  13972. }
  13973. }
  13974. return texture;
  13975. };
  13976. var parseSkeleton = function (parsedSkeleton, scene) {
  13977. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  13978. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  13979. var parsedBone = parsedSkeleton.bones[index];
  13980. var parentBone = null;
  13981. if (parsedBone.parentBoneIndex > -1) {
  13982. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  13983. }
  13984. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  13985. if (parsedBone.animation) {
  13986. bone.animations.push(parseAnimation(parsedBone.animation));
  13987. }
  13988. }
  13989. return skeleton;
  13990. };
  13991. var parseFresnelParameters = function (parsedFresnelParameters) {
  13992. var fresnelParameters = new BABYLON.FresnelParameters();
  13993. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  13994. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  13995. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  13996. fresnelParameters.bias = parsedFresnelParameters.bias;
  13997. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  13998. return fresnelParameters;
  13999. };
  14000. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14001. var material;
  14002. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14003. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14004. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14005. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14006. material.specularPower = parsedMaterial.specularPower;
  14007. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14008. material.alpha = parsedMaterial.alpha;
  14009. material.id = parsedMaterial.id;
  14010. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14011. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14012. material.wireframe = parsedMaterial.wireframe;
  14013. if (parsedMaterial.diffuseTexture) {
  14014. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14015. }
  14016. if (parsedMaterial.diffuseFresnelParameters) {
  14017. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14018. }
  14019. if (parsedMaterial.ambientTexture) {
  14020. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14021. }
  14022. if (parsedMaterial.opacityTexture) {
  14023. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14024. }
  14025. if (parsedMaterial.opacityFresnelParameters) {
  14026. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14027. }
  14028. if (parsedMaterial.reflectionTexture) {
  14029. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14030. }
  14031. if (parsedMaterial.reflectionFresnelParameters) {
  14032. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14033. }
  14034. if (parsedMaterial.emissiveTexture) {
  14035. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14036. }
  14037. if (parsedMaterial.emissiveFresnelParameters) {
  14038. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14039. }
  14040. if (parsedMaterial.specularTexture) {
  14041. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14042. }
  14043. if (parsedMaterial.bumpTexture) {
  14044. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14045. }
  14046. return material;
  14047. };
  14048. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14049. for (var index = 0; index < parsedData.materials.length; index++) {
  14050. var parsedMaterial = parsedData.materials[index];
  14051. if (parsedMaterial.id === id) {
  14052. return parseMaterial(parsedMaterial, scene, rootUrl);
  14053. }
  14054. }
  14055. return null;
  14056. };
  14057. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14058. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14059. multiMaterial.id = parsedMultiMaterial.id;
  14060. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14061. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14062. var subMatId = parsedMultiMaterial.materials[matIndex];
  14063. if (subMatId) {
  14064. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14065. } else {
  14066. multiMaterial.subMaterials.push(null);
  14067. }
  14068. }
  14069. return multiMaterial;
  14070. };
  14071. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14072. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14073. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14074. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14075. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14076. var parsedFlare = parsedLensFlareSystem.flares[index];
  14077. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14078. }
  14079. return lensFlareSystem;
  14080. };
  14081. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14082. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14083. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14084. if (parsedParticleSystem.textureName) {
  14085. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14086. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14087. }
  14088. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14089. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14090. particleSystem.minSize = parsedParticleSystem.minSize;
  14091. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14092. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14093. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14094. particleSystem.emitter = emitter;
  14095. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14096. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14097. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14098. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14099. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14100. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14101. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14102. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14103. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14104. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14105. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14106. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14107. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14108. particleSystem.start();
  14109. return particleSystem;
  14110. };
  14111. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14112. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14113. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14114. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14115. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14116. shadowGenerator.getShadowMap().renderList.push(mesh);
  14117. }
  14118. if (parsedShadowGenerator.usePoissonSampling) {
  14119. shadowGenerator.usePoissonSampling = true;
  14120. } else {
  14121. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14122. }
  14123. return shadowGenerator;
  14124. };
  14125. var parseAnimation = function (parsedAnimation) {
  14126. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14127. var dataType = parsedAnimation.dataType;
  14128. var keys = [];
  14129. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14130. var key = parsedAnimation.keys[index];
  14131. var data;
  14132. switch (dataType) {
  14133. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14134. data = key.values[0];
  14135. break;
  14136. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14137. data = BABYLON.Quaternion.FromArray(key.values);
  14138. break;
  14139. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14140. data = BABYLON.Matrix.FromArray(key.values);
  14141. break;
  14142. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14143. default:
  14144. data = BABYLON.Vector3.FromArray(key.values);
  14145. break;
  14146. }
  14147. keys.push({
  14148. frame: key.frame,
  14149. value: data
  14150. });
  14151. }
  14152. animation.setKeys(keys);
  14153. return animation;
  14154. };
  14155. var parseLight = function (parsedLight, scene) {
  14156. var light;
  14157. switch (parsedLight.type) {
  14158. case 0:
  14159. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14160. break;
  14161. case 1:
  14162. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14163. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14164. break;
  14165. case 2:
  14166. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14167. break;
  14168. case 3:
  14169. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14170. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14171. break;
  14172. }
  14173. light.id = parsedLight.id;
  14174. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14175. if (parsedLight.intensity !== undefined) {
  14176. light.intensity = parsedLight.intensity;
  14177. }
  14178. if (parsedLight.range) {
  14179. light.range = parsedLight.range;
  14180. }
  14181. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14182. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14183. if (parsedLight.excludedMeshesIds) {
  14184. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14185. }
  14186. if (parsedLight.includedOnlyMeshesIds) {
  14187. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14188. }
  14189. if (parsedLight.animations) {
  14190. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14191. var parsedAnimation = parsedLight.animations[animationIndex];
  14192. light.animations.push(parseAnimation(parsedAnimation));
  14193. }
  14194. }
  14195. if (parsedLight.autoAnimate) {
  14196. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14197. }
  14198. };
  14199. var parseCamera = function (parsedCamera, scene) {
  14200. var camera = new BABYLON.FreeCamera(parsedCamera.name, BABYLON.Vector3.FromArray(parsedCamera.position), scene);
  14201. camera.id = parsedCamera.id;
  14202. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14203. if (parsedCamera.parentId) {
  14204. camera._waitingParentId = parsedCamera.parentId;
  14205. }
  14206. if (parsedCamera.target) {
  14207. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14208. } else {
  14209. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14210. }
  14211. if (parsedCamera.lockedTargetId) {
  14212. camera._waitingLockedTargetId = parsedCamera.lockedTargetId;
  14213. }
  14214. camera.fov = parsedCamera.fov;
  14215. camera.minZ = parsedCamera.minZ;
  14216. camera.maxZ = parsedCamera.maxZ;
  14217. camera.speed = parsedCamera.speed;
  14218. camera.inertia = parsedCamera.inertia;
  14219. camera.checkCollisions = parsedCamera.checkCollisions;
  14220. camera.applyGravity = parsedCamera.applyGravity;
  14221. if (parsedCamera.ellipsoid) {
  14222. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14223. }
  14224. if (parsedCamera.animations) {
  14225. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14226. var parsedAnimation = parsedCamera.animations[animationIndex];
  14227. camera.animations.push(parseAnimation(parsedAnimation));
  14228. }
  14229. }
  14230. if (parsedCamera.autoAnimate) {
  14231. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14232. }
  14233. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14234. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14235. } else {
  14236. camera.layerMask = 0xFFFFFFFF;
  14237. }
  14238. return camera;
  14239. };
  14240. var parseGeometry = function (parsedGeometry, scene) {
  14241. var id = parsedGeometry.id;
  14242. return scene.getGeometryByID(id);
  14243. };
  14244. var parseBox = function (parsedBox, scene) {
  14245. if (parseGeometry(parsedBox, scene)) {
  14246. return null;
  14247. }
  14248. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14249. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14250. scene.pushGeometry(box, true);
  14251. return box;
  14252. };
  14253. var parseSphere = function (parsedSphere, scene) {
  14254. if (parseGeometry(parsedSphere, scene)) {
  14255. return null;
  14256. }
  14257. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14258. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14259. scene.pushGeometry(sphere, true);
  14260. return sphere;
  14261. };
  14262. var parseCylinder = function (parsedCylinder, scene) {
  14263. if (parseGeometry(parsedCylinder, scene)) {
  14264. return null;
  14265. }
  14266. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14267. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14268. scene.pushGeometry(cylinder, true);
  14269. return cylinder;
  14270. };
  14271. var parseTorus = function (parsedTorus, scene) {
  14272. if (parseGeometry(parsedTorus, scene)) {
  14273. return null;
  14274. }
  14275. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14276. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14277. scene.pushGeometry(torus, true);
  14278. return torus;
  14279. };
  14280. var parseGround = function (parsedGround, scene) {
  14281. if (parseGeometry(parsedGround, scene)) {
  14282. return null;
  14283. }
  14284. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14285. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14286. scene.pushGeometry(ground, true);
  14287. return ground;
  14288. };
  14289. var parsePlane = function (parsedPlane, scene) {
  14290. if (parseGeometry(parsedPlane, scene)) {
  14291. return null;
  14292. }
  14293. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14294. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14295. scene.pushGeometry(plane, true);
  14296. return plane;
  14297. };
  14298. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14299. if (parseGeometry(parsedTorusKnot, scene)) {
  14300. return null;
  14301. }
  14302. 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);
  14303. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14304. scene.pushGeometry(torusKnot, true);
  14305. return torusKnot;
  14306. };
  14307. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14308. if (parseGeometry(parsedVertexData, scene)) {
  14309. return null;
  14310. }
  14311. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14312. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14313. if (parsedVertexData.delayLoadingFile) {
  14314. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14315. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14316. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14317. geometry._delayInfo = [];
  14318. if (parsedVertexData.hasUVs) {
  14319. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14320. }
  14321. if (parsedVertexData.hasUVs2) {
  14322. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14323. }
  14324. if (parsedVertexData.hasColors) {
  14325. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14326. }
  14327. if (parsedVertexData.hasMatricesIndices) {
  14328. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14329. }
  14330. if (parsedVertexData.hasMatricesWeights) {
  14331. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14332. }
  14333. geometry._delayLoadingFunction = importVertexData;
  14334. } else {
  14335. importVertexData(parsedVertexData, geometry);
  14336. }
  14337. scene.pushGeometry(geometry, true);
  14338. return geometry;
  14339. };
  14340. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14341. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14342. mesh.id = parsedMesh.id;
  14343. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14344. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14345. if (parsedMesh.rotationQuaternion) {
  14346. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14347. } else if (parsedMesh.rotation) {
  14348. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14349. }
  14350. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14351. if (parsedMesh.localMatrix) {
  14352. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14353. } else if (parsedMesh.pivotMatrix) {
  14354. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14355. }
  14356. mesh.setEnabled(parsedMesh.isEnabled);
  14357. mesh.isVisible = parsedMesh.isVisible;
  14358. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14359. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14360. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14361. if (parsedMesh.pickable !== undefined) {
  14362. mesh.isPickable = parsedMesh.pickable;
  14363. }
  14364. mesh.receiveShadows = parsedMesh.receiveShadows;
  14365. mesh.billboardMode = parsedMesh.billboardMode;
  14366. if (parsedMesh.visibility !== undefined) {
  14367. mesh.visibility = parsedMesh.visibility;
  14368. }
  14369. mesh.checkCollisions = parsedMesh.checkCollisions;
  14370. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14371. if (parsedMesh.parentId) {
  14372. mesh.parent = scene.getLastEntryByID(parsedMesh.parentId);
  14373. }
  14374. if (parsedMesh.delayLoadingFile) {
  14375. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14376. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14377. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14378. if (parsedMesh._binaryInfo) {
  14379. mesh._binaryInfo = parsedMesh._binaryInfo;
  14380. }
  14381. mesh._delayInfo = [];
  14382. if (parsedMesh.hasUVs) {
  14383. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14384. }
  14385. if (parsedMesh.hasUVs2) {
  14386. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14387. }
  14388. if (parsedMesh.hasColors) {
  14389. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14390. }
  14391. if (parsedMesh.hasMatricesIndices) {
  14392. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14393. }
  14394. if (parsedMesh.hasMatricesWeights) {
  14395. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14396. }
  14397. mesh._delayLoadingFunction = importGeometry;
  14398. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14399. mesh._checkDelayState();
  14400. }
  14401. } else {
  14402. importGeometry(parsedMesh, mesh);
  14403. }
  14404. if (parsedMesh.materialId) {
  14405. mesh.setMaterialByID(parsedMesh.materialId);
  14406. } else {
  14407. mesh.material = null;
  14408. }
  14409. if (parsedMesh.skeletonId > -1) {
  14410. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14411. }
  14412. if (parsedMesh.physicsImpostor) {
  14413. if (!scene.isPhysicsEnabled()) {
  14414. scene.enablePhysics();
  14415. }
  14416. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14417. }
  14418. if (parsedMesh.animations) {
  14419. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14420. var parsedAnimation = parsedMesh.animations[animationIndex];
  14421. mesh.animations.push(parseAnimation(parsedAnimation));
  14422. }
  14423. }
  14424. if (parsedMesh.autoAnimate) {
  14425. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14426. }
  14427. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14428. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14429. } else {
  14430. mesh.layerMask = 0xFFFFFFFF;
  14431. }
  14432. if (parsedMesh.instances) {
  14433. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14434. var parsedInstance = parsedMesh.instances[index];
  14435. var instance = mesh.createInstance(parsedInstance.name);
  14436. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14437. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14438. if (parsedInstance.rotationQuaternion) {
  14439. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14440. } else if (parsedInstance.rotation) {
  14441. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14442. }
  14443. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14444. instance.checkCollisions = mesh.checkCollisions;
  14445. if (parsedMesh.animations) {
  14446. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14447. parsedAnimation = parsedMesh.animations[animationIndex];
  14448. instance.animations.push(parseAnimation(parsedAnimation));
  14449. }
  14450. }
  14451. }
  14452. }
  14453. return mesh;
  14454. };
  14455. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14456. names = (names instanceof Array) ? names : [names];
  14457. for (var i in names) {
  14458. if (mesh.name === names[i]) {
  14459. hierarchyIds.push(mesh.id);
  14460. return true;
  14461. }
  14462. }
  14463. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14464. hierarchyIds.push(mesh.id);
  14465. return true;
  14466. }
  14467. return false;
  14468. };
  14469. var importVertexData = function (parsedVertexData, geometry) {
  14470. var vertexData = new BABYLON.VertexData();
  14471. var positions = parsedVertexData.positions;
  14472. if (positions) {
  14473. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14474. }
  14475. var normals = parsedVertexData.normals;
  14476. if (normals) {
  14477. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14478. }
  14479. var uvs = parsedVertexData.uvs;
  14480. if (uvs) {
  14481. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14482. }
  14483. var uv2s = parsedVertexData.uv2s;
  14484. if (uv2s) {
  14485. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14486. }
  14487. var colors = parsedVertexData.colors;
  14488. if (colors) {
  14489. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14490. }
  14491. var matricesIndices = parsedVertexData.matricesIndices;
  14492. if (matricesIndices) {
  14493. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14494. }
  14495. var matricesWeights = parsedVertexData.matricesWeights;
  14496. if (matricesWeights) {
  14497. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14498. }
  14499. var indices = parsedVertexData.indices;
  14500. if (indices) {
  14501. vertexData.indices = indices;
  14502. }
  14503. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14504. };
  14505. var importGeometry = function (parsedGeometry, mesh) {
  14506. var scene = mesh.getScene();
  14507. var geometryId = parsedGeometry.geometryId;
  14508. if (geometryId) {
  14509. var geometry = scene.getGeometryByID(geometryId);
  14510. if (geometry) {
  14511. geometry.applyToMesh(mesh);
  14512. }
  14513. } else if (parsedGeometry instanceof ArrayBuffer) {
  14514. var binaryInfo = mesh._binaryInfo;
  14515. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  14516. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  14517. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  14518. }
  14519. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  14520. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  14521. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  14522. }
  14523. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  14524. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  14525. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  14526. }
  14527. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  14528. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  14529. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  14530. }
  14531. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  14532. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  14533. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  14534. }
  14535. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  14536. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  14537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  14538. }
  14539. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  14540. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  14541. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  14542. }
  14543. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  14544. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  14545. mesh.setIndices(indicesData);
  14546. }
  14547. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  14548. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  14549. mesh.subMeshes = [];
  14550. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  14551. var materialIndex = subMeshesData[(i * 5) + 0];
  14552. var verticesStart = subMeshesData[(i * 5) + 1];
  14553. var verticesCount = subMeshesData[(i * 5) + 2];
  14554. var indexStart = subMeshesData[(i * 5) + 3];
  14555. var indexCount = subMeshesData[(i * 5) + 4];
  14556. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  14557. }
  14558. }
  14559. return;
  14560. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14561. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14562. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14563. if (parsedGeometry.uvs) {
  14564. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14565. }
  14566. if (parsedGeometry.uvs2) {
  14567. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14568. }
  14569. if (parsedGeometry.colors) {
  14570. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14571. }
  14572. if (parsedGeometry.matricesIndices) {
  14573. if (!parsedGeometry.matricesIndices._isExpanded) {
  14574. var floatIndices = [];
  14575. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14576. var matricesIndex = parsedGeometry.matricesIndices[i];
  14577. floatIndices.push(matricesIndex & 0x000000FF);
  14578. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14579. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14580. floatIndices.push(matricesIndex >> 24);
  14581. }
  14582. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14583. } else {
  14584. delete parsedGeometry.matricesIndices._isExpanded;
  14585. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14586. }
  14587. }
  14588. if (parsedGeometry.matricesWeights) {
  14589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14590. }
  14591. mesh.setIndices(parsedGeometry.indices);
  14592. }
  14593. if (parsedGeometry.subMeshes) {
  14594. mesh.subMeshes = [];
  14595. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14596. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14597. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14598. }
  14599. }
  14600. if (mesh._shouldGenerateFlatShading) {
  14601. mesh.convertToFlatShadedMesh();
  14602. delete mesh._shouldGenerateFlatShading;
  14603. }
  14604. mesh.computeWorldMatrix(true);
  14605. if (scene._selectionOctree) {
  14606. scene._selectionOctree.addMesh(mesh);
  14607. }
  14608. };
  14609. BABYLON.SceneLoader.RegisterPlugin({
  14610. extensions: ".babylon",
  14611. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14612. var parsedData = JSON.parse(data);
  14613. var loadedSkeletonsIds = [];
  14614. var loadedMaterialsIds = [];
  14615. var hierarchyIds = [];
  14616. for (var index = 0; index < parsedData.meshes.length; index++) {
  14617. var parsedMesh = parsedData.meshes[index];
  14618. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14619. if (meshesNames instanceof Array) {
  14620. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14621. }
  14622. if (parsedMesh.materialId) {
  14623. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14624. if (!materialFound) {
  14625. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14626. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14627. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14628. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14629. var subMatId = parsedMultiMaterial.materials[matIndex];
  14630. loadedMaterialsIds.push(subMatId);
  14631. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14632. }
  14633. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14634. parseMultiMaterial(parsedMultiMaterial, scene);
  14635. materialFound = true;
  14636. break;
  14637. }
  14638. }
  14639. }
  14640. if (!materialFound) {
  14641. loadedMaterialsIds.push(parsedMesh.materialId);
  14642. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14643. }
  14644. }
  14645. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14646. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14647. if (!skeletonAlreadyLoaded) {
  14648. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14649. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14650. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14651. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14652. loadedSkeletonsIds.push(parsedSkeleton.id);
  14653. }
  14654. }
  14655. }
  14656. }
  14657. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14658. meshes.push(mesh);
  14659. }
  14660. }
  14661. if (parsedData.particleSystems) {
  14662. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14663. var parsedParticleSystem = parsedData.particleSystems[index];
  14664. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14665. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14666. }
  14667. }
  14668. }
  14669. return true;
  14670. },
  14671. load: function (scene, data, rootUrl) {
  14672. var parsedData = JSON.parse(data);
  14673. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14674. scene.autoClear = parsedData.autoClear;
  14675. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14676. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14677. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14678. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14679. scene.fogMode = parsedData.fogMode;
  14680. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14681. scene.fogStart = parsedData.fogStart;
  14682. scene.fogEnd = parsedData.fogEnd;
  14683. scene.fogDensity = parsedData.fogDensity;
  14684. }
  14685. for (var index = 0; index < parsedData.lights.length; index++) {
  14686. var parsedLight = parsedData.lights[index];
  14687. parseLight(parsedLight, scene);
  14688. }
  14689. for (index = 0; index < parsedData.cameras.length; index++) {
  14690. var parsedCamera = parsedData.cameras[index];
  14691. parseCamera(parsedCamera, scene);
  14692. }
  14693. if (parsedData.activeCameraID) {
  14694. scene.setActiveCameraByID(parsedData.activeCameraID);
  14695. }
  14696. if (parsedData.materials) {
  14697. for (index = 0; index < parsedData.materials.length; index++) {
  14698. var parsedMaterial = parsedData.materials[index];
  14699. parseMaterial(parsedMaterial, scene, rootUrl);
  14700. }
  14701. }
  14702. if (parsedData.multiMaterials) {
  14703. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14704. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14705. parseMultiMaterial(parsedMultiMaterial, scene);
  14706. }
  14707. }
  14708. if (parsedData.skeletons) {
  14709. for (index = 0; index < parsedData.skeletons.length; index++) {
  14710. var parsedSkeleton = parsedData.skeletons[index];
  14711. parseSkeleton(parsedSkeleton, scene);
  14712. }
  14713. }
  14714. var geometries = parsedData.geometries;
  14715. if (geometries) {
  14716. var boxes = geometries.boxes;
  14717. if (boxes) {
  14718. for (index = 0; index < boxes.length; index++) {
  14719. var parsedBox = boxes[index];
  14720. parseBox(parsedBox, scene);
  14721. }
  14722. }
  14723. var spheres = geometries.spheres;
  14724. if (spheres) {
  14725. for (index = 0; index < spheres.length; index++) {
  14726. var parsedSphere = spheres[index];
  14727. parseSphere(parsedSphere, scene);
  14728. }
  14729. }
  14730. var cylinders = geometries.cylinders;
  14731. if (cylinders) {
  14732. for (index = 0; index < cylinders.length; index++) {
  14733. var parsedCylinder = cylinders[index];
  14734. parseCylinder(parsedCylinder, scene);
  14735. }
  14736. }
  14737. var toruses = geometries.toruses;
  14738. if (toruses) {
  14739. for (index = 0; index < toruses.length; index++) {
  14740. var parsedTorus = toruses[index];
  14741. parseTorus(parsedTorus, scene);
  14742. }
  14743. }
  14744. var grounds = geometries.grounds;
  14745. if (grounds) {
  14746. for (index = 0; index < grounds.length; index++) {
  14747. var parsedGround = grounds[index];
  14748. parseGround(parsedGround, scene);
  14749. }
  14750. }
  14751. var planes = geometries.planes;
  14752. if (planes) {
  14753. for (index = 0; index < planes.length; index++) {
  14754. var parsedPlane = planes[index];
  14755. parsePlane(parsedPlane, scene);
  14756. }
  14757. }
  14758. var torusKnots = geometries.torusKnots;
  14759. if (torusKnots) {
  14760. for (index = 0; index < torusKnots.length; index++) {
  14761. var parsedTorusKnot = torusKnots[index];
  14762. parseTorusKnot(parsedTorusKnot, scene);
  14763. }
  14764. }
  14765. var vertexData = geometries.vertexData;
  14766. if (vertexData) {
  14767. for (index = 0; index < vertexData.length; index++) {
  14768. var parsedVertexData = vertexData[index];
  14769. parseVertexData(parsedVertexData, scene, rootUrl);
  14770. }
  14771. }
  14772. }
  14773. for (index = 0; index < parsedData.meshes.length; index++) {
  14774. var parsedMesh = parsedData.meshes[index];
  14775. parseMesh(parsedMesh, scene, rootUrl);
  14776. }
  14777. for (index = 0; index < scene.cameras.length; index++) {
  14778. var camera = scene.cameras[index];
  14779. if (camera._waitingParentId) {
  14780. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14781. delete camera._waitingParentId;
  14782. }
  14783. if (camera instanceof BABYLON.FreeCamera) {
  14784. var freecamera = camera;
  14785. if (freecamera._waitingLockedTargetId) {
  14786. freecamera.lockedTarget = scene.getLastEntryByID(freecamera._waitingLockedTargetId);
  14787. delete freecamera._waitingLockedTargetId;
  14788. }
  14789. }
  14790. }
  14791. if (parsedData.particleSystems) {
  14792. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14793. var parsedParticleSystem = parsedData.particleSystems[index];
  14794. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  14795. }
  14796. }
  14797. if (parsedData.lensFlareSystems) {
  14798. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  14799. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  14800. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  14801. }
  14802. }
  14803. if (parsedData.shadowGenerators) {
  14804. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  14805. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  14806. parseShadowGenerator(parsedShadowGenerator, scene);
  14807. }
  14808. }
  14809. return true;
  14810. }
  14811. });
  14812. })(BABYLON.Internals || (BABYLON.Internals = {}));
  14813. var Internals = BABYLON.Internals;
  14814. })(BABYLON || (BABYLON = {}));
  14815. var BABYLON;
  14816. (function (BABYLON) {
  14817. var currentCSGMeshId = 0;
  14818. var Vertex = (function () {
  14819. function Vertex(pos, normal, uv) {
  14820. this.pos = pos;
  14821. this.normal = normal;
  14822. this.uv = uv;
  14823. }
  14824. Vertex.prototype.clone = function () {
  14825. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  14826. };
  14827. Vertex.prototype.flip = function () {
  14828. this.normal = this.normal.scale(-1);
  14829. };
  14830. Vertex.prototype.interpolate = function (other, t) {
  14831. 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));
  14832. };
  14833. return Vertex;
  14834. })();
  14835. var Plane = (function () {
  14836. function Plane(normal, w) {
  14837. this.normal = normal;
  14838. this.w = w;
  14839. }
  14840. Plane.FromPoints = function (a, b, c) {
  14841. var v0 = c.subtract(a);
  14842. var v1 = b.subtract(a);
  14843. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  14844. return null;
  14845. }
  14846. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  14847. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  14848. };
  14849. Plane.prototype.clone = function () {
  14850. return new Plane(this.normal.clone(), this.w);
  14851. };
  14852. Plane.prototype.flip = function () {
  14853. this.normal.scaleInPlace(-1);
  14854. this.w = -this.w;
  14855. };
  14856. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  14857. var COPLANAR = 0;
  14858. var FRONT = 1;
  14859. var BACK = 2;
  14860. var SPANNING = 3;
  14861. var polygonType = 0;
  14862. var types = [];
  14863. for (var i = 0; i < polygon.vertices.length; i++) {
  14864. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  14865. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  14866. polygonType |= type;
  14867. types.push(type);
  14868. }
  14869. switch (polygonType) {
  14870. case COPLANAR:
  14871. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  14872. break;
  14873. case FRONT:
  14874. front.push(polygon);
  14875. break;
  14876. case BACK:
  14877. back.push(polygon);
  14878. break;
  14879. case SPANNING:
  14880. var f = [], b = [];
  14881. for (i = 0; i < polygon.vertices.length; i++) {
  14882. var j = (i + 1) % polygon.vertices.length;
  14883. var ti = types[i], tj = types[j];
  14884. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  14885. if (ti != BACK)
  14886. f.push(vi);
  14887. if (ti != FRONT)
  14888. b.push(ti != BACK ? vi.clone() : vi);
  14889. if ((ti | tj) == SPANNING) {
  14890. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  14891. var v = vi.interpolate(vj, t);
  14892. f.push(v);
  14893. b.push(v.clone());
  14894. }
  14895. }
  14896. if (f.length >= 3) {
  14897. var poly = new Polygon(f, polygon.shared);
  14898. if (poly.plane)
  14899. front.push(poly);
  14900. }
  14901. if (b.length >= 3) {
  14902. poly = new Polygon(b, polygon.shared);
  14903. if (poly.plane)
  14904. back.push(poly);
  14905. }
  14906. break;
  14907. }
  14908. };
  14909. Plane.EPSILON = 1e-5;
  14910. return Plane;
  14911. })();
  14912. var Polygon = (function () {
  14913. function Polygon(vertices, shared) {
  14914. this.vertices = vertices;
  14915. this.shared = shared;
  14916. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  14917. }
  14918. Polygon.prototype.clone = function () {
  14919. var vertices = this.vertices.map(function (v) {
  14920. return v.clone();
  14921. });
  14922. return new Polygon(vertices, this.shared);
  14923. };
  14924. Polygon.prototype.flip = function () {
  14925. this.vertices.reverse().map(function (v) {
  14926. v.flip();
  14927. });
  14928. this.plane.flip();
  14929. };
  14930. return Polygon;
  14931. })();
  14932. var Node = (function () {
  14933. function Node(polygons) {
  14934. this.plane = null;
  14935. this.front = null;
  14936. this.back = null;
  14937. this.polygons = [];
  14938. if (polygons) {
  14939. this.build(polygons);
  14940. }
  14941. }
  14942. Node.prototype.clone = function () {
  14943. var node = new Node();
  14944. node.plane = this.plane && this.plane.clone();
  14945. node.front = this.front && this.front.clone();
  14946. node.back = this.back && this.back.clone();
  14947. node.polygons = this.polygons.map(function (p) {
  14948. return p.clone();
  14949. });
  14950. return node;
  14951. };
  14952. Node.prototype.invert = function () {
  14953. for (var i = 0; i < this.polygons.length; i++) {
  14954. this.polygons[i].flip();
  14955. }
  14956. if (this.plane) {
  14957. this.plane.flip();
  14958. }
  14959. if (this.front) {
  14960. this.front.invert();
  14961. }
  14962. if (this.back) {
  14963. this.back.invert();
  14964. }
  14965. var temp = this.front;
  14966. this.front = this.back;
  14967. this.back = temp;
  14968. };
  14969. Node.prototype.clipPolygons = function (polygons) {
  14970. if (!this.plane)
  14971. return polygons.slice();
  14972. var front = [], back = [];
  14973. for (var i = 0; i < polygons.length; i++) {
  14974. this.plane.splitPolygon(polygons[i], front, back, front, back);
  14975. }
  14976. if (this.front) {
  14977. front = this.front.clipPolygons(front);
  14978. }
  14979. if (this.back) {
  14980. back = this.back.clipPolygons(back);
  14981. } else {
  14982. back = [];
  14983. }
  14984. return front.concat(back);
  14985. };
  14986. Node.prototype.clipTo = function (bsp) {
  14987. this.polygons = bsp.clipPolygons(this.polygons);
  14988. if (this.front)
  14989. this.front.clipTo(bsp);
  14990. if (this.back)
  14991. this.back.clipTo(bsp);
  14992. };
  14993. Node.prototype.allPolygons = function () {
  14994. var polygons = this.polygons.slice();
  14995. if (this.front)
  14996. polygons = polygons.concat(this.front.allPolygons());
  14997. if (this.back)
  14998. polygons = polygons.concat(this.back.allPolygons());
  14999. return polygons;
  15000. };
  15001. Node.prototype.build = function (polygons) {
  15002. if (!polygons.length)
  15003. return;
  15004. if (!this.plane)
  15005. this.plane = polygons[0].plane.clone();
  15006. var front = [], back = [];
  15007. for (var i = 0; i < polygons.length; i++) {
  15008. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15009. }
  15010. if (front.length) {
  15011. if (!this.front)
  15012. this.front = new Node();
  15013. this.front.build(front);
  15014. }
  15015. if (back.length) {
  15016. if (!this.back)
  15017. this.back = new Node();
  15018. this.back.build(back);
  15019. }
  15020. };
  15021. return Node;
  15022. })();
  15023. var CSG = (function () {
  15024. function CSG() {
  15025. this.polygons = new Array();
  15026. }
  15027. CSG.FromMesh = function (mesh) {
  15028. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15029. if (mesh instanceof BABYLON.Mesh) {
  15030. mesh.computeWorldMatrix(true);
  15031. var matrix = mesh.getWorldMatrix();
  15032. var meshPosition = mesh.position.clone();
  15033. var meshRotation = mesh.rotation.clone();
  15034. var meshScaling = mesh.scaling.clone();
  15035. } else {
  15036. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15037. }
  15038. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15039. var subMeshes = mesh.subMeshes;
  15040. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15041. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15042. vertices = [];
  15043. for (var j = 0; j < 3; j++) {
  15044. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15045. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15046. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15047. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15048. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15049. vertex = new Vertex(position, normal, uv);
  15050. vertices.push(vertex);
  15051. }
  15052. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15053. if (polygon.plane)
  15054. polygons.push(polygon);
  15055. }
  15056. }
  15057. var csg = CSG.FromPolygons(polygons);
  15058. csg.matrix = matrix;
  15059. csg.position = meshPosition;
  15060. csg.rotation = meshRotation;
  15061. csg.scaling = meshScaling;
  15062. currentCSGMeshId++;
  15063. return csg;
  15064. };
  15065. CSG.FromPolygons = function (polygons) {
  15066. var csg = new BABYLON.CSG();
  15067. csg.polygons = polygons;
  15068. return csg;
  15069. };
  15070. CSG.prototype.clone = function () {
  15071. var csg = new BABYLON.CSG();
  15072. csg.polygons = this.polygons.map(function (p) {
  15073. return p.clone();
  15074. });
  15075. csg.copyTransformAttributes(this);
  15076. return csg;
  15077. };
  15078. CSG.prototype.toPolygons = function () {
  15079. return this.polygons;
  15080. };
  15081. CSG.prototype.union = function (csg) {
  15082. var a = new Node(this.clone().polygons);
  15083. var b = new Node(csg.clone().polygons);
  15084. a.clipTo(b);
  15085. b.clipTo(a);
  15086. b.invert();
  15087. b.clipTo(a);
  15088. b.invert();
  15089. a.build(b.allPolygons());
  15090. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15091. };
  15092. CSG.prototype.unionInPlace = function (csg) {
  15093. var a = new Node(this.polygons);
  15094. var b = new Node(csg.polygons);
  15095. a.clipTo(b);
  15096. b.clipTo(a);
  15097. b.invert();
  15098. b.clipTo(a);
  15099. b.invert();
  15100. a.build(b.allPolygons());
  15101. this.polygons = a.allPolygons();
  15102. };
  15103. CSG.prototype.subtract = function (csg) {
  15104. var a = new Node(this.clone().polygons);
  15105. var b = new Node(csg.clone().polygons);
  15106. a.invert();
  15107. a.clipTo(b);
  15108. b.clipTo(a);
  15109. b.invert();
  15110. b.clipTo(a);
  15111. b.invert();
  15112. a.build(b.allPolygons());
  15113. a.invert();
  15114. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15115. };
  15116. CSG.prototype.subtractInPlace = function (csg) {
  15117. var a = new Node(this.polygons);
  15118. var b = new Node(csg.polygons);
  15119. a.invert();
  15120. a.clipTo(b);
  15121. b.clipTo(a);
  15122. b.invert();
  15123. b.clipTo(a);
  15124. b.invert();
  15125. a.build(b.allPolygons());
  15126. a.invert();
  15127. this.polygons = a.allPolygons();
  15128. };
  15129. CSG.prototype.intersect = function (csg) {
  15130. var a = new Node(this.clone().polygons);
  15131. var b = new Node(csg.clone().polygons);
  15132. a.invert();
  15133. b.clipTo(a);
  15134. b.invert();
  15135. a.clipTo(b);
  15136. b.clipTo(a);
  15137. a.build(b.allPolygons());
  15138. a.invert();
  15139. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15140. };
  15141. CSG.prototype.intersectInPlace = function (csg) {
  15142. var a = new Node(this.polygons);
  15143. var b = new Node(csg.polygons);
  15144. a.invert();
  15145. b.clipTo(a);
  15146. b.invert();
  15147. a.clipTo(b);
  15148. b.clipTo(a);
  15149. a.build(b.allPolygons());
  15150. a.invert();
  15151. this.polygons = a.allPolygons();
  15152. };
  15153. CSG.prototype.inverse = function () {
  15154. var csg = this.clone();
  15155. csg.inverseInPlace();
  15156. return csg;
  15157. };
  15158. CSG.prototype.inverseInPlace = function () {
  15159. this.polygons.map(function (p) {
  15160. p.flip();
  15161. });
  15162. };
  15163. CSG.prototype.copyTransformAttributes = function (csg) {
  15164. this.matrix = csg.matrix;
  15165. this.position = csg.position;
  15166. this.rotation = csg.rotation;
  15167. this.scaling = csg.scaling;
  15168. return this;
  15169. };
  15170. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15171. var matrix = this.matrix.clone();
  15172. matrix.invert();
  15173. 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;
  15174. if (keepSubMeshes) {
  15175. polygons.sort(function (a, b) {
  15176. if (a.shared.meshId === b.shared.meshId) {
  15177. return a.shared.subMeshId - b.shared.subMeshId;
  15178. } else {
  15179. return a.shared.meshId - b.shared.meshId;
  15180. }
  15181. });
  15182. }
  15183. for (var i = 0, il = polygons.length; i < il; i++) {
  15184. polygon = polygons[i];
  15185. if (!subMesh_dict[polygon.shared.meshId]) {
  15186. subMesh_dict[polygon.shared.meshId] = {};
  15187. }
  15188. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15189. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15190. indexStart: +Infinity,
  15191. indexEnd: -Infinity,
  15192. materialIndex: polygon.shared.materialIndex
  15193. };
  15194. }
  15195. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15196. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15197. polygonIndices[0] = 0;
  15198. polygonIndices[1] = j - 1;
  15199. polygonIndices[2] = j;
  15200. for (var k = 0; k < 3; k++) {
  15201. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15202. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15203. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15204. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15205. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15206. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15207. 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)) {
  15208. vertices.push(vertex.x, vertex.y, vertex.z);
  15209. uvs.push(uv.x, uv.y);
  15210. normals.push(normal.x, normal.y, normal.z);
  15211. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15212. }
  15213. indices.push(vertex_idx);
  15214. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15215. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15216. currentIndex++;
  15217. }
  15218. }
  15219. }
  15220. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15221. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15222. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15223. mesh.setIndices(indices);
  15224. if (keepSubMeshes) {
  15225. var materialIndexOffset = 0, materialMaxIndex;
  15226. mesh.subMeshes.length = 0;
  15227. for (var m in subMesh_dict) {
  15228. materialMaxIndex = -1;
  15229. for (var sm in subMesh_dict[m]) {
  15230. subMesh_obj = subMesh_dict[m][sm];
  15231. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15232. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15233. }
  15234. materialIndexOffset += ++materialMaxIndex;
  15235. }
  15236. }
  15237. return mesh;
  15238. };
  15239. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15240. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15241. mesh.material = material;
  15242. mesh.position.copyFrom(this.position);
  15243. mesh.rotation.copyFrom(this.rotation);
  15244. mesh.scaling.copyFrom(this.scaling);
  15245. mesh.computeWorldMatrix(true);
  15246. return mesh;
  15247. };
  15248. return CSG;
  15249. })();
  15250. BABYLON.CSG = CSG;
  15251. })(BABYLON || (BABYLON = {}));
  15252. var __extends = this.__extends || function (d, b) {
  15253. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15254. function __() { this.constructor = d; }
  15255. __.prototype = b.prototype;
  15256. d.prototype = new __();
  15257. };
  15258. var BABYLON;
  15259. (function (BABYLON) {
  15260. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15261. __extends(OculusDistortionCorrectionPostProcess, _super);
  15262. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15263. var _this = this;
  15264. _super.call(this, name, "oculusDistortionCorrection", [
  15265. 'LensCenter',
  15266. 'Scale',
  15267. 'ScaleIn',
  15268. 'HmdWarpParam'
  15269. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15270. this._isRightEye = isRightEye;
  15271. this._distortionFactors = cameraSettings.DistortionK;
  15272. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15273. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15274. this.onSizeChanged = function () {
  15275. _this.aspectRatio = _this.width * .5 / _this.height;
  15276. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15277. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15278. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15279. };
  15280. this.onApply = function (effect) {
  15281. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15282. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15283. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15284. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15285. };
  15286. }
  15287. return OculusDistortionCorrectionPostProcess;
  15288. })(BABYLON.PostProcess);
  15289. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15290. })(BABYLON || (BABYLON = {}));
  15291. var BABYLON;
  15292. (function (BABYLON) {
  15293. (function (JoystickAxis) {
  15294. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15295. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15296. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15297. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15298. var JoystickAxis = BABYLON.JoystickAxis;
  15299. var VirtualJoystick = (function () {
  15300. function VirtualJoystick(leftJoystick) {
  15301. var _this = this;
  15302. if (leftJoystick) {
  15303. this._leftJoystick = true;
  15304. } else {
  15305. this._leftJoystick = false;
  15306. }
  15307. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15308. VirtualJoystick._globalJoystickIndex++;
  15309. this._axisTargetedByLeftAndRight = 0 /* X */;
  15310. this._axisTargetedByUpAndDown = 1 /* Y */;
  15311. this.reverseLeftRight = false;
  15312. this.reverseUpDown = false;
  15313. this._touches = new BABYLON.VirtualJoystick.Collection();
  15314. this.deltaPosition = BABYLON.Vector3.Zero();
  15315. this._joystickSensibility = 25;
  15316. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15317. this._rotationSpeed = 25;
  15318. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15319. this._rotateOnAxisRelativeToMesh = false;
  15320. if (!VirtualJoystick.vjCanvas) {
  15321. window.addEventListener("resize", function () {
  15322. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15323. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15324. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15325. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15326. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15327. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15328. }, false);
  15329. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15330. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15331. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15332. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15333. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15334. VirtualJoystick.vjCanvas.style.width = "100%";
  15335. VirtualJoystick.vjCanvas.style.height = "100%";
  15336. VirtualJoystick.vjCanvas.style.position = "absolute";
  15337. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15338. VirtualJoystick.vjCanvas.style.top = "0px";
  15339. VirtualJoystick.vjCanvas.style.left = "0px";
  15340. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15341. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15342. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15343. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15344. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15345. document.body.appendChild(VirtualJoystick.vjCanvas);
  15346. }
  15347. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15348. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15349. this.pressed = false;
  15350. this._joystickColor = "cyan";
  15351. this._joystickPointerID = -1;
  15352. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15353. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15354. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15355. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15356. _this._onPointerDown(evt);
  15357. }, false);
  15358. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15359. _this._onPointerMove(evt);
  15360. }, false);
  15361. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15362. _this._onPointerUp(evt);
  15363. }, false);
  15364. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15365. _this._onPointerUp(evt);
  15366. }, false);
  15367. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15368. evt.preventDefault();
  15369. }, false);
  15370. requestAnimationFrame(function () {
  15371. _this._drawVirtualJoystick();
  15372. });
  15373. }
  15374. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15375. this._joystickSensibility = newJoystickSensibility;
  15376. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15377. };
  15378. VirtualJoystick.prototype._onPointerDown = function (e) {
  15379. var positionOnScreenCondition;
  15380. e.preventDefault();
  15381. if (this._leftJoystick === true) {
  15382. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15383. } else {
  15384. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15385. }
  15386. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15387. this._joystickPointerID = e.pointerId;
  15388. this._joystickPointerStartPos.x = e.clientX;
  15389. this._joystickPointerStartPos.y = e.clientY;
  15390. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15391. this._deltaJoystickVector.x = 0;
  15392. this._deltaJoystickVector.y = 0;
  15393. this.pressed = true;
  15394. this._touches.add(e.pointerId.toString(), e);
  15395. } else {
  15396. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15397. this._action();
  15398. this._touches.add(e.pointerId.toString(), e);
  15399. }
  15400. }
  15401. };
  15402. VirtualJoystick.prototype._onPointerMove = function (e) {
  15403. if (this._joystickPointerID == e.pointerId) {
  15404. this._joystickPointerPos.x = e.clientX;
  15405. this._joystickPointerPos.y = e.clientY;
  15406. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15407. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15408. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15409. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15410. switch (this._axisTargetedByLeftAndRight) {
  15411. case 0 /* X */:
  15412. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15413. break;
  15414. case 1 /* Y */:
  15415. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15416. break;
  15417. case 2 /* Z */:
  15418. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15419. break;
  15420. }
  15421. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15422. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15423. switch (this._axisTargetedByUpAndDown) {
  15424. case 0 /* X */:
  15425. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15426. break;
  15427. case 1 /* Y */:
  15428. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15429. break;
  15430. case 2 /* Z */:
  15431. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15432. break;
  15433. }
  15434. } else {
  15435. if (this._touches.item(e.pointerId.toString())) {
  15436. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15437. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15438. }
  15439. }
  15440. };
  15441. VirtualJoystick.prototype._onPointerUp = function (e) {
  15442. this._clearCanvas();
  15443. if (this._joystickPointerID == e.pointerId) {
  15444. this._joystickPointerID = -1;
  15445. this.pressed = false;
  15446. }
  15447. this._deltaJoystickVector.x = 0;
  15448. this._deltaJoystickVector.y = 0;
  15449. this._touches.remove(e.pointerId.toString());
  15450. };
  15451. /**
  15452. * Change the color of the virtual joystick
  15453. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15454. */
  15455. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15456. this._joystickColor = newColor;
  15457. };
  15458. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15459. this._action = action;
  15460. };
  15461. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15462. switch (axis) {
  15463. case 0 /* X */:
  15464. case 1 /* Y */:
  15465. case 2 /* Z */:
  15466. this._axisTargetedByLeftAndRight = axis;
  15467. break;
  15468. default:
  15469. this._axisTargetedByLeftAndRight = 0 /* X */;
  15470. break;
  15471. }
  15472. };
  15473. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15474. switch (axis) {
  15475. case 0 /* X */:
  15476. case 1 /* Y */:
  15477. case 2 /* Z */:
  15478. this._axisTargetedByUpAndDown = axis;
  15479. break;
  15480. default:
  15481. this._axisTargetedByUpAndDown = 1 /* Y */;
  15482. break;
  15483. }
  15484. };
  15485. VirtualJoystick.prototype._clearCanvas = function () {
  15486. if (this._leftJoystick) {
  15487. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15488. } else {
  15489. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15490. }
  15491. };
  15492. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15493. var _this = this;
  15494. if (this.pressed) {
  15495. this._clearCanvas();
  15496. this._touches.forEach(function (touch) {
  15497. if (touch.pointerId === _this._joystickPointerID) {
  15498. VirtualJoystick.vjCanvasContext.beginPath();
  15499. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15500. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15501. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15502. VirtualJoystick.vjCanvasContext.stroke();
  15503. VirtualJoystick.vjCanvasContext.beginPath();
  15504. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15505. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15506. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15507. VirtualJoystick.vjCanvasContext.stroke();
  15508. VirtualJoystick.vjCanvasContext.beginPath();
  15509. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15510. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15511. VirtualJoystick.vjCanvasContext.stroke();
  15512. } else {
  15513. VirtualJoystick.vjCanvasContext.beginPath();
  15514. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15515. VirtualJoystick.vjCanvasContext.beginPath();
  15516. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15517. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15518. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15519. VirtualJoystick.vjCanvasContext.stroke();
  15520. }
  15521. ;
  15522. });
  15523. }
  15524. requestAnimationFrame(function () {
  15525. _this._drawVirtualJoystick();
  15526. });
  15527. };
  15528. VirtualJoystick.prototype.releaseCanvas = function () {
  15529. if (VirtualJoystick.vjCanvas) {
  15530. document.body.removeChild(VirtualJoystick.vjCanvas);
  15531. VirtualJoystick.vjCanvas = null;
  15532. }
  15533. };
  15534. VirtualJoystick._globalJoystickIndex = 0;
  15535. return VirtualJoystick;
  15536. })();
  15537. BABYLON.VirtualJoystick = VirtualJoystick;
  15538. })(BABYLON || (BABYLON = {}));
  15539. var BABYLON;
  15540. (function (BABYLON) {
  15541. (function (VirtualJoystick) {
  15542. var Collection = (function () {
  15543. function Collection() {
  15544. this._count = 0;
  15545. this._collection = new Array();
  15546. }
  15547. Collection.prototype.Count = function () {
  15548. return this._count;
  15549. };
  15550. Collection.prototype.add = function (key, item) {
  15551. if (this._collection[key] != undefined) {
  15552. return undefined;
  15553. }
  15554. this._collection[key] = item;
  15555. return ++this._count;
  15556. };
  15557. Collection.prototype.remove = function (key) {
  15558. if (this._collection[key] == undefined) {
  15559. return undefined;
  15560. }
  15561. delete this._collection[key];
  15562. return --this._count;
  15563. };
  15564. Collection.prototype.item = function (key) {
  15565. return this._collection[key];
  15566. };
  15567. Collection.prototype.forEach = function (block) {
  15568. var key;
  15569. for (key in this._collection) {
  15570. if (this._collection.hasOwnProperty(key)) {
  15571. block(this._collection[key]);
  15572. }
  15573. }
  15574. };
  15575. return Collection;
  15576. })();
  15577. VirtualJoystick.Collection = Collection;
  15578. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15579. var VirtualJoystick = BABYLON.VirtualJoystick;
  15580. })(BABYLON || (BABYLON = {}));
  15581. var __extends = this.__extends || function (d, b) {
  15582. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15583. function __() { this.constructor = d; }
  15584. __.prototype = b.prototype;
  15585. d.prototype = new __();
  15586. };
  15587. var BABYLON;
  15588. (function (BABYLON) {
  15589. var OculusRiftDevKit2013_Metric = {
  15590. HResolution: 1280,
  15591. VResolution: 800,
  15592. HScreenSize: 0.149759993,
  15593. VScreenSize: 0.0935999975,
  15594. VScreenCenter: 0.0467999987,
  15595. EyeToScreenDistance: 0.0410000011,
  15596. LensSeparationDistance: 0.0635000020,
  15597. InterpupillaryDistance: 0.0640000030,
  15598. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15599. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15600. PostProcessScaleFactor: 1.714605507808412,
  15601. LensCenterOffset: 0.151976421
  15602. };
  15603. var _OculusInnerCamera = (function (_super) {
  15604. __extends(_OculusInnerCamera, _super);
  15605. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15606. _super.call(this, name, position, scene);
  15607. this._workMatrix = new BABYLON.Matrix();
  15608. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15609. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15610. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15611. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15612. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15613. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15614. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15615. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15616. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15617. }
  15618. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15619. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15620. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15621. return this._projectionMatrix;
  15622. };
  15623. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15624. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15625. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15626. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15627. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15628. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15629. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15630. return this._viewMatrix;
  15631. };
  15632. return _OculusInnerCamera;
  15633. })(BABYLON.FreeCamera);
  15634. var OculusCamera = (function (_super) {
  15635. __extends(OculusCamera, _super);
  15636. function OculusCamera(name, position, scene) {
  15637. _super.call(this, name, position, scene);
  15638. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15639. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15640. this.subCameras.push(this._leftCamera);
  15641. this.subCameras.push(this._rightCamera);
  15642. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15643. }
  15644. OculusCamera.prototype._update = function () {
  15645. this._leftCamera.position.copyFrom(this.position);
  15646. this._rightCamera.position.copyFrom(this.position);
  15647. this._updateCamera(this._leftCamera);
  15648. this._updateCamera(this._rightCamera);
  15649. _super.prototype._update.call(this);
  15650. };
  15651. OculusCamera.prototype._updateCamera = function (camera) {
  15652. camera.minZ = this.minZ;
  15653. camera.maxZ = this.maxZ;
  15654. camera.rotation.x = this.rotation.x;
  15655. camera.rotation.y = this.rotation.y;
  15656. camera.rotation.z = this.rotation.z;
  15657. };
  15658. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15659. var yaw = evt.alpha / 180 * Math.PI;
  15660. var pitch = evt.beta / 180 * Math.PI;
  15661. var roll = evt.gamma / 180 * Math.PI;
  15662. if (!this._offsetOrientation) {
  15663. this._offsetOrientation = {
  15664. yaw: yaw,
  15665. pitch: pitch,
  15666. roll: roll
  15667. };
  15668. return;
  15669. } else {
  15670. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15671. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15672. this.rotation.z += this._offsetOrientation.roll - roll;
  15673. this._offsetOrientation.yaw = yaw;
  15674. this._offsetOrientation.pitch = pitch;
  15675. this._offsetOrientation.roll = roll;
  15676. }
  15677. };
  15678. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15679. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15680. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15681. };
  15682. OculusCamera.prototype.detachControl = function (element) {
  15683. _super.prototype.detachControl.call(this, element);
  15684. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15685. };
  15686. return OculusCamera;
  15687. })(BABYLON.FreeCamera);
  15688. BABYLON.OculusCamera = OculusCamera;
  15689. })(BABYLON || (BABYLON = {}));
  15690. var __extends = this.__extends || function (d, b) {
  15691. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15692. function __() { this.constructor = d; }
  15693. __.prototype = b.prototype;
  15694. d.prototype = new __();
  15695. };
  15696. var BABYLON;
  15697. (function (BABYLON) {
  15698. var VirtualJoysticksCamera = (function (_super) {
  15699. __extends(VirtualJoysticksCamera, _super);
  15700. function VirtualJoysticksCamera(name, position, scene) {
  15701. _super.call(this, name, position, scene);
  15702. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15703. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15704. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15705. this._leftjoystick.setJoystickSensibility(0.15);
  15706. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15707. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15708. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15709. this._rightjoystick.reverseUpDown = true;
  15710. this._rightjoystick.setJoystickSensibility(0.05);
  15711. this._rightjoystick.setJoystickColor("yellow");
  15712. }
  15713. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15714. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15715. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15716. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15717. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15718. if (!this._leftjoystick.pressed) {
  15719. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15720. }
  15721. if (!this._rightjoystick.pressed) {
  15722. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15723. }
  15724. };
  15725. VirtualJoysticksCamera.prototype.dispose = function () {
  15726. this._leftjoystick.releaseCanvas();
  15727. _super.prototype.dispose.call(this);
  15728. };
  15729. return VirtualJoysticksCamera;
  15730. })(BABYLON.FreeCamera);
  15731. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15732. })(BABYLON || (BABYLON = {}));
  15733. var __extends = this.__extends || function (d, b) {
  15734. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15735. function __() { this.constructor = d; }
  15736. __.prototype = b.prototype;
  15737. d.prototype = new __();
  15738. };
  15739. var BABYLON;
  15740. (function (BABYLON) {
  15741. var ShaderMaterial = (function (_super) {
  15742. __extends(ShaderMaterial, _super);
  15743. function ShaderMaterial(name, scene, shaderPath, options) {
  15744. _super.call(this, name, scene);
  15745. this._textures = new Array();
  15746. this._floats = new Array();
  15747. this._floatsArrays = {};
  15748. this._colors3 = new Array();
  15749. this._colors4 = new Array();
  15750. this._vectors2 = new Array();
  15751. this._vectors3 = new Array();
  15752. this._matrices = new Array();
  15753. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15754. this._shaderPath = shaderPath;
  15755. options.needAlphaBlending = options.needAlphaBlending || false;
  15756. options.needAlphaTesting = options.needAlphaTesting || false;
  15757. options.attributes = options.attributes || ["position", "normal", "uv"];
  15758. options.uniforms = options.uniforms || ["worldViewProjection"];
  15759. options.samplers = options.samplers || [];
  15760. this._options = options;
  15761. }
  15762. ShaderMaterial.prototype.needAlphaBlending = function () {
  15763. return this._options.needAlphaBlending;
  15764. };
  15765. ShaderMaterial.prototype.needAlphaTesting = function () {
  15766. return this._options.needAlphaTesting;
  15767. };
  15768. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15769. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15770. this._options.uniforms.push(uniformName);
  15771. }
  15772. };
  15773. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15774. if (this._options.samplers.indexOf(name) === -1) {
  15775. this._options.samplers.push(name);
  15776. }
  15777. this._textures[name] = texture;
  15778. return this;
  15779. };
  15780. ShaderMaterial.prototype.setFloat = function (name, value) {
  15781. this._checkUniform(name);
  15782. this._floats[name] = value;
  15783. return this;
  15784. };
  15785. ShaderMaterial.prototype.setFloats = function (name, value) {
  15786. this._checkUniform(name);
  15787. this._floatsArrays[name] = value;
  15788. return this;
  15789. };
  15790. ShaderMaterial.prototype.setColor3 = function (name, value) {
  15791. this._checkUniform(name);
  15792. this._colors3[name] = value;
  15793. return this;
  15794. };
  15795. ShaderMaterial.prototype.setColor4 = function (name, value) {
  15796. this._checkUniform(name);
  15797. this._colors4[name] = value;
  15798. return this;
  15799. };
  15800. ShaderMaterial.prototype.setVector2 = function (name, value) {
  15801. this._checkUniform(name);
  15802. this._vectors2[name] = value;
  15803. return this;
  15804. };
  15805. ShaderMaterial.prototype.setVector3 = function (name, value) {
  15806. this._checkUniform(name);
  15807. this._vectors3[name] = value;
  15808. return this;
  15809. };
  15810. ShaderMaterial.prototype.setMatrix = function (name, value) {
  15811. this._checkUniform(name);
  15812. this._matrices[name] = value;
  15813. return this;
  15814. };
  15815. ShaderMaterial.prototype.isReady = function () {
  15816. var engine = this.getScene().getEngine();
  15817. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  15818. if (!this._effect.isReady()) {
  15819. return false;
  15820. }
  15821. return true;
  15822. };
  15823. ShaderMaterial.prototype.bind = function (world) {
  15824. if (this._options.uniforms.indexOf("world") !== -1) {
  15825. this._effect.setMatrix("world", world);
  15826. }
  15827. if (this._options.uniforms.indexOf("view") !== -1) {
  15828. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  15829. }
  15830. if (this._options.uniforms.indexOf("worldView") !== -1) {
  15831. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  15832. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  15833. }
  15834. if (this._options.uniforms.indexOf("projection") !== -1) {
  15835. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  15836. }
  15837. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  15838. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  15839. }
  15840. for (var name in this._textures) {
  15841. this._effect.setTexture(name, this._textures[name]);
  15842. }
  15843. for (name in this._floats) {
  15844. this._effect.setFloat(name, this._floats[name]);
  15845. }
  15846. for (name in this._floatsArrays) {
  15847. this._effect.setArray(name, this._floatsArrays[name]);
  15848. }
  15849. for (name in this._colors3) {
  15850. this._effect.setColor3(name, this._colors3[name]);
  15851. }
  15852. for (name in this._colors4) {
  15853. var color = this._colors4[name];
  15854. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15855. }
  15856. for (name in this._vectors2) {
  15857. this._effect.setVector2(name, this._vectors2[name]);
  15858. }
  15859. for (name in this._vectors3) {
  15860. this._effect.setVector3(name, this._vectors3[name]);
  15861. }
  15862. for (name in this._matrices) {
  15863. this._effect.setMatrix(name, this._matrices[name]);
  15864. }
  15865. };
  15866. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  15867. for (var name in this._textures) {
  15868. this._textures[name].dispose();
  15869. }
  15870. this._textures = [];
  15871. _super.prototype.dispose.call(this, forceDisposeEffect);
  15872. };
  15873. return ShaderMaterial;
  15874. })(BABYLON.Material);
  15875. BABYLON.ShaderMaterial = ShaderMaterial;
  15876. })(BABYLON || (BABYLON = {}));
  15877. var BABYLON;
  15878. (function (BABYLON) {
  15879. var VertexData = (function () {
  15880. function VertexData() {
  15881. }
  15882. VertexData.prototype.set = function (data, kind) {
  15883. switch (kind) {
  15884. case BABYLON.VertexBuffer.PositionKind:
  15885. this.positions = data;
  15886. break;
  15887. case BABYLON.VertexBuffer.NormalKind:
  15888. this.normals = data;
  15889. break;
  15890. case BABYLON.VertexBuffer.UVKind:
  15891. this.uvs = data;
  15892. break;
  15893. case BABYLON.VertexBuffer.UV2Kind:
  15894. this.uv2s = data;
  15895. break;
  15896. case BABYLON.VertexBuffer.ColorKind:
  15897. this.colors = data;
  15898. break;
  15899. case BABYLON.VertexBuffer.MatricesIndicesKind:
  15900. this.matricesIndices = data;
  15901. break;
  15902. case BABYLON.VertexBuffer.MatricesWeightsKind:
  15903. this.matricesWeights = data;
  15904. break;
  15905. }
  15906. };
  15907. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  15908. this._applyTo(mesh, updatable);
  15909. };
  15910. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  15911. this._applyTo(geometry, updatable);
  15912. };
  15913. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  15914. this._update(mesh);
  15915. };
  15916. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  15917. this._update(geometry);
  15918. };
  15919. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  15920. if (this.positions) {
  15921. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  15922. }
  15923. if (this.normals) {
  15924. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  15925. }
  15926. if (this.uvs) {
  15927. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  15928. }
  15929. if (this.uv2s) {
  15930. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  15931. }
  15932. if (this.colors) {
  15933. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  15934. }
  15935. if (this.matricesIndices) {
  15936. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  15937. }
  15938. if (this.matricesWeights) {
  15939. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  15940. }
  15941. if (this.indices) {
  15942. meshOrGeometry.setIndices(this.indices);
  15943. }
  15944. };
  15945. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  15946. if (this.positions) {
  15947. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  15948. }
  15949. if (this.normals) {
  15950. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  15951. }
  15952. if (this.uvs) {
  15953. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  15954. }
  15955. if (this.uv2s) {
  15956. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  15957. }
  15958. if (this.colors) {
  15959. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  15960. }
  15961. if (this.matricesIndices) {
  15962. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  15963. }
  15964. if (this.matricesWeights) {
  15965. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  15966. }
  15967. if (this.indices) {
  15968. meshOrGeometry.setIndices(this.indices);
  15969. }
  15970. };
  15971. VertexData.prototype.transform = function (matrix) {
  15972. var transformed = BABYLON.Vector3.Zero();
  15973. if (this.positions) {
  15974. var position = BABYLON.Vector3.Zero();
  15975. for (var index = 0; index < this.positions.length; index += 3) {
  15976. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  15977. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  15978. this.positions[index] = transformed.x;
  15979. this.positions[index + 1] = transformed.y;
  15980. this.positions[index + 2] = transformed.z;
  15981. }
  15982. }
  15983. if (this.normals) {
  15984. var normal = BABYLON.Vector3.Zero();
  15985. for (index = 0; index < this.normals.length; index += 3) {
  15986. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  15987. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  15988. this.normals[index] = transformed.x;
  15989. this.normals[index + 1] = transformed.y;
  15990. this.normals[index + 2] = transformed.z;
  15991. }
  15992. }
  15993. };
  15994. VertexData.prototype.merge = function (other) {
  15995. if (other.indices) {
  15996. if (!this.indices) {
  15997. this.indices = [];
  15998. }
  15999. var offset = this.positions ? this.positions.length / 3 : 0;
  16000. for (var index = 0; index < other.indices.length; index++) {
  16001. this.indices.push(other.indices[index] + offset);
  16002. }
  16003. }
  16004. if (other.positions) {
  16005. if (!this.positions) {
  16006. this.positions = [];
  16007. }
  16008. for (index = 0; index < other.positions.length; index++) {
  16009. this.positions.push(other.positions[index]);
  16010. }
  16011. }
  16012. if (other.normals) {
  16013. if (!this.normals) {
  16014. this.normals = [];
  16015. }
  16016. for (index = 0; index < other.normals.length; index++) {
  16017. this.normals.push(other.normals[index]);
  16018. }
  16019. }
  16020. if (other.uvs) {
  16021. if (!this.uvs) {
  16022. this.uvs = [];
  16023. }
  16024. for (index = 0; index < other.uvs.length; index++) {
  16025. this.uvs.push(other.uvs[index]);
  16026. }
  16027. }
  16028. if (other.uv2s) {
  16029. if (!this.uv2s) {
  16030. this.uv2s = [];
  16031. }
  16032. for (index = 0; index < other.uv2s.length; index++) {
  16033. this.uv2s.push(other.uv2s[index]);
  16034. }
  16035. }
  16036. if (other.matricesIndices) {
  16037. if (!this.matricesIndices) {
  16038. this.matricesIndices = [];
  16039. }
  16040. for (index = 0; index < other.matricesIndices.length; index++) {
  16041. this.matricesIndices.push(other.matricesIndices[index]);
  16042. }
  16043. }
  16044. if (other.matricesWeights) {
  16045. if (!this.matricesWeights) {
  16046. this.matricesWeights = [];
  16047. }
  16048. for (index = 0; index < other.matricesWeights.length; index++) {
  16049. this.matricesWeights.push(other.matricesWeights[index]);
  16050. }
  16051. }
  16052. if (other.colors) {
  16053. if (!this.colors) {
  16054. this.colors = [];
  16055. }
  16056. for (index = 0; index < other.colors.length; index++) {
  16057. this.colors.push(other.colors[index]);
  16058. }
  16059. }
  16060. };
  16061. VertexData.ExtractFromMesh = function (mesh) {
  16062. return VertexData._ExtractFrom(mesh);
  16063. };
  16064. VertexData.ExtractFromGeometry = function (geometry) {
  16065. return VertexData._ExtractFrom(geometry);
  16066. };
  16067. VertexData._ExtractFrom = function (meshOrGeometry) {
  16068. var result = new BABYLON.VertexData();
  16069. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16070. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16071. }
  16072. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16073. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16074. }
  16075. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16076. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16077. }
  16078. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16079. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16080. }
  16081. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16082. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16083. }
  16084. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16085. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16086. }
  16087. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16088. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16089. }
  16090. result.indices = meshOrGeometry.getIndices();
  16091. return result;
  16092. };
  16093. VertexData.CreateBox = function (size) {
  16094. var normalsSource = [
  16095. new BABYLON.Vector3(0, 0, 1),
  16096. new BABYLON.Vector3(0, 0, -1),
  16097. new BABYLON.Vector3(1, 0, 0),
  16098. new BABYLON.Vector3(-1, 0, 0),
  16099. new BABYLON.Vector3(0, 1, 0),
  16100. new BABYLON.Vector3(0, -1, 0)
  16101. ];
  16102. var indices = [];
  16103. var positions = [];
  16104. var normals = [];
  16105. var uvs = [];
  16106. size = size || 1;
  16107. for (var index = 0; index < normalsSource.length; index++) {
  16108. var normal = normalsSource[index];
  16109. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16110. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16111. var verticesLength = positions.length / 3;
  16112. indices.push(verticesLength);
  16113. indices.push(verticesLength + 1);
  16114. indices.push(verticesLength + 2);
  16115. indices.push(verticesLength);
  16116. indices.push(verticesLength + 2);
  16117. indices.push(verticesLength + 3);
  16118. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16119. positions.push(vertex.x, vertex.y, vertex.z);
  16120. normals.push(normal.x, normal.y, normal.z);
  16121. uvs.push(1.0, 1.0);
  16122. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16123. positions.push(vertex.x, vertex.y, vertex.z);
  16124. normals.push(normal.x, normal.y, normal.z);
  16125. uvs.push(0.0, 1.0);
  16126. vertex = normal.add(side1).add(side2).scale(size / 2);
  16127. positions.push(vertex.x, vertex.y, vertex.z);
  16128. normals.push(normal.x, normal.y, normal.z);
  16129. uvs.push(0.0, 0.0);
  16130. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16131. positions.push(vertex.x, vertex.y, vertex.z);
  16132. normals.push(normal.x, normal.y, normal.z);
  16133. uvs.push(1.0, 0.0);
  16134. }
  16135. var vertexData = new BABYLON.VertexData();
  16136. vertexData.indices = indices;
  16137. vertexData.positions = positions;
  16138. vertexData.normals = normals;
  16139. vertexData.uvs = uvs;
  16140. return vertexData;
  16141. };
  16142. VertexData.CreateSphere = function (segments, diameter) {
  16143. segments = segments || 32;
  16144. diameter = diameter || 1;
  16145. var radius = diameter / 2;
  16146. var totalZRotationSteps = 2 + segments;
  16147. var totalYRotationSteps = 2 * totalZRotationSteps;
  16148. var indices = [];
  16149. var positions = [];
  16150. var normals = [];
  16151. var uvs = [];
  16152. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16153. var normalizedZ = zRotationStep / totalZRotationSteps;
  16154. var angleZ = (normalizedZ * Math.PI);
  16155. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16156. var normalizedY = yRotationStep / totalYRotationSteps;
  16157. var angleY = normalizedY * Math.PI * 2;
  16158. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16159. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16160. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16161. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16162. var vertex = complete.scale(radius);
  16163. var normal = BABYLON.Vector3.Normalize(vertex);
  16164. positions.push(vertex.x, vertex.y, vertex.z);
  16165. normals.push(normal.x, normal.y, normal.z);
  16166. uvs.push(normalizedZ, normalizedY);
  16167. }
  16168. if (zRotationStep > 0) {
  16169. var verticesCount = positions.length / 3;
  16170. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16171. indices.push((firstIndex));
  16172. indices.push((firstIndex + 1));
  16173. indices.push(firstIndex + totalYRotationSteps + 1);
  16174. indices.push((firstIndex + totalYRotationSteps + 1));
  16175. indices.push((firstIndex + 1));
  16176. indices.push((firstIndex + totalYRotationSteps + 2));
  16177. }
  16178. }
  16179. }
  16180. var vertexData = new BABYLON.VertexData();
  16181. vertexData.indices = indices;
  16182. vertexData.positions = positions;
  16183. vertexData.normals = normals;
  16184. vertexData.uvs = uvs;
  16185. return vertexData;
  16186. };
  16187. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16188. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16189. var radiusTop = diameterTop / 2;
  16190. var radiusBottom = diameterBottom / 2;
  16191. var indices = [];
  16192. var positions = [];
  16193. var normals = [];
  16194. var uvs = [];
  16195. height = height || 1;
  16196. diameterTop = diameterTop || 0.5;
  16197. diameterBottom = diameterBottom || 1;
  16198. tessellation = tessellation || 16;
  16199. subdivisions = subdivisions || 1;
  16200. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16201. var getCircleVector = function (i) {
  16202. var angle = (i * 2.0 * Math.PI / tessellation);
  16203. var dx = Math.cos(angle);
  16204. var dz = Math.sin(angle);
  16205. return new BABYLON.Vector3(dx, 0, dz);
  16206. };
  16207. var createCylinderCap = function (isTop) {
  16208. var radius = isTop ? radiusTop : radiusBottom;
  16209. if (radius == 0) {
  16210. return;
  16211. }
  16212. var vbase = positions.length / 3;
  16213. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16214. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16215. if (!isTop) {
  16216. offset.scaleInPlace(-1);
  16217. textureScale.x = -textureScale.x;
  16218. }
  16219. for (i = 0; i < tessellation; i++) {
  16220. var circleVector = getCircleVector(i);
  16221. var position = circleVector.scale(radius).add(offset);
  16222. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16223. positions.push(position.x, position.y, position.z);
  16224. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16225. }
  16226. for (var i = 0; i < tessellation - 2; i++) {
  16227. if (!isTop) {
  16228. indices.push(vbase);
  16229. indices.push(vbase + (i + 2) % tessellation);
  16230. indices.push(vbase + (i + 1) % tessellation);
  16231. } else {
  16232. indices.push(vbase);
  16233. indices.push(vbase + (i + 1) % tessellation);
  16234. indices.push(vbase + (i + 2) % tessellation);
  16235. }
  16236. }
  16237. };
  16238. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16239. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16240. var stride = tessellation + 1;
  16241. for (var i = 0; i <= tessellation; i++) {
  16242. var circleVector = getCircleVector(i);
  16243. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16244. var position, radius = radiusBottom;
  16245. for (var s = 0; s <= subdivisions; s++) {
  16246. position = circleVector.scale(radius);
  16247. position.addInPlace(base.add(offset.scale(s)));
  16248. textureCoordinate.y += 1 / subdivisions;
  16249. radius += (radiusTop - radiusBottom) / subdivisions;
  16250. positions.push(position.x, position.y, position.z);
  16251. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16252. }
  16253. }
  16254. subdivisions += 1;
  16255. for (var s = 0; s < subdivisions - 1; s++) {
  16256. for (var i = 0; i <= tessellation; i++) {
  16257. indices.push(i * subdivisions + s);
  16258. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16259. indices.push(i * subdivisions + (s + 1));
  16260. indices.push(i * subdivisions + (s + 1));
  16261. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16262. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16263. }
  16264. }
  16265. createCylinderCap(true);
  16266. createCylinderCap(false);
  16267. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16268. var vertexData = new BABYLON.VertexData();
  16269. vertexData.indices = indices;
  16270. vertexData.positions = positions;
  16271. vertexData.normals = normals;
  16272. vertexData.uvs = uvs;
  16273. return vertexData;
  16274. };
  16275. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16276. var indices = [];
  16277. var positions = [];
  16278. var normals = [];
  16279. var uvs = [];
  16280. diameter = diameter || 1;
  16281. thickness = thickness || 0.5;
  16282. tessellation = tessellation || 16;
  16283. var stride = tessellation + 1;
  16284. for (var i = 0; i <= tessellation; i++) {
  16285. var u = i / tessellation;
  16286. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16287. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16288. for (var j = 0; j <= tessellation; j++) {
  16289. var v = 1 - j / tessellation;
  16290. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16291. var dx = Math.cos(innerAngle);
  16292. var dy = Math.sin(innerAngle);
  16293. var normal = new BABYLON.Vector3(dx, dy, 0);
  16294. var position = normal.scale(thickness / 2);
  16295. var textureCoordinate = new BABYLON.Vector2(u, v);
  16296. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16297. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16298. positions.push(position.x, position.y, position.z);
  16299. normals.push(normal.x, normal.y, normal.z);
  16300. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16301. var nextI = (i + 1) % stride;
  16302. var nextJ = (j + 1) % stride;
  16303. indices.push(i * stride + j);
  16304. indices.push(i * stride + nextJ);
  16305. indices.push(nextI * stride + j);
  16306. indices.push(i * stride + nextJ);
  16307. indices.push(nextI * stride + nextJ);
  16308. indices.push(nextI * stride + j);
  16309. }
  16310. }
  16311. var vertexData = new BABYLON.VertexData();
  16312. vertexData.indices = indices;
  16313. vertexData.positions = positions;
  16314. vertexData.normals = normals;
  16315. vertexData.uvs = uvs;
  16316. return vertexData;
  16317. };
  16318. VertexData.CreateLines = function (points) {
  16319. var indices = [];
  16320. var positions = [];
  16321. for (var index = 0; index < points.length; index++) {
  16322. positions.push(points[index].x, points[index].y, points[index].z);
  16323. if (index > 0) {
  16324. indices.push(index - 1);
  16325. indices.push(index);
  16326. }
  16327. }
  16328. var vertexData = new BABYLON.VertexData();
  16329. vertexData.indices = indices;
  16330. vertexData.positions = positions;
  16331. return vertexData;
  16332. };
  16333. VertexData.CreateGround = function (width, height, subdivisions) {
  16334. var indices = [];
  16335. var positions = [];
  16336. var normals = [];
  16337. var uvs = [];
  16338. var row, col;
  16339. width = width || 1;
  16340. height = height || 1;
  16341. subdivisions = subdivisions || 1;
  16342. for (row = 0; row <= subdivisions; row++) {
  16343. for (col = 0; col <= subdivisions; col++) {
  16344. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16345. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16346. positions.push(position.x, position.y, position.z);
  16347. normals.push(normal.x, normal.y, normal.z);
  16348. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16349. }
  16350. }
  16351. for (row = 0; row < subdivisions; row++) {
  16352. for (col = 0; col < subdivisions; col++) {
  16353. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16354. indices.push(col + 1 + row * (subdivisions + 1));
  16355. indices.push(col + row * (subdivisions + 1));
  16356. indices.push(col + (row + 1) * (subdivisions + 1));
  16357. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16358. indices.push(col + row * (subdivisions + 1));
  16359. }
  16360. }
  16361. var vertexData = new BABYLON.VertexData();
  16362. vertexData.indices = indices;
  16363. vertexData.positions = positions;
  16364. vertexData.normals = normals;
  16365. vertexData.uvs = uvs;
  16366. return vertexData;
  16367. };
  16368. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16369. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16370. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16371. var indices = [];
  16372. var positions = [];
  16373. var normals = [];
  16374. var uvs = [];
  16375. var row, col, tileRow, tileCol;
  16376. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16377. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16378. precision.w = (precision.w < 1) ? 1 : precision.w;
  16379. precision.h = (precision.h < 1) ? 1 : precision.h;
  16380. var tileSize = {
  16381. 'w': (xmax - xmin) / subdivisions.w,
  16382. 'h': (zmax - zmin) / subdivisions.h
  16383. };
  16384. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16385. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16386. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16387. }
  16388. }
  16389. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16390. var base = positions.length / 3;
  16391. var rowLength = precision.w + 1;
  16392. for (row = 0; row < precision.h; row++) {
  16393. for (col = 0; col < precision.w; col++) {
  16394. var square = [
  16395. base + col + row * rowLength,
  16396. base + (col + 1) + row * rowLength,
  16397. base + (col + 1) + (row + 1) * rowLength,
  16398. base + col + (row + 1) * rowLength
  16399. ];
  16400. indices.push(square[1]);
  16401. indices.push(square[2]);
  16402. indices.push(square[3]);
  16403. indices.push(square[0]);
  16404. indices.push(square[1]);
  16405. indices.push(square[3]);
  16406. }
  16407. }
  16408. var position = BABYLON.Vector3.Zero();
  16409. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16410. for (row = 0; row <= precision.h; row++) {
  16411. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16412. for (col = 0; col <= precision.w; col++) {
  16413. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16414. position.y = 0;
  16415. positions.push(position.x, position.y, position.z);
  16416. normals.push(normal.x, normal.y, normal.z);
  16417. uvs.push(col / precision.w, row / precision.h);
  16418. }
  16419. }
  16420. }
  16421. var vertexData = new BABYLON.VertexData();
  16422. vertexData.indices = indices;
  16423. vertexData.positions = positions;
  16424. vertexData.normals = normals;
  16425. vertexData.uvs = uvs;
  16426. return vertexData;
  16427. };
  16428. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16429. var indices = [];
  16430. var positions = [];
  16431. var normals = [];
  16432. var uvs = [];
  16433. var row, col;
  16434. for (row = 0; row <= subdivisions; row++) {
  16435. for (col = 0; col <= subdivisions; col++) {
  16436. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16437. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16438. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16439. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16440. var r = buffer[pos] / 255.0;
  16441. var g = buffer[pos + 1] / 255.0;
  16442. var b = buffer[pos + 2] / 255.0;
  16443. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16444. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16445. positions.push(position.x, position.y, position.z);
  16446. normals.push(0, 0, 0);
  16447. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16448. }
  16449. }
  16450. for (row = 0; row < subdivisions; row++) {
  16451. for (col = 0; col < subdivisions; col++) {
  16452. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16453. indices.push(col + 1 + row * (subdivisions + 1));
  16454. indices.push(col + row * (subdivisions + 1));
  16455. indices.push(col + (row + 1) * (subdivisions + 1));
  16456. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16457. indices.push(col + row * (subdivisions + 1));
  16458. }
  16459. }
  16460. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16461. var vertexData = new BABYLON.VertexData();
  16462. vertexData.indices = indices;
  16463. vertexData.positions = positions;
  16464. vertexData.normals = normals;
  16465. vertexData.uvs = uvs;
  16466. return vertexData;
  16467. };
  16468. VertexData.CreatePlane = function (size) {
  16469. var indices = [];
  16470. var positions = [];
  16471. var normals = [];
  16472. var uvs = [];
  16473. size = size || 1;
  16474. var halfSize = size / 2.0;
  16475. positions.push(-halfSize, -halfSize, 0);
  16476. normals.push(0, 0, -1.0);
  16477. uvs.push(0.0, 0.0);
  16478. positions.push(halfSize, -halfSize, 0);
  16479. normals.push(0, 0, -1.0);
  16480. uvs.push(1.0, 0.0);
  16481. positions.push(halfSize, halfSize, 0);
  16482. normals.push(0, 0, -1.0);
  16483. uvs.push(1.0, 1.0);
  16484. positions.push(-halfSize, halfSize, 0);
  16485. normals.push(0, 0, -1.0);
  16486. uvs.push(0.0, 1.0);
  16487. indices.push(0);
  16488. indices.push(1);
  16489. indices.push(2);
  16490. indices.push(0);
  16491. indices.push(2);
  16492. indices.push(3);
  16493. var vertexData = new BABYLON.VertexData();
  16494. vertexData.indices = indices;
  16495. vertexData.positions = positions;
  16496. vertexData.normals = normals;
  16497. vertexData.uvs = uvs;
  16498. return vertexData;
  16499. };
  16500. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16501. var indices = [];
  16502. var positions = [];
  16503. var normals = [];
  16504. var uvs = [];
  16505. radius = radius || 2;
  16506. tube = tube || 0.5;
  16507. radialSegments = radialSegments || 32;
  16508. tubularSegments = tubularSegments || 32;
  16509. p = p || 2;
  16510. q = q || 3;
  16511. var getPos = function (angle) {
  16512. var cu = Math.cos(angle);
  16513. var su = Math.sin(angle);
  16514. var quOverP = q / p * angle;
  16515. var cs = Math.cos(quOverP);
  16516. var tx = radius * (2 + cs) * 0.5 * cu;
  16517. var ty = radius * (2 + cs) * su * 0.5;
  16518. var tz = radius * Math.sin(quOverP) * 0.5;
  16519. return new BABYLON.Vector3(tx, ty, tz);
  16520. };
  16521. for (var i = 0; i <= radialSegments; i++) {
  16522. var modI = i % radialSegments;
  16523. var u = modI / radialSegments * 2 * p * Math.PI;
  16524. var p1 = getPos(u);
  16525. var p2 = getPos(u + 0.01);
  16526. var tang = p2.subtract(p1);
  16527. var n = p2.add(p1);
  16528. var bitan = BABYLON.Vector3.Cross(tang, n);
  16529. n = BABYLON.Vector3.Cross(bitan, tang);
  16530. bitan.normalize();
  16531. n.normalize();
  16532. for (var j = 0; j < tubularSegments; j++) {
  16533. var modJ = j % tubularSegments;
  16534. var v = modJ / tubularSegments * 2 * Math.PI;
  16535. var cx = -tube * Math.cos(v);
  16536. var cy = tube * Math.sin(v);
  16537. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16538. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16539. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16540. uvs.push(i / radialSegments);
  16541. uvs.push(j / tubularSegments);
  16542. }
  16543. }
  16544. for (i = 0; i < radialSegments; i++) {
  16545. for (j = 0; j < tubularSegments; j++) {
  16546. var jNext = (j + 1) % tubularSegments;
  16547. var a = i * tubularSegments + j;
  16548. var b = (i + 1) * tubularSegments + j;
  16549. var c = (i + 1) * tubularSegments + jNext;
  16550. var d = i * tubularSegments + jNext;
  16551. indices.push(d);
  16552. indices.push(b);
  16553. indices.push(a);
  16554. indices.push(d);
  16555. indices.push(c);
  16556. indices.push(b);
  16557. }
  16558. }
  16559. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16560. var vertexData = new BABYLON.VertexData();
  16561. vertexData.indices = indices;
  16562. vertexData.positions = positions;
  16563. vertexData.normals = normals;
  16564. vertexData.uvs = uvs;
  16565. return vertexData;
  16566. };
  16567. VertexData.ComputeNormals = function (positions, indices, normals) {
  16568. var positionVectors = [];
  16569. var facesOfVertices = [];
  16570. var index;
  16571. for (index = 0; index < positions.length; index += 3) {
  16572. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16573. positionVectors.push(vector3);
  16574. facesOfVertices.push([]);
  16575. }
  16576. var facesNormals = [];
  16577. for (index = 0; index < indices.length / 3; index++) {
  16578. var i1 = indices[index * 3];
  16579. var i2 = indices[index * 3 + 1];
  16580. var i3 = indices[index * 3 + 2];
  16581. var p1 = positionVectors[i1];
  16582. var p2 = positionVectors[i2];
  16583. var p3 = positionVectors[i3];
  16584. var p1p2 = p1.subtract(p2);
  16585. var p3p2 = p3.subtract(p2);
  16586. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16587. facesOfVertices[i1].push(index);
  16588. facesOfVertices[i2].push(index);
  16589. facesOfVertices[i3].push(index);
  16590. }
  16591. for (index = 0; index < positionVectors.length; index++) {
  16592. var faces = facesOfVertices[index];
  16593. var normal = BABYLON.Vector3.Zero();
  16594. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16595. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16596. }
  16597. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16598. normals[index * 3] = normal.x;
  16599. normals[index * 3 + 1] = normal.y;
  16600. normals[index * 3 + 2] = normal.z;
  16601. }
  16602. };
  16603. return VertexData;
  16604. })();
  16605. BABYLON.VertexData = VertexData;
  16606. })(BABYLON || (BABYLON = {}));
  16607. var __extends = this.__extends || function (d, b) {
  16608. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16609. function __() { this.constructor = d; }
  16610. __.prototype = b.prototype;
  16611. d.prototype = new __();
  16612. };
  16613. var BABYLON;
  16614. (function (BABYLON) {
  16615. var buildCamera = function (that, name) {
  16616. that._leftCamera.isIntermediate = true;
  16617. that.subCameras.push(that._leftCamera);
  16618. that.subCameras.push(that._rightCamera);
  16619. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16620. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16621. that._anaglyphPostProcess.onApply = function (effect) {
  16622. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16623. };
  16624. that._update();
  16625. };
  16626. var AnaglyphArcRotateCamera = (function (_super) {
  16627. __extends(AnaglyphArcRotateCamera, _super);
  16628. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16629. _super.call(this, name, alpha, beta, radius, target, scene);
  16630. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16631. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16632. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16633. buildCamera(this, name);
  16634. }
  16635. AnaglyphArcRotateCamera.prototype._update = function () {
  16636. this._updateCamera(this._leftCamera);
  16637. this._updateCamera(this._rightCamera);
  16638. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16639. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16640. _super.prototype._update.call(this);
  16641. };
  16642. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16643. camera.beta = this.beta;
  16644. camera.radius = this.radius;
  16645. camera.minZ = this.minZ;
  16646. camera.maxZ = this.maxZ;
  16647. camera.fov = this.fov;
  16648. camera.target = this.target;
  16649. };
  16650. return AnaglyphArcRotateCamera;
  16651. })(BABYLON.ArcRotateCamera);
  16652. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16653. var AnaglyphFreeCamera = (function (_super) {
  16654. __extends(AnaglyphFreeCamera, _super);
  16655. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16656. _super.call(this, name, position, scene);
  16657. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16658. this._transformMatrix = new BABYLON.Matrix();
  16659. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16660. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16661. buildCamera(this, name);
  16662. }
  16663. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16664. var target = this.getTarget();
  16665. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16666. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16667. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16668. };
  16669. AnaglyphFreeCamera.prototype._update = function () {
  16670. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16671. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16672. this._updateCamera(this._leftCamera);
  16673. this._updateCamera(this._rightCamera);
  16674. _super.prototype._update.call(this);
  16675. };
  16676. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16677. camera.minZ = this.minZ;
  16678. camera.maxZ = this.maxZ;
  16679. camera.fov = this.fov;
  16680. camera.viewport = this.viewport;
  16681. camera.setTarget(this.getTarget());
  16682. };
  16683. return AnaglyphFreeCamera;
  16684. })(BABYLON.FreeCamera);
  16685. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16686. })(BABYLON || (BABYLON = {}));
  16687. var __extends = this.__extends || function (d, b) {
  16688. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16689. function __() { this.constructor = d; }
  16690. __.prototype = b.prototype;
  16691. d.prototype = new __();
  16692. };
  16693. var BABYLON;
  16694. (function (BABYLON) {
  16695. var AnaglyphPostProcess = (function (_super) {
  16696. __extends(AnaglyphPostProcess, _super);
  16697. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16698. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16699. }
  16700. return AnaglyphPostProcess;
  16701. })(BABYLON.PostProcess);
  16702. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16703. })(BABYLON || (BABYLON = {}));
  16704. var BABYLON;
  16705. (function (BABYLON) {
  16706. var Tags = (function () {
  16707. function Tags() {
  16708. }
  16709. Tags.EnableFor = function (obj) {
  16710. obj._tags = obj._tags || {};
  16711. obj.hasTags = function () {
  16712. return Tags.HasTags(obj);
  16713. };
  16714. obj.addTags = function (tagsString) {
  16715. return Tags.AddTagsTo(obj, tagsString);
  16716. };
  16717. obj.removeTags = function (tagsString) {
  16718. return Tags.RemoveTagsFrom(obj, tagsString);
  16719. };
  16720. obj.matchesTagsQuery = function (tagsQuery) {
  16721. return Tags.MatchesQuery(obj, tagsQuery);
  16722. };
  16723. };
  16724. Tags.DisableFor = function (obj) {
  16725. delete obj._tags;
  16726. delete obj.hasTags;
  16727. delete obj.addTags;
  16728. delete obj.removeTags;
  16729. delete obj.matchesTagsQuery;
  16730. };
  16731. Tags.HasTags = function (obj) {
  16732. if (!obj._tags) {
  16733. return false;
  16734. }
  16735. return !BABYLON.Tools.IsEmpty(obj._tags);
  16736. };
  16737. Tags.GetTags = function (obj) {
  16738. if (!obj._tags) {
  16739. return null;
  16740. }
  16741. return obj._tags;
  16742. };
  16743. Tags.AddTagsTo = function (obj, tagsString) {
  16744. if (!tagsString) {
  16745. return;
  16746. }
  16747. var tags = tagsString.split(" ");
  16748. for (var t in tags) {
  16749. Tags._AddTagTo(obj, tags[t]);
  16750. }
  16751. };
  16752. Tags._AddTagTo = function (obj, tag) {
  16753. tag = tag.trim();
  16754. if (tag === "" || tag === "true" || tag === "false") {
  16755. return;
  16756. }
  16757. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16758. return;
  16759. }
  16760. Tags.EnableFor(obj);
  16761. obj._tags[tag] = true;
  16762. };
  16763. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16764. if (!Tags.HasTags(obj)) {
  16765. return;
  16766. }
  16767. var tags = tagsString.split(" ");
  16768. for (var t in tags) {
  16769. Tags._RemoveTagFrom(obj, tags[t]);
  16770. }
  16771. };
  16772. Tags._RemoveTagFrom = function (obj, tag) {
  16773. delete obj._tags[tag];
  16774. };
  16775. Tags.MatchesQuery = function (obj, tagsQuery) {
  16776. if (tagsQuery === undefined) {
  16777. return true;
  16778. }
  16779. if (tagsQuery === "") {
  16780. return Tags.HasTags(obj);
  16781. }
  16782. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16783. return Tags.HasTags(obj) && obj._tags[r];
  16784. });
  16785. };
  16786. return Tags;
  16787. })();
  16788. BABYLON.Tags = Tags;
  16789. })(BABYLON || (BABYLON = {}));
  16790. var BABYLON;
  16791. (function (BABYLON) {
  16792. (function (Internals) {
  16793. var AndOrNotEvaluator = (function () {
  16794. function AndOrNotEvaluator() {
  16795. }
  16796. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  16797. if (!query.match(/\([^\(\)]*\)/g)) {
  16798. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  16799. } else {
  16800. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  16801. r = r.slice(1, r.length - 1);
  16802. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  16803. });
  16804. }
  16805. if (query === "true") {
  16806. return true;
  16807. }
  16808. if (query === "false") {
  16809. return false;
  16810. }
  16811. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  16812. };
  16813. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  16814. evaluateCallback = evaluateCallback || (function (r) {
  16815. return r === "true" ? true : false;
  16816. });
  16817. var result;
  16818. var or = parenthesisContent.split("||");
  16819. for (var i in or) {
  16820. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  16821. var and = ori.split("&&");
  16822. if (and.length > 1) {
  16823. for (var j = 0; j < and.length; ++j) {
  16824. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  16825. if (andj !== "true" && andj !== "false") {
  16826. if (andj[0] === "!") {
  16827. result = !evaluateCallback(andj.substring(1));
  16828. } else {
  16829. result = evaluateCallback(andj);
  16830. }
  16831. } else {
  16832. result = andj === "true" ? true : false;
  16833. }
  16834. if (!result) {
  16835. ori = "false";
  16836. break;
  16837. }
  16838. }
  16839. }
  16840. if (result || ori === "true") {
  16841. result = true;
  16842. break;
  16843. }
  16844. if (ori !== "true" && ori !== "false") {
  16845. if (ori[0] === "!") {
  16846. result = !evaluateCallback(ori.substring(1));
  16847. } else {
  16848. result = evaluateCallback(ori);
  16849. }
  16850. } else {
  16851. result = ori === "true" ? true : false;
  16852. }
  16853. }
  16854. return result ? "true" : "false";
  16855. };
  16856. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  16857. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  16858. r = r.replace(/[\s]/g, function () {
  16859. return "";
  16860. });
  16861. return r.length % 2 ? "!" : "";
  16862. });
  16863. booleanString = booleanString.trim();
  16864. if (booleanString === "!true") {
  16865. booleanString = "false";
  16866. } else if (booleanString === "!false") {
  16867. booleanString = "true";
  16868. }
  16869. return booleanString;
  16870. };
  16871. return AndOrNotEvaluator;
  16872. })();
  16873. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  16874. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16875. var Internals = BABYLON.Internals;
  16876. })(BABYLON || (BABYLON = {}));
  16877. var BABYLON;
  16878. (function (BABYLON) {
  16879. var PostProcessRenderPass = (function () {
  16880. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  16881. this._enabled = true;
  16882. this._refCount = 0;
  16883. this._name = name;
  16884. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  16885. this.setRenderList(renderList);
  16886. this._renderTexture.onBeforeRender = beforeRender;
  16887. this._renderTexture.onAfterRender = afterRender;
  16888. this._scene = scene;
  16889. }
  16890. PostProcessRenderPass.prototype._incRefCount = function () {
  16891. if (this._refCount === 0) {
  16892. this._scene.customRenderTargets.push(this._renderTexture);
  16893. }
  16894. return ++this._refCount;
  16895. };
  16896. PostProcessRenderPass.prototype._decRefCount = function () {
  16897. this._refCount--;
  16898. if (this._refCount <= 0) {
  16899. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  16900. }
  16901. return this._refCount;
  16902. };
  16903. PostProcessRenderPass.prototype._update = function () {
  16904. this.setRenderList(this._renderList);
  16905. };
  16906. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  16907. this._renderTexture.renderList = renderList;
  16908. };
  16909. PostProcessRenderPass.prototype.getRenderTexture = function () {
  16910. return this._renderTexture;
  16911. };
  16912. return PostProcessRenderPass;
  16913. })();
  16914. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  16915. })(BABYLON || (BABYLON = {}));
  16916. var BABYLON;
  16917. (function (BABYLON) {
  16918. var PostProcessRenderEffect = (function () {
  16919. function PostProcessRenderEffect(engine, name, postProcessType, ratio, samplingMode, singleInstance) {
  16920. this._engine = engine;
  16921. this._name = name;
  16922. this._postProcessType = postProcessType;
  16923. this._ratio = ratio || 1.0;
  16924. this._samplingMode = samplingMode || null;
  16925. this._singleInstance = singleInstance || true;
  16926. this._cameras = [];
  16927. this._postProcesses = [];
  16928. this._indicesForCamera = [];
  16929. this._renderPasses = [];
  16930. this._renderEffectAsPasses = [];
  16931. this.parameters = function (effect) {
  16932. };
  16933. }
  16934. PostProcessRenderEffect._GetInstance = function (engine, postProcessType, ratio, samplingMode) {
  16935. var postProcess;
  16936. var instance;
  16937. var args = [];
  16938. var parameters = PostProcessRenderEffect._GetParametersNames(postProcessType);
  16939. for (var i = 0; i < parameters.length; i++) {
  16940. switch (parameters[i]) {
  16941. case "name":
  16942. args[i] = postProcessType.toString();
  16943. break;
  16944. case "ratio":
  16945. args[i] = ratio;
  16946. break;
  16947. case "camera":
  16948. args[i] = null;
  16949. break;
  16950. case "samplingMode":
  16951. args[i] = samplingMode;
  16952. break;
  16953. case "engine":
  16954. args[i] = engine;
  16955. break;
  16956. case "reusable":
  16957. args[i] = true;
  16958. break;
  16959. default:
  16960. args[i] = null;
  16961. break;
  16962. }
  16963. }
  16964. postProcess = function () {
  16965. };
  16966. postProcess.prototype = postProcessType.prototype;
  16967. instance = new postProcess();
  16968. postProcessType.apply(instance, args);
  16969. return instance;
  16970. };
  16971. PostProcessRenderEffect._GetParametersNames = function (func) {
  16972. var commentsRegex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  16973. var functWithoutComments = func.toString().replace(commentsRegex, '');
  16974. var parameters = functWithoutComments.slice(functWithoutComments.indexOf('(') + 1, functWithoutComments.indexOf(')')).match(/([^\s,]+)/g);
  16975. if (parameters === null)
  16976. parameters = [];
  16977. return parameters;
  16978. };
  16979. PostProcessRenderEffect.prototype._update = function () {
  16980. for (var renderPassName in this._renderPasses) {
  16981. this._renderPasses[renderPassName]._update();
  16982. }
  16983. };
  16984. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  16985. this._renderPasses[renderPass._name] = renderPass;
  16986. this._linkParameters();
  16987. };
  16988. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  16989. delete this._renderPasses[renderPass._name];
  16990. this._linkParameters();
  16991. };
  16992. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  16993. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  16994. this._linkParameters();
  16995. };
  16996. PostProcessRenderEffect.prototype.getPass = function (passName) {
  16997. for (var renderPassName in this._renderPasses) {
  16998. if (renderPassName === passName) {
  16999. return this._renderPasses[passName];
  17000. }
  17001. }
  17002. };
  17003. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17004. this._renderPasses.length = 0;
  17005. this._linkParameters();
  17006. };
  17007. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17008. var cameraKey;
  17009. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17010. for (var i = 0; i < _cam.length; i++) {
  17011. var camera = _cam[i];
  17012. var cameraName = camera.name;
  17013. if (this._singleInstance) {
  17014. cameraKey = 0;
  17015. } else {
  17016. cameraKey = cameraName;
  17017. }
  17018. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || PostProcessRenderEffect._GetInstance(this._engine, this._postProcessType, this._ratio, this._samplingMode);
  17019. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17020. if (this._indicesForCamera[cameraName] === null) {
  17021. this._indicesForCamera[cameraName] = [];
  17022. }
  17023. this._indicesForCamera[cameraName].push(index);
  17024. if (this._cameras.indexOf(camera) === -1) {
  17025. this._cameras[cameraName] = camera;
  17026. }
  17027. for (var passName in this._renderPasses) {
  17028. this._renderPasses[passName]._incRefCount();
  17029. }
  17030. }
  17031. this._linkParameters();
  17032. };
  17033. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17034. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17035. for (var i = 0; i < _cam.length; i++) {
  17036. var camera = _cam[i];
  17037. var cameraName = camera.name;
  17038. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17039. var index = this._cameras.indexOf(cameraName);
  17040. this._indicesForCamera.splice(index, 1);
  17041. this._cameras.splice(index, 1);
  17042. for (var passName in this._renderPasses) {
  17043. this._renderPasses[passName]._decRefCount();
  17044. }
  17045. }
  17046. };
  17047. PostProcessRenderEffect.prototype._enable = 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. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17053. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17054. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17055. }
  17056. }
  17057. for (var passName in this._renderPasses) {
  17058. this._renderPasses[passName]._incRefCount();
  17059. }
  17060. }
  17061. };
  17062. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17063. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17064. for (var i = 0; i < _cam.length; i++) {
  17065. var camera = _cam[i];
  17066. var cameraName = camera.Name;
  17067. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17068. for (var passName in this._renderPasses) {
  17069. this._renderPasses[passName]._decRefCount();
  17070. }
  17071. }
  17072. };
  17073. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17074. if (this._singleInstance) {
  17075. return this._postProcesses[0];
  17076. } else {
  17077. return this._postProcesses[camera.name];
  17078. }
  17079. };
  17080. PostProcessRenderEffect.prototype._linkParameters = function () {
  17081. var _this = this;
  17082. for (var index in this._postProcesses) {
  17083. this._postProcesses[index].onApply = function (effect) {
  17084. _this.parameters(effect);
  17085. _this._linkTextures(effect);
  17086. };
  17087. }
  17088. };
  17089. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17090. for (var renderPassName in this._renderPasses) {
  17091. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17092. }
  17093. for (var renderEffectName in this._renderEffectAsPasses) {
  17094. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17095. }
  17096. };
  17097. return PostProcessRenderEffect;
  17098. })();
  17099. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17100. })(BABYLON || (BABYLON = {}));
  17101. var BABYLON;
  17102. (function (BABYLON) {
  17103. var PostProcessRenderPipeline = (function () {
  17104. function PostProcessRenderPipeline(engine, name) {
  17105. this._engine = engine;
  17106. this._name = name;
  17107. this._renderEffects = [];
  17108. this._renderEffectsForIsolatedPass = [];
  17109. this._cameras = [];
  17110. }
  17111. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17112. this._renderEffects[renderEffect._name] = renderEffect;
  17113. };
  17114. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17115. var renderEffects = this._renderEffects[renderEffectName];
  17116. if (!renderEffects) {
  17117. return;
  17118. }
  17119. renderEffects.enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17120. };
  17121. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17122. var renderEffects = this._renderEffects[renderEffectName];
  17123. if (!renderEffects) {
  17124. return;
  17125. }
  17126. renderEffects.disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17127. };
  17128. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17129. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17130. var indicesToDelete = [];
  17131. for (var i = 0; i < _cam.length; i++) {
  17132. var camera = _cam[i];
  17133. var cameraName = camera.name;
  17134. if (this._cameras.indexOf(camera) === -1) {
  17135. this._cameras[cameraName] = camera;
  17136. } else if (unique) {
  17137. indicesToDelete.push(i);
  17138. }
  17139. }
  17140. for (var i = 0; i < indicesToDelete.length; i++) {
  17141. cameras.splice(indicesToDelete[i], 1);
  17142. }
  17143. for (var renderEffectName in this._renderEffects) {
  17144. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17145. }
  17146. };
  17147. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17148. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17149. for (var renderEffectName in this._renderEffects) {
  17150. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17151. }
  17152. for (var i = 0; i < _cam.length; i++) {
  17153. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17154. }
  17155. };
  17156. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17157. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17158. var pass = null;
  17159. for (var renderEffectName in this._renderEffects) {
  17160. pass = this._renderEffects[renderEffectName].getPass(passName);
  17161. if (pass != null) {
  17162. break;
  17163. }
  17164. }
  17165. if (pass === null) {
  17166. return;
  17167. }
  17168. for (var renderEffectName in this._renderEffects) {
  17169. this._renderEffects[renderEffectName]._disable(_cam);
  17170. }
  17171. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17172. for (var i = 0; i < _cam.length; i++) {
  17173. var camera = _cam[i];
  17174. var cameraName = camera.name;
  17175. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17176. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17177. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17178. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17179. }
  17180. };
  17181. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17182. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17183. for (var i = 0; i < _cam.length; i++) {
  17184. var camera = _cam[i];
  17185. var cameraName = camera.name;
  17186. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, "BABYLON.DisplayPassPostProcess", 1.0, null, null);
  17187. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17188. }
  17189. for (var renderEffectName in this._renderEffects) {
  17190. this._renderEffects[renderEffectName]._enable(_cam);
  17191. }
  17192. };
  17193. PostProcessRenderPipeline.prototype._update = function () {
  17194. for (var renderEffectName in this._renderEffects) {
  17195. this._renderEffects[renderEffectName]._update();
  17196. }
  17197. for (var i = 0; i < this._cameras.length; i++) {
  17198. var cameraName = this._cameras[i].name;
  17199. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17200. this._renderEffectsForIsolatedPass[cameraName]._update();
  17201. }
  17202. }
  17203. };
  17204. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17205. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17206. return PostProcessRenderPipeline;
  17207. })();
  17208. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17209. })(BABYLON || (BABYLON = {}));
  17210. var BABYLON;
  17211. (function (BABYLON) {
  17212. var PostProcessRenderPipelineManager = (function () {
  17213. function PostProcessRenderPipelineManager() {
  17214. this._renderPipelines = [];
  17215. }
  17216. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17217. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17218. };
  17219. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17220. var renderPipeline = this._renderPipelines[renderPipelineName];
  17221. if (!renderPipeline) {
  17222. return;
  17223. }
  17224. renderPipeline.attachCameras(cameras, unique);
  17225. };
  17226. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17227. var renderPipeline = this._renderPipelines[renderPipelineName];
  17228. if (!renderPipeline) {
  17229. return;
  17230. }
  17231. renderPipeline.detachCameras(cameras);
  17232. };
  17233. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17234. var renderPipeline = this._renderPipelines[renderPipelineName];
  17235. if (!renderPipeline) {
  17236. return;
  17237. }
  17238. renderPipeline.enableEffect(renderEffectName, cameras);
  17239. };
  17240. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17241. var renderPipeline = this._renderPipelines[renderPipelineName];
  17242. if (!renderPipeline) {
  17243. return;
  17244. }
  17245. renderPipeline.disableEffect(renderEffectName, cameras);
  17246. };
  17247. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17248. var renderPipeline = this._renderPipelines[renderPipelineName];
  17249. if (!renderPipeline) {
  17250. return;
  17251. }
  17252. renderPipeline.enableDisplayOnlyPass(passName, cameras);
  17253. };
  17254. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17255. var renderPipeline = this._renderPipelines[renderPipelineName];
  17256. if (!renderPipeline) {
  17257. return;
  17258. }
  17259. renderPipeline.disableDisplayOnlyPass(cameras);
  17260. };
  17261. PostProcessRenderPipelineManager.prototype.update = function () {
  17262. for (var renderPipelineName in this._renderPipelines) {
  17263. this._renderPipelines[renderPipelineName]._update();
  17264. }
  17265. };
  17266. return PostProcessRenderPipelineManager;
  17267. })();
  17268. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17269. })(BABYLON || (BABYLON = {}));
  17270. var __extends = this.__extends || function (d, b) {
  17271. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17272. function __() { this.constructor = d; }
  17273. __.prototype = b.prototype;
  17274. d.prototype = new __();
  17275. };
  17276. var BABYLON;
  17277. (function (BABYLON) {
  17278. var DisplayPassPostProcess = (function (_super) {
  17279. __extends(DisplayPassPostProcess, _super);
  17280. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17281. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17282. }
  17283. return DisplayPassPostProcess;
  17284. })(BABYLON.PostProcess);
  17285. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17286. })(BABYLON || (BABYLON = {}));
  17287. var BABYLON;
  17288. (function (BABYLON) {
  17289. var BoundingBoxRenderer = (function () {
  17290. function BoundingBoxRenderer(scene) {
  17291. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17292. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17293. this.showBackLines = true;
  17294. this.renderList = new BABYLON.SmartArray(32);
  17295. this._scene = scene;
  17296. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17297. attributes: ["position"],
  17298. uniforms: ["worldViewProjection", "color"]
  17299. });
  17300. var engine = this._scene.getEngine();
  17301. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17302. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17303. 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]);
  17304. }
  17305. BoundingBoxRenderer.prototype.reset = function () {
  17306. this.renderList.reset();
  17307. };
  17308. BoundingBoxRenderer.prototype.render = function () {
  17309. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17310. return;
  17311. }
  17312. var engine = this._scene.getEngine();
  17313. engine.setDepthWrite(false);
  17314. this._colorShader._preBind();
  17315. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17316. var boundingBox = this.renderList.data[boundingBoxIndex];
  17317. var min = boundingBox.minimum;
  17318. var max = boundingBox.maximum;
  17319. var diff = max.subtract(min);
  17320. var median = min.add(diff.scale(0.5));
  17321. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17322. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17323. if (this.showBackLines) {
  17324. engine.setDepthFunctionToGreaterOrEqual();
  17325. this._colorShader.setColor4("color", this.backColor.toColor4());
  17326. this._colorShader.bind(worldMatrix);
  17327. engine.draw(false, 0, 24);
  17328. }
  17329. engine.setDepthFunctionToLess();
  17330. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17331. this._colorShader.bind(worldMatrix);
  17332. engine.draw(false, 0, 24);
  17333. }
  17334. this._colorShader.unbind();
  17335. engine.setDepthFunctionToLessOrEqual();
  17336. engine.setDepthWrite(true);
  17337. };
  17338. BoundingBoxRenderer.prototype.dispose = function () {
  17339. this._colorShader.dispose();
  17340. this._vb.dispose();
  17341. this._scene.getEngine()._releaseBuffer(this._ib);
  17342. };
  17343. return BoundingBoxRenderer;
  17344. })();
  17345. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17346. })(BABYLON || (BABYLON = {}));
  17347. /**
  17348. * Based on jsTGALoader - Javascript loader for TGA file
  17349. * By Vincent Thibault
  17350. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17351. */
  17352. var BABYLON;
  17353. (function (BABYLON) {
  17354. (function (Internals) {
  17355. var TGATools = (function () {
  17356. function TGATools() {
  17357. }
  17358. TGATools.GetTGAHeader = function (data) {
  17359. var offset = 0;
  17360. var header = {
  17361. id_length: data[offset++],
  17362. colormap_type: data[offset++],
  17363. image_type: data[offset++],
  17364. colormap_index: data[offset++] | data[offset++] << 8,
  17365. colormap_length: data[offset++] | data[offset++] << 8,
  17366. colormap_size: data[offset++],
  17367. origin: [
  17368. data[offset++] | data[offset++] << 8,
  17369. data[offset++] | data[offset++] << 8
  17370. ],
  17371. width: data[offset++] | data[offset++] << 8,
  17372. height: data[offset++] | data[offset++] << 8,
  17373. pixel_size: data[offset++],
  17374. flags: data[offset++]
  17375. };
  17376. return header;
  17377. };
  17378. TGATools.UploadContent = function (gl, data) {
  17379. if (data.length < 19) {
  17380. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17381. return;
  17382. }
  17383. var offset = 18;
  17384. var header = TGATools.GetTGAHeader(data);
  17385. if (header.id_length + offset > data.length) {
  17386. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17387. return;
  17388. }
  17389. offset += header.id_length;
  17390. var use_rle = false;
  17391. var use_pal = false;
  17392. var use_rgb = false;
  17393. var use_grey = false;
  17394. switch (header.image_type) {
  17395. case TGATools._TYPE_RLE_INDEXED:
  17396. use_rle = true;
  17397. case TGATools._TYPE_INDEXED:
  17398. use_pal = true;
  17399. break;
  17400. case TGATools._TYPE_RLE_RGB:
  17401. use_rle = true;
  17402. case TGATools._TYPE_RGB:
  17403. use_rgb = true;
  17404. break;
  17405. case TGATools._TYPE_RLE_GREY:
  17406. use_rle = true;
  17407. case TGATools._TYPE_GREY:
  17408. use_grey = true;
  17409. break;
  17410. }
  17411. var pixel_data;
  17412. var numAlphaBits = header.flags & 0xf;
  17413. var pixel_size = header.pixel_size >> 3;
  17414. var pixel_total = header.width * header.height * pixel_size;
  17415. var palettes;
  17416. if (use_pal) {
  17417. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17418. }
  17419. if (use_rle) {
  17420. pixel_data = new Uint8Array(pixel_total);
  17421. var c, count, i;
  17422. var localOffset = 0;
  17423. var pixels = new Uint8Array(pixel_size);
  17424. while (offset < pixel_total && localOffset < pixel_total) {
  17425. c = data[offset++];
  17426. count = (c & 0x7f) + 1;
  17427. if (c & 0x80) {
  17428. for (i = 0; i < pixel_size; ++i) {
  17429. pixels[i] = data[offset++];
  17430. }
  17431. for (i = 0; i < count; ++i) {
  17432. pixel_data.set(pixels, localOffset + i * pixel_size);
  17433. }
  17434. localOffset += pixel_size * count;
  17435. } else {
  17436. count *= pixel_size;
  17437. for (i = 0; i < count; ++i) {
  17438. pixel_data[localOffset + i] = data[offset++];
  17439. }
  17440. localOffset += count;
  17441. }
  17442. }
  17443. } else {
  17444. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17445. }
  17446. var x_start, y_start, x_step, y_step, y_end, x_end;
  17447. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17448. default:
  17449. case TGATools._ORIGIN_UL:
  17450. x_start = 0;
  17451. x_step = 1;
  17452. x_end = header.width;
  17453. y_start = 0;
  17454. y_step = 1;
  17455. y_end = header.height;
  17456. break;
  17457. case TGATools._ORIGIN_BL:
  17458. x_start = 0;
  17459. x_step = 1;
  17460. x_end = header.width;
  17461. y_start = header.height - 1;
  17462. y_step = -1;
  17463. y_end = -1;
  17464. break;
  17465. case TGATools._ORIGIN_UR:
  17466. x_start = header.width - 1;
  17467. x_step = -1;
  17468. x_end = -1;
  17469. y_start = 0;
  17470. y_step = 1;
  17471. y_end = header.height;
  17472. break;
  17473. case TGATools._ORIGIN_BR:
  17474. x_start = header.width - 1;
  17475. x_step = -1;
  17476. x_end = -1;
  17477. y_start = header.height - 1;
  17478. y_step = -1;
  17479. y_end = -1;
  17480. break;
  17481. }
  17482. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17483. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17484. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17485. };
  17486. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17487. var image = pixel_data, colormap = palettes;
  17488. var width = header.width, height = header.height;
  17489. var color, i = 0, x, y;
  17490. var imageData = new Uint8Array(width * height * 4);
  17491. for (y = y_start; y !== y_end; y += y_step) {
  17492. for (x = x_start; x !== x_end; x += x_step, i++) {
  17493. color = image[i];
  17494. imageData[(x + width * y) * 4 + 3] = 255;
  17495. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17496. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17497. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17498. }
  17499. }
  17500. return imageData;
  17501. };
  17502. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17503. var image = pixel_data;
  17504. var width = header.width, height = header.height;
  17505. var color, i = 0, x, y;
  17506. var imageData = new Uint8Array(width * height * 4);
  17507. for (y = y_start; y !== y_end; y += y_step) {
  17508. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17509. color = image[i + 0] + (image[i + 1] << 8);
  17510. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17511. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17512. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17513. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17514. }
  17515. }
  17516. return imageData;
  17517. };
  17518. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17519. var image = pixel_data;
  17520. var width = header.width, height = header.height;
  17521. var i = 0, x, y;
  17522. var imageData = new Uint8Array(width * height * 4);
  17523. for (y = y_start; y !== y_end; y += y_step) {
  17524. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17525. imageData[(x + width * y) * 4 + 3] = 255;
  17526. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17527. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17528. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17529. }
  17530. }
  17531. return imageData;
  17532. };
  17533. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17534. var image = pixel_data;
  17535. var width = header.width, height = header.height;
  17536. var i = 0, x, y;
  17537. var imageData = new Uint8Array(width * height * 4);
  17538. for (y = y_start; y !== y_end; y += y_step) {
  17539. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  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. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17544. }
  17545. }
  17546. return imageData;
  17547. };
  17548. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17549. var image = pixel_data;
  17550. var width = header.width, height = header.height;
  17551. var color, i = 0, x, y;
  17552. var imageData = new Uint8Array(width * height * 4);
  17553. for (y = y_start; y !== y_end; y += y_step) {
  17554. for (x = x_start; x !== x_end; x += x_step, i++) {
  17555. color = image[i];
  17556. imageData[(x + width * y) * 4 + 0] = color;
  17557. imageData[(x + width * y) * 4 + 1] = color;
  17558. imageData[(x + width * y) * 4 + 2] = color;
  17559. imageData[(x + width * y) * 4 + 3] = 255;
  17560. }
  17561. }
  17562. return imageData;
  17563. };
  17564. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17565. var image = pixel_data;
  17566. var width = header.width, height = header.height;
  17567. var i = 0, x, y;
  17568. var imageData = new Uint8Array(width * height * 4);
  17569. for (y = y_start; y !== y_end; y += y_step) {
  17570. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17571. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17572. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17573. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17574. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17575. }
  17576. }
  17577. return imageData;
  17578. };
  17579. TGATools._TYPE_NO_DATA = 0;
  17580. TGATools._TYPE_INDEXED = 1;
  17581. TGATools._TYPE_RGB = 2;
  17582. TGATools._TYPE_GREY = 3;
  17583. TGATools._TYPE_RLE_INDEXED = 9;
  17584. TGATools._TYPE_RLE_RGB = 10;
  17585. TGATools._TYPE_RLE_GREY = 11;
  17586. TGATools._ORIGIN_MASK = 0x30;
  17587. TGATools._ORIGIN_SHIFT = 0x04;
  17588. TGATools._ORIGIN_BL = 0x00;
  17589. TGATools._ORIGIN_BR = 0x01;
  17590. TGATools._ORIGIN_UL = 0x02;
  17591. TGATools._ORIGIN_UR = 0x03;
  17592. return TGATools;
  17593. })();
  17594. Internals.TGATools = TGATools;
  17595. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17596. var Internals = BABYLON.Internals;
  17597. })(BABYLON || (BABYLON = {}));
  17598. var BABYLON;
  17599. (function (BABYLON) {
  17600. (function (Internals) {
  17601. var DDS_MAGIC = 0x20534444;
  17602. 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;
  17603. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17604. 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;
  17605. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17606. function FourCCToInt32(value) {
  17607. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17608. }
  17609. function Int32ToFourCC(value) {
  17610. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17611. }
  17612. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17613. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17614. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17615. var headerLengthInt = 31;
  17616. var off_magic = 0;
  17617. var off_size = 1;
  17618. var off_flags = 2;
  17619. var off_height = 3;
  17620. var off_width = 4;
  17621. var off_mipmapCount = 7;
  17622. var off_pfFlags = 20;
  17623. var off_pfFourCC = 21;
  17624. var off_RGBbpp = 22;
  17625. var off_RMask = 23;
  17626. var off_GMask = 24;
  17627. var off_BMask = 25;
  17628. var off_AMask = 26;
  17629. var off_caps1 = 27;
  17630. var off_caps2 = 28;
  17631. ;
  17632. var DDSTools = (function () {
  17633. function DDSTools() {
  17634. }
  17635. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17636. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17637. var mipmapCount = 1;
  17638. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17639. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17640. }
  17641. return {
  17642. width: header[off_width],
  17643. height: header[off_height],
  17644. mipmapCount: mipmapCount,
  17645. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17646. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17647. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17648. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17649. };
  17650. };
  17651. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17652. var byteArray = new Uint8Array(dataLength);
  17653. var srcData = new Uint8Array(arrayBuffer);
  17654. var index = 0;
  17655. for (var y = height - 1; y >= 0; y--) {
  17656. for (var x = 0; x < width; x++) {
  17657. var srcPos = dataOffset + (x + y * width) * 4;
  17658. byteArray[index + 2] = srcData[srcPos];
  17659. byteArray[index + 1] = srcData[srcPos + 1];
  17660. byteArray[index] = srcData[srcPos + 2];
  17661. byteArray[index + 3] = srcData[srcPos + 3];
  17662. index += 4;
  17663. }
  17664. }
  17665. return byteArray;
  17666. };
  17667. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17668. var byteArray = new Uint8Array(dataLength);
  17669. var srcData = new Uint8Array(arrayBuffer);
  17670. var index = 0;
  17671. for (var y = height - 1; y >= 0; y--) {
  17672. for (var x = 0; x < width; x++) {
  17673. var srcPos = dataOffset + (x + y * width) * 3;
  17674. byteArray[index + 2] = srcData[srcPos];
  17675. byteArray[index + 1] = srcData[srcPos + 1];
  17676. byteArray[index] = srcData[srcPos + 2];
  17677. index += 3;
  17678. }
  17679. }
  17680. return byteArray;
  17681. };
  17682. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17683. var byteArray = new Uint8Array(dataLength);
  17684. var srcData = new Uint8Array(arrayBuffer);
  17685. var index = 0;
  17686. for (var y = height - 1; y >= 0; y--) {
  17687. for (var x = 0; x < width; x++) {
  17688. var srcPos = dataOffset + (x + y * width);
  17689. byteArray[index] = srcData[srcPos];
  17690. index++;
  17691. }
  17692. }
  17693. return byteArray;
  17694. };
  17695. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17696. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17697. if (header[off_magic] != DDS_MAGIC) {
  17698. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17699. return;
  17700. }
  17701. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17702. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17703. return;
  17704. }
  17705. if (info.isFourCC) {
  17706. fourCC = header[off_pfFourCC];
  17707. switch (fourCC) {
  17708. case FOURCC_DXT1:
  17709. blockBytes = 8;
  17710. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17711. break;
  17712. case FOURCC_DXT3:
  17713. blockBytes = 16;
  17714. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17715. break;
  17716. case FOURCC_DXT5:
  17717. blockBytes = 16;
  17718. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17719. break;
  17720. default:
  17721. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17722. return;
  17723. }
  17724. }
  17725. mipmapCount = 1;
  17726. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17727. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17728. }
  17729. var bpp = header[off_RGBbpp];
  17730. for (var face = 0; face < faces; face++) {
  17731. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17732. width = header[off_width];
  17733. height = header[off_height];
  17734. dataOffset = header[off_size] + 4;
  17735. for (i = 0; i < mipmapCount; ++i) {
  17736. if (info.isRGB) {
  17737. if (bpp == 24) {
  17738. dataLength = width * height * 3;
  17739. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17740. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17741. } else {
  17742. dataLength = width * height * 4;
  17743. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17744. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17745. }
  17746. } else if (info.isLuminance) {
  17747. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17748. var unpaddedRowSize = width;
  17749. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17750. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17751. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17752. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17753. } else {
  17754. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17755. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17756. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17757. }
  17758. dataOffset += dataLength;
  17759. width *= 0.5;
  17760. height *= 0.5;
  17761. width = Math.max(1.0, width);
  17762. height = Math.max(1.0, height);
  17763. }
  17764. }
  17765. };
  17766. return DDSTools;
  17767. })();
  17768. Internals.DDSTools = DDSTools;
  17769. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17770. var Internals = BABYLON.Internals;
  17771. })(BABYLON || (BABYLON = {}));
  17772. var BABYLON;
  17773. (function (BABYLON) {
  17774. var SmartArray = (function () {
  17775. function SmartArray(capacity) {
  17776. this.length = 0;
  17777. this._duplicateId = 0;
  17778. this.data = new Array(capacity);
  17779. this._id = SmartArray._GlobalId++;
  17780. }
  17781. SmartArray.prototype.push = function (value) {
  17782. this.data[this.length++] = value;
  17783. if (this.length > this.data.length) {
  17784. this.data.length *= 2;
  17785. }
  17786. if (!value.__smartArrayFlags) {
  17787. value.__smartArrayFlags = {};
  17788. }
  17789. value.__smartArrayFlags[this._id] = this._duplicateId;
  17790. };
  17791. SmartArray.prototype.pushNoDuplicate = function (value) {
  17792. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17793. return;
  17794. }
  17795. this.push(value);
  17796. };
  17797. SmartArray.prototype.sort = function (compareFn) {
  17798. this.data.sort(compareFn);
  17799. };
  17800. SmartArray.prototype.reset = function () {
  17801. this.length = 0;
  17802. this._duplicateId++;
  17803. };
  17804. SmartArray.prototype.concat = function (array) {
  17805. if (array.length === 0) {
  17806. return;
  17807. }
  17808. if (this.length + array.length > this.data.length) {
  17809. this.data.length = (this.length + array.length) * 2;
  17810. }
  17811. for (var index = 0; index < array.length; index++) {
  17812. this.data[this.length++] = (array.data || array)[index];
  17813. }
  17814. };
  17815. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17816. if (array.length === 0) {
  17817. return;
  17818. }
  17819. if (this.length + array.length > this.data.length) {
  17820. this.data.length = (this.length + array.length) * 2;
  17821. }
  17822. for (var index = 0; index < array.length; index++) {
  17823. var item = (array.data || array)[index];
  17824. this.pushNoDuplicate(item);
  17825. }
  17826. };
  17827. SmartArray.prototype.indexOf = function (value) {
  17828. var position = this.data.indexOf(value);
  17829. if (position >= this.length) {
  17830. return -1;
  17831. }
  17832. return position;
  17833. };
  17834. SmartArray._GlobalId = 0;
  17835. return SmartArray;
  17836. })();
  17837. BABYLON.SmartArray = SmartArray;
  17838. })(BABYLON || (BABYLON = {}));
  17839. var BABYLON;
  17840. (function (BABYLON) {
  17841. var CannonJSPlugin = (function () {
  17842. function CannonJSPlugin() {
  17843. this._registeredMeshes = [];
  17844. this._physicsMaterials = [];
  17845. this.updateBodyPosition = function (mesh) {
  17846. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17847. var registeredMesh = this._registeredMeshes[index];
  17848. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17849. var body = registeredMesh.body.body;
  17850. var center = mesh.getBoundingInfo().boundingBox.center;
  17851. body.position.set(center.x, center.z, center.y);
  17852. body.quaternion.x = mesh.rotationQuaternion.x;
  17853. body.quaternion.z = mesh.rotationQuaternion.y;
  17854. body.quaternion.y = mesh.rotationQuaternion.z;
  17855. body.quaternion.w = -mesh.rotationQuaternion.w;
  17856. return;
  17857. }
  17858. }
  17859. };
  17860. }
  17861. CannonJSPlugin.prototype.initialize = function (iterations) {
  17862. if (typeof iterations === "undefined") { iterations = 10; }
  17863. this._world = new CANNON.World();
  17864. this._world.broadphase = new CANNON.NaiveBroadphase();
  17865. this._world.solver.iterations = iterations;
  17866. };
  17867. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  17868. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17869. };
  17870. CannonJSPlugin.prototype.runOneStep = function (delta) {
  17871. this._world.step(delta);
  17872. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17873. var registeredMesh = this._registeredMeshes[index];
  17874. if (registeredMesh.isChild) {
  17875. continue;
  17876. }
  17877. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  17878. var deltaPos = registeredMesh.delta;
  17879. if (deltaPos) {
  17880. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  17881. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  17882. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  17883. } else {
  17884. registeredMesh.mesh.position.x = bodyX;
  17885. registeredMesh.mesh.position.y = bodyZ;
  17886. registeredMesh.mesh.position.z = bodyY;
  17887. }
  17888. if (!registeredMesh.mesh.rotationQuaternion) {
  17889. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17890. }
  17891. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  17892. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  17893. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  17894. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  17895. }
  17896. };
  17897. CannonJSPlugin.prototype.setGravity = function (gravity) {
  17898. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  17899. };
  17900. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17901. this.unregisterMesh(mesh);
  17902. mesh.computeWorldMatrix(true);
  17903. switch (impostor) {
  17904. case BABYLON.PhysicsEngine.SphereImpostor:
  17905. var bbox = mesh.getBoundingInfo().boundingBox;
  17906. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17907. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17908. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17909. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  17910. case BABYLON.PhysicsEngine.BoxImpostor:
  17911. bbox = mesh.getBoundingInfo().boundingBox;
  17912. var min = bbox.minimumWorld;
  17913. var max = bbox.maximumWorld;
  17914. var box = max.subtract(min).scale(0.5);
  17915. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  17916. case BABYLON.PhysicsEngine.PlaneImpostor:
  17917. return this._createPlane(mesh, options);
  17918. case BABYLON.PhysicsEngine.MeshImpostor:
  17919. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17920. var rawFaces = mesh.getIndices();
  17921. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  17922. }
  17923. return null;
  17924. };
  17925. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  17926. var shape = new CANNON.Sphere(radius);
  17927. if (!options) {
  17928. return shape;
  17929. }
  17930. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17931. };
  17932. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  17933. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  17934. if (!options) {
  17935. return shape;
  17936. }
  17937. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17938. };
  17939. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  17940. var shape = new CANNON.Plane();
  17941. if (!options) {
  17942. return shape;
  17943. }
  17944. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17945. };
  17946. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  17947. var verts = [], faces = [];
  17948. mesh.computeWorldMatrix(true);
  17949. for (var i = 0; i < rawVerts.length; i += 3) {
  17950. var transformed = BABYLON.Vector3.Zero();
  17951. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  17952. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  17953. }
  17954. for (var j = 0; j < rawFaces.length; j += 3) {
  17955. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  17956. }
  17957. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  17958. if (!options) {
  17959. return shape;
  17960. }
  17961. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  17962. };
  17963. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  17964. var index;
  17965. var mat;
  17966. for (index = 0; index < this._physicsMaterials.length; index++) {
  17967. mat = this._physicsMaterials[index];
  17968. if (mat.friction === friction && mat.restitution === restitution) {
  17969. return mat;
  17970. }
  17971. }
  17972. var currentMat = new CANNON.Material();
  17973. currentMat.friction = friction;
  17974. currentMat.restitution = restitution;
  17975. this._physicsMaterials.push(currentMat);
  17976. for (index = 0; index < this._physicsMaterials.length; index++) {
  17977. mat = this._physicsMaterials[index];
  17978. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  17979. contactMaterial.contactEquationStiffness = 1e10;
  17980. contactMaterial.contactEquationRegularizationTime = 10;
  17981. this._world.addContactMaterial(contactMaterial);
  17982. }
  17983. return currentMat;
  17984. };
  17985. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  17986. var initialRotation = null;
  17987. if (mesh.rotationQuaternion) {
  17988. initialRotation = mesh.rotationQuaternion.clone();
  17989. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17990. }
  17991. var bbox = mesh.getBoundingInfo().boundingBox;
  17992. var deltaPosition = mesh.position.subtract(bbox.center);
  17993. var material = this._addMaterial(friction, restitution);
  17994. var body = new CANNON.RigidBody(mass, shape, material);
  17995. if (initialRotation) {
  17996. body.quaternion.x = initialRotation.x;
  17997. body.quaternion.z = initialRotation.y;
  17998. body.quaternion.y = initialRotation.z;
  17999. body.quaternion.w = -initialRotation.w;
  18000. }
  18001. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18002. this._world.add(body);
  18003. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18004. return body;
  18005. };
  18006. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18007. var compoundShape = new CANNON.Compound();
  18008. for (var index = 0; index < parts.length; index++) {
  18009. var mesh = parts[index].mesh;
  18010. var shape = this.registerMesh(mesh, parts[index].impostor);
  18011. if (index == 0) {
  18012. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18013. } else {
  18014. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18015. }
  18016. }
  18017. var initialMesh = parts[0].mesh;
  18018. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18019. body.parts = parts;
  18020. return body;
  18021. };
  18022. CannonJSPlugin.prototype._unbindBody = function (body) {
  18023. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18024. var registeredMesh = this._registeredMeshes[index];
  18025. if (registeredMesh.body === body) {
  18026. registeredMesh.body = null;
  18027. registeredMesh.delta = 0;
  18028. }
  18029. }
  18030. };
  18031. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18032. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18033. var registeredMesh = this._registeredMeshes[index];
  18034. if (registeredMesh.mesh === mesh) {
  18035. if (registeredMesh.body) {
  18036. this._world.remove(registeredMesh.body);
  18037. this._unbindBody(registeredMesh.body);
  18038. }
  18039. this._registeredMeshes.splice(index, 1);
  18040. return;
  18041. }
  18042. }
  18043. };
  18044. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18045. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18046. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18047. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18048. var registeredMesh = this._registeredMeshes[index];
  18049. if (registeredMesh.mesh === mesh) {
  18050. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18051. return;
  18052. }
  18053. }
  18054. };
  18055. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18056. var body1 = null, body2 = null;
  18057. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18058. var registeredMesh = this._registeredMeshes[index];
  18059. if (registeredMesh.mesh === mesh1) {
  18060. body1 = registeredMesh.body;
  18061. } else if (registeredMesh.mesh === mesh2) {
  18062. body2 = registeredMesh.body;
  18063. }
  18064. }
  18065. if (!body1 || !body2) {
  18066. return false;
  18067. }
  18068. 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));
  18069. this._world.addConstraint(constraint);
  18070. return true;
  18071. };
  18072. CannonJSPlugin.prototype.dispose = function () {
  18073. while (this._registeredMeshes.length) {
  18074. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18075. }
  18076. };
  18077. CannonJSPlugin.prototype.isSupported = function () {
  18078. return window.CANNON !== undefined;
  18079. };
  18080. return CannonJSPlugin;
  18081. })();
  18082. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18083. })(BABYLON || (BABYLON = {}));
  18084. var __extends = this.__extends || function (d, b) {
  18085. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18086. function __() { this.constructor = d; }
  18087. __.prototype = b.prototype;
  18088. d.prototype = new __();
  18089. };
  18090. var BABYLON;
  18091. (function (BABYLON) {
  18092. var Condition = (function () {
  18093. function Condition(actionManager) {
  18094. this._actionManager = actionManager;
  18095. }
  18096. Condition.prototype.isValid = function () {
  18097. return true;
  18098. };
  18099. Condition.prototype._getProperty = function (propertyPath) {
  18100. return this._actionManager._getProperty(propertyPath);
  18101. };
  18102. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18103. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18104. };
  18105. return Condition;
  18106. })();
  18107. BABYLON.Condition = Condition;
  18108. var ValueCondition = (function (_super) {
  18109. __extends(ValueCondition, _super);
  18110. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18111. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18112. _super.call(this, actionManager);
  18113. this.propertyPath = propertyPath;
  18114. this.value = value;
  18115. this.operator = operator;
  18116. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18117. this._property = this._getProperty(this.propertyPath);
  18118. }
  18119. Object.defineProperty(ValueCondition, "IsEqual", {
  18120. get: function () {
  18121. return ValueCondition._IsEqual;
  18122. },
  18123. enumerable: true,
  18124. configurable: true
  18125. });
  18126. Object.defineProperty(ValueCondition, "IsDifferent", {
  18127. get: function () {
  18128. return ValueCondition._IsDifferent;
  18129. },
  18130. enumerable: true,
  18131. configurable: true
  18132. });
  18133. Object.defineProperty(ValueCondition, "IsGreater", {
  18134. get: function () {
  18135. return ValueCondition._IsGreater;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Object.defineProperty(ValueCondition, "IsLesser", {
  18141. get: function () {
  18142. return ValueCondition._IsLesser;
  18143. },
  18144. enumerable: true,
  18145. configurable: true
  18146. });
  18147. ValueCondition.prototype.isValid = function () {
  18148. switch (this.operator) {
  18149. case ValueCondition.IsGreater:
  18150. return this._target[this._property] > this.value;
  18151. case ValueCondition.IsLesser:
  18152. return this._target[this._property] < this.value;
  18153. case ValueCondition.IsEqual:
  18154. case ValueCondition.IsDifferent:
  18155. var check;
  18156. if (this.value.equals) {
  18157. check = this.value.equals(this._target[this._property]);
  18158. } else {
  18159. check = this.value === this._target[this._property];
  18160. }
  18161. return this.operator === ValueCondition.IsEqual ? check : !check;
  18162. }
  18163. return false;
  18164. };
  18165. ValueCondition._IsEqual = 0;
  18166. ValueCondition._IsDifferent = 1;
  18167. ValueCondition._IsGreater = 2;
  18168. ValueCondition._IsLesser = 3;
  18169. return ValueCondition;
  18170. })(Condition);
  18171. BABYLON.ValueCondition = ValueCondition;
  18172. var PredicateCondition = (function (_super) {
  18173. __extends(PredicateCondition, _super);
  18174. function PredicateCondition(actionManager, predicate) {
  18175. _super.call(this, actionManager);
  18176. this.predicate = predicate;
  18177. }
  18178. PredicateCondition.prototype.isValid = function () {
  18179. return this.predicate();
  18180. };
  18181. return PredicateCondition;
  18182. })(Condition);
  18183. BABYLON.PredicateCondition = PredicateCondition;
  18184. var StateCondition = (function (_super) {
  18185. __extends(StateCondition, _super);
  18186. function StateCondition(actionManager, target, value) {
  18187. _super.call(this, actionManager);
  18188. this.value = value;
  18189. this._target = target;
  18190. }
  18191. StateCondition.prototype.isValid = function () {
  18192. return this._target.state === this.value;
  18193. };
  18194. return StateCondition;
  18195. })(Condition);
  18196. BABYLON.StateCondition = StateCondition;
  18197. })(BABYLON || (BABYLON = {}));
  18198. var BABYLON;
  18199. (function (BABYLON) {
  18200. var Action = (function () {
  18201. function Action(triggerOptions, condition) {
  18202. this.triggerOptions = triggerOptions;
  18203. if (triggerOptions.parameter) {
  18204. this.trigger = triggerOptions.trigger;
  18205. this._triggerParameter = triggerOptions.parameter;
  18206. } else {
  18207. this.trigger = triggerOptions;
  18208. }
  18209. this._nextActiveAction = this;
  18210. this._condition = condition;
  18211. }
  18212. Action.prototype._prepare = function () {
  18213. };
  18214. Action.prototype.getTriggerParameter = function () {
  18215. return this._triggerParameter;
  18216. };
  18217. Action.prototype._executeCurrent = function (evt) {
  18218. if (this._condition) {
  18219. var currentRenderId = this._actionManager.getScene().getRenderId();
  18220. if (this._condition._evaluationId === currentRenderId) {
  18221. if (!this._condition._currentResult) {
  18222. return;
  18223. }
  18224. } else {
  18225. this._condition._evaluationId = currentRenderId;
  18226. if (!this._condition.isValid()) {
  18227. this._condition._currentResult = false;
  18228. return;
  18229. }
  18230. this._condition._currentResult = true;
  18231. }
  18232. }
  18233. this._nextActiveAction.execute(evt);
  18234. if (this._nextActiveAction._child) {
  18235. this._nextActiveAction = this._nextActiveAction._child;
  18236. } else {
  18237. this._nextActiveAction = this;
  18238. }
  18239. };
  18240. Action.prototype.execute = function (evt) {
  18241. };
  18242. Action.prototype.then = function (action) {
  18243. this._child = action;
  18244. action._actionManager = this._actionManager;
  18245. action._prepare();
  18246. return action;
  18247. };
  18248. Action.prototype._getProperty = function (propertyPath) {
  18249. return this._actionManager._getProperty(propertyPath);
  18250. };
  18251. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18252. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18253. };
  18254. return Action;
  18255. })();
  18256. BABYLON.Action = Action;
  18257. })(BABYLON || (BABYLON = {}));
  18258. var BABYLON;
  18259. (function (BABYLON) {
  18260. var ActionEvent = (function () {
  18261. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18262. this.source = source;
  18263. this.pointerX = pointerX;
  18264. this.pointerY = pointerY;
  18265. this.meshUnderPointer = meshUnderPointer;
  18266. this.sourceEvent = sourceEvent;
  18267. }
  18268. ActionEvent.CreateNew = function (source) {
  18269. var scene = source.getScene();
  18270. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18271. };
  18272. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18273. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18274. };
  18275. return ActionEvent;
  18276. })();
  18277. BABYLON.ActionEvent = ActionEvent;
  18278. var ActionManager = (function () {
  18279. function ActionManager(scene) {
  18280. this.actions = new Array();
  18281. this._scene = scene;
  18282. scene._actionManagers.push(this);
  18283. }
  18284. Object.defineProperty(ActionManager, "NothingTrigger", {
  18285. get: function () {
  18286. return ActionManager._NothingTrigger;
  18287. },
  18288. enumerable: true,
  18289. configurable: true
  18290. });
  18291. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18292. get: function () {
  18293. return ActionManager._OnPickTrigger;
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18299. get: function () {
  18300. return ActionManager._OnLeftPickTrigger;
  18301. },
  18302. enumerable: true,
  18303. configurable: true
  18304. });
  18305. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18306. get: function () {
  18307. return ActionManager._OnRightPickTrigger;
  18308. },
  18309. enumerable: true,
  18310. configurable: true
  18311. });
  18312. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18313. get: function () {
  18314. return ActionManager._OnCenterPickTrigger;
  18315. },
  18316. enumerable: true,
  18317. configurable: true
  18318. });
  18319. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18320. get: function () {
  18321. return ActionManager._OnPointerOverTrigger;
  18322. },
  18323. enumerable: true,
  18324. configurable: true
  18325. });
  18326. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18327. get: function () {
  18328. return ActionManager._OnPointerOutTrigger;
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18334. get: function () {
  18335. return ActionManager._OnEveryFrameTrigger;
  18336. },
  18337. enumerable: true,
  18338. configurable: true
  18339. });
  18340. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18341. get: function () {
  18342. return ActionManager._OnIntersectionEnterTrigger;
  18343. },
  18344. enumerable: true,
  18345. configurable: true
  18346. });
  18347. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18348. get: function () {
  18349. return ActionManager._OnIntersectionExitTrigger;
  18350. },
  18351. enumerable: true,
  18352. configurable: true
  18353. });
  18354. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18355. get: function () {
  18356. return ActionManager._OnKeyDownTrigger;
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18362. get: function () {
  18363. return ActionManager._OnKeyUpTrigger;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. ActionManager.prototype.dispose = function () {
  18369. var index = this._scene._actionManagers.indexOf(this);
  18370. if (index > -1) {
  18371. this._scene._actionManagers.splice(index, 1);
  18372. }
  18373. };
  18374. ActionManager.prototype.getScene = function () {
  18375. return this._scene;
  18376. };
  18377. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18378. for (var index = 0; index < this.actions.length; index++) {
  18379. var action = this.actions[index];
  18380. if (triggers.indexOf(action.trigger) > -1) {
  18381. return true;
  18382. }
  18383. }
  18384. return false;
  18385. };
  18386. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18387. get: function () {
  18388. for (var index = 0; index < this.actions.length; index++) {
  18389. var action = this.actions[index];
  18390. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18391. return true;
  18392. }
  18393. }
  18394. return false;
  18395. },
  18396. enumerable: true,
  18397. configurable: true
  18398. });
  18399. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18400. get: function () {
  18401. for (var index = 0; index < this.actions.length; index++) {
  18402. var action = this.actions[index];
  18403. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18404. return true;
  18405. }
  18406. }
  18407. return false;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. ActionManager.prototype.registerAction = function (action) {
  18413. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18414. if (this.getScene().actionManager !== this) {
  18415. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18416. return null;
  18417. }
  18418. }
  18419. this.actions.push(action);
  18420. action._actionManager = this;
  18421. action._prepare();
  18422. return action;
  18423. };
  18424. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18425. for (var index = 0; index < this.actions.length; index++) {
  18426. var action = this.actions[index];
  18427. if (action.trigger === trigger) {
  18428. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18429. var parameter = action.getTriggerParameter();
  18430. if (parameter) {
  18431. if (evt.sourceEvent.key !== parameter) {
  18432. continue;
  18433. }
  18434. }
  18435. }
  18436. action._executeCurrent(evt);
  18437. }
  18438. }
  18439. };
  18440. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18441. var properties = propertyPath.split(".");
  18442. for (var index = 0; index < properties.length - 1; index++) {
  18443. target = target[properties[index]];
  18444. }
  18445. return target;
  18446. };
  18447. ActionManager.prototype._getProperty = function (propertyPath) {
  18448. var properties = propertyPath.split(".");
  18449. return properties[properties.length - 1];
  18450. };
  18451. ActionManager._NothingTrigger = 0;
  18452. ActionManager._OnPickTrigger = 1;
  18453. ActionManager._OnLeftPickTrigger = 2;
  18454. ActionManager._OnRightPickTrigger = 3;
  18455. ActionManager._OnCenterPickTrigger = 4;
  18456. ActionManager._OnPointerOverTrigger = 5;
  18457. ActionManager._OnPointerOutTrigger = 6;
  18458. ActionManager._OnEveryFrameTrigger = 7;
  18459. ActionManager._OnIntersectionEnterTrigger = 8;
  18460. ActionManager._OnIntersectionExitTrigger = 9;
  18461. ActionManager._OnKeyDownTrigger = 10;
  18462. ActionManager._OnKeyUpTrigger = 11;
  18463. return ActionManager;
  18464. })();
  18465. BABYLON.ActionManager = ActionManager;
  18466. })(BABYLON || (BABYLON = {}));
  18467. var __extends = this.__extends || function (d, b) {
  18468. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18469. function __() { this.constructor = d; }
  18470. __.prototype = b.prototype;
  18471. d.prototype = new __();
  18472. };
  18473. var BABYLON;
  18474. (function (BABYLON) {
  18475. var InterpolateValueAction = (function (_super) {
  18476. __extends(InterpolateValueAction, _super);
  18477. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18478. if (typeof duration === "undefined") { duration = 1000; }
  18479. _super.call(this, triggerOptions, condition);
  18480. this.propertyPath = propertyPath;
  18481. this.value = value;
  18482. this.duration = duration;
  18483. this.stopOtherAnimations = stopOtherAnimations;
  18484. this._target = target;
  18485. }
  18486. InterpolateValueAction.prototype._prepare = function () {
  18487. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18488. this._property = this._getProperty(this.propertyPath);
  18489. };
  18490. InterpolateValueAction.prototype.execute = function () {
  18491. var scene = this._actionManager.getScene();
  18492. var keys = [
  18493. {
  18494. frame: 0,
  18495. value: this._target[this._property]
  18496. }, {
  18497. frame: 100,
  18498. value: this.value
  18499. }
  18500. ];
  18501. var dataType;
  18502. if (typeof this.value === "number") {
  18503. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18504. } else if (this.value instanceof BABYLON.Color3) {
  18505. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18506. } else if (this.value instanceof BABYLON.Vector3) {
  18507. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18508. } else if (this.value instanceof BABYLON.Matrix) {
  18509. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18510. } else if (this.value instanceof BABYLON.Quaternion) {
  18511. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18512. } else {
  18513. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18514. return;
  18515. }
  18516. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18517. animation.setKeys(keys);
  18518. if (this.stopOtherAnimations) {
  18519. scene.stopAnimation(this._target);
  18520. }
  18521. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18522. };
  18523. return InterpolateValueAction;
  18524. })(BABYLON.Action);
  18525. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18526. })(BABYLON || (BABYLON = {}));
  18527. var __extends = this.__extends || function (d, b) {
  18528. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18529. function __() { this.constructor = d; }
  18530. __.prototype = b.prototype;
  18531. d.prototype = new __();
  18532. };
  18533. var BABYLON;
  18534. (function (BABYLON) {
  18535. var SwitchBooleanAction = (function (_super) {
  18536. __extends(SwitchBooleanAction, _super);
  18537. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18538. _super.call(this, triggerOptions, condition);
  18539. this.propertyPath = propertyPath;
  18540. this._target = target;
  18541. }
  18542. SwitchBooleanAction.prototype._prepare = function () {
  18543. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18544. this._property = this._getProperty(this.propertyPath);
  18545. };
  18546. SwitchBooleanAction.prototype.execute = function () {
  18547. this._target[this._property] = !this._target[this._property];
  18548. };
  18549. return SwitchBooleanAction;
  18550. })(BABYLON.Action);
  18551. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18552. var SetStateAction = (function (_super) {
  18553. __extends(SetStateAction, _super);
  18554. function SetStateAction(triggerOptions, target, value, condition) {
  18555. _super.call(this, triggerOptions, condition);
  18556. this.value = value;
  18557. this._target = target;
  18558. }
  18559. SetStateAction.prototype.execute = function () {
  18560. this._target.state = this.value;
  18561. };
  18562. return SetStateAction;
  18563. })(BABYLON.Action);
  18564. BABYLON.SetStateAction = SetStateAction;
  18565. var SetValueAction = (function (_super) {
  18566. __extends(SetValueAction, _super);
  18567. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18568. _super.call(this, triggerOptions, condition);
  18569. this.propertyPath = propertyPath;
  18570. this.value = value;
  18571. this._target = target;
  18572. }
  18573. SetValueAction.prototype._prepare = function () {
  18574. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18575. this._property = this._getProperty(this.propertyPath);
  18576. };
  18577. SetValueAction.prototype.execute = function () {
  18578. this._target[this._property] = this.value;
  18579. };
  18580. return SetValueAction;
  18581. })(BABYLON.Action);
  18582. BABYLON.SetValueAction = SetValueAction;
  18583. var IncrementValueAction = (function (_super) {
  18584. __extends(IncrementValueAction, _super);
  18585. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18586. _super.call(this, triggerOptions, condition);
  18587. this.propertyPath = propertyPath;
  18588. this.value = value;
  18589. this._target = target;
  18590. }
  18591. IncrementValueAction.prototype._prepare = function () {
  18592. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18593. this._property = this._getProperty(this.propertyPath);
  18594. if (typeof this._target[this._property] !== "number") {
  18595. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18596. }
  18597. };
  18598. IncrementValueAction.prototype.execute = function () {
  18599. this._target[this._property] += this.value;
  18600. };
  18601. return IncrementValueAction;
  18602. })(BABYLON.Action);
  18603. BABYLON.IncrementValueAction = IncrementValueAction;
  18604. var PlayAnimationAction = (function (_super) {
  18605. __extends(PlayAnimationAction, _super);
  18606. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18607. _super.call(this, triggerOptions, condition);
  18608. this.from = from;
  18609. this.to = to;
  18610. this.loop = loop;
  18611. this._target = target;
  18612. }
  18613. PlayAnimationAction.prototype._prepare = function () {
  18614. };
  18615. PlayAnimationAction.prototype.execute = function () {
  18616. var scene = this._actionManager.getScene();
  18617. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18618. };
  18619. return PlayAnimationAction;
  18620. })(BABYLON.Action);
  18621. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18622. var StopAnimationAction = (function (_super) {
  18623. __extends(StopAnimationAction, _super);
  18624. function StopAnimationAction(triggerOptions, target, condition) {
  18625. _super.call(this, triggerOptions, condition);
  18626. this._target = target;
  18627. }
  18628. StopAnimationAction.prototype._prepare = function () {
  18629. };
  18630. StopAnimationAction.prototype.execute = function () {
  18631. var scene = this._actionManager.getScene();
  18632. scene.stopAnimation(this._target);
  18633. };
  18634. return StopAnimationAction;
  18635. })(BABYLON.Action);
  18636. BABYLON.StopAnimationAction = StopAnimationAction;
  18637. var DoNothingAction = (function (_super) {
  18638. __extends(DoNothingAction, _super);
  18639. function DoNothingAction(triggerOptions, condition) {
  18640. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18641. _super.call(this, triggerOptions, condition);
  18642. }
  18643. DoNothingAction.prototype.execute = function () {
  18644. };
  18645. return DoNothingAction;
  18646. })(BABYLON.Action);
  18647. BABYLON.DoNothingAction = DoNothingAction;
  18648. var CombineAction = (function (_super) {
  18649. __extends(CombineAction, _super);
  18650. function CombineAction(triggerOptions, children, condition) {
  18651. _super.call(this, triggerOptions, condition);
  18652. this.children = children;
  18653. }
  18654. CombineAction.prototype._prepare = function () {
  18655. for (var index = 0; index < this.children.length; index++) {
  18656. this.children[index]._actionManager = this._actionManager;
  18657. this.children[index]._prepare();
  18658. }
  18659. };
  18660. CombineAction.prototype.execute = function (evt) {
  18661. for (var index = 0; index < this.children.length; index++) {
  18662. this.children[index].execute(evt);
  18663. }
  18664. };
  18665. return CombineAction;
  18666. })(BABYLON.Action);
  18667. BABYLON.CombineAction = CombineAction;
  18668. var ExecuteCodeAction = (function (_super) {
  18669. __extends(ExecuteCodeAction, _super);
  18670. function ExecuteCodeAction(triggerOptions, func, condition) {
  18671. _super.call(this, triggerOptions, condition);
  18672. this.func = func;
  18673. }
  18674. ExecuteCodeAction.prototype.execute = function (evt) {
  18675. this.func(evt);
  18676. };
  18677. return ExecuteCodeAction;
  18678. })(BABYLON.Action);
  18679. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18680. var SetParentAction = (function (_super) {
  18681. __extends(SetParentAction, _super);
  18682. function SetParentAction(triggerOptions, target, parent, condition) {
  18683. _super.call(this, triggerOptions, condition);
  18684. this._target = target;
  18685. this._parent = parent;
  18686. }
  18687. SetParentAction.prototype._prepare = function () {
  18688. };
  18689. SetParentAction.prototype.execute = function () {
  18690. if (this._target.parent === this._parent) {
  18691. return;
  18692. }
  18693. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18694. invertParentWorldMatrix.invert();
  18695. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18696. this._target.parent = this._parent;
  18697. };
  18698. return SetParentAction;
  18699. })(BABYLON.Action);
  18700. BABYLON.SetParentAction = SetParentAction;
  18701. })(BABYLON || (BABYLON = {}));
  18702. var __extends = this.__extends || function (d, b) {
  18703. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18704. function __() { this.constructor = d; }
  18705. __.prototype = b.prototype;
  18706. d.prototype = new __();
  18707. };
  18708. var BABYLON;
  18709. (function (BABYLON) {
  18710. var Geometry = (function () {
  18711. function Geometry(id, scene, vertexData, updatable, mesh) {
  18712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18713. this._totalVertices = 0;
  18714. this._indices = [];
  18715. this.id = id;
  18716. this._engine = scene.getEngine();
  18717. this._meshes = [];
  18718. this._scene = scene;
  18719. if (vertexData) {
  18720. this.setAllVerticesData(vertexData, updatable);
  18721. } else {
  18722. this._totalVertices = 0;
  18723. this._indices = [];
  18724. }
  18725. if (mesh) {
  18726. this.applyToMesh(mesh);
  18727. }
  18728. }
  18729. Geometry.prototype.getScene = function () {
  18730. return this._scene;
  18731. };
  18732. Geometry.prototype.getEngine = function () {
  18733. return this._engine;
  18734. };
  18735. Geometry.prototype.isReady = function () {
  18736. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18737. };
  18738. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18739. vertexData.applyToGeometry(this, updatable);
  18740. };
  18741. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18742. this._vertexBuffers = this._vertexBuffers || {};
  18743. if (this._vertexBuffers[kind]) {
  18744. this._vertexBuffers[kind].dispose();
  18745. }
  18746. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18747. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18748. var stride = this._vertexBuffers[kind].getStrideSize();
  18749. this._totalVertices = data.length / stride;
  18750. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18751. var meshes = this._meshes;
  18752. var numOfMeshes = meshes.length;
  18753. for (var index = 0; index < numOfMeshes; index++) {
  18754. var mesh = meshes[index];
  18755. mesh._resetPointsArrayCache();
  18756. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18757. mesh._createGlobalSubMesh();
  18758. mesh.computeWorldMatrix(true);
  18759. }
  18760. }
  18761. };
  18762. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18763. var vertexBuffer = this.getVertexBuffer(kind);
  18764. if (!vertexBuffer) {
  18765. return;
  18766. }
  18767. vertexBuffer.update(data);
  18768. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18769. var extend;
  18770. if (updateExtends) {
  18771. var stride = vertexBuffer.getStrideSize();
  18772. this._totalVertices = data.length / stride;
  18773. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18774. }
  18775. var meshes = this._meshes;
  18776. var numOfMeshes = meshes.length;
  18777. for (var index = 0; index < numOfMeshes; index++) {
  18778. var mesh = meshes[index];
  18779. mesh._resetPointsArrayCache();
  18780. if (updateExtends) {
  18781. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18782. }
  18783. }
  18784. }
  18785. };
  18786. Geometry.prototype.getTotalVertices = function () {
  18787. if (!this.isReady()) {
  18788. return 0;
  18789. }
  18790. return this._totalVertices;
  18791. };
  18792. Geometry.prototype.getVerticesData = function (kind) {
  18793. var vertexBuffer = this.getVertexBuffer(kind);
  18794. if (!vertexBuffer) {
  18795. return null;
  18796. }
  18797. return vertexBuffer.getData();
  18798. };
  18799. Geometry.prototype.getVertexBuffer = function (kind) {
  18800. if (!this.isReady()) {
  18801. return null;
  18802. }
  18803. return this._vertexBuffers[kind];
  18804. };
  18805. Geometry.prototype.getVertexBuffers = function () {
  18806. if (!this.isReady()) {
  18807. return null;
  18808. }
  18809. return this._vertexBuffers;
  18810. };
  18811. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18812. if (!this._vertexBuffers) {
  18813. if (this._delayInfo) {
  18814. return this._delayInfo.indexOf(kind) !== -1;
  18815. }
  18816. return false;
  18817. }
  18818. return this._vertexBuffers[kind] !== undefined;
  18819. };
  18820. Geometry.prototype.getVerticesDataKinds = function () {
  18821. var result = [];
  18822. if (!this._vertexBuffers && this._delayInfo) {
  18823. for (var kind in this._delayInfo) {
  18824. result.push(kind);
  18825. }
  18826. } else {
  18827. for (kind in this._vertexBuffers) {
  18828. result.push(kind);
  18829. }
  18830. }
  18831. return result;
  18832. };
  18833. Geometry.prototype.setIndices = function (indices) {
  18834. if (this._indexBuffer) {
  18835. this._engine._releaseBuffer(this._indexBuffer);
  18836. }
  18837. this._indices = indices;
  18838. if (this._meshes.length !== 0 && this._indices) {
  18839. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18840. }
  18841. var meshes = this._meshes;
  18842. var numOfMeshes = meshes.length;
  18843. for (var index = 0; index < numOfMeshes; index++) {
  18844. meshes[index]._createGlobalSubMesh();
  18845. }
  18846. };
  18847. Geometry.prototype.getTotalIndices = function () {
  18848. if (!this.isReady()) {
  18849. return 0;
  18850. }
  18851. return this._indices.length;
  18852. };
  18853. Geometry.prototype.getIndices = function () {
  18854. if (!this.isReady()) {
  18855. return null;
  18856. }
  18857. return this._indices;
  18858. };
  18859. Geometry.prototype.getIndexBuffer = function () {
  18860. if (!this.isReady()) {
  18861. return null;
  18862. }
  18863. return this._indexBuffer;
  18864. };
  18865. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  18866. var meshes = this._meshes;
  18867. var index = meshes.indexOf(mesh);
  18868. if (index === -1) {
  18869. return;
  18870. }
  18871. for (var kind in this._vertexBuffers) {
  18872. this._vertexBuffers[kind].dispose();
  18873. }
  18874. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  18875. this._indexBuffer = null;
  18876. }
  18877. meshes.splice(index, 1);
  18878. mesh._geometry = null;
  18879. if (meshes.length == 0 && shouldDispose) {
  18880. this.dispose();
  18881. }
  18882. };
  18883. Geometry.prototype.applyToMesh = function (mesh) {
  18884. if (mesh._geometry === this) {
  18885. return;
  18886. }
  18887. var previousGeometry = mesh._geometry;
  18888. if (previousGeometry) {
  18889. previousGeometry.releaseForMesh(mesh);
  18890. }
  18891. var meshes = this._meshes;
  18892. mesh._geometry = this;
  18893. this._scene.pushGeometry(this);
  18894. meshes.push(mesh);
  18895. if (this.isReady()) {
  18896. this._applyToMesh(mesh);
  18897. } else {
  18898. mesh._boundingInfo = this._boundingInfo;
  18899. }
  18900. };
  18901. Geometry.prototype._applyToMesh = function (mesh) {
  18902. var numOfMeshes = this._meshes.length;
  18903. for (var kind in this._vertexBuffers) {
  18904. if (numOfMeshes === 1) {
  18905. this._vertexBuffers[kind].create();
  18906. }
  18907. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  18908. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18909. mesh._resetPointsArrayCache();
  18910. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  18911. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18912. mesh._createGlobalSubMesh();
  18913. }
  18914. }
  18915. if (numOfMeshes === 1 && this._indices) {
  18916. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  18917. }
  18918. if (this._indexBuffer) {
  18919. this._indexBuffer.references = numOfMeshes;
  18920. }
  18921. };
  18922. Geometry.prototype.load = function (scene, onLoaded) {
  18923. var _this = this;
  18924. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18925. return;
  18926. }
  18927. if (this.isReady()) {
  18928. if (onLoaded) {
  18929. onLoaded();
  18930. }
  18931. return;
  18932. }
  18933. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18934. scene._addPendingData(this);
  18935. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18936. _this._delayLoadingFunction(JSON.parse(data), _this);
  18937. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18938. _this._delayInfo = [];
  18939. scene._removePendingData(_this);
  18940. var meshes = _this._meshes;
  18941. var numOfMeshes = meshes.length;
  18942. for (var index = 0; index < numOfMeshes; index++) {
  18943. _this._applyToMesh(meshes[index]);
  18944. }
  18945. if (onLoaded) {
  18946. onLoaded();
  18947. }
  18948. }, function () {
  18949. }, scene.database);
  18950. };
  18951. Geometry.prototype.dispose = function () {
  18952. var meshes = this._meshes;
  18953. var numOfMeshes = meshes.length;
  18954. for (var index = 0; index < numOfMeshes; index++) {
  18955. this.releaseForMesh(meshes[index]);
  18956. }
  18957. this._meshes = [];
  18958. for (var kind in this._vertexBuffers) {
  18959. this._vertexBuffers[kind].dispose();
  18960. }
  18961. this._vertexBuffers = [];
  18962. this._totalVertices = 0;
  18963. if (this._indexBuffer) {
  18964. this._engine._releaseBuffer(this._indexBuffer);
  18965. }
  18966. this._indexBuffer = null;
  18967. this._indices = [];
  18968. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18969. this.delayLoadingFile = null;
  18970. this._delayLoadingFunction = null;
  18971. this._delayInfo = [];
  18972. this._boundingInfo = null;
  18973. var geometries = this._scene.getGeometries();
  18974. index = geometries.indexOf(this);
  18975. if (index > -1) {
  18976. geometries.splice(index, 1);
  18977. }
  18978. };
  18979. Geometry.prototype.copy = function (id) {
  18980. var vertexData = new BABYLON.VertexData();
  18981. vertexData.indices = [];
  18982. var indices = this.getIndices();
  18983. for (var index = 0; index < indices.length; index++) {
  18984. vertexData.indices.push(indices[index]);
  18985. }
  18986. var updatable = false;
  18987. var stopChecking = false;
  18988. for (var kind in this._vertexBuffers) {
  18989. vertexData.set(this.getVerticesData(kind), kind);
  18990. if (!stopChecking) {
  18991. updatable = this.getVertexBuffer(kind).isUpdatable();
  18992. stopChecking = !updatable;
  18993. }
  18994. }
  18995. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  18996. geometry.delayLoadState = this.delayLoadState;
  18997. geometry.delayLoadingFile = this.delayLoadingFile;
  18998. geometry._delayLoadingFunction = this._delayLoadingFunction;
  18999. for (kind in this._delayInfo) {
  19000. geometry._delayInfo = geometry._delayInfo || [];
  19001. geometry._delayInfo.push(kind);
  19002. }
  19003. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19004. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19005. return geometry;
  19006. };
  19007. Geometry.ExtractFromMesh = function (mesh, id) {
  19008. var geometry = mesh._geometry;
  19009. if (!geometry) {
  19010. return null;
  19011. }
  19012. return geometry.copy(id);
  19013. };
  19014. Geometry.RandomId = function () {
  19015. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19016. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19017. return v.toString(16);
  19018. });
  19019. };
  19020. return Geometry;
  19021. })();
  19022. BABYLON.Geometry = Geometry;
  19023. (function (Geometry) {
  19024. (function (Primitives) {
  19025. var _Primitive = (function (_super) {
  19026. __extends(_Primitive, _super);
  19027. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19028. this._beingRegenerated = true;
  19029. this._canBeRegenerated = canBeRegenerated;
  19030. _super.call(this, id, scene, vertexData, false, mesh);
  19031. this._beingRegenerated = false;
  19032. }
  19033. _Primitive.prototype.canBeRegenerated = function () {
  19034. return this._canBeRegenerated;
  19035. };
  19036. _Primitive.prototype.regenerate = function () {
  19037. if (!this._canBeRegenerated) {
  19038. return;
  19039. }
  19040. this._beingRegenerated = true;
  19041. this.setAllVerticesData(this._regenerateVertexData(), false);
  19042. this._beingRegenerated = false;
  19043. };
  19044. _Primitive.prototype.asNewGeometry = function (id) {
  19045. return _super.prototype.copy.call(this, id);
  19046. };
  19047. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19048. if (!this._beingRegenerated) {
  19049. return;
  19050. }
  19051. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19052. };
  19053. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19054. if (!this._beingRegenerated) {
  19055. return;
  19056. }
  19057. _super.prototype.setVerticesData.call(this, kind, data, false);
  19058. };
  19059. _Primitive.prototype._regenerateVertexData = function () {
  19060. throw new Error("Abstract method");
  19061. };
  19062. _Primitive.prototype.copy = function (id) {
  19063. throw new Error("Must be overriden in sub-classes.");
  19064. };
  19065. return _Primitive;
  19066. })(Geometry);
  19067. Primitives._Primitive = _Primitive;
  19068. var Box = (function (_super) {
  19069. __extends(Box, _super);
  19070. function Box(id, scene, size, canBeRegenerated, mesh) {
  19071. this.size = size;
  19072. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19073. }
  19074. Box.prototype._regenerateVertexData = function () {
  19075. return BABYLON.VertexData.CreateBox(this.size);
  19076. };
  19077. Box.prototype.copy = function (id) {
  19078. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19079. };
  19080. return Box;
  19081. })(_Primitive);
  19082. Primitives.Box = Box;
  19083. var Sphere = (function (_super) {
  19084. __extends(Sphere, _super);
  19085. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19086. this.segments = segments;
  19087. this.diameter = diameter;
  19088. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19089. }
  19090. Sphere.prototype._regenerateVertexData = function () {
  19091. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19092. };
  19093. Sphere.prototype.copy = function (id) {
  19094. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19095. };
  19096. return Sphere;
  19097. })(_Primitive);
  19098. Primitives.Sphere = Sphere;
  19099. var Cylinder = (function (_super) {
  19100. __extends(Cylinder, _super);
  19101. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19102. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19103. this.height = height;
  19104. this.diameterTop = diameterTop;
  19105. this.diameterBottom = diameterBottom;
  19106. this.tessellation = tessellation;
  19107. this.subdivisions = subdivisions;
  19108. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19109. }
  19110. Cylinder.prototype._regenerateVertexData = function () {
  19111. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19112. };
  19113. Cylinder.prototype.copy = function (id) {
  19114. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19115. };
  19116. return Cylinder;
  19117. })(_Primitive);
  19118. Primitives.Cylinder = Cylinder;
  19119. var Torus = (function (_super) {
  19120. __extends(Torus, _super);
  19121. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19122. this.diameter = diameter;
  19123. this.thickness = thickness;
  19124. this.tessellation = tessellation;
  19125. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19126. }
  19127. Torus.prototype._regenerateVertexData = function () {
  19128. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19129. };
  19130. Torus.prototype.copy = function (id) {
  19131. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19132. };
  19133. return Torus;
  19134. })(_Primitive);
  19135. Primitives.Torus = Torus;
  19136. var Ground = (function (_super) {
  19137. __extends(Ground, _super);
  19138. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19139. this.width = width;
  19140. this.height = height;
  19141. this.subdivisions = subdivisions;
  19142. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19143. }
  19144. Ground.prototype._regenerateVertexData = function () {
  19145. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19146. };
  19147. Ground.prototype.copy = function (id) {
  19148. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19149. };
  19150. return Ground;
  19151. })(_Primitive);
  19152. Primitives.Ground = Ground;
  19153. var TiledGround = (function (_super) {
  19154. __extends(TiledGround, _super);
  19155. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19156. this.xmin = xmin;
  19157. this.zmin = zmin;
  19158. this.xmax = xmax;
  19159. this.zmax = zmax;
  19160. this.subdivisions = subdivisions;
  19161. this.precision = precision;
  19162. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19163. }
  19164. TiledGround.prototype._regenerateVertexData = function () {
  19165. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19166. };
  19167. TiledGround.prototype.copy = function (id) {
  19168. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19169. };
  19170. return TiledGround;
  19171. })(_Primitive);
  19172. Primitives.TiledGround = TiledGround;
  19173. var Plane = (function (_super) {
  19174. __extends(Plane, _super);
  19175. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19176. this.size = size;
  19177. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19178. }
  19179. Plane.prototype._regenerateVertexData = function () {
  19180. return BABYLON.VertexData.CreatePlane(this.size);
  19181. };
  19182. Plane.prototype.copy = function (id) {
  19183. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19184. };
  19185. return Plane;
  19186. })(_Primitive);
  19187. Primitives.Plane = Plane;
  19188. var TorusKnot = (function (_super) {
  19189. __extends(TorusKnot, _super);
  19190. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19191. this.radius = radius;
  19192. this.tube = tube;
  19193. this.radialSegments = radialSegments;
  19194. this.tubularSegments = tubularSegments;
  19195. this.p = p;
  19196. this.q = q;
  19197. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19198. }
  19199. TorusKnot.prototype._regenerateVertexData = function () {
  19200. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19201. };
  19202. TorusKnot.prototype.copy = function (id) {
  19203. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19204. };
  19205. return TorusKnot;
  19206. })(_Primitive);
  19207. Primitives.TorusKnot = TorusKnot;
  19208. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19209. var Primitives = Geometry.Primitives;
  19210. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19211. var Geometry = BABYLON.Geometry;
  19212. })(BABYLON || (BABYLON = {}));
  19213. var __extends = this.__extends || function (d, b) {
  19214. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19215. function __() { this.constructor = d; }
  19216. __.prototype = b.prototype;
  19217. d.prototype = new __();
  19218. };
  19219. var BABYLON;
  19220. (function (BABYLON) {
  19221. var Gamepads = (function () {
  19222. function Gamepads(ongamedpadconnected) {
  19223. var _this = this;
  19224. this.babylonGamepads = [];
  19225. this.oneGamepadConnected = false;
  19226. this.isMonitoring = false;
  19227. this.gamepadEventSupported = 'GamepadEvent' in window;
  19228. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19229. 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=";
  19230. this._callbackGamepadConnected = ongamedpadconnected;
  19231. if (this.gamepadSupportAvailable) {
  19232. if (this.gamepadEventSupported) {
  19233. window.addEventListener('gamepadconnected', function (evt) {
  19234. _this._onGamepadConnected(evt);
  19235. }, false);
  19236. window.addEventListener('gamepaddisconnected', function (evt) {
  19237. _this._onGamepadDisconnected(evt);
  19238. }, false);
  19239. } else {
  19240. this._startMonitoringGamepads();
  19241. }
  19242. if (!this.oneGamepadConnected) {
  19243. this._insertGamepadDOMInstructions();
  19244. }
  19245. } else {
  19246. this._insertGamepadDOMNotSupported();
  19247. }
  19248. }
  19249. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19250. Gamepads.gamepadDOMInfo = document.createElement("div");
  19251. var buttonAImage = document.createElement("img");
  19252. buttonAImage.src = this.buttonADataURL;
  19253. var spanMessage = document.createElement("span");
  19254. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19255. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19256. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19257. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19258. Gamepads.gamepadDOMInfo.style.width = "100%";
  19259. Gamepads.gamepadDOMInfo.style.height = "48px";
  19260. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19261. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19262. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19263. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19264. buttonAImage.style.position = "relative";
  19265. buttonAImage.style.bottom = "8px";
  19266. spanMessage.style.position = "relative";
  19267. spanMessage.style.fontSize = "32px";
  19268. spanMessage.style.bottom = "32px";
  19269. spanMessage.style.color = "green";
  19270. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19271. };
  19272. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19273. Gamepads.gamepadDOMInfo = document.createElement("div");
  19274. var spanMessage = document.createElement("span");
  19275. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19276. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19277. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19278. Gamepads.gamepadDOMInfo.style.width = "100%";
  19279. Gamepads.gamepadDOMInfo.style.height = "40px";
  19280. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19281. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19282. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19283. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19284. spanMessage.style.position = "relative";
  19285. spanMessage.style.fontSize = "32px";
  19286. spanMessage.style.color = "red";
  19287. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19288. };
  19289. Gamepads.prototype.dispose = function () {
  19290. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19291. };
  19292. Gamepads.prototype._onGamepadConnected = function (evt) {
  19293. var newGamepad = this._addNewGamepad(evt.gamepad);
  19294. if (this._callbackGamepadConnected)
  19295. this._callbackGamepadConnected(newGamepad);
  19296. this._startMonitoringGamepads();
  19297. };
  19298. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19299. if (!this.oneGamepadConnected) {
  19300. this.oneGamepadConnected = true;
  19301. if (Gamepads.gamepadDOMInfo) {
  19302. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19303. Gamepads.gamepadDOMInfo = null;
  19304. }
  19305. }
  19306. var newGamepad;
  19307. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19308. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19309. } else {
  19310. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19311. }
  19312. this.babylonGamepads.push(newGamepad);
  19313. return newGamepad;
  19314. };
  19315. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19316. for (var i in this.babylonGamepads) {
  19317. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19318. this.babylonGamepads.splice(i, 1);
  19319. break;
  19320. }
  19321. }
  19322. if (this.babylonGamepads.length == 0) {
  19323. this._stopMonitoringGamepads();
  19324. }
  19325. };
  19326. Gamepads.prototype._startMonitoringGamepads = function () {
  19327. if (!this.isMonitoring) {
  19328. this.isMonitoring = true;
  19329. this._checkGamepadsStatus();
  19330. }
  19331. };
  19332. Gamepads.prototype._stopMonitoringGamepads = function () {
  19333. this.isMonitoring = false;
  19334. };
  19335. Gamepads.prototype._checkGamepadsStatus = function () {
  19336. var _this = this;
  19337. this._updateGamepadObjects();
  19338. for (var i in this.babylonGamepads) {
  19339. this.babylonGamepads[i].update();
  19340. }
  19341. if (this.isMonitoring) {
  19342. if (window.requestAnimationFrame) {
  19343. window.requestAnimationFrame(function () {
  19344. _this._checkGamepadsStatus();
  19345. });
  19346. } else if (window.mozRequestAnimationFrame) {
  19347. window.mozRequestAnimationFrame(function () {
  19348. _this._checkGamepadsStatus();
  19349. });
  19350. } else if (window.webkitRequestAnimationFrame) {
  19351. window.webkitRequestAnimationFrame(function () {
  19352. _this._checkGamepadsStatus();
  19353. });
  19354. }
  19355. }
  19356. };
  19357. Gamepads.prototype._updateGamepadObjects = function () {
  19358. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19359. for (var i = 0; i < gamepads.length; i++) {
  19360. if (gamepads[i]) {
  19361. if (!(gamepads[i].index in this.babylonGamepads)) {
  19362. var newGamepad = this._addNewGamepad(gamepads[i]);
  19363. if (this._callbackGamepadConnected) {
  19364. this._callbackGamepadConnected(newGamepad);
  19365. }
  19366. } else {
  19367. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19368. }
  19369. }
  19370. }
  19371. };
  19372. return Gamepads;
  19373. })();
  19374. BABYLON.Gamepads = Gamepads;
  19375. var StickValues = (function () {
  19376. function StickValues(x, y) {
  19377. this.x = x;
  19378. this.y = y;
  19379. }
  19380. return StickValues;
  19381. })();
  19382. BABYLON.StickValues = StickValues;
  19383. var Gamepad = (function () {
  19384. function Gamepad(id, index, browserGamepad) {
  19385. this.id = id;
  19386. this.index = index;
  19387. this.browserGamepad = browserGamepad;
  19388. if (this.browserGamepad.axes.length >= 2) {
  19389. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19390. }
  19391. if (this.browserGamepad.axes.length >= 4) {
  19392. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19393. }
  19394. }
  19395. Gamepad.prototype.onleftstickchanged = function (callback) {
  19396. this._onleftstickchanged = callback;
  19397. };
  19398. Gamepad.prototype.onrightstickchanged = function (callback) {
  19399. this._onrightstickchanged = callback;
  19400. };
  19401. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19402. get: function () {
  19403. return this._leftStick;
  19404. },
  19405. set: function (newValues) {
  19406. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19407. this._onleftstickchanged(newValues);
  19408. }
  19409. this._leftStick = newValues;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19415. get: function () {
  19416. return this._rightStick;
  19417. },
  19418. set: function (newValues) {
  19419. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19420. this._onrightstickchanged(newValues);
  19421. }
  19422. this._rightStick = newValues;
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. Gamepad.prototype.update = function () {
  19428. if (this._leftStick) {
  19429. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19430. }
  19431. if (this._rightStick) {
  19432. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19433. }
  19434. };
  19435. return Gamepad;
  19436. })();
  19437. BABYLON.Gamepad = Gamepad;
  19438. var GenericPad = (function (_super) {
  19439. __extends(GenericPad, _super);
  19440. function GenericPad(id, index, gamepad) {
  19441. _super.call(this, id, index, gamepad);
  19442. this.id = id;
  19443. this.index = index;
  19444. this.gamepad = gamepad;
  19445. this._buttons = new Array(gamepad.buttons.length);
  19446. }
  19447. GenericPad.prototype.onbuttondown = function (callback) {
  19448. this._onbuttondown = callback;
  19449. };
  19450. GenericPad.prototype.onbuttonup = function (callback) {
  19451. this._onbuttonup = callback;
  19452. };
  19453. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19454. if (newValue !== currentValue) {
  19455. if (this._onbuttondown && newValue === 1) {
  19456. this._onbuttondown(buttonIndex);
  19457. }
  19458. if (this._onbuttonup && newValue === 0) {
  19459. this._onbuttonup(buttonIndex);
  19460. }
  19461. }
  19462. return newValue;
  19463. };
  19464. GenericPad.prototype.update = function () {
  19465. _super.prototype.update.call(this);
  19466. for (var index = 0; index < this._buttons.length; index++) {
  19467. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19468. }
  19469. };
  19470. return GenericPad;
  19471. })(Gamepad);
  19472. BABYLON.GenericPad = GenericPad;
  19473. (function (Xbox360Button) {
  19474. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19475. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19476. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19477. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19478. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19479. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19480. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19481. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19482. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19483. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19484. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19485. var Xbox360Button = BABYLON.Xbox360Button;
  19486. (function (Xbox360Dpad) {
  19487. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19488. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19489. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19490. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19491. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19492. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19493. var Xbox360Pad = (function (_super) {
  19494. __extends(Xbox360Pad, _super);
  19495. function Xbox360Pad() {
  19496. _super.apply(this, arguments);
  19497. this._leftTrigger = 0;
  19498. this._rightTrigger = 0;
  19499. this._buttonA = 0;
  19500. this._buttonB = 0;
  19501. this._buttonX = 0;
  19502. this._buttonY = 0;
  19503. this._buttonBack = 0;
  19504. this._buttonStart = 0;
  19505. this._buttonLB = 0;
  19506. this._buttonRB = 0;
  19507. this._buttonLeftStick = 0;
  19508. this._buttonRightStick = 0;
  19509. this._dPadUp = 0;
  19510. this._dPadDown = 0;
  19511. this._dPadLeft = 0;
  19512. this._dPadRight = 0;
  19513. }
  19514. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19515. this._onlefttriggerchanged = callback;
  19516. };
  19517. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19518. this._onrighttriggerchanged = callback;
  19519. };
  19520. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19521. get: function () {
  19522. return this._leftTrigger;
  19523. },
  19524. set: function (newValue) {
  19525. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19526. this._onlefttriggerchanged(newValue);
  19527. }
  19528. this._leftTrigger = newValue;
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19534. get: function () {
  19535. return this._rightTrigger;
  19536. },
  19537. set: function (newValue) {
  19538. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19539. this._onrighttriggerchanged(newValue);
  19540. }
  19541. this._rightTrigger = newValue;
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19547. this._onbuttondown = callback;
  19548. };
  19549. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19550. this._onbuttonup = callback;
  19551. };
  19552. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19553. this._ondpaddown = callback;
  19554. };
  19555. Xbox360Pad.prototype.ondpadup = function (callback) {
  19556. this._ondpadup = callback;
  19557. };
  19558. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19559. if (newValue !== currentValue) {
  19560. if (this._onbuttondown && newValue === 1) {
  19561. this._onbuttondown(buttonType);
  19562. }
  19563. if (this._onbuttonup && newValue === 0) {
  19564. this._onbuttonup(buttonType);
  19565. }
  19566. }
  19567. return newValue;
  19568. };
  19569. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19570. if (newValue !== currentValue) {
  19571. if (this._ondpaddown && newValue === 1) {
  19572. this._ondpaddown(buttonType);
  19573. }
  19574. if (this._ondpadup && newValue === 0) {
  19575. this._ondpadup(buttonType);
  19576. }
  19577. }
  19578. return newValue;
  19579. };
  19580. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19581. get: function () {
  19582. return this._buttonA;
  19583. },
  19584. set: function (value) {
  19585. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19591. get: function () {
  19592. return this._buttonB;
  19593. },
  19594. set: function (value) {
  19595. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19596. },
  19597. enumerable: true,
  19598. configurable: true
  19599. });
  19600. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19601. get: function () {
  19602. return this._buttonX;
  19603. },
  19604. set: function (value) {
  19605. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19606. },
  19607. enumerable: true,
  19608. configurable: true
  19609. });
  19610. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19611. get: function () {
  19612. return this._buttonY;
  19613. },
  19614. set: function (value) {
  19615. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19621. get: function () {
  19622. return this._buttonStart;
  19623. },
  19624. set: function (value) {
  19625. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19631. get: function () {
  19632. return this._buttonBack;
  19633. },
  19634. set: function (value) {
  19635. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19641. get: function () {
  19642. return this._buttonLB;
  19643. },
  19644. set: function (value) {
  19645. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19646. },
  19647. enumerable: true,
  19648. configurable: true
  19649. });
  19650. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19651. get: function () {
  19652. return this._buttonRB;
  19653. },
  19654. set: function (value) {
  19655. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19661. get: function () {
  19662. return this._buttonLeftStick;
  19663. },
  19664. set: function (value) {
  19665. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19671. get: function () {
  19672. return this._buttonRightStick;
  19673. },
  19674. set: function (value) {
  19675. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19681. get: function () {
  19682. return this._dPadUp;
  19683. },
  19684. set: function (value) {
  19685. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19691. get: function () {
  19692. return this._dPadDown;
  19693. },
  19694. set: function (value) {
  19695. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19701. get: function () {
  19702. return this._dPadLeft;
  19703. },
  19704. set: function (value) {
  19705. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19711. get: function () {
  19712. return this._dPadRight;
  19713. },
  19714. set: function (value) {
  19715. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Xbox360Pad.prototype.update = function () {
  19721. _super.prototype.update.call(this);
  19722. this.buttonA = this.browserGamepad.buttons[0].value;
  19723. this.buttonB = this.browserGamepad.buttons[1].value;
  19724. this.buttonX = this.browserGamepad.buttons[2].value;
  19725. this.buttonY = this.browserGamepad.buttons[3].value;
  19726. this.buttonLB = this.browserGamepad.buttons[4].value;
  19727. this.buttonRB = this.browserGamepad.buttons[5].value;
  19728. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19729. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19730. this.buttonBack = this.browserGamepad.buttons[8].value;
  19731. this.buttonStart = this.browserGamepad.buttons[9].value;
  19732. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19733. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19734. this.dPadUp = this.browserGamepad.buttons[12].value;
  19735. this.dPadDown = this.browserGamepad.buttons[13].value;
  19736. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19737. this.dPadRight = this.browserGamepad.buttons[15].value;
  19738. };
  19739. return Xbox360Pad;
  19740. })(Gamepad);
  19741. BABYLON.Xbox360Pad = Xbox360Pad;
  19742. })(BABYLON || (BABYLON = {}));
  19743. var __extends = this.__extends || function (d, b) {
  19744. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19745. function __() { this.constructor = d; }
  19746. __.prototype = b.prototype;
  19747. d.prototype = new __();
  19748. };
  19749. var BABYLON;
  19750. (function (BABYLON) {
  19751. var GamepadCamera = (function (_super) {
  19752. __extends(GamepadCamera, _super);
  19753. function GamepadCamera(name, position, scene) {
  19754. var _this = this;
  19755. _super.call(this, name, position, scene);
  19756. this.angularSensibility = 200;
  19757. this.moveSensibility = 75;
  19758. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19759. _this._onNewGameConnected(gamepad);
  19760. });
  19761. }
  19762. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19763. if (gamepad.index === 0) {
  19764. this._gamepad = gamepad;
  19765. }
  19766. };
  19767. GamepadCamera.prototype._checkInputs = function () {
  19768. if (!this._gamepad) {
  19769. return;
  19770. }
  19771. var LSValues = this._gamepad.leftStick;
  19772. var normalizedLX = LSValues.x / this.moveSensibility;
  19773. var normalizedLY = LSValues.y / this.moveSensibility;
  19774. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19775. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19776. var RSValues = this._gamepad.rightStick;
  19777. var normalizedRX = RSValues.x / this.angularSensibility;
  19778. var normalizedRY = RSValues.y / this.angularSensibility;
  19779. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19780. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19781. ;
  19782. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19783. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19784. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19785. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19786. };
  19787. GamepadCamera.prototype.dispose = function () {
  19788. this._gamepads.dispose();
  19789. _super.prototype.dispose.call(this);
  19790. };
  19791. return GamepadCamera;
  19792. })(BABYLON.FreeCamera);
  19793. BABYLON.GamepadCamera = GamepadCamera;
  19794. })(BABYLON || (BABYLON = {}));
  19795. var __extends = this.__extends || function (d, b) {
  19796. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19797. function __() { this.constructor = d; }
  19798. __.prototype = b.prototype;
  19799. d.prototype = new __();
  19800. };
  19801. var BABYLON;
  19802. (function (BABYLON) {
  19803. var LinesMesh = (function (_super) {
  19804. __extends(LinesMesh, _super);
  19805. function LinesMesh(name, scene, updatable) {
  19806. if (typeof updatable === "undefined") { updatable = false; }
  19807. _super.call(this, name, scene);
  19808. this.color = new BABYLON.Color3(1, 1, 1);
  19809. this.alpha = 1;
  19810. this._indices = new Array();
  19811. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19812. attributes: ["position"],
  19813. uniforms: ["worldViewProjection", "color"],
  19814. needAlphaBlending: true
  19815. });
  19816. }
  19817. Object.defineProperty(LinesMesh.prototype, "material", {
  19818. get: function () {
  19819. return this._colorShader;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  19825. get: function () {
  19826. return false;
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  19832. get: function () {
  19833. return false;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  19839. var engine = this.getScene().getEngine();
  19840. var indexToBind = this._geometry.getIndexBuffer();
  19841. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  19842. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  19843. };
  19844. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  19845. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19846. return;
  19847. }
  19848. var engine = this.getScene().getEngine();
  19849. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  19850. };
  19851. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  19852. return null;
  19853. };
  19854. LinesMesh.prototype.dispose = function (doNotRecurse) {
  19855. this._colorShader.dispose();
  19856. _super.prototype.dispose.call(this, doNotRecurse);
  19857. };
  19858. return LinesMesh;
  19859. })(BABYLON.Mesh);
  19860. BABYLON.LinesMesh = LinesMesh;
  19861. })(BABYLON || (BABYLON = {}));
  19862. var BABYLON;
  19863. (function (BABYLON) {
  19864. var OutlineRenderer = (function () {
  19865. function OutlineRenderer(scene) {
  19866. this._scene = scene;
  19867. }
  19868. OutlineRenderer.prototype.render = function (subMesh, batch) {
  19869. var scene = this._scene;
  19870. var engine = this._scene.getEngine();
  19871. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  19872. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  19873. return;
  19874. }
  19875. var mesh = subMesh.getRenderingMesh();
  19876. var material = subMesh.getMaterial();
  19877. engine.enableEffect(this._effect);
  19878. this._effect.setFloat("offset", mesh.outlineWidth);
  19879. this._effect.setColor3("color", mesh.outlineColor);
  19880. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19881. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  19882. if (useBones) {
  19883. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19884. }
  19885. mesh._bind(subMesh, this._effect, false);
  19886. if (material && material.needAlphaTesting()) {
  19887. var alphaTexture = material.getAlphaTestTexture();
  19888. this._effect.setTexture("diffuseSampler", alphaTexture);
  19889. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  19890. }
  19891. if (hardwareInstancedRendering) {
  19892. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  19893. } else {
  19894. if (batch.renderSelf[subMesh._id]) {
  19895. this._effect.setMatrix("world", mesh.getWorldMatrix());
  19896. mesh._draw(subMesh, true);
  19897. }
  19898. if (batch.visibleInstances[subMesh._id]) {
  19899. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19900. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19901. this._effect.setMatrix("world", instance.getWorldMatrix());
  19902. mesh._draw(subMesh, true);
  19903. }
  19904. }
  19905. }
  19906. };
  19907. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  19908. var defines = [];
  19909. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  19910. var mesh = subMesh.getMesh();
  19911. var material = subMesh.getMaterial();
  19912. if (material && material.needAlphaTesting()) {
  19913. defines.push("#define ALPHATEST");
  19914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19915. attribs.push(BABYLON.VertexBuffer.UVKind);
  19916. defines.push("#define UV1");
  19917. }
  19918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19919. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19920. defines.push("#define UV2");
  19921. }
  19922. }
  19923. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19924. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19925. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19926. defines.push("#define BONES");
  19927. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  19928. }
  19929. if (useInstances) {
  19930. defines.push("#define INSTANCES");
  19931. attribs.push("world0");
  19932. attribs.push("world1");
  19933. attribs.push("world2");
  19934. attribs.push("world3");
  19935. }
  19936. var join = defines.join("\n");
  19937. if (this._cachedDefines != join) {
  19938. this._cachedDefines = join;
  19939. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  19940. }
  19941. return this._effect.isReady();
  19942. };
  19943. return OutlineRenderer;
  19944. })();
  19945. BABYLON.OutlineRenderer = OutlineRenderer;
  19946. })(BABYLON || (BABYLON = {}));
  19947. var BABYLON;
  19948. (function (BABYLON) {
  19949. var MeshAssetTask = (function () {
  19950. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  19951. this.name = name;
  19952. this.meshesNames = meshesNames;
  19953. this.rootUrl = rootUrl;
  19954. this.sceneFilename = sceneFilename;
  19955. this.isCompleted = false;
  19956. }
  19957. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19958. var _this = this;
  19959. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  19960. _this.loadedMeshes = meshes;
  19961. _this.loadedParticleSystems = particleSystems;
  19962. _this.loadedSkeletons = skeletons;
  19963. _this.isCompleted = true;
  19964. if (_this.onSuccess) {
  19965. _this.onSuccess(_this);
  19966. }
  19967. onSuccess();
  19968. }, null, function () {
  19969. if (_this.onError) {
  19970. _this.onError(_this);
  19971. }
  19972. onError();
  19973. });
  19974. };
  19975. return MeshAssetTask;
  19976. })();
  19977. BABYLON.MeshAssetTask = MeshAssetTask;
  19978. var TextFileAssetTask = (function () {
  19979. function TextFileAssetTask(name, url) {
  19980. this.name = name;
  19981. this.url = url;
  19982. this.isCompleted = false;
  19983. }
  19984. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  19985. var _this = this;
  19986. BABYLON.Tools.LoadFile(this.url, function (data) {
  19987. _this.text = data;
  19988. _this.isCompleted = true;
  19989. if (_this.onSuccess) {
  19990. _this.onSuccess(_this);
  19991. }
  19992. onSuccess();
  19993. }, null, scene.database, false, function () {
  19994. if (_this.onError) {
  19995. _this.onError(_this);
  19996. }
  19997. onError();
  19998. });
  19999. };
  20000. return TextFileAssetTask;
  20001. })();
  20002. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20003. var BinaryFileAssetTask = (function () {
  20004. function BinaryFileAssetTask(name, url) {
  20005. this.name = name;
  20006. this.url = url;
  20007. this.isCompleted = false;
  20008. }
  20009. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20010. var _this = this;
  20011. BABYLON.Tools.LoadFile(this.url, function (data) {
  20012. _this.data = data;
  20013. _this.isCompleted = true;
  20014. if (_this.onSuccess) {
  20015. _this.onSuccess(_this);
  20016. }
  20017. onSuccess();
  20018. }, null, scene.database, true, function () {
  20019. if (_this.onError) {
  20020. _this.onError(_this);
  20021. }
  20022. onError();
  20023. });
  20024. };
  20025. return BinaryFileAssetTask;
  20026. })();
  20027. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20028. var ImageAssetTask = (function () {
  20029. function ImageAssetTask(name, url) {
  20030. this.name = name;
  20031. this.url = url;
  20032. this.isCompleted = false;
  20033. }
  20034. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20035. var _this = this;
  20036. var img = new Image();
  20037. img.onload = function () {
  20038. _this.image = img;
  20039. _this.isCompleted = true;
  20040. if (_this.onSuccess) {
  20041. _this.onSuccess(_this);
  20042. }
  20043. onSuccess();
  20044. };
  20045. img.onerror = function () {
  20046. if (_this.onError) {
  20047. _this.onError(_this);
  20048. }
  20049. onError();
  20050. };
  20051. img.src = this.url;
  20052. };
  20053. return ImageAssetTask;
  20054. })();
  20055. BABYLON.ImageAssetTask = ImageAssetTask;
  20056. var AssetsManager = (function () {
  20057. function AssetsManager(scene) {
  20058. this._tasks = new Array();
  20059. this._waitingTasksCount = 0;
  20060. this.useDefaultLoadingScreen = true;
  20061. this._scene = scene;
  20062. }
  20063. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20064. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20065. this._tasks.push(task);
  20066. return task;
  20067. };
  20068. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20069. var task = new TextFileAssetTask(taskName, url);
  20070. this._tasks.push(task);
  20071. return task;
  20072. };
  20073. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20074. var task = new BinaryFileAssetTask(taskName, url);
  20075. this._tasks.push(task);
  20076. return task;
  20077. };
  20078. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20079. var task = new ImageAssetTask(taskName, url);
  20080. this._tasks.push(task);
  20081. return task;
  20082. };
  20083. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20084. this._waitingTasksCount--;
  20085. if (this._waitingTasksCount === 0) {
  20086. if (this.onFinish) {
  20087. this.onFinish(this._tasks);
  20088. }
  20089. this._scene.getEngine().hideLoadingUI();
  20090. }
  20091. };
  20092. AssetsManager.prototype._runTask = function (task) {
  20093. var _this = this;
  20094. task.run(this._scene, function () {
  20095. if (_this.onTaskSuccess) {
  20096. _this.onTaskSuccess(task);
  20097. }
  20098. _this._decreaseWaitingTasksCount();
  20099. }, function () {
  20100. if (_this.onTaskError) {
  20101. _this.onTaskError(task);
  20102. }
  20103. _this._decreaseWaitingTasksCount();
  20104. });
  20105. };
  20106. AssetsManager.prototype.reset = function () {
  20107. this._tasks = new Array();
  20108. return this;
  20109. };
  20110. AssetsManager.prototype.load = function () {
  20111. this._waitingTasksCount = this._tasks.length;
  20112. if (this._waitingTasksCount === 0) {
  20113. if (this.onFinish) {
  20114. this.onFinish(this._tasks);
  20115. }
  20116. return this;
  20117. }
  20118. if (this.useDefaultLoadingScreen) {
  20119. this._scene.getEngine().displayLoadingUI();
  20120. }
  20121. for (var index = 0; index < this._tasks.length; index++) {
  20122. var task = this._tasks[index];
  20123. this._runTask(task);
  20124. }
  20125. return this;
  20126. };
  20127. return AssetsManager;
  20128. })();
  20129. BABYLON.AssetsManager = AssetsManager;
  20130. })(BABYLON || (BABYLON = {}));