babylon.1.14-RC-debug.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908
  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. return this;
  265. };
  266. Vector2.prototype.scale = function (scale) {
  267. return new Vector2(this.x * scale, this.y * scale);
  268. };
  269. Vector2.prototype.equals = function (otherVector) {
  270. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  271. };
  272. Vector2.prototype.length = function () {
  273. return Math.sqrt(this.x * this.x + this.y * this.y);
  274. };
  275. Vector2.prototype.lengthSquared = function () {
  276. return (this.x * this.x + this.y * this.y);
  277. };
  278. Vector2.prototype.normalize = function () {
  279. var len = this.length();
  280. if (len === 0)
  281. return;
  282. var num = 1.0 / len;
  283. this.x *= num;
  284. this.y *= num;
  285. return this;
  286. };
  287. Vector2.prototype.clone = function () {
  288. return new Vector2(this.x, this.y);
  289. };
  290. Vector2.Zero = function () {
  291. return new Vector2(0, 0);
  292. };
  293. Vector2.FromArray = function (array, offset) {
  294. if (!offset) {
  295. offset = 0;
  296. }
  297. return new Vector2(array[offset], array[offset + 1]);
  298. };
  299. Vector2.FromArrayToRef = function (array, offset, result) {
  300. result.x = array[offset];
  301. result.y = array[offset + 1];
  302. };
  303. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  304. var squared = amount * amount;
  305. var cubed = amount * squared;
  306. 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));
  307. 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));
  308. return new Vector2(x, y);
  309. };
  310. Vector2.Clamp = function (value, min, max) {
  311. var x = value.x;
  312. x = (x > max.x) ? max.x : x;
  313. x = (x < min.x) ? min.x : x;
  314. var y = value.y;
  315. y = (y > max.y) ? max.y : y;
  316. y = (y < min.y) ? min.y : y;
  317. return new Vector2(x, y);
  318. };
  319. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  320. var squared = amount * amount;
  321. var cubed = amount * squared;
  322. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  323. var part2 = (-2.0 * cubed) + (3.0 * squared);
  324. var part3 = (cubed - (2.0 * squared)) + amount;
  325. var part4 = cubed - squared;
  326. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  327. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  328. return new Vector2(x, y);
  329. };
  330. Vector2.Lerp = function (start, end, amount) {
  331. var x = start.x + ((end.x - start.x) * amount);
  332. var y = start.y + ((end.y - start.y) * amount);
  333. return new Vector2(x, y);
  334. };
  335. Vector2.Dot = function (left, right) {
  336. return left.x * right.x + left.y * right.y;
  337. };
  338. Vector2.Normalize = function (vector) {
  339. var newVector = vector.clone();
  340. newVector.normalize();
  341. return newVector;
  342. };
  343. Vector2.Minimize = function (left, right) {
  344. var x = (left.x < right.x) ? left.x : right.x;
  345. var y = (left.y < right.y) ? left.y : right.y;
  346. return new Vector2(x, y);
  347. };
  348. Vector2.Maximize = function (left, right) {
  349. var x = (left.x > right.x) ? left.x : right.x;
  350. var y = (left.y > right.y) ? left.y : right.y;
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Transform = function (vector, transformation) {
  354. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  355. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Distance = function (value1, value2) {
  359. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  360. };
  361. Vector2.DistanceSquared = function (value1, value2) {
  362. var x = value1.x - value2.x;
  363. var y = value1.y - value2.y;
  364. return (x * x) + (y * y);
  365. };
  366. return Vector2;
  367. })();
  368. BABYLON.Vector2 = Vector2;
  369. var Vector3 = (function () {
  370. function Vector3(x, y, z) {
  371. this.x = x;
  372. this.y = y;
  373. this.z = z;
  374. }
  375. Vector3.prototype.toString = function () {
  376. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  377. };
  378. Vector3.prototype.asArray = function () {
  379. var result = [];
  380. this.toArray(result, 0);
  381. return result;
  382. };
  383. Vector3.prototype.toArray = function (array, index) {
  384. if (index === undefined) {
  385. index = 0;
  386. }
  387. array[index] = this.x;
  388. array[index + 1] = this.y;
  389. array[index + 2] = this.z;
  390. };
  391. Vector3.prototype.addInPlace = function (otherVector) {
  392. this.x += otherVector.x;
  393. this.y += otherVector.y;
  394. this.z += otherVector.z;
  395. };
  396. Vector3.prototype.add = function (otherVector) {
  397. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  398. };
  399. Vector3.prototype.addToRef = function (otherVector, result) {
  400. result.x = this.x + otherVector.x;
  401. result.y = this.y + otherVector.y;
  402. result.z = this.z + otherVector.z;
  403. };
  404. Vector3.prototype.subtractInPlace = function (otherVector) {
  405. this.x -= otherVector.x;
  406. this.y -= otherVector.y;
  407. this.z -= otherVector.z;
  408. };
  409. Vector3.prototype.subtract = function (otherVector) {
  410. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  411. };
  412. Vector3.prototype.subtractToRef = function (otherVector, result) {
  413. result.x = this.x - otherVector.x;
  414. result.y = this.y - otherVector.y;
  415. result.z = this.z - otherVector.z;
  416. };
  417. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  418. return new Vector3(this.x - x, this.y - y, this.z - z);
  419. };
  420. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  421. result.x = this.x - x;
  422. result.y = this.y - y;
  423. result.z = this.z - z;
  424. };
  425. Vector3.prototype.negate = function () {
  426. return new Vector3(-this.x, -this.y, -this.z);
  427. };
  428. Vector3.prototype.scaleInPlace = function (scale) {
  429. this.x *= scale;
  430. this.y *= scale;
  431. this.z *= scale;
  432. return this;
  433. };
  434. Vector3.prototype.scale = function (scale) {
  435. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  436. };
  437. Vector3.prototype.scaleToRef = function (scale, result) {
  438. result.x = this.x * scale;
  439. result.y = this.y * scale;
  440. result.z = this.z * scale;
  441. };
  442. Vector3.prototype.equals = function (otherVector) {
  443. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  444. };
  445. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  446. 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;
  447. };
  448. Vector3.prototype.equalsToFloats = function (x, y, z) {
  449. return this.x === x && this.y === y && this.z === z;
  450. };
  451. Vector3.prototype.multiplyInPlace = function (otherVector) {
  452. this.x *= otherVector.x;
  453. this.y *= otherVector.y;
  454. this.z *= otherVector.z;
  455. };
  456. Vector3.prototype.multiply = function (otherVector) {
  457. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  458. };
  459. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  460. result.x = this.x * otherVector.x;
  461. result.y = this.y * otherVector.y;
  462. result.z = this.z * otherVector.z;
  463. };
  464. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  465. return new Vector3(this.x * x, this.y * y, this.z * z);
  466. };
  467. Vector3.prototype.divide = function (otherVector) {
  468. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  469. };
  470. Vector3.prototype.divideToRef = function (otherVector, result) {
  471. result.x = this.x / otherVector.x;
  472. result.y = this.y / otherVector.y;
  473. result.z = this.z / otherVector.z;
  474. };
  475. Vector3.prototype.MinimizeInPlace = function (other) {
  476. if (other.x < this.x)
  477. this.x = other.x;
  478. if (other.y < this.y)
  479. this.y = other.y;
  480. if (other.z < this.z)
  481. this.z = other.z;
  482. };
  483. Vector3.prototype.MaximizeInPlace = function (other) {
  484. if (other.x > this.x)
  485. this.x = other.x;
  486. if (other.y > this.y)
  487. this.y = other.y;
  488. if (other.z > this.z)
  489. this.z = other.z;
  490. };
  491. Vector3.prototype.length = function () {
  492. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  493. };
  494. Vector3.prototype.lengthSquared = function () {
  495. return (this.x * this.x + this.y * this.y + this.z * this.z);
  496. };
  497. Vector3.prototype.normalize = function () {
  498. var len = this.length();
  499. if (len === 0)
  500. return;
  501. var num = 1.0 / len;
  502. this.x *= num;
  503. this.y *= num;
  504. this.z *= num;
  505. return this;
  506. };
  507. Vector3.prototype.clone = function () {
  508. return new Vector3(this.x, this.y, this.z);
  509. };
  510. Vector3.prototype.copyFrom = function (source) {
  511. this.x = source.x;
  512. this.y = source.y;
  513. this.z = source.z;
  514. };
  515. Vector3.prototype.copyFromFloats = function (x, y, z) {
  516. this.x = x;
  517. this.y = y;
  518. this.z = z;
  519. };
  520. Vector3.FromArray = function (array, offset) {
  521. if (!offset) {
  522. offset = 0;
  523. }
  524. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  525. };
  526. Vector3.FromArrayToRef = function (array, offset, result) {
  527. result.x = array[offset];
  528. result.y = array[offset + 1];
  529. result.z = array[offset + 2];
  530. };
  531. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  532. result.x = array[offset];
  533. result.y = array[offset + 1];
  534. result.z = array[offset + 2];
  535. };
  536. Vector3.FromFloatsToRef = function (x, y, z, result) {
  537. result.x = x;
  538. result.y = y;
  539. result.z = z;
  540. };
  541. Vector3.Zero = function () {
  542. return new Vector3(0, 0, 0);
  543. };
  544. Vector3.Up = function () {
  545. return new Vector3(0, 1.0, 0);
  546. };
  547. Vector3.TransformCoordinates = function (vector, transformation) {
  548. var result = Vector3.Zero();
  549. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  550. return result;
  551. };
  552. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  553. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  554. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  555. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  556. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  557. result.x = x / w;
  558. result.y = y / w;
  559. result.z = z / w;
  560. };
  561. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  562. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  563. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  564. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  565. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  566. result.x = rx / rw;
  567. result.y = ry / rw;
  568. result.z = rz / rw;
  569. };
  570. Vector3.TransformNormal = function (vector, transformation) {
  571. var result = Vector3.Zero();
  572. Vector3.TransformNormalToRef(vector, transformation, result);
  573. return result;
  574. };
  575. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  576. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  577. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  578. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  579. };
  580. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  581. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  582. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  583. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  584. };
  585. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  586. var squared = amount * amount;
  587. var cubed = amount * squared;
  588. 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));
  589. 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));
  590. 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));
  591. return new Vector3(x, y, z);
  592. };
  593. Vector3.Clamp = function (value, min, max) {
  594. var x = value.x;
  595. x = (x > max.x) ? max.x : x;
  596. x = (x < min.x) ? min.x : x;
  597. var y = value.y;
  598. y = (y > max.y) ? max.y : y;
  599. y = (y < min.y) ? min.y : y;
  600. var z = value.z;
  601. z = (z > max.z) ? max.z : z;
  602. z = (z < min.z) ? min.z : z;
  603. return new Vector3(x, y, z);
  604. };
  605. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  606. var squared = amount * amount;
  607. var cubed = amount * squared;
  608. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  609. var part2 = (-2.0 * cubed) + (3.0 * squared);
  610. var part3 = (cubed - (2.0 * squared)) + amount;
  611. var part4 = cubed - squared;
  612. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  613. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  614. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  615. return new Vector3(x, y, z);
  616. };
  617. Vector3.Lerp = function (start, end, amount) {
  618. var x = start.x + ((end.x - start.x) * amount);
  619. var y = start.y + ((end.y - start.y) * amount);
  620. var z = start.z + ((end.z - start.z) * amount);
  621. return new Vector3(x, y, z);
  622. };
  623. Vector3.Dot = function (left, right) {
  624. return (left.x * right.x + left.y * right.y + left.z * right.z);
  625. };
  626. Vector3.Cross = function (left, right) {
  627. var result = Vector3.Zero();
  628. Vector3.CrossToRef(left, right, result);
  629. return result;
  630. };
  631. Vector3.CrossToRef = function (left, right, result) {
  632. result.x = left.y * right.z - left.z * right.y;
  633. result.y = left.z * right.x - left.x * right.z;
  634. result.z = left.x * right.y - left.y * right.x;
  635. };
  636. Vector3.Normalize = function (vector) {
  637. var result = Vector3.Zero();
  638. Vector3.NormalizeToRef(vector, result);
  639. return result;
  640. };
  641. Vector3.NormalizeToRef = function (vector, result) {
  642. result.copyFrom(vector);
  643. result.normalize();
  644. };
  645. Vector3.Project = function (vector, world, transform, viewport) {
  646. var cw = viewport.width;
  647. var ch = viewport.height;
  648. var cx = viewport.x;
  649. var cy = viewport.y;
  650. 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);
  651. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  652. return Vector3.TransformCoordinates(vector, finalMatrix);
  653. };
  654. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  655. var matrix = world.multiply(view).multiply(projection);
  656. matrix.invert();
  657. source.x = source.x / viewportWidth * 2 - 1;
  658. source.y = -(source.y / viewportHeight * 2 - 1);
  659. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  660. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  661. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  662. vector = vector.scale(1.0 / num);
  663. }
  664. return vector;
  665. };
  666. Vector3.Minimize = function (left, right) {
  667. var min = left.clone();
  668. min.MinimizeInPlace(right);
  669. return min;
  670. };
  671. Vector3.Maximize = function (left, right) {
  672. var max = left.clone();
  673. max.MaximizeInPlace(right);
  674. return max;
  675. };
  676. Vector3.Distance = function (value1, value2) {
  677. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  678. };
  679. Vector3.DistanceSquared = function (value1, value2) {
  680. var x = value1.x - value2.x;
  681. var y = value1.y - value2.y;
  682. var z = value1.z - value2.z;
  683. return (x * x) + (y * y) + (z * z);
  684. };
  685. Vector3.Center = function (value1, value2) {
  686. var center = value1.add(value2);
  687. center.scaleInPlace(0.5);
  688. return center;
  689. };
  690. return Vector3;
  691. })();
  692. BABYLON.Vector3 = Vector3;
  693. var Quaternion = (function () {
  694. function Quaternion(x, y, z, w) {
  695. if (typeof x === "undefined") { x = 0; }
  696. if (typeof y === "undefined") { y = 0; }
  697. if (typeof z === "undefined") { z = 0; }
  698. if (typeof w === "undefined") { w = 1; }
  699. this.x = x;
  700. this.y = y;
  701. this.z = z;
  702. this.w = w;
  703. }
  704. Quaternion.prototype.toString = function () {
  705. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  706. };
  707. Quaternion.prototype.asArray = function () {
  708. return [this.x, this.y, this.z, this.w];
  709. };
  710. Quaternion.prototype.equals = function (otherQuaternion) {
  711. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  712. };
  713. Quaternion.prototype.clone = function () {
  714. return new Quaternion(this.x, this.y, this.z, this.w);
  715. };
  716. Quaternion.prototype.copyFrom = function (other) {
  717. this.x = other.x;
  718. this.y = other.y;
  719. this.z = other.z;
  720. this.w = other.w;
  721. };
  722. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  723. this.x = x;
  724. this.y = y;
  725. this.z = z;
  726. this.w = w;
  727. };
  728. Quaternion.prototype.add = function (other) {
  729. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  730. };
  731. Quaternion.prototype.subtract = function (other) {
  732. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  733. };
  734. Quaternion.prototype.scale = function (value) {
  735. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  736. };
  737. Quaternion.prototype.multiply = function (q1) {
  738. var result = new Quaternion(0, 0, 0, 1.0);
  739. this.multiplyToRef(q1, result);
  740. return result;
  741. };
  742. Quaternion.prototype.multiplyToRef = function (q1, result) {
  743. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  744. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  745. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  746. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  747. };
  748. Quaternion.prototype.length = function () {
  749. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  750. };
  751. Quaternion.prototype.normalize = function () {
  752. var length = 1.0 / this.length();
  753. this.x *= length;
  754. this.y *= length;
  755. this.z *= length;
  756. this.w *= length;
  757. };
  758. Quaternion.prototype.toEulerAngles = function () {
  759. var result = Vector3.Zero();
  760. this.toEulerAnglesToRef(result);
  761. return result;
  762. };
  763. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  764. var qx = this.x;
  765. var qy = this.y;
  766. var qz = this.z;
  767. var qw = this.w;
  768. var sqx = qx * qx;
  769. var sqy = qy * qy;
  770. var sqz = qz * qz;
  771. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  772. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  773. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  774. var gimbaLockTest = qx * qy + qz * qw;
  775. if (gimbaLockTest > 0.499) {
  776. yaw = 2.0 * Math.atan2(qx, qw);
  777. roll = 0;
  778. } else if (gimbaLockTest < -0.499) {
  779. yaw = -2.0 * Math.atan2(qx, qw);
  780. roll = 0;
  781. }
  782. result.x = pitch;
  783. result.y = yaw;
  784. result.z = roll;
  785. };
  786. Quaternion.prototype.toRotationMatrix = function (result) {
  787. var xx = this.x * this.x;
  788. var yy = this.y * this.y;
  789. var zz = this.z * this.z;
  790. var xy = this.x * this.y;
  791. var zw = this.z * this.w;
  792. var zx = this.z * this.x;
  793. var yw = this.y * this.w;
  794. var yz = this.y * this.z;
  795. var xw = this.x * this.w;
  796. result.m[0] = 1.0 - (2.0 * (yy + zz));
  797. result.m[1] = 2.0 * (xy + zw);
  798. result.m[2] = 2.0 * (zx - yw);
  799. result.m[3] = 0;
  800. result.m[4] = 2.0 * (xy - zw);
  801. result.m[5] = 1.0 - (2.0 * (zz + xx));
  802. result.m[6] = 2.0 * (yz + xw);
  803. result.m[7] = 0;
  804. result.m[8] = 2.0 * (zx + yw);
  805. result.m[9] = 2.0 * (yz - xw);
  806. result.m[10] = 1.0 - (2.0 * (yy + xx));
  807. result.m[11] = 0;
  808. result.m[12] = 0;
  809. result.m[13] = 0;
  810. result.m[14] = 0;
  811. result.m[15] = 1.0;
  812. };
  813. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  814. var data = matrix.m;
  815. var m11 = data[0], m12 = data[4], m13 = data[8];
  816. var m21 = data[1], m22 = data[5], m23 = data[9];
  817. var m31 = data[2], m32 = data[6], m33 = data[10];
  818. var trace = m11 + m22 + m33;
  819. var s;
  820. if (trace > 0) {
  821. s = 0.5 / Math.sqrt(trace + 1.0);
  822. this.w = 0.25 / s;
  823. this.x = (m32 - m23) * s;
  824. this.y = (m13 - m31) * s;
  825. this.z = (m21 - m12) * s;
  826. return;
  827. }
  828. if (m11 > m22 && m11 > m33) {
  829. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  830. this.w = (m32 - m23) / s;
  831. this.x = 0.25 * s;
  832. this.y = (m12 + m21) / s;
  833. this.z = (m13 + m31) / s;
  834. return;
  835. }
  836. if (m22 > m33) {
  837. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  838. this.w = (m13 - m31) / s;
  839. this.x = (m12 + m21) / s;
  840. this.y = 0.25 * s;
  841. this.z = (m23 + m32) / s;
  842. return;
  843. }
  844. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  845. this.w = (m21 - m12) / s;
  846. this.x = (m13 + m31) / s;
  847. this.y = (m23 + m32) / s;
  848. this.z = 0.25 * s;
  849. };
  850. Quaternion.Inverse = function (q) {
  851. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  852. };
  853. Quaternion.RotationAxis = function (axis, angle) {
  854. var result = new Quaternion();
  855. var sin = Math.sin(angle / 2);
  856. result.w = Math.cos(angle / 2);
  857. result.x = axis.x * sin;
  858. result.y = axis.y * sin;
  859. result.z = axis.z * sin;
  860. return result;
  861. };
  862. Quaternion.FromArray = function (array, offset) {
  863. if (!offset) {
  864. offset = 0;
  865. }
  866. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  867. };
  868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  869. var result = new Quaternion();
  870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  871. return result;
  872. };
  873. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  874. var halfRoll = roll * 0.5;
  875. var halfPitch = pitch * 0.5;
  876. var halfYaw = yaw * 0.5;
  877. var sinRoll = Math.sin(halfRoll);
  878. var cosRoll = Math.cos(halfRoll);
  879. var sinPitch = Math.sin(halfPitch);
  880. var cosPitch = Math.cos(halfPitch);
  881. var sinYaw = Math.sin(halfYaw);
  882. var cosYaw = Math.cos(halfYaw);
  883. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  884. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  885. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  886. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  887. };
  888. Quaternion.Slerp = function (left, right, amount) {
  889. var num2;
  890. var num3;
  891. var num = amount;
  892. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  893. var flag = false;
  894. if (num4 < 0) {
  895. flag = true;
  896. num4 = -num4;
  897. }
  898. if (num4 > 0.999999) {
  899. num3 = 1 - num;
  900. num2 = flag ? -num : num;
  901. } else {
  902. var num5 = Math.acos(num4);
  903. var num6 = (1.0 / Math.sin(num5));
  904. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  905. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  906. }
  907. 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));
  908. };
  909. return Quaternion;
  910. })();
  911. BABYLON.Quaternion = Quaternion;
  912. var Matrix = (function () {
  913. function Matrix() {
  914. this.m = new Float32Array(16);
  915. }
  916. Matrix.prototype.isIdentity = function () {
  917. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  918. return false;
  919. 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)
  920. return false;
  921. return true;
  922. };
  923. Matrix.prototype.determinant = function () {
  924. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  925. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  926. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  927. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  928. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  929. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  930. 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))));
  931. };
  932. Matrix.prototype.toArray = function () {
  933. return this.m;
  934. };
  935. Matrix.prototype.asArray = function () {
  936. return this.toArray();
  937. };
  938. Matrix.prototype.invert = function () {
  939. this.invertToRef(this);
  940. };
  941. Matrix.prototype.invertToRef = function (other) {
  942. var l1 = this.m[0];
  943. var l2 = this.m[1];
  944. var l3 = this.m[2];
  945. var l4 = this.m[3];
  946. var l5 = this.m[4];
  947. var l6 = this.m[5];
  948. var l7 = this.m[6];
  949. var l8 = this.m[7];
  950. var l9 = this.m[8];
  951. var l10 = this.m[9];
  952. var l11 = this.m[10];
  953. var l12 = this.m[11];
  954. var l13 = this.m[12];
  955. var l14 = this.m[13];
  956. var l15 = this.m[14];
  957. var l16 = this.m[15];
  958. var l17 = (l11 * l16) - (l12 * l15);
  959. var l18 = (l10 * l16) - (l12 * l14);
  960. var l19 = (l10 * l15) - (l11 * l14);
  961. var l20 = (l9 * l16) - (l12 * l13);
  962. var l21 = (l9 * l15) - (l11 * l13);
  963. var l22 = (l9 * l14) - (l10 * l13);
  964. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  965. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  966. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  967. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  968. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  969. var l28 = (l7 * l16) - (l8 * l15);
  970. var l29 = (l6 * l16) - (l8 * l14);
  971. var l30 = (l6 * l15) - (l7 * l14);
  972. var l31 = (l5 * l16) - (l8 * l13);
  973. var l32 = (l5 * l15) - (l7 * l13);
  974. var l33 = (l5 * l14) - (l6 * l13);
  975. var l34 = (l7 * l12) - (l8 * l11);
  976. var l35 = (l6 * l12) - (l8 * l10);
  977. var l36 = (l6 * l11) - (l7 * l10);
  978. var l37 = (l5 * l12) - (l8 * l9);
  979. var l38 = (l5 * l11) - (l7 * l9);
  980. var l39 = (l5 * l10) - (l6 * l9);
  981. other.m[0] = l23 * l27;
  982. other.m[4] = l24 * l27;
  983. other.m[8] = l25 * l27;
  984. other.m[12] = l26 * l27;
  985. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  986. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  987. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  988. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  989. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  990. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  991. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  992. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  993. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  994. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  995. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  996. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  997. };
  998. Matrix.prototype.setTranslation = function (vector3) {
  999. this.m[12] = vector3.x;
  1000. this.m[13] = vector3.y;
  1001. this.m[14] = vector3.z;
  1002. };
  1003. Matrix.prototype.multiply = function (other) {
  1004. var result = new Matrix();
  1005. this.multiplyToRef(other, result);
  1006. return result;
  1007. };
  1008. Matrix.prototype.copyFrom = function (other) {
  1009. for (var index = 0; index < 16; index++) {
  1010. this.m[index] = other.m[index];
  1011. }
  1012. };
  1013. Matrix.prototype.copyToArray = function (array, offset) {
  1014. if (typeof offset === "undefined") { offset = 0; }
  1015. for (var index = 0; index < 16; index++) {
  1016. array[offset + index] = this.m[index];
  1017. }
  1018. };
  1019. Matrix.prototype.multiplyToRef = function (other, result) {
  1020. this.multiplyToArray(other, result.m, 0);
  1021. };
  1022. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1023. var tm0 = this.m[0];
  1024. var tm1 = this.m[1];
  1025. var tm2 = this.m[2];
  1026. var tm3 = this.m[3];
  1027. var tm4 = this.m[4];
  1028. var tm5 = this.m[5];
  1029. var tm6 = this.m[6];
  1030. var tm7 = this.m[7];
  1031. var tm8 = this.m[8];
  1032. var tm9 = this.m[9];
  1033. var tm10 = this.m[10];
  1034. var tm11 = this.m[11];
  1035. var tm12 = this.m[12];
  1036. var tm13 = this.m[13];
  1037. var tm14 = this.m[14];
  1038. var tm15 = this.m[15];
  1039. var om0 = other.m[0];
  1040. var om1 = other.m[1];
  1041. var om2 = other.m[2];
  1042. var om3 = other.m[3];
  1043. var om4 = other.m[4];
  1044. var om5 = other.m[5];
  1045. var om6 = other.m[6];
  1046. var om7 = other.m[7];
  1047. var om8 = other.m[8];
  1048. var om9 = other.m[9];
  1049. var om10 = other.m[10];
  1050. var om11 = other.m[11];
  1051. var om12 = other.m[12];
  1052. var om13 = other.m[13];
  1053. var om14 = other.m[14];
  1054. var om15 = other.m[15];
  1055. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1056. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1057. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1058. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1059. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1060. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1061. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1062. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1063. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1064. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1065. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1066. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1067. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1068. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1069. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1070. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1071. };
  1072. Matrix.prototype.equals = function (value) {
  1073. 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]);
  1074. };
  1075. Matrix.prototype.clone = function () {
  1076. 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]);
  1077. };
  1078. Matrix.FromArray = function (array, offset) {
  1079. var result = new Matrix();
  1080. if (!offset) {
  1081. offset = 0;
  1082. }
  1083. Matrix.FromArrayToRef(array, offset, result);
  1084. return result;
  1085. };
  1086. Matrix.FromArrayToRef = function (array, offset, result) {
  1087. for (var index = 0; index < 16; index++) {
  1088. result.m[index] = array[index + offset];
  1089. }
  1090. };
  1091. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1092. result.m[0] = initialM11;
  1093. result.m[1] = initialM12;
  1094. result.m[2] = initialM13;
  1095. result.m[3] = initialM14;
  1096. result.m[4] = initialM21;
  1097. result.m[5] = initialM22;
  1098. result.m[6] = initialM23;
  1099. result.m[7] = initialM24;
  1100. result.m[8] = initialM31;
  1101. result.m[9] = initialM32;
  1102. result.m[10] = initialM33;
  1103. result.m[11] = initialM34;
  1104. result.m[12] = initialM41;
  1105. result.m[13] = initialM42;
  1106. result.m[14] = initialM43;
  1107. result.m[15] = initialM44;
  1108. };
  1109. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1110. var result = new Matrix();
  1111. result.m[0] = initialM11;
  1112. result.m[1] = initialM12;
  1113. result.m[2] = initialM13;
  1114. result.m[3] = initialM14;
  1115. result.m[4] = initialM21;
  1116. result.m[5] = initialM22;
  1117. result.m[6] = initialM23;
  1118. result.m[7] = initialM24;
  1119. result.m[8] = initialM31;
  1120. result.m[9] = initialM32;
  1121. result.m[10] = initialM33;
  1122. result.m[11] = initialM34;
  1123. result.m[12] = initialM41;
  1124. result.m[13] = initialM42;
  1125. result.m[14] = initialM43;
  1126. result.m[15] = initialM44;
  1127. return result;
  1128. };
  1129. Matrix.Identity = function () {
  1130. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1131. };
  1132. Matrix.IdentityToRef = function (result) {
  1133. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1134. };
  1135. Matrix.Zero = function () {
  1136. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1137. };
  1138. Matrix.RotationX = function (angle) {
  1139. var result = new Matrix();
  1140. Matrix.RotationXToRef(angle, result);
  1141. return result;
  1142. };
  1143. Matrix.RotationXToRef = function (angle, result) {
  1144. var s = Math.sin(angle);
  1145. var c = Math.cos(angle);
  1146. result.m[0] = 1.0;
  1147. result.m[15] = 1.0;
  1148. result.m[5] = c;
  1149. result.m[10] = c;
  1150. result.m[9] = -s;
  1151. result.m[6] = s;
  1152. result.m[1] = 0;
  1153. result.m[2] = 0;
  1154. result.m[3] = 0;
  1155. result.m[4] = 0;
  1156. result.m[7] = 0;
  1157. result.m[8] = 0;
  1158. result.m[11] = 0;
  1159. result.m[12] = 0;
  1160. result.m[13] = 0;
  1161. result.m[14] = 0;
  1162. };
  1163. Matrix.RotationY = function (angle) {
  1164. var result = new Matrix();
  1165. Matrix.RotationYToRef(angle, result);
  1166. return result;
  1167. };
  1168. Matrix.RotationYToRef = function (angle, result) {
  1169. var s = Math.sin(angle);
  1170. var c = Math.cos(angle);
  1171. result.m[5] = 1.0;
  1172. result.m[15] = 1.0;
  1173. result.m[0] = c;
  1174. result.m[2] = -s;
  1175. result.m[8] = s;
  1176. result.m[10] = c;
  1177. result.m[1] = 0;
  1178. result.m[3] = 0;
  1179. result.m[4] = 0;
  1180. result.m[6] = 0;
  1181. result.m[7] = 0;
  1182. result.m[9] = 0;
  1183. result.m[11] = 0;
  1184. result.m[12] = 0;
  1185. result.m[13] = 0;
  1186. result.m[14] = 0;
  1187. };
  1188. Matrix.RotationZ = function (angle) {
  1189. var result = new Matrix();
  1190. Matrix.RotationZToRef(angle, result);
  1191. return result;
  1192. };
  1193. Matrix.RotationZToRef = function (angle, result) {
  1194. var s = Math.sin(angle);
  1195. var c = Math.cos(angle);
  1196. result.m[10] = 1.0;
  1197. result.m[15] = 1.0;
  1198. result.m[0] = c;
  1199. result.m[1] = s;
  1200. result.m[4] = -s;
  1201. result.m[5] = c;
  1202. result.m[2] = 0;
  1203. result.m[3] = 0;
  1204. result.m[6] = 0;
  1205. result.m[7] = 0;
  1206. result.m[8] = 0;
  1207. result.m[9] = 0;
  1208. result.m[11] = 0;
  1209. result.m[12] = 0;
  1210. result.m[13] = 0;
  1211. result.m[14] = 0;
  1212. };
  1213. Matrix.RotationAxis = function (axis, angle) {
  1214. var s = Math.sin(-angle);
  1215. var c = Math.cos(-angle);
  1216. var c1 = 1 - c;
  1217. axis.normalize();
  1218. var result = Matrix.Zero();
  1219. result.m[0] = (axis.x * axis.x) * c1 + c;
  1220. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1221. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1222. result.m[3] = 0.0;
  1223. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1224. result.m[5] = (axis.y * axis.y) * c1 + c;
  1225. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1226. result.m[7] = 0.0;
  1227. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1228. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1229. result.m[10] = (axis.z * axis.z) * c1 + c;
  1230. result.m[11] = 0.0;
  1231. result.m[15] = 1.0;
  1232. return result;
  1233. };
  1234. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1235. var result = new Matrix();
  1236. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1237. return result;
  1238. };
  1239. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1240. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1241. this._tempQuaternion.toRotationMatrix(result);
  1242. };
  1243. Matrix.Scaling = function (x, y, z) {
  1244. var result = Matrix.Zero();
  1245. Matrix.ScalingToRef(x, y, z, result);
  1246. return result;
  1247. };
  1248. Matrix.ScalingToRef = function (x, y, z, result) {
  1249. result.m[0] = x;
  1250. result.m[1] = 0;
  1251. result.m[2] = 0;
  1252. result.m[3] = 0;
  1253. result.m[4] = 0;
  1254. result.m[5] = y;
  1255. result.m[6] = 0;
  1256. result.m[7] = 0;
  1257. result.m[8] = 0;
  1258. result.m[9] = 0;
  1259. result.m[10] = z;
  1260. result.m[11] = 0;
  1261. result.m[12] = 0;
  1262. result.m[13] = 0;
  1263. result.m[14] = 0;
  1264. result.m[15] = 1.0;
  1265. };
  1266. Matrix.Translation = function (x, y, z) {
  1267. var result = Matrix.Identity();
  1268. Matrix.TranslationToRef(x, y, z, result);
  1269. return result;
  1270. };
  1271. Matrix.TranslationToRef = function (x, y, z, result) {
  1272. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1273. };
  1274. Matrix.LookAtLH = function (eye, target, up) {
  1275. var result = Matrix.Zero();
  1276. Matrix.LookAtLHToRef(eye, target, up, result);
  1277. return result;
  1278. };
  1279. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1280. target.subtractToRef(eye, this._zAxis);
  1281. this._zAxis.normalize();
  1282. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1283. this._xAxis.normalize();
  1284. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1285. this._yAxis.normalize();
  1286. var ex = -Vector3.Dot(this._xAxis, eye);
  1287. var ey = -Vector3.Dot(this._yAxis, eye);
  1288. var ez = -Vector3.Dot(this._zAxis, eye);
  1289. 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);
  1290. };
  1291. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1292. var hw = 2.0 / width;
  1293. var hh = 2.0 / height;
  1294. var id = 1.0 / (zfar - znear);
  1295. var nid = znear / (znear - zfar);
  1296. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1297. };
  1298. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1299. var matrix = Matrix.Zero();
  1300. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1301. return matrix;
  1302. };
  1303. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1304. result.m[0] = 2.0 / (right - left);
  1305. result.m[1] = result.m[2] = result.m[3] = 0;
  1306. result.m[5] = 2.0 / (top - bottom);
  1307. result.m[4] = result.m[6] = result.m[7] = 0;
  1308. result.m[10] = -1.0 / (znear - zfar);
  1309. result.m[8] = result.m[9] = result.m[11] = 0;
  1310. result.m[12] = (left + right) / (left - right);
  1311. result.m[13] = (top + bottom) / (bottom - top);
  1312. result.m[14] = znear / (znear - zfar);
  1313. result.m[15] = 1.0;
  1314. };
  1315. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1316. var matrix = Matrix.Zero();
  1317. matrix.m[0] = (2.0 * znear) / width;
  1318. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1319. matrix.m[5] = (2.0 * znear) / height;
  1320. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1321. matrix.m[10] = -zfar / (znear - zfar);
  1322. matrix.m[8] = matrix.m[9] = 0.0;
  1323. matrix.m[11] = 1.0;
  1324. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1325. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1326. return matrix;
  1327. };
  1328. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1329. var matrix = Matrix.Zero();
  1330. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1331. return matrix;
  1332. };
  1333. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1334. var tan = 1.0 / (Math.tan(fov * 0.5));
  1335. result.m[0] = tan / aspect;
  1336. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1337. result.m[5] = tan;
  1338. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1339. result.m[8] = result.m[9] = 0.0;
  1340. result.m[10] = -zfar / (znear - zfar);
  1341. result.m[11] = 1.0;
  1342. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1343. result.m[14] = (znear * zfar) / (znear - zfar);
  1344. };
  1345. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1346. var cw = viewport.width;
  1347. var ch = viewport.height;
  1348. var cx = viewport.x;
  1349. var cy = viewport.y;
  1350. 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);
  1351. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1352. };
  1353. Matrix.Transpose = function (matrix) {
  1354. var result = new Matrix();
  1355. result.m[0] = matrix.m[0];
  1356. result.m[1] = matrix.m[4];
  1357. result.m[2] = matrix.m[8];
  1358. result.m[3] = matrix.m[12];
  1359. result.m[4] = matrix.m[1];
  1360. result.m[5] = matrix.m[5];
  1361. result.m[6] = matrix.m[9];
  1362. result.m[7] = matrix.m[13];
  1363. result.m[8] = matrix.m[2];
  1364. result.m[9] = matrix.m[6];
  1365. result.m[10] = matrix.m[10];
  1366. result.m[11] = matrix.m[14];
  1367. result.m[12] = matrix.m[3];
  1368. result.m[13] = matrix.m[7];
  1369. result.m[14] = matrix.m[11];
  1370. result.m[15] = matrix.m[15];
  1371. return result;
  1372. };
  1373. Matrix.Reflection = function (plane) {
  1374. var matrix = new Matrix();
  1375. Matrix.ReflectionToRef(plane, matrix);
  1376. return matrix;
  1377. };
  1378. Matrix.ReflectionToRef = function (plane, result) {
  1379. plane.normalize();
  1380. var x = plane.normal.x;
  1381. var y = plane.normal.y;
  1382. var z = plane.normal.z;
  1383. var temp = -2 * x;
  1384. var temp2 = -2 * y;
  1385. var temp3 = -2 * z;
  1386. result.m[0] = (temp * x) + 1;
  1387. result.m[1] = temp2 * x;
  1388. result.m[2] = temp3 * x;
  1389. result.m[3] = 0.0;
  1390. result.m[4] = temp * y;
  1391. result.m[5] = (temp2 * y) + 1;
  1392. result.m[6] = temp3 * y;
  1393. result.m[7] = 0.0;
  1394. result.m[8] = temp * z;
  1395. result.m[9] = temp2 * z;
  1396. result.m[10] = (temp3 * z) + 1;
  1397. result.m[11] = 0.0;
  1398. result.m[12] = temp * plane.d;
  1399. result.m[13] = temp2 * plane.d;
  1400. result.m[14] = temp3 * plane.d;
  1401. result.m[15] = 1.0;
  1402. };
  1403. Matrix._tempQuaternion = new Quaternion();
  1404. Matrix._xAxis = Vector3.Zero();
  1405. Matrix._yAxis = Vector3.Zero();
  1406. Matrix._zAxis = Vector3.Zero();
  1407. return Matrix;
  1408. })();
  1409. BABYLON.Matrix = Matrix;
  1410. var Plane = (function () {
  1411. function Plane(a, b, c, d) {
  1412. this.normal = new Vector3(a, b, c);
  1413. this.d = d;
  1414. }
  1415. Plane.prototype.asArray = function () {
  1416. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1417. };
  1418. Plane.prototype.clone = function () {
  1419. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1420. };
  1421. Plane.prototype.normalize = function () {
  1422. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1423. var magnitude = 0;
  1424. if (norm != 0) {
  1425. magnitude = 1.0 / norm;
  1426. }
  1427. this.normal.x *= magnitude;
  1428. this.normal.y *= magnitude;
  1429. this.normal.z *= magnitude;
  1430. this.d *= magnitude;
  1431. };
  1432. Plane.prototype.transform = function (transformation) {
  1433. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1434. var x = this.normal.x;
  1435. var y = this.normal.y;
  1436. var z = this.normal.z;
  1437. var d = this.d;
  1438. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1439. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1440. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1441. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1442. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1443. };
  1444. Plane.prototype.dotCoordinate = function (point) {
  1445. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1446. };
  1447. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1448. var x1 = point2.x - point1.x;
  1449. var y1 = point2.y - point1.y;
  1450. var z1 = point2.z - point1.z;
  1451. var x2 = point3.x - point1.x;
  1452. var y2 = point3.y - point1.y;
  1453. var z2 = point3.z - point1.z;
  1454. var yz = (y1 * z2) - (z1 * y2);
  1455. var xz = (z1 * x2) - (x1 * z2);
  1456. var xy = (x1 * y2) - (y1 * x2);
  1457. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1458. var invPyth;
  1459. if (pyth != 0) {
  1460. invPyth = 1.0 / pyth;
  1461. } else {
  1462. invPyth = 0;
  1463. }
  1464. this.normal.x = yz * invPyth;
  1465. this.normal.y = xz * invPyth;
  1466. this.normal.z = xy * invPyth;
  1467. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1468. };
  1469. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1470. var dot = Vector3.Dot(this.normal, direction);
  1471. return (dot <= epsilon);
  1472. };
  1473. Plane.prototype.signedDistanceTo = function (point) {
  1474. return Vector3.Dot(point, this.normal) + this.d;
  1475. };
  1476. Plane.FromArray = function (array) {
  1477. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1478. };
  1479. Plane.FromPoints = function (point1, point2, point3) {
  1480. var result = new BABYLON.Plane(0, 0, 0, 0);
  1481. result.copyFromPoints(point1, point2, point3);
  1482. return result;
  1483. };
  1484. Plane.FromPositionAndNormal = function (origin, normal) {
  1485. var result = new BABYLON.Plane(0, 0, 0, 0);
  1486. normal.normalize();
  1487. result.normal = normal;
  1488. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1489. return result;
  1490. };
  1491. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1492. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return Vector3.Dot(point, normal) + d;
  1494. };
  1495. return Plane;
  1496. })();
  1497. BABYLON.Plane = Plane;
  1498. var Viewport = (function () {
  1499. function Viewport(x, y, width, height) {
  1500. this.x = x;
  1501. this.y = y;
  1502. this.width = width;
  1503. this.height = height;
  1504. }
  1505. Viewport.prototype.toGlobal = function (engine) {
  1506. var width = engine.getRenderWidth();
  1507. var height = engine.getRenderHeight();
  1508. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1509. };
  1510. return Viewport;
  1511. })();
  1512. BABYLON.Viewport = Viewport;
  1513. var Frustum = (function () {
  1514. function Frustum() {
  1515. }
  1516. Frustum.GetPlanes = function (transform) {
  1517. var frustumPlanes = [];
  1518. for (var index = 0; index < 6; index++) {
  1519. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1520. }
  1521. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1522. return frustumPlanes;
  1523. };
  1524. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1525. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1526. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1527. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1528. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1529. frustumPlanes[0].normalize();
  1530. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1531. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1532. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1533. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1534. frustumPlanes[1].normalize();
  1535. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1536. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1537. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1538. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1539. frustumPlanes[2].normalize();
  1540. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1541. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1542. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1543. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1544. frustumPlanes[3].normalize();
  1545. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1546. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1547. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1548. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1549. frustumPlanes[4].normalize();
  1550. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1551. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1552. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1553. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1554. frustumPlanes[5].normalize();
  1555. };
  1556. return Frustum;
  1557. })();
  1558. BABYLON.Frustum = Frustum;
  1559. var Ray = (function () {
  1560. function Ray(origin, direction) {
  1561. this.origin = origin;
  1562. this.direction = direction;
  1563. }
  1564. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1565. var d = 0.0;
  1566. var maxValue = Number.MAX_VALUE;
  1567. if (Math.abs(this.direction.x) < 0.0000001) {
  1568. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1569. return false;
  1570. }
  1571. } else {
  1572. var inv = 1.0 / this.direction.x;
  1573. var min = (minimum.x - this.origin.x) * inv;
  1574. var max = (maximum.x - this.origin.x) * inv;
  1575. if (min > max) {
  1576. var temp = min;
  1577. min = max;
  1578. max = temp;
  1579. }
  1580. d = Math.max(min, d);
  1581. maxValue = Math.min(max, maxValue);
  1582. if (d > maxValue) {
  1583. return false;
  1584. }
  1585. }
  1586. if (Math.abs(this.direction.y) < 0.0000001) {
  1587. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1588. return false;
  1589. }
  1590. } else {
  1591. inv = 1.0 / this.direction.y;
  1592. min = (minimum.y - this.origin.y) * inv;
  1593. max = (maximum.y - this.origin.y) * inv;
  1594. if (min > max) {
  1595. temp = min;
  1596. min = max;
  1597. max = temp;
  1598. }
  1599. d = Math.max(min, d);
  1600. maxValue = Math.min(max, maxValue);
  1601. if (d > maxValue) {
  1602. return false;
  1603. }
  1604. }
  1605. if (Math.abs(this.direction.z) < 0.0000001) {
  1606. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1607. return false;
  1608. }
  1609. } else {
  1610. inv = 1.0 / this.direction.z;
  1611. min = (minimum.z - this.origin.z) * inv;
  1612. max = (maximum.z - this.origin.z) * inv;
  1613. if (min > max) {
  1614. temp = min;
  1615. min = max;
  1616. max = temp;
  1617. }
  1618. d = Math.max(min, d);
  1619. maxValue = Math.min(max, maxValue);
  1620. if (d > maxValue) {
  1621. return false;
  1622. }
  1623. }
  1624. return true;
  1625. };
  1626. Ray.prototype.intersectsBox = function (box) {
  1627. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1628. };
  1629. Ray.prototype.intersectsSphere = function (sphere) {
  1630. var x = sphere.center.x - this.origin.x;
  1631. var y = sphere.center.y - this.origin.y;
  1632. var z = sphere.center.z - this.origin.z;
  1633. var pyth = (x * x) + (y * y) + (z * z);
  1634. var rr = sphere.radius * sphere.radius;
  1635. if (pyth <= rr) {
  1636. return true;
  1637. }
  1638. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1639. if (dot < 0.0) {
  1640. return false;
  1641. }
  1642. var temp = pyth - (dot * dot);
  1643. return temp <= rr;
  1644. };
  1645. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1646. if (!this._edge1) {
  1647. this._edge1 = BABYLON.Vector3.Zero();
  1648. this._edge2 = BABYLON.Vector3.Zero();
  1649. this._pvec = BABYLON.Vector3.Zero();
  1650. this._tvec = BABYLON.Vector3.Zero();
  1651. this._qvec = BABYLON.Vector3.Zero();
  1652. }
  1653. vertex1.subtractToRef(vertex0, this._edge1);
  1654. vertex2.subtractToRef(vertex0, this._edge2);
  1655. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1656. var det = Vector3.Dot(this._edge1, this._pvec);
  1657. if (det === 0) {
  1658. return null;
  1659. }
  1660. var invdet = 1 / det;
  1661. this.origin.subtractToRef(vertex0, this._tvec);
  1662. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1663. if (bu < 0 || bu > 1.0) {
  1664. return null;
  1665. }
  1666. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1667. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1668. if (bv < 0 || bu + bv > 1.0) {
  1669. return null;
  1670. }
  1671. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1672. };
  1673. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1674. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1675. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1676. var direction = end.subtract(start);
  1677. direction.normalize();
  1678. return new Ray(start, direction);
  1679. };
  1680. Ray.Transform = function (ray, matrix) {
  1681. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1682. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1683. return new Ray(newOrigin, newDirection);
  1684. };
  1685. return Ray;
  1686. })();
  1687. BABYLON.Ray = Ray;
  1688. (function (Space) {
  1689. Space[Space["LOCAL"] = 0] = "LOCAL";
  1690. Space[Space["WORLD"] = 1] = "WORLD";
  1691. })(BABYLON.Space || (BABYLON.Space = {}));
  1692. var Space = BABYLON.Space;
  1693. var Axis = (function () {
  1694. function Axis() {
  1695. }
  1696. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1697. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1698. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1699. return Axis;
  1700. })();
  1701. BABYLON.Axis = Axis;
  1702. ;
  1703. })(BABYLON || (BABYLON = {}));
  1704. var BABYLON;
  1705. (function (BABYLON) {
  1706. var screenshotCanvas;
  1707. var fpsRange = 60;
  1708. var previousFramesDuration = [];
  1709. var fps = 60;
  1710. var deltaTime = 0;
  1711. var cloneValue = function (source, destinationObject) {
  1712. if (!source)
  1713. return null;
  1714. if (source instanceof BABYLON.Mesh) {
  1715. return null;
  1716. }
  1717. if (source instanceof BABYLON.SubMesh) {
  1718. return source.clone(destinationObject);
  1719. } else if (source.clone) {
  1720. return source.clone();
  1721. }
  1722. return null;
  1723. };
  1724. var Tools = (function () {
  1725. function Tools() {
  1726. }
  1727. Tools.GetFilename = function (path) {
  1728. var index = path.lastIndexOf("/");
  1729. if (index < 0)
  1730. return path;
  1731. return path.substring(index + 1);
  1732. };
  1733. Tools.GetDOMTextContent = function (element) {
  1734. var result = "";
  1735. var child = element.firstChild;
  1736. while (child) {
  1737. if (child.nodeType == 3) {
  1738. result += child.textContent;
  1739. }
  1740. child = child.nextSibling;
  1741. }
  1742. return result;
  1743. };
  1744. Tools.ToDegrees = function (angle) {
  1745. return angle * 180 / Math.PI;
  1746. };
  1747. Tools.ToRadians = function (angle) {
  1748. return angle * Math.PI / 180;
  1749. };
  1750. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1751. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1752. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1753. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1754. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1755. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1756. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1757. }
  1758. return {
  1759. minimum: minimum,
  1760. maximum: maximum
  1761. };
  1762. };
  1763. Tools.ExtractMinAndMax = function (positions, start, count) {
  1764. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1765. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1766. for (var index = start; index < start + count; index++) {
  1767. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1768. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1769. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1770. }
  1771. return {
  1772. minimum: minimum,
  1773. maximum: maximum
  1774. };
  1775. };
  1776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1778. return undefined;
  1779. return Array.isArray(obj) ? obj : [obj];
  1780. };
  1781. Tools.GetPointerPrefix = function () {
  1782. var eventPrefix = "pointer";
  1783. if (!navigator.pointerEnabled) {
  1784. eventPrefix = "mouse";
  1785. }
  1786. return eventPrefix;
  1787. };
  1788. Tools.QueueNewFrame = function (func) {
  1789. if (window.requestAnimationFrame)
  1790. window.requestAnimationFrame(func);
  1791. else if (window.msRequestAnimationFrame)
  1792. window.msRequestAnimationFrame(func);
  1793. else if (window.webkitRequestAnimationFrame)
  1794. window.webkitRequestAnimationFrame(func);
  1795. else if (window.mozRequestAnimationFrame)
  1796. window.mozRequestAnimationFrame(func);
  1797. else if (window.oRequestAnimationFrame)
  1798. window.oRequestAnimationFrame(func);
  1799. else {
  1800. window.setTimeout(func, 16);
  1801. }
  1802. };
  1803. Tools.RequestFullscreen = function (element) {
  1804. if (element.requestFullscreen)
  1805. element.requestFullscreen();
  1806. else if (element.msRequestFullscreen)
  1807. element.msRequestFullscreen();
  1808. else if (element.webkitRequestFullscreen)
  1809. element.webkitRequestFullscreen();
  1810. else if (element.mozRequestFullScreen)
  1811. element.mozRequestFullScreen();
  1812. };
  1813. Tools.ExitFullscreen = function () {
  1814. if (document.exitFullscreen) {
  1815. document.exitFullscreen();
  1816. } else if (document.mozCancelFullScreen) {
  1817. document.mozCancelFullScreen();
  1818. } else if (document.webkitCancelFullScreen) {
  1819. document.webkitCancelFullScreen();
  1820. } else if (document.msCancelFullScreen) {
  1821. document.msCancelFullScreen();
  1822. }
  1823. };
  1824. Tools.CleanUrl = function (url) {
  1825. url = url.replace(/#/mg, "%23");
  1826. return url;
  1827. };
  1828. Tools.LoadImage = function (url, onload, onerror, database) {
  1829. url = Tools.CleanUrl(url);
  1830. var img = new Image();
  1831. if (url.substr(0, 5) != "data:")
  1832. img.crossOrigin = 'anonymous';
  1833. img.onload = function () {
  1834. onload(img);
  1835. };
  1836. img.onerror = function (err) {
  1837. onerror(img, err);
  1838. };
  1839. var noIndexedDB = function () {
  1840. img.src = url;
  1841. };
  1842. var loadFromIndexedDB = function () {
  1843. database.loadImageFromDB(url, img);
  1844. };
  1845. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1846. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1847. } else {
  1848. if (url.indexOf("file:") === -1) {
  1849. noIndexedDB();
  1850. } else {
  1851. try {
  1852. var textureName = url.substring(5);
  1853. var blobURL;
  1854. try {
  1855. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1856. } catch (ex) {
  1857. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1858. }
  1859. img.src = blobURL;
  1860. } catch (e) {
  1861. Tools.Log("Error while trying to load texture: " + textureName);
  1862. img.src = null;
  1863. }
  1864. }
  1865. }
  1866. return img;
  1867. };
  1868. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1869. url = Tools.CleanUrl(url);
  1870. var noIndexedDB = function () {
  1871. var request = new XMLHttpRequest();
  1872. var loadUrl = Tools.BaseUrl + url;
  1873. request.open('GET', loadUrl, true);
  1874. if (useArrayBuffer) {
  1875. request.responseType = "arraybuffer";
  1876. }
  1877. request.onprogress = progressCallBack;
  1878. request.onreadystatechange = function () {
  1879. if (request.readyState == 4) {
  1880. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1881. callback(!useArrayBuffer ? request.responseText : request.response);
  1882. } else {
  1883. if (onError) {
  1884. onError();
  1885. } else {
  1886. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1887. }
  1888. }
  1889. }
  1890. };
  1891. request.send(null);
  1892. };
  1893. var loadFromIndexedDB = function () {
  1894. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1895. };
  1896. if (url.indexOf("file:") !== -1) {
  1897. var fileName = url.substring(5);
  1898. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1899. } else {
  1900. if (database && database.enableSceneOffline) {
  1901. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1902. } else {
  1903. noIndexedDB();
  1904. }
  1905. }
  1906. };
  1907. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  1908. var reader = new FileReader();
  1909. reader.onload = function (e) {
  1910. callback(e.target.result);
  1911. };
  1912. reader.onprogress = progressCallback;
  1913. reader.readAsDataURL(fileToLoad);
  1914. };
  1915. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1916. var reader = new FileReader();
  1917. reader.onload = function (e) {
  1918. callback(e.target.result);
  1919. };
  1920. reader.onprogress = progressCallBack;
  1921. if (!useArrayBuffer) {
  1922. reader.readAsText(fileToLoad);
  1923. } else {
  1924. reader.readAsArrayBuffer(fileToLoad);
  1925. }
  1926. };
  1927. Tools.CheckExtends = function (v, min, max) {
  1928. if (v.x < min.x)
  1929. min.x = v.x;
  1930. if (v.y < min.y)
  1931. min.y = v.y;
  1932. if (v.z < min.z)
  1933. min.z = v.z;
  1934. if (v.x > max.x)
  1935. max.x = v.x;
  1936. if (v.y > max.y)
  1937. max.y = v.y;
  1938. if (v.z > max.z)
  1939. max.z = v.z;
  1940. };
  1941. Tools.WithinEpsilon = function (a, b) {
  1942. var num = a - b;
  1943. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1944. };
  1945. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1946. for (var prop in source) {
  1947. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1948. continue;
  1949. }
  1950. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1951. continue;
  1952. }
  1953. var sourceValue = source[prop];
  1954. var typeOfSourceValue = typeof sourceValue;
  1955. if (typeOfSourceValue == "function") {
  1956. continue;
  1957. }
  1958. if (typeOfSourceValue == "object") {
  1959. if (sourceValue instanceof Array) {
  1960. destination[prop] = [];
  1961. if (sourceValue.length > 0) {
  1962. if (typeof sourceValue[0] == "object") {
  1963. for (var index = 0; index < sourceValue.length; index++) {
  1964. var clonedValue = cloneValue(sourceValue[index], destination);
  1965. if (destination[prop].indexOf(clonedValue) === -1) {
  1966. destination[prop].push(clonedValue);
  1967. }
  1968. }
  1969. } else {
  1970. destination[prop] = sourceValue.slice(0);
  1971. }
  1972. }
  1973. } else {
  1974. destination[prop] = cloneValue(sourceValue, destination);
  1975. }
  1976. } else {
  1977. destination[prop] = sourceValue;
  1978. }
  1979. }
  1980. };
  1981. Tools.IsEmpty = function (obj) {
  1982. for (var i in obj) {
  1983. return false;
  1984. }
  1985. return true;
  1986. };
  1987. Tools.RegisterTopRootEvents = function (events) {
  1988. for (var index = 0; index < events.length; index++) {
  1989. var event = events[index];
  1990. window.addEventListener(event.name, event.handler, false);
  1991. try {
  1992. if (window.parent) {
  1993. window.parent.addEventListener(event.name, event.handler, false);
  1994. }
  1995. } catch (e) {
  1996. }
  1997. }
  1998. };
  1999. Tools.UnregisterTopRootEvents = function (events) {
  2000. for (var index = 0; index < events.length; index++) {
  2001. var event = events[index];
  2002. window.removeEventListener(event.name, event.handler);
  2003. try {
  2004. if (window.parent) {
  2005. window.parent.removeEventListener(event.name, event.handler);
  2006. }
  2007. } catch (e) {
  2008. }
  2009. }
  2010. };
  2011. Tools.GetFps = function () {
  2012. return fps;
  2013. };
  2014. Tools.GetDeltaTime = function () {
  2015. return deltaTime;
  2016. };
  2017. Tools._MeasureFps = function () {
  2018. previousFramesDuration.push((new Date).getTime());
  2019. var length = previousFramesDuration.length;
  2020. if (length >= 2) {
  2021. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2022. }
  2023. if (length >= fpsRange) {
  2024. if (length > fpsRange) {
  2025. previousFramesDuration.splice(0, 1);
  2026. length = previousFramesDuration.length;
  2027. }
  2028. var sum = 0;
  2029. for (var id = 0; id < length - 1; id++) {
  2030. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2031. }
  2032. fps = 1000.0 / (sum / (length - 1));
  2033. }
  2034. };
  2035. Tools.CreateScreenshot = function (engine, camera, size) {
  2036. var width;
  2037. var height;
  2038. var scene = camera.getScene();
  2039. var previousCamera = null;
  2040. if (scene.activeCamera !== camera) {
  2041. previousCamera = scene.activeCamera;
  2042. scene.activeCamera = camera;
  2043. }
  2044. if (size.precision) {
  2045. width = Math.round(engine.getRenderWidth() * size.precision);
  2046. height = Math.round(width / engine.getAspectRatio(camera));
  2047. size = { width: width, height: height };
  2048. } else if (size.width && size.height) {
  2049. width = size.width;
  2050. height = size.height;
  2051. } else if (size.width && !size.height) {
  2052. width = size.width;
  2053. height = Math.round(width / engine.getAspectRatio(camera));
  2054. size = { width: width, height: height };
  2055. } else if (size.height && !size.width) {
  2056. height = size.height;
  2057. width = Math.round(height * engine.getAspectRatio(camera));
  2058. size = { width: width, height: height };
  2059. } else if (!isNaN(size)) {
  2060. height = size;
  2061. width = size;
  2062. } else {
  2063. Tools.Error("Invalid 'size' parameter !");
  2064. return;
  2065. }
  2066. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2067. texture.renderList = engine.scenes[0].meshes;
  2068. texture.onAfterRender = function () {
  2069. var numberOfChannelsByLine = width * 4;
  2070. var halfHeight = height / 2;
  2071. var data = engine.readPixels(0, 0, width, height);
  2072. for (var i = 0; i < halfHeight; i++) {
  2073. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2074. var currentCell = j + i * numberOfChannelsByLine;
  2075. var targetLine = height - i - 1;
  2076. var targetCell = j + targetLine * numberOfChannelsByLine;
  2077. var temp = data[currentCell];
  2078. data[currentCell] = data[targetCell];
  2079. data[targetCell] = temp;
  2080. }
  2081. }
  2082. if (!screenshotCanvas) {
  2083. screenshotCanvas = document.createElement('canvas');
  2084. }
  2085. screenshotCanvas.width = width;
  2086. screenshotCanvas.height = height;
  2087. var context = screenshotCanvas.getContext('2d');
  2088. var imageData = context.createImageData(width, height);
  2089. imageData.data.set(data);
  2090. context.putImageData(imageData, 0, 0);
  2091. var base64Image = screenshotCanvas.toDataURL();
  2092. if (("download" in document.createElement("a"))) {
  2093. var a = window.document.createElement("a");
  2094. a.href = base64Image;
  2095. var date = new Date();
  2096. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2097. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2098. window.document.body.appendChild(a);
  2099. a.addEventListener("click", function () {
  2100. a.parentElement.removeChild(a);
  2101. });
  2102. a.click();
  2103. } else {
  2104. var newWindow = window.open("");
  2105. var img = newWindow.document.createElement("img");
  2106. img.src = base64Image;
  2107. newWindow.document.body.appendChild(img);
  2108. }
  2109. };
  2110. texture.render(true);
  2111. texture.dispose();
  2112. if (previousCamera) {
  2113. scene.activeCamera = previousCamera;
  2114. }
  2115. };
  2116. Tools.ValidateXHRData = function (xhr, dataType) {
  2117. if (typeof dataType === "undefined") { dataType = 7; }
  2118. try {
  2119. if (dataType & 1) {
  2120. if (xhr.responseText && xhr.responseText.length > 0) {
  2121. return true;
  2122. } else if (dataType === 1) {
  2123. return false;
  2124. }
  2125. }
  2126. if (dataType & 2) {
  2127. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2128. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2129. return true;
  2130. } else if (dataType === 2) {
  2131. return false;
  2132. }
  2133. }
  2134. if (dataType & 4) {
  2135. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2136. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2137. return true;
  2138. } else {
  2139. return false;
  2140. }
  2141. }
  2142. } catch (e) {
  2143. }
  2144. return false;
  2145. };
  2146. Object.defineProperty(Tools, "NoneLogLevel", {
  2147. get: function () {
  2148. return Tools._NoneLogLevel;
  2149. },
  2150. enumerable: true,
  2151. configurable: true
  2152. });
  2153. Object.defineProperty(Tools, "MessageLogLevel", {
  2154. get: function () {
  2155. return Tools._MessageLogLevel;
  2156. },
  2157. enumerable: true,
  2158. configurable: true
  2159. });
  2160. Object.defineProperty(Tools, "WarningLogLevel", {
  2161. get: function () {
  2162. return Tools._WarningLogLevel;
  2163. },
  2164. enumerable: true,
  2165. configurable: true
  2166. });
  2167. Object.defineProperty(Tools, "ErrorLogLevel", {
  2168. get: function () {
  2169. return Tools._ErrorLogLevel;
  2170. },
  2171. enumerable: true,
  2172. configurable: true
  2173. });
  2174. Object.defineProperty(Tools, "AllLogLevel", {
  2175. get: function () {
  2176. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2177. },
  2178. enumerable: true,
  2179. configurable: true
  2180. });
  2181. Tools._FormatMessage = function (message) {
  2182. var padStr = function (i) {
  2183. return (i < 10) ? "0" + i : "" + i;
  2184. };
  2185. var date = new Date();
  2186. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2187. };
  2188. Tools._LogDisabled = function (message) {
  2189. };
  2190. Tools._LogEnabled = function (message) {
  2191. console.log(Tools._FormatMessage(message));
  2192. };
  2193. Tools._WarnDisabled = function (message) {
  2194. };
  2195. Tools._WarnEnabled = function (message) {
  2196. console.warn(Tools._FormatMessage(message));
  2197. };
  2198. Tools._ErrorDisabled = function (message) {
  2199. };
  2200. Tools._ErrorEnabled = function (message) {
  2201. console.error(Tools._FormatMessage(message));
  2202. };
  2203. Object.defineProperty(Tools, "LogLevels", {
  2204. set: function (level) {
  2205. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2206. Tools.Log = Tools._LogEnabled;
  2207. } else {
  2208. Tools.Log = Tools._LogDisabled;
  2209. }
  2210. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2211. Tools.Warn = Tools._WarnEnabled;
  2212. } else {
  2213. Tools.Warn = Tools._WarnDisabled;
  2214. }
  2215. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2216. Tools.Error = Tools._ErrorEnabled;
  2217. } else {
  2218. Tools.Error = Tools._ErrorDisabled;
  2219. }
  2220. },
  2221. enumerable: true,
  2222. configurable: true
  2223. });
  2224. Tools.BaseUrl = "";
  2225. Tools.GetExponantOfTwo = function (value, max) {
  2226. var count = 1;
  2227. do {
  2228. count *= 2;
  2229. } while(count < value);
  2230. if (count > max)
  2231. count = max;
  2232. return count;
  2233. };
  2234. Tools._NoneLogLevel = 0;
  2235. Tools._MessageLogLevel = 1;
  2236. Tools._WarningLogLevel = 2;
  2237. Tools._ErrorLogLevel = 4;
  2238. Tools.Log = Tools._LogEnabled;
  2239. Tools.Warn = Tools._WarnEnabled;
  2240. Tools.Error = Tools._ErrorEnabled;
  2241. return Tools;
  2242. })();
  2243. BABYLON.Tools = Tools;
  2244. })(BABYLON || (BABYLON = {}));
  2245. var BABYLON;
  2246. (function (BABYLON) {
  2247. var _DepthCullingState = (function () {
  2248. function _DepthCullingState() {
  2249. this._isDepthTestDirty = false;
  2250. this._isDepthMaskDirty = false;
  2251. this._isDepthFuncDirty = false;
  2252. this._isCullFaceDirty = false;
  2253. this._isCullDirty = false;
  2254. }
  2255. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2256. get: function () {
  2257. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2258. },
  2259. enumerable: true,
  2260. configurable: true
  2261. });
  2262. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2263. get: function () {
  2264. return this._cullFace;
  2265. },
  2266. set: function (value) {
  2267. if (this._cullFace === value) {
  2268. return;
  2269. }
  2270. this._cullFace = value;
  2271. this._isCullFaceDirty = true;
  2272. },
  2273. enumerable: true,
  2274. configurable: true
  2275. });
  2276. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2277. get: function () {
  2278. return this._cull;
  2279. },
  2280. set: function (value) {
  2281. if (this._cull === value) {
  2282. return;
  2283. }
  2284. this._cull = value;
  2285. this._isCullDirty = true;
  2286. },
  2287. enumerable: true,
  2288. configurable: true
  2289. });
  2290. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2291. get: function () {
  2292. return this._depthFunc;
  2293. },
  2294. set: function (value) {
  2295. if (this._depthFunc === value) {
  2296. return;
  2297. }
  2298. this._depthFunc = value;
  2299. this._isDepthFuncDirty = true;
  2300. },
  2301. enumerable: true,
  2302. configurable: true
  2303. });
  2304. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2305. get: function () {
  2306. return this._depthMask;
  2307. },
  2308. set: function (value) {
  2309. if (this._depthMask === value) {
  2310. return;
  2311. }
  2312. this._depthMask = value;
  2313. this._isDepthMaskDirty = true;
  2314. },
  2315. enumerable: true,
  2316. configurable: true
  2317. });
  2318. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2319. get: function () {
  2320. return this._depthTest;
  2321. },
  2322. set: function (value) {
  2323. if (this._depthTest === value) {
  2324. return;
  2325. }
  2326. this._depthTest = value;
  2327. this._isDepthTestDirty = true;
  2328. },
  2329. enumerable: true,
  2330. configurable: true
  2331. });
  2332. _DepthCullingState.prototype.reset = function () {
  2333. this._depthMask = true;
  2334. this._depthTest = true;
  2335. this._depthFunc = null;
  2336. this._cull = null;
  2337. this._cullFace = null;
  2338. this._isDepthTestDirty = true;
  2339. this._isDepthMaskDirty = true;
  2340. this._isDepthFuncDirty = false;
  2341. this._isCullFaceDirty = false;
  2342. this._isCullDirty = false;
  2343. };
  2344. _DepthCullingState.prototype.apply = function (gl) {
  2345. if (!this.isDirty) {
  2346. return;
  2347. }
  2348. if (this._isCullDirty) {
  2349. if (this.cull === true) {
  2350. gl.enable(gl.CULL_FACE);
  2351. } else if (this.cull === false) {
  2352. gl.disable(gl.CULL_FACE);
  2353. }
  2354. this._isCullDirty = false;
  2355. }
  2356. if (this._isCullFaceDirty) {
  2357. gl.cullFace(this.cullFace);
  2358. this._isCullFaceDirty = false;
  2359. }
  2360. if (this._isDepthMaskDirty) {
  2361. gl.depthMask(this.depthMask);
  2362. this._isDepthMaskDirty = false;
  2363. }
  2364. if (this._isDepthTestDirty) {
  2365. if (this.depthTest === true) {
  2366. gl.enable(gl.DEPTH_TEST);
  2367. } else if (this.depthTest === false) {
  2368. gl.disable(gl.DEPTH_TEST);
  2369. }
  2370. this._isDepthTestDirty = false;
  2371. }
  2372. if (this._isDepthFuncDirty) {
  2373. gl.depthFunc(this.depthFunc);
  2374. this._isDepthFuncDirty = false;
  2375. }
  2376. };
  2377. return _DepthCullingState;
  2378. })();
  2379. BABYLON._DepthCullingState = _DepthCullingState;
  2380. var _AlphaState = (function () {
  2381. function _AlphaState() {
  2382. this._isAlphaBlendDirty = false;
  2383. this._isBlendFunctionParametersDirty = false;
  2384. this._alphaBlend = false;
  2385. this._blendFunctionParameters = new Array(4);
  2386. }
  2387. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2388. get: function () {
  2389. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2390. },
  2391. enumerable: true,
  2392. configurable: true
  2393. });
  2394. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2395. get: function () {
  2396. return this._alphaBlend;
  2397. },
  2398. set: function (value) {
  2399. if (this._alphaBlend === value) {
  2400. return;
  2401. }
  2402. this._alphaBlend = value;
  2403. this._isAlphaBlendDirty = true;
  2404. },
  2405. enumerable: true,
  2406. configurable: true
  2407. });
  2408. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2409. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2410. return;
  2411. }
  2412. this._blendFunctionParameters[0] = value0;
  2413. this._blendFunctionParameters[1] = value1;
  2414. this._blendFunctionParameters[2] = value2;
  2415. this._blendFunctionParameters[3] = value3;
  2416. this._isBlendFunctionParametersDirty = true;
  2417. };
  2418. _AlphaState.prototype.reset = function () {
  2419. this._alphaBlend = false;
  2420. this._blendFunctionParameters[0] = null;
  2421. this._blendFunctionParameters[1] = null;
  2422. this._blendFunctionParameters[2] = null;
  2423. this._blendFunctionParameters[3] = null;
  2424. this._isAlphaBlendDirty = true;
  2425. this._isBlendFunctionParametersDirty = false;
  2426. };
  2427. _AlphaState.prototype.apply = function (gl) {
  2428. if (!this.isDirty) {
  2429. return;
  2430. }
  2431. if (this._isAlphaBlendDirty) {
  2432. if (this._alphaBlend === true) {
  2433. gl.enable(gl.BLEND);
  2434. } else if (this._alphaBlend === false) {
  2435. gl.disable(gl.BLEND);
  2436. }
  2437. this._isAlphaBlendDirty = false;
  2438. }
  2439. if (this._isBlendFunctionParametersDirty) {
  2440. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2441. this._isBlendFunctionParametersDirty = false;
  2442. }
  2443. };
  2444. return _AlphaState;
  2445. })();
  2446. BABYLON._AlphaState = _AlphaState;
  2447. var compileShader = function (gl, source, type, defines) {
  2448. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2449. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2450. gl.compileShader(shader);
  2451. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2452. throw new Error(gl.getShaderInfoLog(shader));
  2453. }
  2454. return shader;
  2455. };
  2456. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2457. var magFilter = gl.NEAREST;
  2458. var minFilter = gl.NEAREST;
  2459. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2460. magFilter = gl.LINEAR;
  2461. if (generateMipMaps) {
  2462. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2463. } else {
  2464. minFilter = gl.LINEAR;
  2465. }
  2466. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2467. magFilter = gl.LINEAR;
  2468. if (generateMipMaps) {
  2469. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2470. } else {
  2471. minFilter = gl.LINEAR;
  2472. }
  2473. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2474. magFilter = gl.NEAREST;
  2475. if (generateMipMaps) {
  2476. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2477. } else {
  2478. minFilter = gl.NEAREST;
  2479. }
  2480. }
  2481. return {
  2482. min: minFilter,
  2483. mag: magFilter
  2484. };
  2485. };
  2486. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2487. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2488. var engine = scene.getEngine();
  2489. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2490. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2491. gl.bindTexture(gl.TEXTURE_2D, texture);
  2492. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2493. processFunction(potWidth, potHeight);
  2494. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2496. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2497. if (!noMipmap && !isCompressed) {
  2498. gl.generateMipmap(gl.TEXTURE_2D);
  2499. }
  2500. gl.bindTexture(gl.TEXTURE_2D, null);
  2501. engine._activeTexturesCache = [];
  2502. texture._baseWidth = width;
  2503. texture._baseHeight = height;
  2504. texture._width = potWidth;
  2505. texture._height = potHeight;
  2506. texture.isReady = true;
  2507. scene._removePendingData(texture);
  2508. };
  2509. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  2510. var img;
  2511. var onload = function () {
  2512. loadedImages.push(img);
  2513. scene._removePendingData(img);
  2514. if (index != extensions.length - 1) {
  2515. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  2516. } else {
  2517. onfinish(loadedImages);
  2518. }
  2519. };
  2520. var onerror = function () {
  2521. scene._removePendingData(img);
  2522. };
  2523. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  2524. scene._addPendingData(img);
  2525. };
  2526. var EngineCapabilities = (function () {
  2527. function EngineCapabilities() {
  2528. }
  2529. return EngineCapabilities;
  2530. })();
  2531. BABYLON.EngineCapabilities = EngineCapabilities;
  2532. var Engine = (function () {
  2533. function Engine(canvas, antialias, options) {
  2534. var _this = this;
  2535. this.isFullscreen = false;
  2536. this.isPointerLock = false;
  2537. this.forceWireframe = false;
  2538. this.cullBackFaces = true;
  2539. this.renderEvenInBackground = true;
  2540. this.scenes = new Array();
  2541. this._windowIsBackground = false;
  2542. this._runningLoop = false;
  2543. this._loadingDivBackgroundColor = "black";
  2544. this._depthCullingState = new _DepthCullingState();
  2545. this._alphaState = new _AlphaState();
  2546. this._loadedTexturesCache = new Array();
  2547. this._activeTexturesCache = new Array();
  2548. this._compiledEffects = {};
  2549. this._renderingCanvas = canvas;
  2550. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2551. options = options || {};
  2552. options.antialias = antialias;
  2553. try {
  2554. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2555. } catch (e) {
  2556. throw new Error("WebGL not supported");
  2557. }
  2558. if (!this._gl) {
  2559. throw new Error("WebGL not supported");
  2560. }
  2561. this._onBlur = function () {
  2562. _this._windowIsBackground = true;
  2563. };
  2564. this._onFocus = function () {
  2565. _this._windowIsBackground = false;
  2566. };
  2567. window.addEventListener("blur", this._onBlur);
  2568. window.addEventListener("focus", this._onFocus);
  2569. this._workingCanvas = document.createElement("canvas");
  2570. this._workingContext = this._workingCanvas.getContext("2d");
  2571. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2572. this.resize();
  2573. this._caps = new EngineCapabilities();
  2574. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2575. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2576. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2577. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2578. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2579. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2580. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2581. 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');
  2582. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2583. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2584. this.setDepthBuffer(true);
  2585. this.setDepthFunctionToLessOrEqual();
  2586. this.setDepthWrite(true);
  2587. this._onFullscreenChange = function () {
  2588. if (document.fullscreen !== undefined) {
  2589. _this.isFullscreen = document.fullscreen;
  2590. } else if (document.mozFullScreen !== undefined) {
  2591. _this.isFullscreen = document.mozFullScreen;
  2592. } else if (document.webkitIsFullScreen !== undefined) {
  2593. _this.isFullscreen = document.webkitIsFullScreen;
  2594. } else if (document.msIsFullScreen !== undefined) {
  2595. _this.isFullscreen = document.msIsFullScreen;
  2596. }
  2597. if (_this.isFullscreen && _this._pointerLockRequested) {
  2598. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2599. if (canvas.requestPointerLock) {
  2600. canvas.requestPointerLock();
  2601. }
  2602. }
  2603. };
  2604. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2605. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2606. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2607. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2608. this._onPointerLockChange = function () {
  2609. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2610. };
  2611. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2612. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2613. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2614. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2615. }
  2616. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2617. get: function () {
  2618. return Engine._ALPHA_DISABLE;
  2619. },
  2620. enumerable: true,
  2621. configurable: true
  2622. });
  2623. Object.defineProperty(Engine, "ALPHA_ADD", {
  2624. get: function () {
  2625. return Engine._ALPHA_ADD;
  2626. },
  2627. enumerable: true,
  2628. configurable: true
  2629. });
  2630. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2631. get: function () {
  2632. return Engine._ALPHA_COMBINE;
  2633. },
  2634. enumerable: true,
  2635. configurable: true
  2636. });
  2637. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2638. get: function () {
  2639. return Engine._DELAYLOADSTATE_NONE;
  2640. },
  2641. enumerable: true,
  2642. configurable: true
  2643. });
  2644. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2645. get: function () {
  2646. return Engine._DELAYLOADSTATE_LOADED;
  2647. },
  2648. enumerable: true,
  2649. configurable: true
  2650. });
  2651. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2652. get: function () {
  2653. return Engine._DELAYLOADSTATE_LOADING;
  2654. },
  2655. enumerable: true,
  2656. configurable: true
  2657. });
  2658. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2659. get: function () {
  2660. return Engine._DELAYLOADSTATE_NOTLOADED;
  2661. },
  2662. enumerable: true,
  2663. configurable: true
  2664. });
  2665. Object.defineProperty(Engine, "Version", {
  2666. get: function () {
  2667. return "1.14.0";
  2668. },
  2669. enumerable: true,
  2670. configurable: true
  2671. });
  2672. Engine.prototype.getAspectRatio = function (camera) {
  2673. var viewport = camera.viewport;
  2674. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2675. };
  2676. Engine.prototype.getRenderWidth = function () {
  2677. if (this._currentRenderTarget) {
  2678. return this._currentRenderTarget._width;
  2679. }
  2680. return this._renderingCanvas.width;
  2681. };
  2682. Engine.prototype.getRenderHeight = function () {
  2683. if (this._currentRenderTarget) {
  2684. return this._currentRenderTarget._height;
  2685. }
  2686. return this._renderingCanvas.height;
  2687. };
  2688. Engine.prototype.getRenderingCanvas = function () {
  2689. return this._renderingCanvas;
  2690. };
  2691. Engine.prototype.getRenderingCanvasClientRect = function () {
  2692. return this._renderingCanvas.getBoundingClientRect();
  2693. };
  2694. Engine.prototype.setHardwareScalingLevel = function (level) {
  2695. this._hardwareScalingLevel = level;
  2696. this.resize();
  2697. };
  2698. Engine.prototype.getHardwareScalingLevel = function () {
  2699. return this._hardwareScalingLevel;
  2700. };
  2701. Engine.prototype.getLoadedTexturesCache = function () {
  2702. return this._loadedTexturesCache;
  2703. };
  2704. Engine.prototype.getCaps = function () {
  2705. return this._caps;
  2706. };
  2707. Engine.prototype.setDepthFunctionToGreater = function () {
  2708. this._depthCullingState.depthFunc = this._gl.GREATER;
  2709. };
  2710. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2711. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2712. };
  2713. Engine.prototype.setDepthFunctionToLess = function () {
  2714. this._depthCullingState.depthFunc = this._gl.LESS;
  2715. };
  2716. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2717. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2718. };
  2719. Engine.prototype.stopRenderLoop = function () {
  2720. this._renderFunction = null;
  2721. this._runningLoop = false;
  2722. };
  2723. Engine.prototype._renderLoop = function () {
  2724. var _this = this;
  2725. var shouldRender = true;
  2726. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2727. shouldRender = false;
  2728. }
  2729. if (shouldRender) {
  2730. this.beginFrame();
  2731. if (this._renderFunction) {
  2732. this._renderFunction();
  2733. }
  2734. this.endFrame();
  2735. }
  2736. if (this._runningLoop) {
  2737. BABYLON.Tools.QueueNewFrame(function () {
  2738. _this._renderLoop();
  2739. });
  2740. }
  2741. };
  2742. Engine.prototype.runRenderLoop = function (renderFunction) {
  2743. var _this = this;
  2744. this._runningLoop = true;
  2745. this._renderFunction = renderFunction;
  2746. BABYLON.Tools.QueueNewFrame(function () {
  2747. _this._renderLoop();
  2748. });
  2749. };
  2750. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2751. if (this.isFullscreen) {
  2752. BABYLON.Tools.ExitFullscreen();
  2753. } else {
  2754. this._pointerLockRequested = requestPointerLock;
  2755. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2756. }
  2757. };
  2758. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2759. this.applyStates();
  2760. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2761. if (this._depthCullingState.depthMask) {
  2762. this._gl.clearDepth(1.0);
  2763. }
  2764. var mode = 0;
  2765. if (backBuffer)
  2766. mode |= this._gl.COLOR_BUFFER_BIT;
  2767. if (depthStencil && this._depthCullingState.depthMask)
  2768. mode |= this._gl.DEPTH_BUFFER_BIT;
  2769. this._gl.clear(mode);
  2770. };
  2771. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2772. var width = requiredWidth || this._renderingCanvas.width;
  2773. var height = requiredHeight || this._renderingCanvas.height;
  2774. var x = viewport.x || 0;
  2775. var y = viewport.y || 0;
  2776. this._cachedViewport = viewport;
  2777. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2778. };
  2779. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2780. this._cachedViewport = null;
  2781. this._gl.viewport(x, y, width, height);
  2782. };
  2783. Engine.prototype.beginFrame = function () {
  2784. BABYLON.Tools._MeasureFps();
  2785. };
  2786. Engine.prototype.endFrame = function () {
  2787. this.flushFramebuffer();
  2788. };
  2789. Engine.prototype.resize = function () {
  2790. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2791. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2792. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2793. };
  2794. Engine.prototype.bindFramebuffer = function (texture) {
  2795. this._currentRenderTarget = texture;
  2796. var gl = this._gl;
  2797. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2798. this._gl.viewport(0, 0, texture._width, texture._height);
  2799. this.wipeCaches();
  2800. };
  2801. Engine.prototype.unBindFramebuffer = function (texture) {
  2802. this._currentRenderTarget = null;
  2803. if (texture.generateMipMaps) {
  2804. var gl = this._gl;
  2805. gl.bindTexture(gl.TEXTURE_2D, texture);
  2806. gl.generateMipmap(gl.TEXTURE_2D);
  2807. gl.bindTexture(gl.TEXTURE_2D, null);
  2808. }
  2809. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2810. };
  2811. Engine.prototype.flushFramebuffer = function () {
  2812. this._gl.flush();
  2813. };
  2814. Engine.prototype.restoreDefaultFramebuffer = function () {
  2815. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2816. this.setViewport(this._cachedViewport);
  2817. this.wipeCaches();
  2818. };
  2819. Engine.prototype._resetVertexBufferBinding = function () {
  2820. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2821. this._cachedVertexBuffers = null;
  2822. };
  2823. Engine.prototype.createVertexBuffer = function (vertices) {
  2824. var vbo = this._gl.createBuffer();
  2825. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2826. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2827. this._resetVertexBufferBinding();
  2828. vbo.references = 1;
  2829. return vbo;
  2830. };
  2831. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2832. var vbo = this._gl.createBuffer();
  2833. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2834. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2835. this._resetVertexBufferBinding();
  2836. vbo.references = 1;
  2837. return vbo;
  2838. };
  2839. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2840. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2841. if (vertices instanceof Float32Array) {
  2842. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2843. } else {
  2844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2845. }
  2846. this._resetVertexBufferBinding();
  2847. };
  2848. Engine.prototype._resetIndexBufferBinding = function () {
  2849. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2850. this._cachedIndexBuffer = null;
  2851. };
  2852. Engine.prototype.createIndexBuffer = function (indices) {
  2853. var vbo = this._gl.createBuffer();
  2854. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2855. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2856. this._resetIndexBufferBinding();
  2857. vbo.references = 1;
  2858. return vbo;
  2859. };
  2860. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2861. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2862. this._cachedVertexBuffers = vertexBuffer;
  2863. this._cachedEffectForVertexBuffers = effect;
  2864. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2865. var offset = 0;
  2866. for (var index = 0; index < vertexDeclaration.length; index++) {
  2867. var order = effect.getAttributeLocation(index);
  2868. if (order >= 0) {
  2869. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2870. }
  2871. offset += vertexDeclaration[index] * 4;
  2872. }
  2873. }
  2874. if (this._cachedIndexBuffer !== indexBuffer) {
  2875. this._cachedIndexBuffer = indexBuffer;
  2876. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2877. }
  2878. };
  2879. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2880. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2881. this._cachedVertexBuffers = vertexBuffers;
  2882. this._cachedEffectForVertexBuffers = effect;
  2883. var attributes = effect.getAttributesNames();
  2884. for (var index = 0; index < attributes.length; index++) {
  2885. var order = effect.getAttributeLocation(index);
  2886. if (order >= 0) {
  2887. var vertexBuffer = vertexBuffers[attributes[index]];
  2888. if (!vertexBuffer) {
  2889. continue;
  2890. }
  2891. var stride = vertexBuffer.getStrideSize();
  2892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2893. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2894. }
  2895. }
  2896. }
  2897. if (this._cachedIndexBuffer !== indexBuffer) {
  2898. this._cachedIndexBuffer = indexBuffer;
  2899. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2900. }
  2901. };
  2902. Engine.prototype._releaseBuffer = function (buffer) {
  2903. buffer.references--;
  2904. if (buffer.references === 0) {
  2905. this._gl.deleteBuffer(buffer);
  2906. return true;
  2907. }
  2908. return false;
  2909. };
  2910. Engine.prototype.createInstancesBuffer = function (capacity) {
  2911. var buffer = this._gl.createBuffer();
  2912. buffer.capacity = capacity;
  2913. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2914. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2915. return buffer;
  2916. };
  2917. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2918. this._gl.deleteBuffer(buffer);
  2919. };
  2920. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2921. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2922. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2923. for (var index = 0; index < 4; index++) {
  2924. var offsetLocation = offsetLocations[index];
  2925. this._gl.enableVertexAttribArray(offsetLocation);
  2926. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2927. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2928. }
  2929. };
  2930. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2931. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2932. for (var index = 0; index < 4; index++) {
  2933. var offsetLocation = offsetLocations[index];
  2934. this._gl.disableVertexAttribArray(offsetLocation);
  2935. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2936. }
  2937. };
  2938. Engine.prototype.applyStates = function () {
  2939. this._depthCullingState.apply(this._gl);
  2940. this._alphaState.apply(this._gl);
  2941. };
  2942. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2943. this.applyStates();
  2944. if (instancesCount) {
  2945. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2946. return;
  2947. }
  2948. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2949. };
  2950. Engine.prototype._releaseEffect = function (effect) {
  2951. if (this._compiledEffects[effect._key]) {
  2952. delete this._compiledEffects[effect._key];
  2953. if (effect.getProgram()) {
  2954. this._gl.deleteProgram(effect.getProgram());
  2955. }
  2956. }
  2957. };
  2958. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2959. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2960. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2961. var name = vertex + "+" + fragment + "@" + defines;
  2962. if (this._compiledEffects[name]) {
  2963. return this._compiledEffects[name];
  2964. }
  2965. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2966. effect._key = name;
  2967. this._compiledEffects[name] = effect;
  2968. return effect;
  2969. };
  2970. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2971. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2972. if (typeof samplers === "undefined") { samplers = []; }
  2973. if (typeof defines === "undefined") { defines = ""; }
  2974. return this.createEffect({
  2975. vertex: "particles",
  2976. fragmentElement: fragmentName
  2977. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2978. };
  2979. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2980. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2981. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2982. var shaderProgram = this._gl.createProgram();
  2983. this._gl.attachShader(shaderProgram, vertexShader);
  2984. this._gl.attachShader(shaderProgram, fragmentShader);
  2985. this._gl.linkProgram(shaderProgram);
  2986. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2987. if (!linked) {
  2988. var error = this._gl.getProgramInfoLog(shaderProgram);
  2989. if (error) {
  2990. throw new Error(error);
  2991. }
  2992. }
  2993. this._gl.deleteShader(vertexShader);
  2994. this._gl.deleteShader(fragmentShader);
  2995. return shaderProgram;
  2996. };
  2997. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  2998. var results = [];
  2999. for (var index = 0; index < uniformsNames.length; index++) {
  3000. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3001. }
  3002. return results;
  3003. };
  3004. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3005. var results = [];
  3006. for (var index = 0; index < attributesNames.length; index++) {
  3007. try {
  3008. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3009. } catch (e) {
  3010. results.push(-1);
  3011. }
  3012. }
  3013. return results;
  3014. };
  3015. Engine.prototype.enableEffect = function (effect) {
  3016. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3017. return;
  3018. }
  3019. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3020. this._gl.useProgram(effect.getProgram());
  3021. for (var i in this._vertexAttribArrays) {
  3022. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3023. continue;
  3024. }
  3025. this._vertexAttribArrays[i] = false;
  3026. this._gl.disableVertexAttribArray(i);
  3027. }
  3028. var attributesCount = effect.getAttributesCount();
  3029. for (var index = 0; index < attributesCount; index++) {
  3030. var order = effect.getAttributeLocation(index);
  3031. if (order >= 0) {
  3032. this._vertexAttribArrays[order] = true;
  3033. this._gl.enableVertexAttribArray(order);
  3034. }
  3035. }
  3036. this._currentEffect = effect;
  3037. };
  3038. Engine.prototype.setArray = function (uniform, array) {
  3039. if (!uniform)
  3040. return;
  3041. this._gl.uniform1fv(uniform, array);
  3042. };
  3043. Engine.prototype.setMatrices = function (uniform, matrices) {
  3044. if (!uniform)
  3045. return;
  3046. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3047. };
  3048. Engine.prototype.setMatrix = function (uniform, matrix) {
  3049. if (!uniform)
  3050. return;
  3051. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3052. };
  3053. Engine.prototype.setFloat = function (uniform, value) {
  3054. if (!uniform)
  3055. return;
  3056. this._gl.uniform1f(uniform, value);
  3057. };
  3058. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3059. if (!uniform)
  3060. return;
  3061. this._gl.uniform2f(uniform, x, y);
  3062. };
  3063. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3064. if (!uniform)
  3065. return;
  3066. this._gl.uniform3f(uniform, x, y, z);
  3067. };
  3068. Engine.prototype.setBool = function (uniform, bool) {
  3069. if (!uniform)
  3070. return;
  3071. this._gl.uniform1i(uniform, bool);
  3072. };
  3073. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3074. if (!uniform)
  3075. return;
  3076. this._gl.uniform4f(uniform, x, y, z, w);
  3077. };
  3078. Engine.prototype.setColor3 = function (uniform, color3) {
  3079. if (!uniform)
  3080. return;
  3081. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3082. };
  3083. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3084. if (!uniform)
  3085. return;
  3086. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3087. };
  3088. Engine.prototype.setState = function (culling, force) {
  3089. if (this._depthCullingState.cull !== culling || force) {
  3090. if (culling) {
  3091. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3092. this._depthCullingState.cull = true;
  3093. } else {
  3094. this._depthCullingState.cull = false;
  3095. }
  3096. }
  3097. };
  3098. Engine.prototype.setDepthBuffer = function (enable) {
  3099. this._depthCullingState.depthTest = enable;
  3100. };
  3101. Engine.prototype.getDepthWrite = function () {
  3102. return this._depthCullingState.depthMask;
  3103. };
  3104. Engine.prototype.setDepthWrite = function (enable) {
  3105. this._depthCullingState.depthMask = enable;
  3106. };
  3107. Engine.prototype.setColorWrite = function (enable) {
  3108. this._gl.colorMask(enable, enable, enable, enable);
  3109. };
  3110. Engine.prototype.setAlphaMode = function (mode) {
  3111. switch (mode) {
  3112. case BABYLON.Engine.ALPHA_DISABLE:
  3113. this.setDepthWrite(true);
  3114. this._alphaState.alphaBlend = false;
  3115. break;
  3116. case BABYLON.Engine.ALPHA_COMBINE:
  3117. this.setDepthWrite(false);
  3118. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3119. this._alphaState.alphaBlend = true;
  3120. break;
  3121. case BABYLON.Engine.ALPHA_ADD:
  3122. this.setDepthWrite(false);
  3123. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3124. this._alphaState.alphaBlend = true;
  3125. break;
  3126. }
  3127. };
  3128. Engine.prototype.setAlphaTesting = function (enable) {
  3129. this._alphaTest = enable;
  3130. };
  3131. Engine.prototype.getAlphaTesting = function () {
  3132. return this._alphaTest;
  3133. };
  3134. Engine.prototype.wipeCaches = function () {
  3135. this._activeTexturesCache = [];
  3136. this._currentEffect = null;
  3137. this._depthCullingState.reset();
  3138. this._alphaState.reset();
  3139. this._cachedVertexBuffers = null;
  3140. this._cachedIndexBuffer = null;
  3141. this._cachedEffectForVertexBuffers = null;
  3142. };
  3143. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3144. var gl = this._gl;
  3145. gl.bindTexture(gl.TEXTURE_2D, texture);
  3146. var magFilter = gl.NEAREST;
  3147. var minFilter = gl.NEAREST;
  3148. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3149. magFilter = gl.LINEAR;
  3150. minFilter = gl.LINEAR;
  3151. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3152. magFilter = gl.LINEAR;
  3153. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3154. }
  3155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3157. gl.bindTexture(gl.TEXTURE_2D, null);
  3158. };
  3159. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3160. var _this = this;
  3161. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3162. if (typeof onLoad === "undefined") { onLoad = null; }
  3163. if (typeof onError === "undefined") { onError = null; }
  3164. if (typeof buffer === "undefined") { buffer = null; }
  3165. var texture = this._gl.createTexture();
  3166. var extension;
  3167. var fromData = false;
  3168. if (url.substr(0, 5) === "data:") {
  3169. fromData = true;
  3170. }
  3171. if (!fromData)
  3172. extension = url.substr(url.length - 4, 4).toLowerCase();
  3173. else {
  3174. var oldUrl = url;
  3175. fromData = oldUrl.split(':');
  3176. url = oldUrl;
  3177. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3178. }
  3179. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3180. var isTGA = (extension === ".tga");
  3181. scene._addPendingData(texture);
  3182. texture.url = url;
  3183. texture.noMipmap = noMipmap;
  3184. texture.references = 1;
  3185. this._loadedTexturesCache.push(texture);
  3186. var onerror = function () {
  3187. scene._removePendingData(texture);
  3188. if (onError) {
  3189. onError();
  3190. }
  3191. };
  3192. if (isTGA) {
  3193. var callback = function (arrayBuffer) {
  3194. var data = new Uint8Array(arrayBuffer);
  3195. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3196. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3197. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3198. if (onLoad) {
  3199. onLoad();
  3200. }
  3201. }, samplingMode);
  3202. };
  3203. if (!(fromData instanceof Array))
  3204. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3205. callback(arrayBuffer);
  3206. }, onerror, scene.database, true);
  3207. else
  3208. callback(buffer);
  3209. } else if (isDDS) {
  3210. var callback = function (data) {
  3211. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3212. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3213. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3214. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3215. if (onLoad) {
  3216. onLoad();
  3217. }
  3218. }, samplingMode);
  3219. };
  3220. if (!(fromData instanceof Array))
  3221. BABYLON.Tools.LoadFile(url, function (data) {
  3222. callback(data);
  3223. }, onerror, scene.database, true);
  3224. else
  3225. callback(buffer);
  3226. } else {
  3227. var onload = function (img) {
  3228. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3229. var isPot = (img.width == potWidth && img.height == potHeight);
  3230. if (!isPot) {
  3231. _this._workingCanvas.width = potWidth;
  3232. _this._workingCanvas.height = potHeight;
  3233. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3234. }
  3235. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3236. if (onLoad) {
  3237. onLoad();
  3238. }
  3239. }, samplingMode);
  3240. };
  3241. if (!(fromData instanceof Array))
  3242. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3243. else
  3244. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3245. }
  3246. return texture;
  3247. };
  3248. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3249. var texture = this._gl.createTexture();
  3250. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3251. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3252. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3253. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3254. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3255. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3256. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3257. this._activeTexturesCache = [];
  3258. texture._baseWidth = width;
  3259. texture._baseHeight = height;
  3260. texture._width = width;
  3261. texture._height = height;
  3262. texture.isReady = false;
  3263. texture.generateMipMaps = generateMipMaps;
  3264. texture.references = 1;
  3265. this._loadedTexturesCache.push(texture);
  3266. return texture;
  3267. };
  3268. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3269. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3270. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3271. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3272. if (texture.generateMipMaps) {
  3273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3274. }
  3275. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3276. this._activeTexturesCache = [];
  3277. texture.isReady = true;
  3278. };
  3279. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3280. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3281. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3282. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3283. if (!texture._workingCanvas) {
  3284. texture._workingCanvas = document.createElement("canvas");
  3285. texture._workingContext = texture._workingCanvas.getContext("2d");
  3286. texture._workingCanvas.width = texture._width;
  3287. texture._workingCanvas.height = texture._height;
  3288. }
  3289. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3290. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3291. } else {
  3292. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3293. }
  3294. if (texture.generateMipMaps) {
  3295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3296. }
  3297. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3298. this._activeTexturesCache = [];
  3299. texture.isReady = true;
  3300. };
  3301. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3302. var generateMipMaps = false;
  3303. var generateDepthBuffer = true;
  3304. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3305. if (options !== undefined) {
  3306. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3307. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3308. if (options.samplingMode !== undefined) {
  3309. samplingMode = options.samplingMode;
  3310. }
  3311. }
  3312. var gl = this._gl;
  3313. var texture = gl.createTexture();
  3314. gl.bindTexture(gl.TEXTURE_2D, texture);
  3315. var width = size.width || size;
  3316. var height = size.height || size;
  3317. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3322. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3323. var depthBuffer;
  3324. if (generateDepthBuffer) {
  3325. depthBuffer = gl.createRenderbuffer();
  3326. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3327. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3328. }
  3329. var framebuffer = gl.createFramebuffer();
  3330. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3331. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3332. if (generateDepthBuffer) {
  3333. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3334. }
  3335. gl.bindTexture(gl.TEXTURE_2D, null);
  3336. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3337. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3338. texture._framebuffer = framebuffer;
  3339. if (generateDepthBuffer) {
  3340. texture._depthBuffer = depthBuffer;
  3341. }
  3342. texture._width = width;
  3343. texture._height = height;
  3344. texture.isReady = true;
  3345. texture.generateMipMaps = generateMipMaps;
  3346. texture.references = 1;
  3347. this._activeTexturesCache = [];
  3348. this._loadedTexturesCache.push(texture);
  3349. return texture;
  3350. };
  3351. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3352. var _this = this;
  3353. var gl = this._gl;
  3354. var texture = gl.createTexture();
  3355. texture.isCube = true;
  3356. texture.url = rootUrl;
  3357. texture.references = 1;
  3358. this._loadedTexturesCache.push(texture);
  3359. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3360. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3361. if (isDDS) {
  3362. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3363. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3364. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3365. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3366. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3367. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3368. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3369. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3370. }
  3371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3375. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3376. _this._activeTexturesCache = [];
  3377. texture._width = info.width;
  3378. texture._height = info.height;
  3379. texture.isReady = true;
  3380. }, null, null, true);
  3381. } else {
  3382. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  3383. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3384. var height = width;
  3385. _this._workingCanvas.width = width;
  3386. _this._workingCanvas.height = height;
  3387. var faces = [
  3388. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3389. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3390. ];
  3391. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3392. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3393. for (var index = 0; index < faces.length; index++) {
  3394. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3395. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3396. }
  3397. if (!noMipmap) {
  3398. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3399. }
  3400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3403. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3404. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3405. _this._activeTexturesCache = [];
  3406. texture._width = width;
  3407. texture._height = height;
  3408. texture.isReady = true;
  3409. }, extensions);
  3410. }
  3411. return texture;
  3412. };
  3413. Engine.prototype._releaseTexture = function (texture) {
  3414. var gl = this._gl;
  3415. if (texture._framebuffer) {
  3416. gl.deleteFramebuffer(texture._framebuffer);
  3417. }
  3418. if (texture._depthBuffer) {
  3419. gl.deleteRenderbuffer(texture._depthBuffer);
  3420. }
  3421. gl.deleteTexture(texture);
  3422. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3423. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3424. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3425. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3426. this._activeTexturesCache[channel] = null;
  3427. }
  3428. var index = this._loadedTexturesCache.indexOf(texture);
  3429. if (index !== -1) {
  3430. this._loadedTexturesCache.splice(index, 1);
  3431. }
  3432. };
  3433. Engine.prototype.bindSamplers = function (effect) {
  3434. this._gl.useProgram(effect.getProgram());
  3435. var samplers = effect.getSamplers();
  3436. for (var index = 0; index < samplers.length; index++) {
  3437. var uniform = effect.getUniform(samplers[index]);
  3438. this._gl.uniform1i(uniform, index);
  3439. }
  3440. this._currentEffect = null;
  3441. };
  3442. Engine.prototype._bindTexture = function (channel, texture) {
  3443. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3444. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3445. this._activeTexturesCache[channel] = null;
  3446. };
  3447. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3448. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3449. };
  3450. Engine.prototype.setTexture = function (channel, texture) {
  3451. if (channel < 0) {
  3452. return;
  3453. }
  3454. if (!texture || !texture.isReady()) {
  3455. if (this._activeTexturesCache[channel] != null) {
  3456. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3457. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3458. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3459. this._activeTexturesCache[channel] = null;
  3460. }
  3461. return;
  3462. }
  3463. if (texture instanceof BABYLON.VideoTexture) {
  3464. if (texture.update()) {
  3465. this._activeTexturesCache[channel] = null;
  3466. }
  3467. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3468. texture.delayLoad();
  3469. return;
  3470. }
  3471. if (this._activeTexturesCache[channel] == texture) {
  3472. return;
  3473. }
  3474. this._activeTexturesCache[channel] = texture;
  3475. var internalTexture = texture.getInternalTexture();
  3476. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3477. if (internalTexture.isCube) {
  3478. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3479. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3480. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3481. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3482. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3483. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3484. }
  3485. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3486. } else {
  3487. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3488. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3489. internalTexture._cachedWrapU = texture.wrapU;
  3490. switch (texture.wrapU) {
  3491. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3492. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3493. break;
  3494. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3495. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3496. break;
  3497. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3498. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3499. break;
  3500. }
  3501. }
  3502. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3503. internalTexture._cachedWrapV = texture.wrapV;
  3504. switch (texture.wrapV) {
  3505. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3506. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3507. break;
  3508. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3509. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3510. break;
  3511. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3512. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3513. break;
  3514. }
  3515. }
  3516. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3517. }
  3518. };
  3519. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3520. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3521. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3522. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3523. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3524. }
  3525. };
  3526. Engine.prototype.readPixels = function (x, y, width, height) {
  3527. var data = new Uint8Array(height * width * 4);
  3528. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3529. return data;
  3530. };
  3531. Engine.prototype.dispose = function () {
  3532. this.hideLoadingUI();
  3533. this.stopRenderLoop();
  3534. while (this.scenes.length) {
  3535. this.scenes[0].dispose();
  3536. }
  3537. for (var name in this._compiledEffects) {
  3538. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3539. }
  3540. for (var i in this._vertexAttribArrays) {
  3541. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3542. continue;
  3543. }
  3544. this._gl.disableVertexAttribArray(i);
  3545. }
  3546. window.removeEventListener("blur", this._onBlur);
  3547. window.removeEventListener("focus", this._onFocus);
  3548. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3549. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3550. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3551. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3552. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3553. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3554. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3555. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3556. };
  3557. Engine.prototype.displayLoadingUI = function () {
  3558. var _this = this;
  3559. this._loadingDiv = document.createElement("div");
  3560. this._loadingDiv.style.opacity = "0";
  3561. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3562. this._loadingTextDiv = document.createElement("div");
  3563. this._loadingTextDiv.style.position = "absolute";
  3564. this._loadingTextDiv.style.left = "0";
  3565. this._loadingTextDiv.style.top = "50%";
  3566. this._loadingTextDiv.style.marginTop = "80px";
  3567. this._loadingTextDiv.style.width = "100%";
  3568. this._loadingTextDiv.style.height = "20px";
  3569. this._loadingTextDiv.style.fontFamily = "Arial";
  3570. this._loadingTextDiv.style.fontSize = "14px";
  3571. this._loadingTextDiv.style.color = "white";
  3572. this._loadingTextDiv.style.textAlign = "center";
  3573. this._loadingTextDiv.innerHTML = "Loading";
  3574. this._loadingDiv.appendChild(this._loadingTextDiv);
  3575. var imgBack = new Image();
  3576. 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==";
  3577. imgBack.style.position = "absolute";
  3578. imgBack.style.left = "50%";
  3579. imgBack.style.top = "50%";
  3580. imgBack.style.marginLeft = "-50px";
  3581. imgBack.style.marginTop = "-50px";
  3582. imgBack.style.transition = "transform 1.0s ease";
  3583. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3584. var deg = 360;
  3585. var onTransitionEnd = function () {
  3586. deg += 360;
  3587. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3588. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3589. };
  3590. imgBack.addEventListener("transitionend", onTransitionEnd);
  3591. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3592. this._loadingDiv.appendChild(imgBack);
  3593. var imgFront = new Image();
  3594. 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=";
  3595. imgFront.style.position = "absolute";
  3596. imgFront.style.left = "50%";
  3597. imgFront.style.top = "50%";
  3598. imgFront.style.marginLeft = "-50px";
  3599. imgFront.style.marginTop = "-50px";
  3600. this._loadingDiv.appendChild(imgFront);
  3601. this._resizeLoadingUI = function () {
  3602. var canvasRect = _this.getRenderingCanvasClientRect();
  3603. _this._loadingDiv.style.position = "absolute";
  3604. _this._loadingDiv.style.left = canvasRect.left + "px";
  3605. _this._loadingDiv.style.top = canvasRect.top + "px";
  3606. _this._loadingDiv.style.width = canvasRect.width + "px";
  3607. _this._loadingDiv.style.height = canvasRect.height + "px";
  3608. };
  3609. this._resizeLoadingUI();
  3610. window.addEventListener("resize", this._resizeLoadingUI);
  3611. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3612. document.body.appendChild(this._loadingDiv);
  3613. setTimeout(function () {
  3614. _this._loadingDiv.style.opacity = "1";
  3615. imgBack.style.transform = "rotateZ(360deg)";
  3616. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3617. }, 0);
  3618. };
  3619. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3620. set: function (text) {
  3621. if (!this._loadingDiv) {
  3622. return;
  3623. }
  3624. this._loadingTextDiv.innerHTML = text;
  3625. },
  3626. enumerable: true,
  3627. configurable: true
  3628. });
  3629. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3630. get: function () {
  3631. return this._loadingDivBackgroundColor;
  3632. },
  3633. set: function (color) {
  3634. this._loadingDivBackgroundColor = color;
  3635. if (!this._loadingDiv) {
  3636. return;
  3637. }
  3638. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3639. },
  3640. enumerable: true,
  3641. configurable: true
  3642. });
  3643. Engine.prototype.hideLoadingUI = function () {
  3644. var _this = this;
  3645. if (!this._loadingDiv) {
  3646. return;
  3647. }
  3648. var onTransitionEnd = function () {
  3649. if (!_this._loadingDiv) {
  3650. return;
  3651. }
  3652. document.body.removeChild(_this._loadingDiv);
  3653. window.removeEventListener("resize", _this._resizeLoadingUI);
  3654. _this._loadingDiv = null;
  3655. };
  3656. this._loadingDiv.style.opacity = "0";
  3657. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3658. };
  3659. Engine.isSupported = function () {
  3660. try {
  3661. var tempcanvas = document.createElement("canvas");
  3662. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3663. return gl != null && !!window.WebGLRenderingContext;
  3664. } catch (e) {
  3665. return false;
  3666. }
  3667. };
  3668. Engine._ALPHA_DISABLE = 0;
  3669. Engine._ALPHA_ADD = 1;
  3670. Engine._ALPHA_COMBINE = 2;
  3671. Engine._DELAYLOADSTATE_NONE = 0;
  3672. Engine._DELAYLOADSTATE_LOADED = 1;
  3673. Engine._DELAYLOADSTATE_LOADING = 2;
  3674. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3675. Engine.Epsilon = 0.001;
  3676. Engine.CollisionsEpsilon = 0.001;
  3677. Engine.ShadersRepository = "Babylon/Shaders/";
  3678. return Engine;
  3679. })();
  3680. BABYLON.Engine = Engine;
  3681. })(BABYLON || (BABYLON = {}));
  3682. var BABYLON;
  3683. (function (BABYLON) {
  3684. var Node = (function () {
  3685. function Node(name, scene) {
  3686. this.state = "";
  3687. this.animations = new Array();
  3688. this._childrenFlag = -1;
  3689. this._isEnabled = true;
  3690. this._isReady = true;
  3691. this._currentRenderId = -1;
  3692. this.name = name;
  3693. this.id = name;
  3694. this._scene = scene;
  3695. this._initCache();
  3696. }
  3697. Node.prototype.getScene = function () {
  3698. return this._scene;
  3699. };
  3700. Node.prototype.getEngine = function () {
  3701. return this._scene.getEngine();
  3702. };
  3703. Node.prototype.getWorldMatrix = function () {
  3704. return BABYLON.Matrix.Identity();
  3705. };
  3706. Node.prototype._initCache = function () {
  3707. this._cache = {};
  3708. this._cache.parent = undefined;
  3709. };
  3710. Node.prototype.updateCache = function (force) {
  3711. if (!force && this.isSynchronized())
  3712. return;
  3713. this._cache.parent = this.parent;
  3714. this._updateCache();
  3715. };
  3716. Node.prototype._updateCache = function (ignoreParentClass) {
  3717. };
  3718. Node.prototype._isSynchronized = function () {
  3719. return true;
  3720. };
  3721. Node.prototype.isSynchronizedWithParent = function () {
  3722. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3723. };
  3724. Node.prototype.isSynchronized = function (updateCache) {
  3725. var check = this.hasNewParent();
  3726. check = check || !this.isSynchronizedWithParent();
  3727. check = check || !this._isSynchronized();
  3728. if (updateCache)
  3729. this.updateCache(true);
  3730. return !check;
  3731. };
  3732. Node.prototype.hasNewParent = function (update) {
  3733. if (this._cache.parent === this.parent)
  3734. return false;
  3735. if (update)
  3736. this._cache.parent = this.parent;
  3737. return true;
  3738. };
  3739. Node.prototype.isReady = function () {
  3740. return this._isReady;
  3741. };
  3742. Node.prototype.isEnabled = function () {
  3743. if (!this._isEnabled) {
  3744. return false;
  3745. }
  3746. if (this.parent) {
  3747. return this.parent.isEnabled();
  3748. }
  3749. return true;
  3750. };
  3751. Node.prototype.setEnabled = function (value) {
  3752. this._isEnabled = value;
  3753. };
  3754. Node.prototype.isDescendantOf = function (ancestor) {
  3755. if (this.parent) {
  3756. if (this.parent === ancestor) {
  3757. return true;
  3758. }
  3759. return this.parent.isDescendantOf(ancestor);
  3760. }
  3761. return false;
  3762. };
  3763. Node.prototype._getDescendants = function (list, results) {
  3764. for (var index = 0; index < list.length; index++) {
  3765. var item = list[index];
  3766. if (item.isDescendantOf(this)) {
  3767. results.push(item);
  3768. }
  3769. }
  3770. };
  3771. Node.prototype.getDescendants = function () {
  3772. var results = [];
  3773. this._getDescendants(this._scene.meshes, results);
  3774. this._getDescendants(this._scene.lights, results);
  3775. this._getDescendants(this._scene.cameras, results);
  3776. return results;
  3777. };
  3778. Node.prototype._setReady = function (state) {
  3779. if (state == this._isReady) {
  3780. return;
  3781. }
  3782. if (!state) {
  3783. this._isReady = false;
  3784. return;
  3785. }
  3786. this._isReady = true;
  3787. if (this.onReady) {
  3788. this.onReady(this);
  3789. }
  3790. };
  3791. return Node;
  3792. })();
  3793. BABYLON.Node = Node;
  3794. })(BABYLON || (BABYLON = {}));
  3795. var BABYLON;
  3796. (function (BABYLON) {
  3797. var BoundingSphere = (function () {
  3798. function BoundingSphere(minimum, maximum) {
  3799. this.minimum = minimum;
  3800. this.maximum = maximum;
  3801. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3802. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3803. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3804. this.radius = distance * 0.5;
  3805. this.centerWorld = BABYLON.Vector3.Zero();
  3806. this._update(BABYLON.Matrix.Identity());
  3807. }
  3808. BoundingSphere.prototype._update = function (world) {
  3809. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3810. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3811. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3812. };
  3813. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3814. for (var i = 0; i < 6; i++) {
  3815. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3816. return false;
  3817. }
  3818. return true;
  3819. };
  3820. BoundingSphere.prototype.intersectsPoint = function (point) {
  3821. var x = this.centerWorld.x - point.x;
  3822. var y = this.centerWorld.y - point.y;
  3823. var z = this.centerWorld.z - point.z;
  3824. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3825. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3826. return false;
  3827. return true;
  3828. };
  3829. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3830. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3831. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3832. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3833. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3834. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3835. return false;
  3836. return true;
  3837. };
  3838. return BoundingSphere;
  3839. })();
  3840. BABYLON.BoundingSphere = BoundingSphere;
  3841. })(BABYLON || (BABYLON = {}));
  3842. var BABYLON;
  3843. (function (BABYLON) {
  3844. var BoundingBox = (function () {
  3845. function BoundingBox(minimum, maximum) {
  3846. this.minimum = minimum;
  3847. this.maximum = maximum;
  3848. this.vectors = new Array();
  3849. this.vectorsWorld = new Array();
  3850. this.vectors.push(this.minimum.clone());
  3851. this.vectors.push(this.maximum.clone());
  3852. this.vectors.push(this.minimum.clone());
  3853. this.vectors[2].x = this.maximum.x;
  3854. this.vectors.push(this.minimum.clone());
  3855. this.vectors[3].y = this.maximum.y;
  3856. this.vectors.push(this.minimum.clone());
  3857. this.vectors[4].z = this.maximum.z;
  3858. this.vectors.push(this.maximum.clone());
  3859. this.vectors[5].z = this.minimum.z;
  3860. this.vectors.push(this.maximum.clone());
  3861. this.vectors[6].x = this.minimum.x;
  3862. this.vectors.push(this.maximum.clone());
  3863. this.vectors[7].y = this.minimum.y;
  3864. this.center = this.maximum.add(this.minimum).scale(0.5);
  3865. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3866. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3867. for (var index = 0; index < this.vectors.length; index++) {
  3868. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3869. }
  3870. this.minimumWorld = BABYLON.Vector3.Zero();
  3871. this.maximumWorld = BABYLON.Vector3.Zero();
  3872. this._update(BABYLON.Matrix.Identity());
  3873. }
  3874. BoundingBox.prototype.getWorldMatrix = function () {
  3875. return this._worldMatrix;
  3876. };
  3877. BoundingBox.prototype._update = function (world) {
  3878. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3879. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3880. for (var index = 0; index < this.vectors.length; index++) {
  3881. var v = this.vectorsWorld[index];
  3882. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3883. if (v.x < this.minimumWorld.x)
  3884. this.minimumWorld.x = v.x;
  3885. if (v.y < this.minimumWorld.y)
  3886. this.minimumWorld.y = v.y;
  3887. if (v.z < this.minimumWorld.z)
  3888. this.minimumWorld.z = v.z;
  3889. if (v.x > this.maximumWorld.x)
  3890. this.maximumWorld.x = v.x;
  3891. if (v.y > this.maximumWorld.y)
  3892. this.maximumWorld.y = v.y;
  3893. if (v.z > this.maximumWorld.z)
  3894. this.maximumWorld.z = v.z;
  3895. }
  3896. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3897. this.center.scaleInPlace(0.5);
  3898. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3899. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3900. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3901. this._worldMatrix = world;
  3902. };
  3903. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3904. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3905. };
  3906. BoundingBox.prototype.intersectsPoint = function (point) {
  3907. var delta = BABYLON.Engine.Epsilon;
  3908. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3909. return false;
  3910. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3911. return false;
  3912. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3913. return false;
  3914. return true;
  3915. };
  3916. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3917. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3918. };
  3919. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3920. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3921. return false;
  3922. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3923. return false;
  3924. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3925. return false;
  3926. return true;
  3927. };
  3928. BoundingBox.Intersects = function (box0, box1) {
  3929. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3930. return false;
  3931. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3932. return false;
  3933. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3934. return false;
  3935. return true;
  3936. };
  3937. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3938. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3939. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3940. return (num <= (sphereRadius * sphereRadius));
  3941. };
  3942. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3943. for (var p = 0; p < 6; p++) {
  3944. var inCount = 8;
  3945. for (var i = 0; i < 8; i++) {
  3946. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3947. --inCount;
  3948. } else {
  3949. break;
  3950. }
  3951. }
  3952. if (inCount == 0)
  3953. return false;
  3954. }
  3955. return true;
  3956. };
  3957. return BoundingBox;
  3958. })();
  3959. BABYLON.BoundingBox = BoundingBox;
  3960. })(BABYLON || (BABYLON = {}));
  3961. var BABYLON;
  3962. (function (BABYLON) {
  3963. var computeBoxExtents = function (axis, box) {
  3964. var p = BABYLON.Vector3.Dot(box.center, axis);
  3965. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3966. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3967. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3968. var r = r0 + r1 + r2;
  3969. return {
  3970. min: p - r,
  3971. max: p + r
  3972. };
  3973. };
  3974. var extentsOverlap = function (min0, max0, min1, max1) {
  3975. return !(min0 > max1 || min1 > max0);
  3976. };
  3977. var axisOverlap = function (axis, box0, box1) {
  3978. var result0 = computeBoxExtents(axis, box0);
  3979. var result1 = computeBoxExtents(axis, box1);
  3980. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3981. };
  3982. var BoundingInfo = (function () {
  3983. function BoundingInfo(minimum, maximum) {
  3984. this.minimum = minimum;
  3985. this.maximum = maximum;
  3986. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3987. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3988. }
  3989. BoundingInfo.prototype._update = function (world) {
  3990. this.boundingBox._update(world);
  3991. this.boundingSphere._update(world);
  3992. };
  3993. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  3994. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  3995. return false;
  3996. return this.boundingBox.isInFrustum(frustumPlanes);
  3997. };
  3998. BoundingInfo.prototype._checkCollision = function (collider) {
  3999. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4000. };
  4001. BoundingInfo.prototype.intersectsPoint = function (point) {
  4002. if (!this.boundingSphere.centerWorld) {
  4003. return false;
  4004. }
  4005. if (!this.boundingSphere.intersectsPoint(point)) {
  4006. return false;
  4007. }
  4008. if (!this.boundingBox.intersectsPoint(point)) {
  4009. return false;
  4010. }
  4011. return true;
  4012. };
  4013. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4014. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4015. return false;
  4016. }
  4017. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4018. return false;
  4019. }
  4020. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4021. return false;
  4022. }
  4023. if (!precise) {
  4024. return true;
  4025. }
  4026. var box0 = this.boundingBox;
  4027. var box1 = boundingInfo.boundingBox;
  4028. if (!axisOverlap(box0.directions[0], box0, box1))
  4029. return false;
  4030. if (!axisOverlap(box0.directions[1], box0, box1))
  4031. return false;
  4032. if (!axisOverlap(box0.directions[2], box0, box1))
  4033. return false;
  4034. if (!axisOverlap(box1.directions[0], box0, box1))
  4035. return false;
  4036. if (!axisOverlap(box1.directions[1], box0, box1))
  4037. return false;
  4038. if (!axisOverlap(box1.directions[2], box0, box1))
  4039. return false;
  4040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4041. return false;
  4042. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4043. return false;
  4044. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4045. return false;
  4046. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4047. return false;
  4048. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4049. return false;
  4050. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4051. return false;
  4052. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4053. return false;
  4054. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4055. return false;
  4056. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4057. return false;
  4058. return true;
  4059. };
  4060. return BoundingInfo;
  4061. })();
  4062. BABYLON.BoundingInfo = BoundingInfo;
  4063. })(BABYLON || (BABYLON = {}));
  4064. var __extends = this.__extends || function (d, b) {
  4065. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4066. function __() { this.constructor = d; }
  4067. __.prototype = b.prototype;
  4068. d.prototype = new __();
  4069. };
  4070. var BABYLON;
  4071. (function (BABYLON) {
  4072. var Light = (function (_super) {
  4073. __extends(Light, _super);
  4074. function Light(name, scene) {
  4075. _super.call(this, name, scene);
  4076. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4077. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4078. this.intensity = 1.0;
  4079. this.range = Number.MAX_VALUE;
  4080. this.includedOnlyMeshes = new Array();
  4081. this.excludedMeshes = new Array();
  4082. this._excludedMeshesIds = new Array();
  4083. this._includedOnlyMeshesIds = new Array();
  4084. scene.lights.push(this);
  4085. }
  4086. Light.prototype.getShadowGenerator = function () {
  4087. return this._shadowGenerator;
  4088. };
  4089. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4090. };
  4091. Light.prototype._getWorldMatrix = function () {
  4092. return BABYLON.Matrix.Identity();
  4093. };
  4094. Light.prototype.canAffectMesh = function (mesh) {
  4095. if (!mesh) {
  4096. return true;
  4097. }
  4098. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4099. return false;
  4100. }
  4101. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4102. return false;
  4103. }
  4104. return true;
  4105. };
  4106. Light.prototype.getWorldMatrix = function () {
  4107. this._currentRenderId = this.getScene().getRenderId();
  4108. var worldMatrix = this._getWorldMatrix();
  4109. if (this.parent && this.parent.getWorldMatrix) {
  4110. if (!this._parentedWorldMatrix) {
  4111. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4112. }
  4113. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4114. return this._parentedWorldMatrix;
  4115. }
  4116. return worldMatrix;
  4117. };
  4118. Light.prototype.dispose = function () {
  4119. if (this._shadowGenerator) {
  4120. this._shadowGenerator.dispose();
  4121. this._shadowGenerator = null;
  4122. }
  4123. var index = this.getScene().lights.indexOf(this);
  4124. this.getScene().lights.splice(index, 1);
  4125. };
  4126. return Light;
  4127. })(BABYLON.Node);
  4128. BABYLON.Light = Light;
  4129. })(BABYLON || (BABYLON = {}));
  4130. var __extends = this.__extends || function (d, b) {
  4131. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4132. function __() { this.constructor = d; }
  4133. __.prototype = b.prototype;
  4134. d.prototype = new __();
  4135. };
  4136. var BABYLON;
  4137. (function (BABYLON) {
  4138. var PointLight = (function (_super) {
  4139. __extends(PointLight, _super);
  4140. function PointLight(name, position, scene) {
  4141. _super.call(this, name, scene);
  4142. this.position = position;
  4143. }
  4144. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4145. if (this.parent && this.parent.getWorldMatrix) {
  4146. if (!this._transformedPosition) {
  4147. this._transformedPosition = BABYLON.Vector3.Zero();
  4148. }
  4149. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4150. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4151. return;
  4152. }
  4153. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4154. };
  4155. PointLight.prototype.getShadowGenerator = function () {
  4156. return null;
  4157. };
  4158. PointLight.prototype._getWorldMatrix = function () {
  4159. if (!this._worldMatrix) {
  4160. this._worldMatrix = BABYLON.Matrix.Identity();
  4161. }
  4162. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4163. return this._worldMatrix;
  4164. };
  4165. return PointLight;
  4166. })(BABYLON.Light);
  4167. BABYLON.PointLight = PointLight;
  4168. })(BABYLON || (BABYLON = {}));
  4169. var __extends = this.__extends || function (d, b) {
  4170. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4171. function __() { this.constructor = d; }
  4172. __.prototype = b.prototype;
  4173. d.prototype = new __();
  4174. };
  4175. var BABYLON;
  4176. (function (BABYLON) {
  4177. var SpotLight = (function (_super) {
  4178. __extends(SpotLight, _super);
  4179. function SpotLight(name, position, direction, angle, exponent, scene) {
  4180. _super.call(this, name, scene);
  4181. this.position = position;
  4182. this.direction = direction;
  4183. this.angle = angle;
  4184. this.exponent = exponent;
  4185. }
  4186. SpotLight.prototype.setDirectionToTarget = function (target) {
  4187. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4188. return this.direction;
  4189. };
  4190. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4191. var normalizeDirection;
  4192. if (this.parent && this.parent.getWorldMatrix) {
  4193. if (!this._transformedDirection) {
  4194. this._transformedDirection = BABYLON.Vector3.Zero();
  4195. }
  4196. if (!this._transformedPosition) {
  4197. this._transformedPosition = BABYLON.Vector3.Zero();
  4198. }
  4199. var parentWorldMatrix = this.parent.getWorldMatrix();
  4200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4201. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4202. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4203. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4204. } else {
  4205. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4206. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4207. }
  4208. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4209. };
  4210. SpotLight.prototype._getWorldMatrix = function () {
  4211. if (!this._worldMatrix) {
  4212. this._worldMatrix = BABYLON.Matrix.Identity();
  4213. }
  4214. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4215. return this._worldMatrix;
  4216. };
  4217. return SpotLight;
  4218. })(BABYLON.Light);
  4219. BABYLON.SpotLight = SpotLight;
  4220. })(BABYLON || (BABYLON = {}));
  4221. var __extends = this.__extends || function (d, b) {
  4222. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4223. function __() { this.constructor = d; }
  4224. __.prototype = b.prototype;
  4225. d.prototype = new __();
  4226. };
  4227. var BABYLON;
  4228. (function (BABYLON) {
  4229. var DirectionalLight = (function (_super) {
  4230. __extends(DirectionalLight, _super);
  4231. function DirectionalLight(name, direction, scene) {
  4232. _super.call(this, name, scene);
  4233. this.direction = direction;
  4234. this.position = direction.scale(-1);
  4235. }
  4236. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4237. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4238. return this.direction;
  4239. };
  4240. DirectionalLight.prototype._computeTransformedPosition = function () {
  4241. if (this.parent && this.parent.getWorldMatrix) {
  4242. if (!this._transformedPosition) {
  4243. this._transformedPosition = BABYLON.Vector3.Zero();
  4244. }
  4245. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4246. return true;
  4247. }
  4248. return false;
  4249. };
  4250. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4251. if (this.parent && this.parent.getWorldMatrix) {
  4252. if (!this._transformedDirection) {
  4253. this._transformedDirection = BABYLON.Vector3.Zero();
  4254. }
  4255. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4256. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4257. return;
  4258. }
  4259. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4260. };
  4261. DirectionalLight.prototype._getWorldMatrix = function () {
  4262. if (!this._worldMatrix) {
  4263. this._worldMatrix = BABYLON.Matrix.Identity();
  4264. }
  4265. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4266. return this._worldMatrix;
  4267. };
  4268. return DirectionalLight;
  4269. })(BABYLON.Light);
  4270. BABYLON.DirectionalLight = DirectionalLight;
  4271. })(BABYLON || (BABYLON = {}));
  4272. var BABYLON;
  4273. (function (BABYLON) {
  4274. var ShadowGenerator = (function () {
  4275. function ShadowGenerator(mapSize, light) {
  4276. var _this = this;
  4277. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4278. this._darkness = 0;
  4279. this._transparencyShadow = false;
  4280. this._viewMatrix = BABYLON.Matrix.Zero();
  4281. this._projectionMatrix = BABYLON.Matrix.Zero();
  4282. this._transformMatrix = BABYLON.Matrix.Zero();
  4283. this._worldViewProjection = BABYLON.Matrix.Zero();
  4284. this._light = light;
  4285. this._scene = light.getScene();
  4286. light._shadowGenerator = this;
  4287. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4288. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4289. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4290. this._shadowMap.renderParticles = false;
  4291. var renderSubMesh = function (subMesh) {
  4292. var mesh = subMesh.getRenderingMesh();
  4293. var scene = _this._scene;
  4294. var engine = scene.getEngine();
  4295. engine.setState(subMesh.getMaterial().backFaceCulling);
  4296. var batch = mesh._getInstancesRenderList(subMesh._id);
  4297. if (batch.mustReturn) {
  4298. return;
  4299. }
  4300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4301. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4302. engine.enableEffect(_this._effect);
  4303. mesh._bind(subMesh, _this._effect, false);
  4304. var material = subMesh.getMaterial();
  4305. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4306. if (material && material.needAlphaTesting()) {
  4307. var alphaTexture = material.getAlphaTestTexture();
  4308. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4309. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4310. }
  4311. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4312. if (useBones) {
  4313. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4314. }
  4315. if (hardwareInstancedRendering) {
  4316. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4317. } else {
  4318. if (batch.renderSelf[subMesh._id]) {
  4319. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4320. mesh._draw(subMesh, true);
  4321. }
  4322. if (batch.visibleInstances[subMesh._id]) {
  4323. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4324. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4325. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4326. mesh._draw(subMesh, true);
  4327. }
  4328. }
  4329. }
  4330. } else {
  4331. _this._shadowMap.resetRefreshCounter();
  4332. }
  4333. };
  4334. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4335. var index;
  4336. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4337. renderSubMesh(opaqueSubMeshes.data[index]);
  4338. }
  4339. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4340. renderSubMesh(alphaTestSubMeshes.data[index]);
  4341. }
  4342. if (_this._transparencyShadow) {
  4343. for (index = 0; index < transparentSubMeshes.length; index++) {
  4344. renderSubMesh(transparentSubMeshes.data[index]);
  4345. }
  4346. }
  4347. };
  4348. }
  4349. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4350. get: function () {
  4351. return ShadowGenerator._FILTER_NONE;
  4352. },
  4353. enumerable: true,
  4354. configurable: true
  4355. });
  4356. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4357. get: function () {
  4358. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4359. },
  4360. enumerable: true,
  4361. configurable: true
  4362. });
  4363. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4364. get: function () {
  4365. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4366. },
  4367. enumerable: true,
  4368. configurable: true
  4369. });
  4370. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4371. get: function () {
  4372. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4373. },
  4374. set: function (value) {
  4375. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4376. },
  4377. enumerable: true,
  4378. configurable: true
  4379. });
  4380. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4381. get: function () {
  4382. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4383. },
  4384. set: function (value) {
  4385. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4386. },
  4387. enumerable: true,
  4388. configurable: true
  4389. });
  4390. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4391. var defines = [];
  4392. if (this.useVarianceShadowMap) {
  4393. defines.push("#define VSM");
  4394. }
  4395. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4396. var mesh = subMesh.getMesh();
  4397. var material = subMesh.getMaterial();
  4398. if (material && material.needAlphaTesting()) {
  4399. defines.push("#define ALPHATEST");
  4400. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4401. attribs.push(BABYLON.VertexBuffer.UVKind);
  4402. defines.push("#define UV1");
  4403. }
  4404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4405. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4406. defines.push("#define UV2");
  4407. }
  4408. }
  4409. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4410. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4411. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4412. defines.push("#define BONES");
  4413. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4414. }
  4415. if (useInstances) {
  4416. defines.push("#define INSTANCES");
  4417. attribs.push("world0");
  4418. attribs.push("world1");
  4419. attribs.push("world2");
  4420. attribs.push("world3");
  4421. }
  4422. var join = defines.join("\n");
  4423. if (this._cachedDefines != join) {
  4424. this._cachedDefines = join;
  4425. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4426. }
  4427. return this._effect.isReady();
  4428. };
  4429. ShadowGenerator.prototype.getShadowMap = function () {
  4430. return this._shadowMap;
  4431. };
  4432. ShadowGenerator.prototype.getLight = function () {
  4433. return this._light;
  4434. };
  4435. ShadowGenerator.prototype.getTransformMatrix = function () {
  4436. var lightPosition = this._light.position;
  4437. var lightDirection = this._light.direction;
  4438. if (this._light._computeTransformedPosition()) {
  4439. lightPosition = this._light._transformedPosition;
  4440. }
  4441. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4442. this._cachedPosition = lightPosition.clone();
  4443. this._cachedDirection = lightDirection.clone();
  4444. var activeCamera = this._scene.activeCamera;
  4445. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4446. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4447. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4448. }
  4449. return this._transformMatrix;
  4450. };
  4451. ShadowGenerator.prototype.getDarkness = function () {
  4452. return this._darkness;
  4453. };
  4454. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4455. if (darkness >= 1.0)
  4456. this._darkness = 1.0;
  4457. else if (darkness <= 0.0)
  4458. this._darkness = 0.0;
  4459. else
  4460. this._darkness = darkness;
  4461. };
  4462. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4463. this._transparencyShadow = hasShadow;
  4464. };
  4465. ShadowGenerator.prototype.dispose = function () {
  4466. this._shadowMap.dispose();
  4467. };
  4468. ShadowGenerator._FILTER_NONE = 0;
  4469. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4470. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4471. return ShadowGenerator;
  4472. })();
  4473. BABYLON.ShadowGenerator = ShadowGenerator;
  4474. })(BABYLON || (BABYLON = {}));
  4475. var __extends = this.__extends || function (d, b) {
  4476. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4477. function __() { this.constructor = d; }
  4478. __.prototype = b.prototype;
  4479. d.prototype = new __();
  4480. };
  4481. var BABYLON;
  4482. (function (BABYLON) {
  4483. var HemisphericLight = (function (_super) {
  4484. __extends(HemisphericLight, _super);
  4485. function HemisphericLight(name, direction, scene) {
  4486. _super.call(this, name, scene);
  4487. this.direction = direction;
  4488. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4489. }
  4490. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4491. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4492. return this.direction;
  4493. };
  4494. HemisphericLight.prototype.getShadowGenerator = function () {
  4495. return null;
  4496. };
  4497. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4498. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4499. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4500. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4501. };
  4502. HemisphericLight.prototype._getWorldMatrix = function () {
  4503. if (!this._worldMatrix) {
  4504. this._worldMatrix = BABYLON.Matrix.Identity();
  4505. }
  4506. return this._worldMatrix;
  4507. };
  4508. return HemisphericLight;
  4509. })(BABYLON.Light);
  4510. BABYLON.HemisphericLight = HemisphericLight;
  4511. })(BABYLON || (BABYLON = {}));
  4512. var BABYLON;
  4513. (function (BABYLON) {
  4514. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4515. if (boxMin.x > sphereCenter.x + sphereRadius)
  4516. return false;
  4517. if (sphereCenter.x - sphereRadius > boxMax.x)
  4518. return false;
  4519. if (boxMin.y > sphereCenter.y + sphereRadius)
  4520. return false;
  4521. if (sphereCenter.y - sphereRadius > boxMax.y)
  4522. return false;
  4523. if (boxMin.z > sphereCenter.z + sphereRadius)
  4524. return false;
  4525. if (sphereCenter.z - sphereRadius > boxMax.z)
  4526. return false;
  4527. return true;
  4528. };
  4529. var getLowestRoot = function (a, b, c, maxR) {
  4530. var determinant = b * b - 4.0 * a * c;
  4531. var result = { root: 0, found: false };
  4532. if (determinant < 0)
  4533. return result;
  4534. var sqrtD = Math.sqrt(determinant);
  4535. var r1 = (-b - sqrtD) / (2.0 * a);
  4536. var r2 = (-b + sqrtD) / (2.0 * a);
  4537. if (r1 > r2) {
  4538. var temp = r2;
  4539. r2 = r1;
  4540. r1 = temp;
  4541. }
  4542. if (r1 > 0 && r1 < maxR) {
  4543. result.root = r1;
  4544. result.found = true;
  4545. return result;
  4546. }
  4547. if (r2 > 0 && r2 < maxR) {
  4548. result.root = r2;
  4549. result.found = true;
  4550. return result;
  4551. }
  4552. return result;
  4553. };
  4554. var Collider = (function () {
  4555. function Collider() {
  4556. this.radius = new BABYLON.Vector3(1, 1, 1);
  4557. this.retry = 0;
  4558. this.basePointWorld = BABYLON.Vector3.Zero();
  4559. this.velocityWorld = BABYLON.Vector3.Zero();
  4560. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4561. this._collisionPoint = BABYLON.Vector3.Zero();
  4562. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4563. this._tempVector = BABYLON.Vector3.Zero();
  4564. this._tempVector2 = BABYLON.Vector3.Zero();
  4565. this._tempVector3 = BABYLON.Vector3.Zero();
  4566. this._tempVector4 = BABYLON.Vector3.Zero();
  4567. this._edge = BABYLON.Vector3.Zero();
  4568. this._baseToVertex = BABYLON.Vector3.Zero();
  4569. this._destinationPoint = BABYLON.Vector3.Zero();
  4570. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4571. this._displacementVector = BABYLON.Vector3.Zero();
  4572. }
  4573. Collider.prototype._initialize = function (source, dir, e) {
  4574. this.velocity = dir;
  4575. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4576. this.basePoint = source;
  4577. source.multiplyToRef(this.radius, this.basePointWorld);
  4578. dir.multiplyToRef(this.radius, this.velocityWorld);
  4579. this.velocityWorldLength = this.velocityWorld.length();
  4580. this.epsilon = e;
  4581. this.collisionFound = false;
  4582. };
  4583. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4584. pa.subtractToRef(point, this._tempVector);
  4585. pb.subtractToRef(point, this._tempVector2);
  4586. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4587. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4588. if (d < 0)
  4589. return false;
  4590. pc.subtractToRef(point, this._tempVector3);
  4591. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4592. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4593. if (d < 0)
  4594. return false;
  4595. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4596. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4597. return d >= 0;
  4598. };
  4599. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4600. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4601. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4602. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4603. return false;
  4604. }
  4605. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4606. return false;
  4607. return true;
  4608. };
  4609. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4610. var t0;
  4611. var embeddedInPlane = false;
  4612. if (!subMesh._trianglePlanes) {
  4613. subMesh._trianglePlanes = [];
  4614. }
  4615. if (!subMesh._trianglePlanes[faceIndex]) {
  4616. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4617. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4618. }
  4619. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4620. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4621. return;
  4622. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4623. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4624. if (normalDotVelocity == 0) {
  4625. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4626. return;
  4627. embeddedInPlane = true;
  4628. t0 = 0;
  4629. } else {
  4630. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4631. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4632. if (t0 > t1) {
  4633. var temp = t1;
  4634. t1 = t0;
  4635. t0 = temp;
  4636. }
  4637. if (t0 > 1.0 || t1 < 0.0)
  4638. return;
  4639. if (t0 < 0)
  4640. t0 = 0;
  4641. if (t0 > 1.0)
  4642. t0 = 1.0;
  4643. }
  4644. this._collisionPoint.copyFromFloats(0, 0, 0);
  4645. var found = false;
  4646. var t = 1.0;
  4647. if (!embeddedInPlane) {
  4648. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4649. this.velocity.scaleToRef(t0, this._tempVector);
  4650. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4651. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4652. found = true;
  4653. t = t0;
  4654. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4655. }
  4656. }
  4657. if (!found) {
  4658. var velocitySquaredLength = this.velocity.lengthSquared();
  4659. var a = velocitySquaredLength;
  4660. this.basePoint.subtractToRef(p1, this._tempVector);
  4661. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4662. var c = this._tempVector.lengthSquared() - 1.0;
  4663. var lowestRoot = getLowestRoot(a, b, c, t);
  4664. if (lowestRoot.found) {
  4665. t = lowestRoot.root;
  4666. found = true;
  4667. this._collisionPoint.copyFrom(p1);
  4668. }
  4669. this.basePoint.subtractToRef(p2, this._tempVector);
  4670. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4671. c = this._tempVector.lengthSquared() - 1.0;
  4672. lowestRoot = getLowestRoot(a, b, c, t);
  4673. if (lowestRoot.found) {
  4674. t = lowestRoot.root;
  4675. found = true;
  4676. this._collisionPoint.copyFrom(p2);
  4677. }
  4678. this.basePoint.subtractToRef(p3, this._tempVector);
  4679. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4680. c = this._tempVector.lengthSquared() - 1.0;
  4681. lowestRoot = getLowestRoot(a, b, c, t);
  4682. if (lowestRoot.found) {
  4683. t = lowestRoot.root;
  4684. found = true;
  4685. this._collisionPoint.copyFrom(p3);
  4686. }
  4687. p2.subtractToRef(p1, this._edge);
  4688. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4689. var edgeSquaredLength = this._edge.lengthSquared();
  4690. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4691. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4692. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4693. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4694. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4695. lowestRoot = getLowestRoot(a, b, c, t);
  4696. if (lowestRoot.found) {
  4697. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4698. if (f >= 0.0 && f <= 1.0) {
  4699. t = lowestRoot.root;
  4700. found = true;
  4701. this._edge.scaleInPlace(f);
  4702. p1.addToRef(this._edge, this._collisionPoint);
  4703. }
  4704. }
  4705. p3.subtractToRef(p2, this._edge);
  4706. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4707. edgeSquaredLength = this._edge.lengthSquared();
  4708. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4709. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4710. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4711. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4712. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4713. lowestRoot = getLowestRoot(a, b, c, t);
  4714. if (lowestRoot.found) {
  4715. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4716. if (f >= 0.0 && f <= 1.0) {
  4717. t = lowestRoot.root;
  4718. found = true;
  4719. this._edge.scaleInPlace(f);
  4720. p2.addToRef(this._edge, this._collisionPoint);
  4721. }
  4722. }
  4723. p1.subtractToRef(p3, this._edge);
  4724. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4725. edgeSquaredLength = this._edge.lengthSquared();
  4726. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4727. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4728. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4729. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4730. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4731. lowestRoot = getLowestRoot(a, b, c, t);
  4732. if (lowestRoot.found) {
  4733. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4734. if (f >= 0.0 && f <= 1.0) {
  4735. t = lowestRoot.root;
  4736. found = true;
  4737. this._edge.scaleInPlace(f);
  4738. p3.addToRef(this._edge, this._collisionPoint);
  4739. }
  4740. }
  4741. }
  4742. if (found) {
  4743. var distToCollision = t * this.velocity.length();
  4744. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4745. if (!this.intersectionPoint) {
  4746. this.intersectionPoint = this._collisionPoint.clone();
  4747. } else {
  4748. this.intersectionPoint.copyFrom(this._collisionPoint);
  4749. }
  4750. this.nearestDistance = distToCollision;
  4751. this.collisionFound = true;
  4752. this.collidedMesh = subMesh.getMesh();
  4753. }
  4754. }
  4755. };
  4756. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4757. for (var i = indexStart; i < indexEnd; i += 3) {
  4758. var p1 = pts[indices[i] - decal];
  4759. var p2 = pts[indices[i + 1] - decal];
  4760. var p3 = pts[indices[i + 2] - decal];
  4761. this._testTriangle(i, subMesh, p3, p2, p1);
  4762. }
  4763. };
  4764. Collider.prototype._getResponse = function (pos, vel) {
  4765. pos.addToRef(vel, this._destinationPoint);
  4766. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4767. this.basePoint.addToRef(vel, pos);
  4768. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4769. this._slidePlaneNormal.normalize();
  4770. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4771. pos.addInPlace(this._displacementVector);
  4772. this.intersectionPoint.addInPlace(this._displacementVector);
  4773. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4774. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4775. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4776. };
  4777. return Collider;
  4778. })();
  4779. BABYLON.Collider = Collider;
  4780. })(BABYLON || (BABYLON = {}));
  4781. var __extends = this.__extends || function (d, b) {
  4782. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4783. function __() { this.constructor = d; }
  4784. __.prototype = b.prototype;
  4785. d.prototype = new __();
  4786. };
  4787. var BABYLON;
  4788. (function (BABYLON) {
  4789. var Camera = (function (_super) {
  4790. __extends(Camera, _super);
  4791. function Camera(name, position, scene) {
  4792. _super.call(this, name, scene);
  4793. this.position = position;
  4794. this.upVector = BABYLON.Vector3.Up();
  4795. this.orthoLeft = null;
  4796. this.orthoRight = null;
  4797. this.orthoBottom = null;
  4798. this.orthoTop = null;
  4799. this.fov = 0.8;
  4800. this.minZ = 1.0;
  4801. this.maxZ = 10000.0;
  4802. this.inertia = 0.9;
  4803. this.mode = Camera.PERSPECTIVE_CAMERA;
  4804. this.isIntermediate = false;
  4805. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4806. this.subCameras = [];
  4807. this.layerMask = 0xFFFFFFFF;
  4808. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4809. this._projectionMatrix = new BABYLON.Matrix();
  4810. this._postProcesses = new Array();
  4811. this._postProcessesTakenIndices = [];
  4812. scene.cameras.push(this);
  4813. if (!scene.activeCamera) {
  4814. scene.activeCamera = this;
  4815. }
  4816. }
  4817. Camera.prototype._initCache = function () {
  4818. _super.prototype._initCache.call(this);
  4819. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4820. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4821. this._cache.mode = undefined;
  4822. this._cache.minZ = undefined;
  4823. this._cache.maxZ = undefined;
  4824. this._cache.fov = undefined;
  4825. this._cache.aspectRatio = undefined;
  4826. this._cache.orthoLeft = undefined;
  4827. this._cache.orthoRight = undefined;
  4828. this._cache.orthoBottom = undefined;
  4829. this._cache.orthoTop = undefined;
  4830. this._cache.renderWidth = undefined;
  4831. this._cache.renderHeight = undefined;
  4832. };
  4833. Camera.prototype._updateCache = function (ignoreParentClass) {
  4834. if (!ignoreParentClass) {
  4835. _super.prototype._updateCache.call(this);
  4836. }
  4837. var engine = this.getEngine();
  4838. this._cache.position.copyFrom(this.position);
  4839. this._cache.upVector.copyFrom(this.upVector);
  4840. this._cache.mode = this.mode;
  4841. this._cache.minZ = this.minZ;
  4842. this._cache.maxZ = this.maxZ;
  4843. this._cache.fov = this.fov;
  4844. this._cache.aspectRatio = engine.getAspectRatio(this);
  4845. this._cache.orthoLeft = this.orthoLeft;
  4846. this._cache.orthoRight = this.orthoRight;
  4847. this._cache.orthoBottom = this.orthoBottom;
  4848. this._cache.orthoTop = this.orthoTop;
  4849. this._cache.renderWidth = engine.getRenderWidth();
  4850. this._cache.renderHeight = engine.getRenderHeight();
  4851. };
  4852. Camera.prototype._updateFromScene = function () {
  4853. this.updateCache();
  4854. this._update();
  4855. };
  4856. Camera.prototype._isSynchronized = function () {
  4857. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4858. };
  4859. Camera.prototype._isSynchronizedViewMatrix = function () {
  4860. if (!_super.prototype._isSynchronized.call(this))
  4861. return false;
  4862. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4863. };
  4864. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4865. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4866. if (!check) {
  4867. return false;
  4868. }
  4869. var engine = this.getEngine();
  4870. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4871. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4872. } else {
  4873. 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();
  4874. }
  4875. return check;
  4876. };
  4877. Camera.prototype.attachControl = function (element) {
  4878. };
  4879. Camera.prototype.detachControl = function (element) {
  4880. };
  4881. Camera.prototype._update = function () {
  4882. };
  4883. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4884. if (typeof insertAt === "undefined") { insertAt = null; }
  4885. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4886. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4887. return 0;
  4888. }
  4889. if (insertAt == null || insertAt < 0) {
  4890. this._postProcesses.push(postProcess);
  4891. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4892. return this._postProcesses.length - 1;
  4893. }
  4894. var add = 0;
  4895. if (this._postProcesses[insertAt]) {
  4896. var start = this._postProcesses.length - 1;
  4897. for (var i = start; i >= insertAt + 1; --i) {
  4898. this._postProcesses[i + 1] = this._postProcesses[i];
  4899. }
  4900. add = 1;
  4901. }
  4902. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4903. if (this._postProcessesTakenIndices[i] < insertAt) {
  4904. continue;
  4905. }
  4906. start = this._postProcessesTakenIndices.length - 1;
  4907. for (var j = start; j >= i; --j) {
  4908. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4909. }
  4910. this._postProcessesTakenIndices[i] = insertAt;
  4911. break;
  4912. }
  4913. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4914. this._postProcessesTakenIndices.push(insertAt);
  4915. }
  4916. var result = insertAt + add;
  4917. this._postProcesses[result] = postProcess;
  4918. return result;
  4919. };
  4920. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4921. if (typeof atIndices === "undefined") { atIndices = null; }
  4922. var result = [];
  4923. if (!atIndices) {
  4924. var length = this._postProcesses.length;
  4925. for (var i = 0; i < length; i++) {
  4926. if (this._postProcesses[i] !== postProcess) {
  4927. continue;
  4928. }
  4929. delete this._postProcesses[i];
  4930. var index = this._postProcessesTakenIndices.indexOf(i);
  4931. this._postProcessesTakenIndices.splice(index, 1);
  4932. }
  4933. } else {
  4934. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4935. for (i = 0; i < atIndices.length; i++) {
  4936. var foundPostProcess = this._postProcesses[atIndices[i]];
  4937. if (foundPostProcess !== postProcess) {
  4938. result.push(i);
  4939. continue;
  4940. }
  4941. delete this._postProcesses[atIndices[i]];
  4942. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4943. this._postProcessesTakenIndices.splice(index, 1);
  4944. }
  4945. }
  4946. return result;
  4947. };
  4948. Camera.prototype.getWorldMatrix = function () {
  4949. if (!this._worldMatrix) {
  4950. this._worldMatrix = BABYLON.Matrix.Identity();
  4951. }
  4952. var viewMatrix = this.getViewMatrix();
  4953. viewMatrix.invertToRef(this._worldMatrix);
  4954. return this._worldMatrix;
  4955. };
  4956. Camera.prototype._getViewMatrix = function () {
  4957. return BABYLON.Matrix.Identity();
  4958. };
  4959. Camera.prototype.getViewMatrix = function () {
  4960. this._computedViewMatrix = this._computeViewMatrix();
  4961. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4962. return this._computedViewMatrix;
  4963. }
  4964. if (!this._worldMatrix) {
  4965. this._worldMatrix = BABYLON.Matrix.Identity();
  4966. }
  4967. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4968. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4969. this._computedViewMatrix.invert();
  4970. this._currentRenderId = this.getScene().getRenderId();
  4971. return this._computedViewMatrix;
  4972. };
  4973. Camera.prototype._computeViewMatrix = function (force) {
  4974. if (!force && this._isSynchronizedViewMatrix()) {
  4975. return this._computedViewMatrix;
  4976. }
  4977. this._computedViewMatrix = this._getViewMatrix();
  4978. if (!this.parent || !this.parent.getWorldMatrix) {
  4979. this._currentRenderId = this.getScene().getRenderId();
  4980. }
  4981. return this._computedViewMatrix;
  4982. };
  4983. Camera.prototype.getProjectionMatrix = function (force) {
  4984. if (!force && this._isSynchronizedProjectionMatrix()) {
  4985. return this._projectionMatrix;
  4986. }
  4987. var engine = this.getEngine();
  4988. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4989. if (this.minZ <= 0) {
  4990. this.minZ = 0.1;
  4991. }
  4992. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  4993. return this._projectionMatrix;
  4994. }
  4995. var halfWidth = engine.getRenderWidth() / 2.0;
  4996. var halfHeight = engine.getRenderHeight() / 2.0;
  4997. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  4998. return this._projectionMatrix;
  4999. };
  5000. Camera.prototype.dispose = function () {
  5001. var index = this.getScene().cameras.indexOf(this);
  5002. this.getScene().cameras.splice(index, 1);
  5003. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5004. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5005. }
  5006. };
  5007. Camera.PERSPECTIVE_CAMERA = 0;
  5008. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5009. return Camera;
  5010. })(BABYLON.Node);
  5011. BABYLON.Camera = Camera;
  5012. })(BABYLON || (BABYLON = {}));
  5013. var __extends = this.__extends || function (d, b) {
  5014. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5015. function __() { this.constructor = d; }
  5016. __.prototype = b.prototype;
  5017. d.prototype = new __();
  5018. };
  5019. var BABYLON;
  5020. (function (BABYLON) {
  5021. var TargetCamera = (function (_super) {
  5022. __extends(TargetCamera, _super);
  5023. function TargetCamera(name, position, scene) {
  5024. _super.call(this, name, position, scene);
  5025. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5026. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5027. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5028. this.speed = 2.0;
  5029. this.noRotationConstraint = false;
  5030. this.lockedTarget = null;
  5031. this._currentTarget = BABYLON.Vector3.Zero();
  5032. this._viewMatrix = BABYLON.Matrix.Zero();
  5033. this._camMatrix = BABYLON.Matrix.Zero();
  5034. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5035. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5036. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5037. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5038. this._lookAtTemp = BABYLON.Matrix.Zero();
  5039. this._tempMatrix = BABYLON.Matrix.Zero();
  5040. }
  5041. TargetCamera.prototype._getLockedTargetPosition = function () {
  5042. if (!this.lockedTarget) {
  5043. return null;
  5044. }
  5045. return this.lockedTarget.position || this.lockedTarget;
  5046. };
  5047. TargetCamera.prototype._initCache = function () {
  5048. _super.prototype._initCache.call(this);
  5049. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5050. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5051. };
  5052. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5053. if (!ignoreParentClass) {
  5054. _super.prototype._updateCache.call(this);
  5055. }
  5056. var lockedTargetPosition = this._getLockedTargetPosition();
  5057. if (!lockedTargetPosition) {
  5058. this._cache.lockedTarget = null;
  5059. } else {
  5060. if (!this._cache.lockedTarget) {
  5061. this._cache.lockedTarget = lockedTargetPosition.clone();
  5062. } else {
  5063. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5064. }
  5065. }
  5066. this._cache.rotation.copyFrom(this.rotation);
  5067. };
  5068. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5069. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5070. return false;
  5071. }
  5072. var lockedTargetPosition = this._getLockedTargetPosition();
  5073. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5074. };
  5075. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5076. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5077. };
  5078. TargetCamera.prototype.setTarget = function (target) {
  5079. this.upVector.normalize();
  5080. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5081. this._camMatrix.invert();
  5082. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5083. var vDir = target.subtract(this.position);
  5084. if (vDir.x >= 0.0) {
  5085. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5086. } else {
  5087. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5088. }
  5089. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5090. if (isNaN(this.rotation.x)) {
  5091. this.rotation.x = 0;
  5092. }
  5093. if (isNaN(this.rotation.y)) {
  5094. this.rotation.y = 0;
  5095. }
  5096. if (isNaN(this.rotation.z)) {
  5097. this.rotation.z = 0;
  5098. }
  5099. };
  5100. TargetCamera.prototype.getTarget = function () {
  5101. return this._currentTarget;
  5102. };
  5103. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5104. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5105. };
  5106. TargetCamera.prototype._updatePosition = function () {
  5107. this.position.addInPlace(this.cameraDirection);
  5108. };
  5109. TargetCamera.prototype._update = function () {
  5110. var needToMove = this._decideIfNeedsToMove();
  5111. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5112. if (needToMove) {
  5113. this._updatePosition();
  5114. }
  5115. if (needToRotate) {
  5116. this.rotation.x += this.cameraRotation.x;
  5117. this.rotation.y += this.cameraRotation.y;
  5118. if (!this.noRotationConstraint) {
  5119. var limit = (Math.PI / 2) * 0.95;
  5120. if (this.rotation.x > limit)
  5121. this.rotation.x = limit;
  5122. if (this.rotation.x < -limit)
  5123. this.rotation.x = -limit;
  5124. }
  5125. }
  5126. if (needToMove) {
  5127. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5128. this.cameraDirection.x = 0;
  5129. }
  5130. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5131. this.cameraDirection.y = 0;
  5132. }
  5133. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5134. this.cameraDirection.z = 0;
  5135. }
  5136. this.cameraDirection.scaleInPlace(this.inertia);
  5137. }
  5138. if (needToRotate) {
  5139. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5140. this.cameraRotation.x = 0;
  5141. }
  5142. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5143. this.cameraRotation.y = 0;
  5144. }
  5145. this.cameraRotation.scaleInPlace(this.inertia);
  5146. }
  5147. };
  5148. TargetCamera.prototype._getViewMatrix = function () {
  5149. if (!this.lockedTarget) {
  5150. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5151. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5152. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5153. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5154. this._lookAtTemp.invert();
  5155. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5156. } else {
  5157. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5158. }
  5159. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5160. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5161. } else {
  5162. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5163. }
  5164. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5165. return this._viewMatrix;
  5166. };
  5167. return TargetCamera;
  5168. })(BABYLON.Camera);
  5169. BABYLON.TargetCamera = TargetCamera;
  5170. })(BABYLON || (BABYLON = {}));
  5171. var __extends = this.__extends || function (d, b) {
  5172. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5173. function __() { this.constructor = d; }
  5174. __.prototype = b.prototype;
  5175. d.prototype = new __();
  5176. };
  5177. var BABYLON;
  5178. (function (BABYLON) {
  5179. var FollowCamera = (function (_super) {
  5180. __extends(FollowCamera, _super);
  5181. function FollowCamera(name, position, scene) {
  5182. _super.call(this, name, position, scene);
  5183. this.radius = 12;
  5184. this.rotationOffset = 0;
  5185. this.heightOffset = 4;
  5186. this.cameraAcceleration = 0.05;
  5187. this.maxCameraSpeed = 20;
  5188. }
  5189. FollowCamera.prototype.getRadians = function (degrees) {
  5190. return degrees * Math.PI / 180;
  5191. };
  5192. FollowCamera.prototype.follow = function (cameraTarget) {
  5193. if (!cameraTarget)
  5194. return;
  5195. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5196. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5197. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5198. var dx = targetX - this.position.x;
  5199. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5200. var dz = (targetZ) - this.position.z;
  5201. var vx = dx * this.cameraAcceleration * 2;
  5202. var vy = dy * this.cameraAcceleration;
  5203. var vz = dz * this.cameraAcceleration * 2;
  5204. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5205. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5206. }
  5207. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5208. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5209. }
  5210. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5211. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5212. }
  5213. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5214. this.setTarget(cameraTarget.position);
  5215. };
  5216. FollowCamera.prototype._update = function () {
  5217. _super.prototype._update.call(this);
  5218. this.follow(this.target);
  5219. };
  5220. return FollowCamera;
  5221. })(BABYLON.TargetCamera);
  5222. BABYLON.FollowCamera = FollowCamera;
  5223. })(BABYLON || (BABYLON = {}));
  5224. var __extends = this.__extends || function (d, b) {
  5225. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5226. function __() { this.constructor = d; }
  5227. __.prototype = b.prototype;
  5228. d.prototype = new __();
  5229. };
  5230. var BABYLON;
  5231. (function (BABYLON) {
  5232. var FreeCamera = (function (_super) {
  5233. __extends(FreeCamera, _super);
  5234. function FreeCamera(name, position, scene) {
  5235. _super.call(this, name, position, scene);
  5236. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5237. this.keysUp = [38];
  5238. this.keysDown = [40];
  5239. this.keysLeft = [37];
  5240. this.keysRight = [39];
  5241. this.checkCollisions = false;
  5242. this.applyGravity = false;
  5243. this.angularSensibility = 2000.0;
  5244. this._keys = [];
  5245. this._collider = new BABYLON.Collider();
  5246. this._needMoveForGravity = true;
  5247. this._oldPosition = BABYLON.Vector3.Zero();
  5248. this._diffPosition = BABYLON.Vector3.Zero();
  5249. this._newPosition = BABYLON.Vector3.Zero();
  5250. }
  5251. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5252. var _this = this;
  5253. var previousPosition;
  5254. var engine = this.getEngine();
  5255. if (this._attachedElement) {
  5256. return;
  5257. }
  5258. this._attachedElement = element;
  5259. if (this._onMouseDown === undefined) {
  5260. this._onMouseDown = function (evt) {
  5261. previousPosition = {
  5262. x: evt.clientX,
  5263. y: evt.clientY
  5264. };
  5265. if (!noPreventDefault) {
  5266. evt.preventDefault();
  5267. }
  5268. };
  5269. this._onMouseUp = function (evt) {
  5270. previousPosition = null;
  5271. if (!noPreventDefault) {
  5272. evt.preventDefault();
  5273. }
  5274. };
  5275. this._onMouseOut = function (evt) {
  5276. previousPosition = null;
  5277. _this._keys = [];
  5278. if (!noPreventDefault) {
  5279. evt.preventDefault();
  5280. }
  5281. };
  5282. this._onMouseMove = function (evt) {
  5283. if (!previousPosition && !engine.isPointerLock) {
  5284. return;
  5285. }
  5286. var offsetX;
  5287. var offsetY;
  5288. if (!engine.isPointerLock) {
  5289. offsetX = evt.clientX - previousPosition.x;
  5290. offsetY = evt.clientY - previousPosition.y;
  5291. } else {
  5292. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5293. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5294. }
  5295. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5296. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5297. previousPosition = {
  5298. x: evt.clientX,
  5299. y: evt.clientY
  5300. };
  5301. if (!noPreventDefault) {
  5302. evt.preventDefault();
  5303. }
  5304. };
  5305. this._onKeyDown = function (evt) {
  5306. 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) {
  5307. var index = _this._keys.indexOf(evt.keyCode);
  5308. if (index === -1) {
  5309. _this._keys.push(evt.keyCode);
  5310. }
  5311. if (!noPreventDefault) {
  5312. evt.preventDefault();
  5313. }
  5314. }
  5315. };
  5316. this._onKeyUp = function (evt) {
  5317. 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) {
  5318. var index = _this._keys.indexOf(evt.keyCode);
  5319. if (index >= 0) {
  5320. _this._keys.splice(index, 1);
  5321. }
  5322. if (!noPreventDefault) {
  5323. evt.preventDefault();
  5324. }
  5325. }
  5326. };
  5327. this._onLostFocus = function () {
  5328. _this._keys = [];
  5329. };
  5330. this._reset = function () {
  5331. _this._keys = [];
  5332. previousPosition = null;
  5333. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5334. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5335. };
  5336. }
  5337. element.addEventListener("mousedown", this._onMouseDown, false);
  5338. element.addEventListener("mouseup", this._onMouseUp, false);
  5339. element.addEventListener("mouseout", this._onMouseOut, false);
  5340. element.addEventListener("mousemove", this._onMouseMove, false);
  5341. BABYLON.Tools.RegisterTopRootEvents([
  5342. { name: "keydown", handler: this._onKeyDown },
  5343. { name: "keyup", handler: this._onKeyUp },
  5344. { name: "blur", handler: this._onLostFocus }
  5345. ]);
  5346. };
  5347. FreeCamera.prototype.detachControl = function (element) {
  5348. if (this._attachedElement != element) {
  5349. return;
  5350. }
  5351. element.removeEventListener("mousedown", this._onMouseDown);
  5352. element.removeEventListener("mouseup", this._onMouseUp);
  5353. element.removeEventListener("mouseout", this._onMouseOut);
  5354. element.removeEventListener("mousemove", this._onMouseMove);
  5355. BABYLON.Tools.UnregisterTopRootEvents([
  5356. { name: "keydown", handler: this._onKeyDown },
  5357. { name: "keyup", handler: this._onKeyUp },
  5358. { name: "blur", handler: this._onLostFocus }
  5359. ]);
  5360. this._attachedElement = null;
  5361. if (this._reset) {
  5362. this._reset();
  5363. }
  5364. };
  5365. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5366. var globalPosition;
  5367. if (this.parent) {
  5368. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5369. } else {
  5370. globalPosition = this.position;
  5371. }
  5372. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5373. this._collider.radius = this.ellipsoid;
  5374. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5375. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5376. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5377. this.position.addInPlace(this._diffPosition);
  5378. if (this.onCollide) {
  5379. this.onCollide(this._collider.collidedMesh);
  5380. }
  5381. }
  5382. };
  5383. FreeCamera.prototype._checkInputs = function () {
  5384. if (!this._localDirection) {
  5385. this._localDirection = BABYLON.Vector3.Zero();
  5386. this._transformedDirection = BABYLON.Vector3.Zero();
  5387. }
  5388. for (var index = 0; index < this._keys.length; index++) {
  5389. var keyCode = this._keys[index];
  5390. var speed = this._computeLocalCameraSpeed();
  5391. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5392. this._localDirection.copyFromFloats(-speed, 0, 0);
  5393. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5394. this._localDirection.copyFromFloats(0, 0, speed);
  5395. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5396. this._localDirection.copyFromFloats(speed, 0, 0);
  5397. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5398. this._localDirection.copyFromFloats(0, 0, -speed);
  5399. }
  5400. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5401. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5402. this.cameraDirection.addInPlace(this._transformedDirection);
  5403. }
  5404. };
  5405. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5406. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5407. };
  5408. FreeCamera.prototype._updatePosition = function () {
  5409. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5410. this._collideWithWorld(this.cameraDirection);
  5411. if (this.applyGravity) {
  5412. var oldPosition = this.position;
  5413. this._collideWithWorld(this.getScene().gravity);
  5414. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5415. }
  5416. } else {
  5417. this.position.addInPlace(this.cameraDirection);
  5418. }
  5419. };
  5420. FreeCamera.prototype._update = function () {
  5421. this._checkInputs();
  5422. _super.prototype._update.call(this);
  5423. };
  5424. return FreeCamera;
  5425. })(BABYLON.TargetCamera);
  5426. BABYLON.FreeCamera = FreeCamera;
  5427. })(BABYLON || (BABYLON = {}));
  5428. var __extends = this.__extends || function (d, b) {
  5429. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5430. function __() { this.constructor = d; }
  5431. __.prototype = b.prototype;
  5432. d.prototype = new __();
  5433. };
  5434. var BABYLON;
  5435. (function (BABYLON) {
  5436. var TouchCamera = (function (_super) {
  5437. __extends(TouchCamera, _super);
  5438. function TouchCamera(name, position, scene) {
  5439. _super.call(this, name, position, scene);
  5440. this._offsetX = null;
  5441. this._offsetY = null;
  5442. this._pointerCount = 0;
  5443. this._pointerPressed = [];
  5444. this.angularSensibility = 200000.0;
  5445. this.moveSensibility = 500.0;
  5446. }
  5447. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5448. var _this = this;
  5449. var previousPosition;
  5450. if (this._attachedCanvas) {
  5451. return;
  5452. }
  5453. this._attachedCanvas = canvas;
  5454. if (this._onPointerDown === undefined) {
  5455. this._onPointerDown = function (evt) {
  5456. if (!noPreventDefault) {
  5457. evt.preventDefault();
  5458. }
  5459. _this._pointerPressed.push(evt.pointerId);
  5460. if (_this._pointerPressed.length !== 1) {
  5461. return;
  5462. }
  5463. previousPosition = {
  5464. x: evt.clientX,
  5465. y: evt.clientY
  5466. };
  5467. };
  5468. this._onPointerUp = function (evt) {
  5469. if (!noPreventDefault) {
  5470. evt.preventDefault();
  5471. }
  5472. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5473. if (index === -1) {
  5474. return;
  5475. }
  5476. _this._pointerPressed.splice(index, 1);
  5477. if (index != 0) {
  5478. return;
  5479. }
  5480. previousPosition = null;
  5481. _this._offsetX = null;
  5482. _this._offsetY = null;
  5483. };
  5484. this._onPointerMove = function (evt) {
  5485. if (!noPreventDefault) {
  5486. evt.preventDefault();
  5487. }
  5488. if (!previousPosition) {
  5489. return;
  5490. }
  5491. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5492. if (index != 0) {
  5493. return;
  5494. }
  5495. _this._offsetX = evt.clientX - previousPosition.x;
  5496. _this._offsetY = -(evt.clientY - previousPosition.y);
  5497. };
  5498. this._onLostFocus = function () {
  5499. _this._offsetX = null;
  5500. _this._offsetY = null;
  5501. };
  5502. }
  5503. canvas.addEventListener("pointerdown", this._onPointerDown);
  5504. canvas.addEventListener("pointerup", this._onPointerUp);
  5505. canvas.addEventListener("pointerout", this._onPointerUp);
  5506. canvas.addEventListener("pointermove", this._onPointerMove);
  5507. BABYLON.Tools.RegisterTopRootEvents([
  5508. { name: "blur", handler: this._onLostFocus }
  5509. ]);
  5510. };
  5511. TouchCamera.prototype.detachControl = function (canvas) {
  5512. if (this._attachedCanvas != canvas) {
  5513. return;
  5514. }
  5515. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5516. canvas.removeEventListener("pointerup", this._onPointerUp);
  5517. canvas.removeEventListener("pointerout", this._onPointerUp);
  5518. canvas.removeEventListener("pointermove", this._onPointerMove);
  5519. BABYLON.Tools.UnregisterTopRootEvents([
  5520. { name: "blur", handler: this._onLostFocus }
  5521. ]);
  5522. this._attachedCanvas = null;
  5523. };
  5524. TouchCamera.prototype._checkInputs = function () {
  5525. if (!this._offsetX) {
  5526. return;
  5527. }
  5528. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5529. if (this._pointerPressed.length > 1) {
  5530. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5531. } else {
  5532. var speed = this._computeLocalCameraSpeed();
  5533. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5534. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5535. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5536. }
  5537. };
  5538. return TouchCamera;
  5539. })(BABYLON.FreeCamera);
  5540. BABYLON.TouchCamera = TouchCamera;
  5541. })(BABYLON || (BABYLON = {}));
  5542. var __extends = this.__extends || function (d, b) {
  5543. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5544. function __() { this.constructor = d; }
  5545. __.prototype = b.prototype;
  5546. d.prototype = new __();
  5547. };
  5548. var BABYLON;
  5549. (function (BABYLON) {
  5550. var DeviceOrientationCamera = (function (_super) {
  5551. __extends(DeviceOrientationCamera, _super);
  5552. function DeviceOrientationCamera(name, position, scene) {
  5553. var _this = this;
  5554. _super.call(this, name, position, scene);
  5555. this._offsetX = null;
  5556. this._offsetY = null;
  5557. this._orientationGamma = 0;
  5558. this._orientationBeta = 0;
  5559. this._initialOrientationGamma = 0;
  5560. this._initialOrientationBeta = 0;
  5561. this.angularSensibility = 10000.0;
  5562. this.moveSensibility = 50.0;
  5563. window.addEventListener("resize", function () {
  5564. _this._initialOrientationGamma = null;
  5565. }, false);
  5566. }
  5567. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5568. var _this = this;
  5569. if (this._attachedCanvas) {
  5570. return;
  5571. }
  5572. this._attachedCanvas = canvas;
  5573. if (!this._orientationChanged) {
  5574. this._orientationChanged = function (evt) {
  5575. if (!_this._initialOrientationGamma) {
  5576. _this._initialOrientationGamma = evt.gamma;
  5577. _this._initialOrientationBeta = evt.beta;
  5578. }
  5579. _this._orientationGamma = evt.gamma;
  5580. _this._orientationBeta = evt.beta;
  5581. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5582. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5583. };
  5584. }
  5585. window.addEventListener("deviceorientation", this._orientationChanged);
  5586. };
  5587. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5588. if (this._attachedCanvas != canvas) {
  5589. return;
  5590. }
  5591. window.removeEventListener("deviceorientation", this._orientationChanged);
  5592. this._attachedCanvas = null;
  5593. this._orientationGamma = 0;
  5594. this._orientationBeta = 0;
  5595. this._initialOrientationGamma = 0;
  5596. this._initialOrientationBeta = 0;
  5597. };
  5598. DeviceOrientationCamera.prototype._checkInputs = function () {
  5599. if (!this._offsetX) {
  5600. return;
  5601. }
  5602. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5603. var speed = this._computeLocalCameraSpeed();
  5604. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5605. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5606. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5607. };
  5608. return DeviceOrientationCamera;
  5609. })(BABYLON.FreeCamera);
  5610. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5611. })(BABYLON || (BABYLON = {}));
  5612. var __extends = this.__extends || function (d, b) {
  5613. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5614. function __() { this.constructor = d; }
  5615. __.prototype = b.prototype;
  5616. d.prototype = new __();
  5617. };
  5618. var BABYLON;
  5619. (function (BABYLON) {
  5620. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5621. var ArcRotateCamera = (function (_super) {
  5622. __extends(ArcRotateCamera, _super);
  5623. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5624. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5625. this.alpha = alpha;
  5626. this.beta = beta;
  5627. this.radius = radius;
  5628. this.target = target;
  5629. this.inertialAlphaOffset = 0;
  5630. this.inertialBetaOffset = 0;
  5631. this.inertialRadiusOffset = 0;
  5632. this.lowerAlphaLimit = null;
  5633. this.upperAlphaLimit = null;
  5634. this.lowerBetaLimit = 0.01;
  5635. this.upperBetaLimit = Math.PI;
  5636. this.lowerRadiusLimit = null;
  5637. this.upperRadiusLimit = null;
  5638. this.angularSensibility = 1000.0;
  5639. this.wheelPrecision = 3.0;
  5640. this.keysUp = [38];
  5641. this.keysDown = [40];
  5642. this.keysLeft = [37];
  5643. this.keysRight = [39];
  5644. this.zoomOnFactor = 1;
  5645. this._keys = [];
  5646. this._viewMatrix = new BABYLON.Matrix();
  5647. this.checkCollisions = false;
  5648. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5649. this._collider = new BABYLON.Collider();
  5650. this._previousPosition = BABYLON.Vector3.Zero();
  5651. this._collisionVelocity = BABYLON.Vector3.Zero();
  5652. this._newPosition = BABYLON.Vector3.Zero();
  5653. this.pinchPrecision = 20;
  5654. this.getViewMatrix();
  5655. }
  5656. ArcRotateCamera.prototype._getTargetPosition = function () {
  5657. return this.target.position || this.target;
  5658. };
  5659. ArcRotateCamera.prototype._initCache = function () {
  5660. _super.prototype._initCache.call(this);
  5661. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5662. this._cache.alpha = undefined;
  5663. this._cache.beta = undefined;
  5664. this._cache.radius = undefined;
  5665. };
  5666. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5667. if (!ignoreParentClass) {
  5668. _super.prototype._updateCache.call(this);
  5669. }
  5670. this._cache.target.copyFrom(this._getTargetPosition());
  5671. this._cache.alpha = this.alpha;
  5672. this._cache.beta = this.beta;
  5673. this._cache.radius = this.radius;
  5674. };
  5675. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5676. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5677. return false;
  5678. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius;
  5679. };
  5680. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5681. var _this = this;
  5682. var previousPosition;
  5683. var pointerId;
  5684. var pinchStarted = false;
  5685. var pinchPointX1, pinchPointX2;
  5686. if (this._attachedElement) {
  5687. return;
  5688. }
  5689. this._attachedElement = element;
  5690. var engine = this.getEngine();
  5691. if (this._onPointerDown === undefined) {
  5692. this._onPointerDown = function (evt) {
  5693. if (pointerId) {
  5694. return;
  5695. }
  5696. pointerId = evt.pointerId;
  5697. previousPosition = {
  5698. x: evt.clientX,
  5699. y: evt.clientY
  5700. };
  5701. if (!noPreventDefault) {
  5702. evt.preventDefault();
  5703. }
  5704. };
  5705. this._onPointerUp = function (evt) {
  5706. previousPosition = null;
  5707. pointerId = null;
  5708. if (!noPreventDefault) {
  5709. evt.preventDefault();
  5710. }
  5711. };
  5712. this._onPointerMove = function (evt) {
  5713. if (!previousPosition) {
  5714. return;
  5715. }
  5716. if (pointerId !== evt.pointerId) {
  5717. return;
  5718. }
  5719. if (pinchStarted) {
  5720. return;
  5721. }
  5722. var offsetX = evt.clientX - previousPosition.x;
  5723. var offsetY = evt.clientY - previousPosition.y;
  5724. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5725. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5726. previousPosition = {
  5727. x: evt.clientX,
  5728. y: evt.clientY
  5729. };
  5730. if (!noPreventDefault) {
  5731. evt.preventDefault();
  5732. }
  5733. };
  5734. this._onMouseMove = function (evt) {
  5735. if (!engine.isPointerLock) {
  5736. return;
  5737. }
  5738. if (pinchStarted) {
  5739. return;
  5740. }
  5741. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5742. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5743. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5744. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5745. if (!noPreventDefault) {
  5746. evt.preventDefault();
  5747. }
  5748. };
  5749. this._wheel = function (event) {
  5750. var delta = 0;
  5751. if (event.wheelDelta) {
  5752. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5753. } else if (event.detail) {
  5754. delta = -event.detail / _this.wheelPrecision;
  5755. }
  5756. if (delta)
  5757. _this.inertialRadiusOffset += delta;
  5758. if (event.preventDefault) {
  5759. if (!noPreventDefault) {
  5760. event.preventDefault();
  5761. }
  5762. }
  5763. };
  5764. this._onKeyDown = function (evt) {
  5765. 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) {
  5766. var index = _this._keys.indexOf(evt.keyCode);
  5767. if (index === -1) {
  5768. _this._keys.push(evt.keyCode);
  5769. }
  5770. if (evt.preventDefault) {
  5771. if (!noPreventDefault) {
  5772. evt.preventDefault();
  5773. }
  5774. }
  5775. }
  5776. };
  5777. this._onKeyUp = function (evt) {
  5778. 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) {
  5779. var index = _this._keys.indexOf(evt.keyCode);
  5780. if (index >= 0) {
  5781. _this._keys.splice(index, 1);
  5782. }
  5783. if (evt.preventDefault) {
  5784. if (!noPreventDefault) {
  5785. evt.preventDefault();
  5786. }
  5787. }
  5788. }
  5789. };
  5790. this._onLostFocus = function () {
  5791. _this._keys = [];
  5792. pointerId = null;
  5793. };
  5794. this._onGestureStart = function (e) {
  5795. if (window.MSGesture === undefined) {
  5796. return;
  5797. }
  5798. if (!_this._MSGestureHandler) {
  5799. _this._MSGestureHandler = new MSGesture();
  5800. _this._MSGestureHandler.target = element;
  5801. }
  5802. _this._MSGestureHandler.addPointer(e.pointerId);
  5803. };
  5804. this._onGesture = function (e) {
  5805. _this.radius *= e.scale;
  5806. if (e.preventDefault) {
  5807. if (!noPreventDefault) {
  5808. e.stopPropagation();
  5809. e.preventDefault();
  5810. }
  5811. }
  5812. };
  5813. this._reset = function () {
  5814. _this._keys = [];
  5815. _this.inertialAlphaOffset = 0;
  5816. _this.inertialBetaOffset = 0;
  5817. _this.inertialRadiusOffset = 0;
  5818. previousPosition = null;
  5819. pointerId = null;
  5820. };
  5821. this._touchStart = function (event) {
  5822. if (event.touches.length == 2) {
  5823. pinchStarted = true;
  5824. _this._pinchStart(event);
  5825. }
  5826. };
  5827. this._touchMove = function (event) {
  5828. if (pinchStarted) {
  5829. _this._pinchMove(event);
  5830. }
  5831. };
  5832. this._touchEnd = function (event) {
  5833. if (pinchStarted) {
  5834. _this._pinchEnd(event);
  5835. }
  5836. };
  5837. this._pinchStart = function (event) {
  5838. pinchPointX1 = event.touches[0].clientX;
  5839. pinchPointX2 = event.touches[1].clientX;
  5840. pinchStarted = true;
  5841. };
  5842. this._pinchMove = function (event) {
  5843. var delta = 0;
  5844. var direction = 1;
  5845. var distanceXOrigine, distanceXNow;
  5846. if (event.touches.length != 2)
  5847. return;
  5848. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5849. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5850. if (distanceXNow < distanceXOrigine) {
  5851. direction = -1;
  5852. }
  5853. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5854. _this.inertialRadiusOffset += delta;
  5855. pinchPointX1 = event.touches[0].clientX;
  5856. pinchPointX2 = event.touches[1].clientX;
  5857. };
  5858. this._pinchEnd = function (event) {
  5859. pinchStarted = false;
  5860. };
  5861. }
  5862. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5863. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5864. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5865. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5866. element.addEventListener("mousemove", this._onMouseMove, false);
  5867. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5868. element.addEventListener("MSGestureChange", this._onGesture, false);
  5869. element.addEventListener('mousewheel', this._wheel, false);
  5870. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5871. element.addEventListener('touchstart', this._touchStart, false);
  5872. element.addEventListener('touchmove', this._touchMove, false);
  5873. element.addEventListener('touchend', this._touchEnd, false);
  5874. BABYLON.Tools.RegisterTopRootEvents([
  5875. { name: "keydown", handler: this._onKeyDown },
  5876. { name: "keyup", handler: this._onKeyUp },
  5877. { name: "blur", handler: this._onLostFocus }
  5878. ]);
  5879. };
  5880. ArcRotateCamera.prototype.detachControl = function (element) {
  5881. if (this._attachedElement != element) {
  5882. return;
  5883. }
  5884. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5885. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5886. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5887. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5888. element.removeEventListener("mousemove", this._onMouseMove);
  5889. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5890. element.removeEventListener("MSGestureChange", this._onGesture);
  5891. element.removeEventListener('mousewheel', this._wheel);
  5892. element.removeEventListener('DOMMouseScroll', this._wheel);
  5893. element.removeEventListener('touchstart', this._touchStart);
  5894. element.removeEventListener('touchmove', this._touchMove);
  5895. element.removeEventListener('touchend', this._touchEnd);
  5896. BABYLON.Tools.UnregisterTopRootEvents([
  5897. { name: "keydown", handler: this._onKeyDown },
  5898. { name: "keyup", handler: this._onKeyUp },
  5899. { name: "blur", handler: this._onLostFocus }
  5900. ]);
  5901. this._MSGestureHandler = null;
  5902. this._attachedElement = null;
  5903. if (this._reset) {
  5904. this._reset();
  5905. }
  5906. };
  5907. ArcRotateCamera.prototype._update = function () {
  5908. for (var index = 0; index < this._keys.length; index++) {
  5909. var keyCode = this._keys[index];
  5910. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5911. this.inertialAlphaOffset -= 0.01;
  5912. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5913. this.inertialBetaOffset -= 0.01;
  5914. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5915. this.inertialAlphaOffset += 0.01;
  5916. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5917. this.inertialBetaOffset += 0.01;
  5918. }
  5919. }
  5920. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5921. this.alpha += this.inertialAlphaOffset;
  5922. this.beta += this.inertialBetaOffset;
  5923. this.radius -= this.inertialRadiusOffset;
  5924. this.inertialAlphaOffset *= this.inertia;
  5925. this.inertialBetaOffset *= this.inertia;
  5926. this.inertialRadiusOffset *= this.inertia;
  5927. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5928. this.inertialAlphaOffset = 0;
  5929. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5930. this.inertialBetaOffset = 0;
  5931. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5932. this.inertialRadiusOffset = 0;
  5933. }
  5934. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5935. this.alpha = this.lowerAlphaLimit;
  5936. }
  5937. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5938. this.alpha = this.upperAlphaLimit;
  5939. }
  5940. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5941. this.beta = this.lowerBetaLimit;
  5942. }
  5943. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5944. this.beta = this.upperBetaLimit;
  5945. }
  5946. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5947. this.radius = this.lowerRadiusLimit;
  5948. }
  5949. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5950. this.radius = this.upperRadiusLimit;
  5951. }
  5952. };
  5953. ArcRotateCamera.prototype.setPosition = function (position) {
  5954. var radiusv3 = position.subtract(this._getTargetPosition());
  5955. this.radius = radiusv3.length();
  5956. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5957. if (radiusv3.z < 0) {
  5958. this.alpha = 2 * Math.PI - this.alpha;
  5959. }
  5960. this.beta = Math.acos(radiusv3.y / this.radius);
  5961. };
  5962. ArcRotateCamera.prototype._getViewMatrix = function () {
  5963. var cosa = Math.cos(this.alpha);
  5964. var sina = Math.sin(this.alpha);
  5965. var cosb = Math.cos(this.beta);
  5966. var sinb = Math.sin(this.beta);
  5967. var target = this._getTargetPosition();
  5968. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5969. if (this.checkCollisions) {
  5970. this._collider.radius = this.collisionRadius;
  5971. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5972. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5973. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5974. this.position.copyFrom(this._previousPosition);
  5975. this.alpha = this._previousAlpha;
  5976. this.beta = this._previousBeta;
  5977. this.radius = this._previousRadius;
  5978. if (this.onCollide) {
  5979. this.onCollide(this._collider.collidedMesh);
  5980. }
  5981. }
  5982. }
  5983. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5984. this._previousAlpha = this.alpha;
  5985. this._previousBeta = this.beta;
  5986. this._previousRadius = this.radius;
  5987. this._previousPosition.copyFrom(this.position);
  5988. return this._viewMatrix;
  5989. };
  5990. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  5991. meshes = meshes || this.getScene().meshes;
  5992. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  5993. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  5994. this.radius = distance * this.zoomOnFactor;
  5995. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  5996. };
  5997. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  5998. var meshesOrMinMaxVector;
  5999. var distance;
  6000. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6001. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6002. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6003. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6004. } else {
  6005. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6006. distance = meshesOrMinMaxVectorAndDistance.distance;
  6007. }
  6008. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6009. this.maxZ = distance * 2;
  6010. };
  6011. return ArcRotateCamera;
  6012. })(BABYLON.Camera);
  6013. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6014. })(BABYLON || (BABYLON = {}));
  6015. var BABYLON;
  6016. (function (BABYLON) {
  6017. var Scene = (function () {
  6018. function Scene(engine) {
  6019. this.autoClear = true;
  6020. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6021. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6022. this.forceWireframe = false;
  6023. this.cameraToUseForPointers = null;
  6024. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6025. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6026. this.fogDensity = 0.1;
  6027. this.fogStart = 0;
  6028. this.fogEnd = 1000.0;
  6029. this.lightsEnabled = true;
  6030. this.lights = new Array();
  6031. this.cameras = new Array();
  6032. this.activeCameras = new Array();
  6033. this.meshes = new Array();
  6034. this._geometries = new Array();
  6035. this.materials = new Array();
  6036. this.multiMaterials = new Array();
  6037. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6038. this.texturesEnabled = true;
  6039. this.textures = new Array();
  6040. this.particlesEnabled = true;
  6041. this.particleSystems = new Array();
  6042. this.spriteManagers = new Array();
  6043. this.layers = new Array();
  6044. this.skeletons = new Array();
  6045. this.lensFlareSystems = new Array();
  6046. this.collisionsEnabled = true;
  6047. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6048. this.postProcessesEnabled = true;
  6049. this.renderTargetsEnabled = true;
  6050. this.customRenderTargets = new Array();
  6051. this.importedMeshesFiles = new Array();
  6052. this._actionManagers = new Array();
  6053. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6054. this._totalVertices = 0;
  6055. this._activeVertices = 0;
  6056. this._activeParticles = 0;
  6057. this._lastFrameDuration = 0;
  6058. this._evaluateActiveMeshesDuration = 0;
  6059. this._renderTargetsDuration = 0;
  6060. this._particlesDuration = 0;
  6061. this._renderDuration = 0;
  6062. this._spritesDuration = 0;
  6063. this._animationRatio = 0;
  6064. this._renderId = 0;
  6065. this._executeWhenReadyTimeoutId = -1;
  6066. this._toBeDisposed = new BABYLON.SmartArray(256);
  6067. this._onReadyCallbacks = new Array();
  6068. this._pendingData = [];
  6069. this._onBeforeRenderCallbacks = new Array();
  6070. this._activeMeshes = new BABYLON.SmartArray(256);
  6071. this._processedMaterials = new BABYLON.SmartArray(256);
  6072. this._renderTargets = new BABYLON.SmartArray(256);
  6073. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6074. this._activeSkeletons = new BABYLON.SmartArray(32);
  6075. this._activeAnimatables = new Array();
  6076. this._transformMatrix = BABYLON.Matrix.Zero();
  6077. this._scaledPosition = BABYLON.Vector3.Zero();
  6078. this._scaledVelocity = BABYLON.Vector3.Zero();
  6079. this._engine = engine;
  6080. engine.scenes.push(this);
  6081. this._renderingManager = new BABYLON.RenderingManager(this);
  6082. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6083. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6084. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6085. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6086. this.attachControl();
  6087. }
  6088. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6089. get: function () {
  6090. return this._meshUnderPointer;
  6091. },
  6092. enumerable: true,
  6093. configurable: true
  6094. });
  6095. Object.defineProperty(Scene.prototype, "pointerX", {
  6096. get: function () {
  6097. return this._pointerX;
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. Object.defineProperty(Scene.prototype, "pointerY", {
  6103. get: function () {
  6104. return this._pointerY;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Scene.prototype.getBoundingBoxRenderer = function () {
  6110. return this._boundingBoxRenderer;
  6111. };
  6112. Scene.prototype.getOutlineRenderer = function () {
  6113. return this._outlineRenderer;
  6114. };
  6115. Scene.prototype.getEngine = function () {
  6116. return this._engine;
  6117. };
  6118. Scene.prototype.getTotalVertices = function () {
  6119. return this._totalVertices;
  6120. };
  6121. Scene.prototype.getActiveVertices = function () {
  6122. return this._activeVertices;
  6123. };
  6124. Scene.prototype.getActiveParticles = function () {
  6125. return this._activeParticles;
  6126. };
  6127. Scene.prototype.getLastFrameDuration = function () {
  6128. return this._lastFrameDuration;
  6129. };
  6130. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6131. return this._evaluateActiveMeshesDuration;
  6132. };
  6133. Scene.prototype.getActiveMeshes = function () {
  6134. return this._activeMeshes;
  6135. };
  6136. Scene.prototype.getRenderTargetsDuration = function () {
  6137. return this._renderTargetsDuration;
  6138. };
  6139. Scene.prototype.getRenderDuration = function () {
  6140. return this._renderDuration;
  6141. };
  6142. Scene.prototype.getParticlesDuration = function () {
  6143. return this._particlesDuration;
  6144. };
  6145. Scene.prototype.getSpritesDuration = function () {
  6146. return this._spritesDuration;
  6147. };
  6148. Scene.prototype.getAnimationRatio = function () {
  6149. return this._animationRatio;
  6150. };
  6151. Scene.prototype.getRenderId = function () {
  6152. return this._renderId;
  6153. };
  6154. Scene.prototype._updatePointerPosition = function (evt) {
  6155. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6156. this._pointerX = evt.clientX - canvasRect.left;
  6157. this._pointerY = evt.clientY - canvasRect.top;
  6158. if (this.cameraToUseForPointers) {
  6159. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6160. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6161. }
  6162. };
  6163. Scene.prototype.attachControl = function () {
  6164. var _this = this;
  6165. this._onPointerMove = function (evt) {
  6166. var canvas = _this._engine.getRenderingCanvas();
  6167. _this._updatePointerPosition(evt);
  6168. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6169. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6170. }, false, _this.cameraToUseForPointers);
  6171. if (pickResult.hit) {
  6172. _this._meshUnderPointer = pickResult.pickedMesh;
  6173. _this.setPointerOverMesh(pickResult.pickedMesh);
  6174. canvas.style.cursor = "pointer";
  6175. } else {
  6176. _this.setPointerOverMesh(null);
  6177. canvas.style.cursor = "";
  6178. _this._meshUnderPointer = null;
  6179. }
  6180. };
  6181. this._onPointerDown = function (evt) {
  6182. var predicate = null;
  6183. if (!_this.onPointerDown) {
  6184. predicate = function (mesh) {
  6185. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6186. };
  6187. }
  6188. _this._updatePointerPosition(evt);
  6189. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6190. if (pickResult.hit) {
  6191. if (pickResult.pickedMesh.actionManager) {
  6192. switch (evt.button) {
  6193. case 0:
  6194. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6195. break;
  6196. case 1:
  6197. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6198. break;
  6199. case 2:
  6200. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6201. break;
  6202. }
  6203. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6204. }
  6205. }
  6206. if (_this.onPointerDown) {
  6207. _this.onPointerDown(evt, pickResult);
  6208. }
  6209. };
  6210. this._onKeyDown = function (evt) {
  6211. if (_this.actionManager) {
  6212. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6213. }
  6214. };
  6215. this._onKeyUp = function (evt) {
  6216. if (_this.actionManager) {
  6217. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6218. }
  6219. };
  6220. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6221. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6222. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6223. window.addEventListener("keydown", this._onKeyDown, false);
  6224. window.addEventListener("keyup", this._onKeyUp, false);
  6225. };
  6226. Scene.prototype.detachControl = function () {
  6227. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6228. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6229. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6230. window.removeEventListener("keydown", this._onKeyDown);
  6231. window.removeEventListener("keyup", this._onKeyUp);
  6232. };
  6233. Scene.prototype.isReady = function () {
  6234. if (this._pendingData.length > 0) {
  6235. return false;
  6236. }
  6237. for (var index = 0; index < this._geometries.length; index++) {
  6238. var geometry = this._geometries[index];
  6239. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6240. return false;
  6241. }
  6242. }
  6243. for (index = 0; index < this.meshes.length; index++) {
  6244. var mesh = this.meshes[index];
  6245. if (!mesh.isReady()) {
  6246. return false;
  6247. }
  6248. var mat = mesh.material;
  6249. if (mat) {
  6250. if (!mat.isReady(mesh)) {
  6251. return false;
  6252. }
  6253. }
  6254. }
  6255. return true;
  6256. };
  6257. Scene.prototype.registerBeforeRender = function (func) {
  6258. this._onBeforeRenderCallbacks.push(func);
  6259. };
  6260. Scene.prototype.unregisterBeforeRender = function (func) {
  6261. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6262. if (index > -1) {
  6263. this._onBeforeRenderCallbacks.splice(index, 1);
  6264. }
  6265. };
  6266. Scene.prototype._addPendingData = function (data) {
  6267. this._pendingData.push(data);
  6268. };
  6269. Scene.prototype._removePendingData = function (data) {
  6270. var index = this._pendingData.indexOf(data);
  6271. if (index !== -1) {
  6272. this._pendingData.splice(index, 1);
  6273. }
  6274. };
  6275. Scene.prototype.getWaitingItemsCount = function () {
  6276. return this._pendingData.length;
  6277. };
  6278. Scene.prototype.executeWhenReady = function (func) {
  6279. var _this = this;
  6280. this._onReadyCallbacks.push(func);
  6281. if (this._executeWhenReadyTimeoutId !== -1) {
  6282. return;
  6283. }
  6284. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6285. _this._checkIsReady();
  6286. }, 150);
  6287. };
  6288. Scene.prototype._checkIsReady = function () {
  6289. var _this = this;
  6290. if (this.isReady()) {
  6291. this._onReadyCallbacks.forEach(function (func) {
  6292. func();
  6293. });
  6294. this._onReadyCallbacks = [];
  6295. this._executeWhenReadyTimeoutId = -1;
  6296. return;
  6297. }
  6298. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6299. _this._checkIsReady();
  6300. }, 150);
  6301. };
  6302. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6303. if (speedRatio === undefined) {
  6304. speedRatio = 1.0;
  6305. }
  6306. this.stopAnimation(target);
  6307. if (!animatable) {
  6308. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6309. }
  6310. if (target.animations) {
  6311. animatable.appendAnimations(target, target.animations);
  6312. }
  6313. if (target.getAnimatables) {
  6314. var animatables = target.getAnimatables();
  6315. for (var index = 0; index < animatables.length; index++) {
  6316. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6317. }
  6318. }
  6319. return animatable;
  6320. };
  6321. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6322. if (speedRatio === undefined) {
  6323. speedRatio = 1.0;
  6324. }
  6325. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6326. return animatable;
  6327. };
  6328. Scene.prototype.getAnimatableByTarget = function (target) {
  6329. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6330. if (this._activeAnimatables[index].target === target) {
  6331. return this._activeAnimatables[index];
  6332. }
  6333. }
  6334. return null;
  6335. };
  6336. Scene.prototype.stopAnimation = function (target) {
  6337. var animatable = this.getAnimatableByTarget(target);
  6338. if (animatable) {
  6339. animatable.stop();
  6340. }
  6341. };
  6342. Scene.prototype._animate = function () {
  6343. if (!this._animationStartDate) {
  6344. this._animationStartDate = new Date().getTime();
  6345. }
  6346. var now = new Date().getTime();
  6347. var delay = now - this._animationStartDate;
  6348. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6349. if (!this._activeAnimatables[index]._animate(delay)) {
  6350. this._activeAnimatables.splice(index, 1);
  6351. index--;
  6352. }
  6353. }
  6354. };
  6355. Scene.prototype.getViewMatrix = function () {
  6356. return this._viewMatrix;
  6357. };
  6358. Scene.prototype.getProjectionMatrix = function () {
  6359. return this._projectionMatrix;
  6360. };
  6361. Scene.prototype.getTransformMatrix = function () {
  6362. return this._transformMatrix;
  6363. };
  6364. Scene.prototype.setTransformMatrix = function (view, projection) {
  6365. this._viewMatrix = view;
  6366. this._projectionMatrix = projection;
  6367. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6368. };
  6369. Scene.prototype.setActiveCameraByID = function (id) {
  6370. var camera = this.getCameraByID(id);
  6371. if (camera) {
  6372. this.activeCamera = camera;
  6373. return camera;
  6374. }
  6375. return null;
  6376. };
  6377. Scene.prototype.setActiveCameraByName = function (name) {
  6378. var camera = this.getCameraByName(name);
  6379. if (camera) {
  6380. this.activeCamera = camera;
  6381. return camera;
  6382. }
  6383. return null;
  6384. };
  6385. Scene.prototype.getMaterialByID = function (id) {
  6386. for (var index = 0; index < this.materials.length; index++) {
  6387. if (this.materials[index].id === id) {
  6388. return this.materials[index];
  6389. }
  6390. }
  6391. return null;
  6392. };
  6393. Scene.prototype.getMaterialByName = function (name) {
  6394. for (var index = 0; index < this.materials.length; index++) {
  6395. if (this.materials[index].name === name) {
  6396. return this.materials[index];
  6397. }
  6398. }
  6399. return null;
  6400. };
  6401. Scene.prototype.getCameraByID = function (id) {
  6402. for (var index = 0; index < this.cameras.length; index++) {
  6403. if (this.cameras[index].id === id) {
  6404. return this.cameras[index];
  6405. }
  6406. }
  6407. return null;
  6408. };
  6409. Scene.prototype.getCameraByName = function (name) {
  6410. for (var index = 0; index < this.cameras.length; index++) {
  6411. if (this.cameras[index].name === name) {
  6412. return this.cameras[index];
  6413. }
  6414. }
  6415. return null;
  6416. };
  6417. Scene.prototype.getLightByName = function (name) {
  6418. for (var index = 0; index < this.lights.length; index++) {
  6419. if (this.lights[index].name === name) {
  6420. return this.lights[index];
  6421. }
  6422. }
  6423. return null;
  6424. };
  6425. Scene.prototype.getLightByID = function (id) {
  6426. for (var index = 0; index < this.lights.length; index++) {
  6427. if (this.lights[index].id === id) {
  6428. return this.lights[index];
  6429. }
  6430. }
  6431. return null;
  6432. };
  6433. Scene.prototype.getGeometryByID = function (id) {
  6434. for (var index = 0; index < this._geometries.length; index++) {
  6435. if (this._geometries[index].id === id) {
  6436. return this._geometries[index];
  6437. }
  6438. }
  6439. return null;
  6440. };
  6441. Scene.prototype.pushGeometry = function (geometry, force) {
  6442. if (!force && this.getGeometryByID(geometry.id)) {
  6443. return false;
  6444. }
  6445. this._geometries.push(geometry);
  6446. return true;
  6447. };
  6448. Scene.prototype.getGeometries = function () {
  6449. return this._geometries;
  6450. };
  6451. Scene.prototype.getMeshByID = function (id) {
  6452. for (var index = 0; index < this.meshes.length; index++) {
  6453. if (this.meshes[index].id === id) {
  6454. return this.meshes[index];
  6455. }
  6456. }
  6457. return null;
  6458. };
  6459. Scene.prototype.getLastMeshByID = function (id) {
  6460. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6461. if (this.meshes[index].id === id) {
  6462. return this.meshes[index];
  6463. }
  6464. }
  6465. return null;
  6466. };
  6467. Scene.prototype.getLastEntryByID = function (id) {
  6468. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6469. if (this.meshes[index].id === id) {
  6470. return this.meshes[index];
  6471. }
  6472. }
  6473. for (index = this.cameras.length - 1; index >= 0; index--) {
  6474. if (this.cameras[index].id === id) {
  6475. return this.cameras[index];
  6476. }
  6477. }
  6478. for (index = this.lights.length - 1; index >= 0; index--) {
  6479. if (this.lights[index].id === id) {
  6480. return this.lights[index];
  6481. }
  6482. }
  6483. return null;
  6484. };
  6485. Scene.prototype.getMeshByName = function (name) {
  6486. for (var index = 0; index < this.meshes.length; index++) {
  6487. if (this.meshes[index].name === name) {
  6488. return this.meshes[index];
  6489. }
  6490. }
  6491. return null;
  6492. };
  6493. Scene.prototype.getLastSkeletonByID = function (id) {
  6494. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6495. if (this.skeletons[index].id === id) {
  6496. return this.skeletons[index];
  6497. }
  6498. }
  6499. return null;
  6500. };
  6501. Scene.prototype.getSkeletonById = function (id) {
  6502. for (var index = 0; index < this.skeletons.length; index++) {
  6503. if (this.skeletons[index].id === id) {
  6504. return this.skeletons[index];
  6505. }
  6506. }
  6507. return null;
  6508. };
  6509. Scene.prototype.getSkeletonByName = function (name) {
  6510. for (var index = 0; index < this.skeletons.length; index++) {
  6511. if (this.skeletons[index].name === name) {
  6512. return this.skeletons[index];
  6513. }
  6514. }
  6515. return null;
  6516. };
  6517. Scene.prototype.isActiveMesh = function (mesh) {
  6518. return (this._activeMeshes.indexOf(mesh) !== -1);
  6519. };
  6520. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6521. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6522. var material = subMesh.getMaterial();
  6523. if (mesh.showSubMeshesBoundingBox) {
  6524. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6525. }
  6526. if (material) {
  6527. if (material.getRenderTargetTextures) {
  6528. if (this._processedMaterials.indexOf(material) === -1) {
  6529. this._processedMaterials.push(material);
  6530. this._renderTargets.concat(material.getRenderTargetTextures());
  6531. }
  6532. }
  6533. this._activeVertices += subMesh.verticesCount;
  6534. this._renderingManager.dispatch(subMesh);
  6535. }
  6536. }
  6537. };
  6538. Scene.prototype._evaluateActiveMeshes = function () {
  6539. this._activeMeshes.reset();
  6540. this._renderingManager.reset();
  6541. this._processedMaterials.reset();
  6542. this._activeParticleSystems.reset();
  6543. this._activeSkeletons.reset();
  6544. this._boundingBoxRenderer.reset();
  6545. if (!this._frustumPlanes) {
  6546. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6547. } else {
  6548. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6549. }
  6550. var meshes;
  6551. var len;
  6552. if (this._selectionOctree) {
  6553. var selection = this._selectionOctree.select(this._frustumPlanes);
  6554. meshes = selection.data;
  6555. len = selection.length;
  6556. } else {
  6557. len = this.meshes.length;
  6558. meshes = this.meshes;
  6559. }
  6560. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6561. var mesh = meshes[meshIndex];
  6562. this._totalVertices += mesh.getTotalVertices();
  6563. if (!mesh.isReady()) {
  6564. continue;
  6565. }
  6566. mesh.computeWorldMatrix();
  6567. mesh._preActivate();
  6568. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6569. this._meshesForIntersections.pushNoDuplicate(mesh);
  6570. }
  6571. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6572. this._activeMeshes.push(mesh);
  6573. mesh._activate(this._renderId);
  6574. this._activeMesh(mesh);
  6575. }
  6576. }
  6577. var beforeParticlesDate = new Date().getTime();
  6578. if (this.particlesEnabled) {
  6579. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6580. var particleSystem = this.particleSystems[particleIndex];
  6581. if (!particleSystem.isStarted()) {
  6582. continue;
  6583. }
  6584. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6585. this._activeParticleSystems.push(particleSystem);
  6586. particleSystem.animate();
  6587. }
  6588. }
  6589. }
  6590. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6591. };
  6592. Scene.prototype._activeMesh = function (mesh) {
  6593. if (mesh.skeleton) {
  6594. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6595. }
  6596. if (mesh.showBoundingBox) {
  6597. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6598. }
  6599. if (mesh.subMeshes) {
  6600. var len;
  6601. var subMeshes;
  6602. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6603. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6604. len = intersections.length;
  6605. subMeshes = intersections.data;
  6606. } else {
  6607. subMeshes = mesh.subMeshes;
  6608. len = subMeshes.length;
  6609. }
  6610. for (var subIndex = 0; subIndex < len; subIndex++) {
  6611. var subMesh = subMeshes[subIndex];
  6612. this._evaluateSubMesh(subMesh, mesh);
  6613. }
  6614. }
  6615. };
  6616. Scene.prototype.updateTransformMatrix = function (force) {
  6617. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6618. };
  6619. Scene.prototype._renderForCamera = function (camera) {
  6620. var engine = this._engine;
  6621. this.activeCamera = camera;
  6622. if (!this.activeCamera)
  6623. throw new Error("Active camera not set");
  6624. engine.setViewport(this.activeCamera.viewport);
  6625. this._renderId++;
  6626. this.updateTransformMatrix();
  6627. if (this.beforeCameraRender) {
  6628. this.beforeCameraRender(this.activeCamera);
  6629. }
  6630. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6631. this._evaluateActiveMeshes();
  6632. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6633. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6634. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6635. skeleton.prepare();
  6636. }
  6637. var beforeRenderTargetDate = new Date().getTime();
  6638. if (this.renderTargetsEnabled) {
  6639. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6640. var renderTarget = this._renderTargets.data[renderIndex];
  6641. if (renderTarget._shouldRender()) {
  6642. this._renderId++;
  6643. renderTarget.render();
  6644. }
  6645. }
  6646. this._renderId++;
  6647. }
  6648. if (this._renderTargets.length > 0) {
  6649. engine.restoreDefaultFramebuffer();
  6650. }
  6651. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6652. this.postProcessManager._prepareFrame();
  6653. var beforeRenderDate = new Date().getTime();
  6654. if (this.layers.length) {
  6655. engine.setDepthBuffer(false);
  6656. var layerIndex;
  6657. var layer;
  6658. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6659. layer = this.layers[layerIndex];
  6660. if (layer.isBackground) {
  6661. layer.render();
  6662. }
  6663. }
  6664. engine.setDepthBuffer(true);
  6665. }
  6666. this._renderingManager.render(null, null, true, true);
  6667. this._boundingBoxRenderer.render();
  6668. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6669. this.lensFlareSystems[lensFlareSystemIndex].render();
  6670. }
  6671. if (this.layers.length) {
  6672. engine.setDepthBuffer(false);
  6673. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6674. layer = this.layers[layerIndex];
  6675. if (!layer.isBackground) {
  6676. layer.render();
  6677. }
  6678. }
  6679. engine.setDepthBuffer(true);
  6680. }
  6681. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6682. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6683. this.activeCamera._updateFromScene();
  6684. this._renderTargets.reset();
  6685. if (this.afterCameraRender) {
  6686. this.afterCameraRender(this.activeCamera);
  6687. }
  6688. };
  6689. Scene.prototype._processSubCameras = function (camera) {
  6690. if (camera.subCameras.length == 0) {
  6691. this._renderForCamera(camera);
  6692. return;
  6693. }
  6694. for (var index = 0; index < camera.subCameras.length; index++) {
  6695. this._renderForCamera(camera.subCameras[index]);
  6696. }
  6697. this.activeCamera = camera;
  6698. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6699. this.activeCamera._updateFromScene();
  6700. };
  6701. Scene.prototype._checkIntersections = function () {
  6702. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6703. var sourceMesh = this._meshesForIntersections.data[index];
  6704. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6705. var action = sourceMesh.actionManager.actions[actionIndex];
  6706. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6707. var otherMesh = action.getTriggerParameter();
  6708. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6709. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6710. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6711. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6712. sourceMesh._intersectionsInProgress.push(otherMesh);
  6713. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6714. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6715. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6716. if (indexOfOther > -1) {
  6717. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6718. }
  6719. }
  6720. }
  6721. }
  6722. }
  6723. };
  6724. Scene.prototype.render = function () {
  6725. var startDate = new Date().getTime();
  6726. this._particlesDuration = 0;
  6727. this._spritesDuration = 0;
  6728. this._activeParticles = 0;
  6729. this._renderDuration = 0;
  6730. this._evaluateActiveMeshesDuration = 0;
  6731. this._totalVertices = 0;
  6732. this._activeVertices = 0;
  6733. this._meshesForIntersections.reset();
  6734. if (this.actionManager) {
  6735. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6736. }
  6737. if (this.beforeRender) {
  6738. this.beforeRender();
  6739. }
  6740. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6741. this._onBeforeRenderCallbacks[callbackIndex]();
  6742. }
  6743. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6744. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6745. this._animate();
  6746. if (this._physicsEngine) {
  6747. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6748. }
  6749. var beforeRenderTargetDate = new Date().getTime();
  6750. var engine = this.getEngine();
  6751. if (this.renderTargetsEnabled) {
  6752. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6753. var renderTarget = this.customRenderTargets[customIndex];
  6754. if (renderTarget._shouldRender()) {
  6755. this._renderId++;
  6756. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6757. if (!this.activeCamera)
  6758. throw new Error("Active camera not set");
  6759. engine.setViewport(this.activeCamera.viewport);
  6760. this.updateTransformMatrix();
  6761. renderTarget.render();
  6762. }
  6763. }
  6764. this._renderId++;
  6765. }
  6766. if (this.customRenderTargets.length > 0) {
  6767. engine.restoreDefaultFramebuffer();
  6768. }
  6769. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6770. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6771. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6772. var light = this.lights[lightIndex];
  6773. var shadowGenerator = light.getShadowGenerator();
  6774. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6775. this._renderTargets.push(shadowGenerator.getShadowMap());
  6776. }
  6777. }
  6778. this.postProcessRenderPipelineManager.update();
  6779. if (this.activeCameras.length > 0) {
  6780. var currentRenderId = this._renderId;
  6781. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6782. this._renderId = currentRenderId;
  6783. this._processSubCameras(this.activeCameras[cameraIndex]);
  6784. }
  6785. } else {
  6786. if (!this.activeCamera) {
  6787. throw new Error("No camera defined");
  6788. }
  6789. this._processSubCameras(this.activeCamera);
  6790. }
  6791. this._checkIntersections();
  6792. if (this.afterRender) {
  6793. this.afterRender();
  6794. }
  6795. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6796. this._toBeDisposed.data[index].dispose();
  6797. this._toBeDisposed[index] = null;
  6798. }
  6799. this._toBeDisposed.reset();
  6800. this._lastFrameDuration = new Date().getTime() - startDate;
  6801. };
  6802. Scene.prototype.dispose = function () {
  6803. this.beforeRender = null;
  6804. this.afterRender = null;
  6805. this.skeletons = [];
  6806. this._boundingBoxRenderer.dispose();
  6807. if (this.onDispose) {
  6808. this.onDispose();
  6809. }
  6810. this.detachControl();
  6811. var canvas = this._engine.getRenderingCanvas();
  6812. var index;
  6813. for (index = 0; index < this.cameras.length; index++) {
  6814. this.cameras[index].detachControl(canvas);
  6815. }
  6816. while (this.lights.length) {
  6817. this.lights[0].dispose();
  6818. }
  6819. while (this.meshes.length) {
  6820. this.meshes[0].dispose(true);
  6821. }
  6822. while (this.cameras.length) {
  6823. this.cameras[0].dispose();
  6824. }
  6825. while (this.materials.length) {
  6826. this.materials[0].dispose();
  6827. }
  6828. while (this.particleSystems.length) {
  6829. this.particleSystems[0].dispose();
  6830. }
  6831. while (this.spriteManagers.length) {
  6832. this.spriteManagers[0].dispose();
  6833. }
  6834. while (this.layers.length) {
  6835. this.layers[0].dispose();
  6836. }
  6837. while (this.textures.length) {
  6838. this.textures[0].dispose();
  6839. }
  6840. this.postProcessManager.dispose();
  6841. if (this._physicsEngine) {
  6842. this.disablePhysicsEngine();
  6843. }
  6844. index = this._engine.scenes.indexOf(this);
  6845. if (index > -1) {
  6846. this._engine.scenes.splice(index, 1);
  6847. }
  6848. this._engine.wipeCaches();
  6849. };
  6850. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6851. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6852. position.divideToRef(collider.radius, this._scaledPosition);
  6853. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6854. collider.retry = 0;
  6855. collider.initialVelocity = this._scaledVelocity;
  6856. collider.initialPosition = this._scaledPosition;
  6857. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6858. finalPosition.multiplyInPlace(collider.radius);
  6859. };
  6860. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6861. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6862. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6863. if (collider.retry >= maximumRetry) {
  6864. finalPosition.copyFrom(position);
  6865. return;
  6866. }
  6867. collider._initialize(position, velocity, closeDistance);
  6868. for (var index = 0; index < this.meshes.length; index++) {
  6869. var mesh = this.meshes[index];
  6870. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6871. mesh._checkCollision(collider);
  6872. }
  6873. }
  6874. if (!collider.collisionFound) {
  6875. position.addToRef(velocity, finalPosition);
  6876. return;
  6877. }
  6878. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6879. collider._getResponse(position, velocity);
  6880. }
  6881. if (velocity.length() <= closeDistance) {
  6882. finalPosition.copyFrom(position);
  6883. return;
  6884. }
  6885. collider.retry++;
  6886. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6887. };
  6888. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6889. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6890. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6891. if (!this._selectionOctree) {
  6892. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6893. }
  6894. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6895. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6896. for (var index = 0; index < this.meshes.length; index++) {
  6897. var mesh = this.meshes[index];
  6898. mesh.computeWorldMatrix(true);
  6899. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6900. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6901. BABYLON.Tools.CheckExtends(minBox, min, max);
  6902. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6903. }
  6904. this._selectionOctree.update(min, max, this.meshes);
  6905. return this._selectionOctree;
  6906. };
  6907. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6908. var engine = this._engine;
  6909. if (!camera) {
  6910. if (!this.activeCamera)
  6911. throw new Error("Active camera not set");
  6912. camera = this.activeCamera;
  6913. }
  6914. var cameraViewport = camera.viewport;
  6915. var viewport = cameraViewport.toGlobal(engine);
  6916. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6917. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6918. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6919. };
  6920. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6921. var pickingInfo = null;
  6922. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6923. var mesh = this.meshes[meshIndex];
  6924. if (predicate) {
  6925. if (!predicate(mesh)) {
  6926. continue;
  6927. }
  6928. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6929. continue;
  6930. }
  6931. var world = mesh.getWorldMatrix();
  6932. var ray = rayFunction(world);
  6933. var result = mesh.intersects(ray, fastCheck);
  6934. if (!result || !result.hit)
  6935. continue;
  6936. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6937. continue;
  6938. pickingInfo = result;
  6939. if (fastCheck) {
  6940. break;
  6941. }
  6942. }
  6943. return pickingInfo || new BABYLON.PickingInfo();
  6944. };
  6945. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6946. var _this = this;
  6947. return this._internalPick(function (world) {
  6948. return _this.createPickingRay(x, y, world, camera);
  6949. }, predicate, fastCheck);
  6950. };
  6951. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6952. var _this = this;
  6953. return this._internalPick(function (world) {
  6954. if (!_this._pickWithRayInverseMatrix) {
  6955. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6956. }
  6957. world.invertToRef(_this._pickWithRayInverseMatrix);
  6958. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6959. }, predicate, fastCheck);
  6960. };
  6961. Scene.prototype.setPointerOverMesh = function (mesh) {
  6962. if (this._pointerOverMesh === mesh) {
  6963. return;
  6964. }
  6965. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6966. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6967. }
  6968. this._pointerOverMesh = mesh;
  6969. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6970. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6971. }
  6972. };
  6973. Scene.prototype.getPointerOverMesh = function () {
  6974. return this._pointerOverMesh;
  6975. };
  6976. Scene.prototype.getPhysicsEngine = function () {
  6977. return this._physicsEngine;
  6978. };
  6979. Scene.prototype.enablePhysics = function (gravity, plugin) {
  6980. if (this._physicsEngine) {
  6981. return true;
  6982. }
  6983. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  6984. if (!this._physicsEngine.isSupported()) {
  6985. this._physicsEngine = null;
  6986. return false;
  6987. }
  6988. this._physicsEngine._initialize(gravity);
  6989. return true;
  6990. };
  6991. Scene.prototype.disablePhysicsEngine = function () {
  6992. if (!this._physicsEngine) {
  6993. return;
  6994. }
  6995. this._physicsEngine.dispose();
  6996. this._physicsEngine = undefined;
  6997. };
  6998. Scene.prototype.isPhysicsEnabled = function () {
  6999. return this._physicsEngine !== undefined;
  7000. };
  7001. Scene.prototype.setGravity = function (gravity) {
  7002. if (!this._physicsEngine) {
  7003. return;
  7004. }
  7005. this._physicsEngine._setGravity(gravity);
  7006. };
  7007. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7008. if (parts.parts) {
  7009. options = parts;
  7010. parts = parts.parts;
  7011. }
  7012. if (!this._physicsEngine) {
  7013. return null;
  7014. }
  7015. for (var index = 0; index < parts.length; index++) {
  7016. var mesh = parts[index].mesh;
  7017. mesh._physicImpostor = parts[index].impostor;
  7018. mesh._physicsMass = options.mass / parts.length;
  7019. mesh._physicsFriction = options.friction;
  7020. mesh._physicRestitution = options.restitution;
  7021. }
  7022. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7023. };
  7024. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7025. for (var index = 0; index < compound.parts.length; index++) {
  7026. var mesh = compound.parts[index].mesh;
  7027. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7028. this._physicsEngine._unregisterMesh(mesh);
  7029. }
  7030. };
  7031. Scene.prototype._getByTags = function (list, tagsQuery) {
  7032. if (tagsQuery === undefined) {
  7033. return list;
  7034. }
  7035. var listByTags = [];
  7036. for (var i in list) {
  7037. var item = list[i];
  7038. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7039. listByTags.push(item);
  7040. }
  7041. }
  7042. return listByTags;
  7043. };
  7044. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7045. return this._getByTags(this.meshes, tagsQuery);
  7046. };
  7047. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7048. return this._getByTags(this.cameras, tagsQuery);
  7049. };
  7050. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7051. return this._getByTags(this.lights, tagsQuery);
  7052. };
  7053. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7054. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7055. };
  7056. Scene.FOGMODE_NONE = 0;
  7057. Scene.FOGMODE_EXP = 1;
  7058. Scene.FOGMODE_EXP2 = 2;
  7059. Scene.FOGMODE_LINEAR = 3;
  7060. Scene.MinDeltaTime = 1.0;
  7061. Scene.MaxDeltaTime = 1000.0;
  7062. return Scene;
  7063. })();
  7064. BABYLON.Scene = Scene;
  7065. })(BABYLON || (BABYLON = {}));
  7066. var BABYLON;
  7067. (function (BABYLON) {
  7068. var VertexBuffer = (function () {
  7069. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7070. if (engine instanceof BABYLON.Mesh) {
  7071. this._engine = engine.getScene().getEngine();
  7072. } else {
  7073. this._engine = engine;
  7074. }
  7075. this._updatable = updatable;
  7076. this._data = data;
  7077. if (!postponeInternalCreation) {
  7078. this.create();
  7079. }
  7080. this._kind = kind;
  7081. switch (kind) {
  7082. case VertexBuffer.PositionKind:
  7083. this._strideSize = 3;
  7084. break;
  7085. case VertexBuffer.NormalKind:
  7086. this._strideSize = 3;
  7087. break;
  7088. case VertexBuffer.UVKind:
  7089. this._strideSize = 2;
  7090. break;
  7091. case VertexBuffer.UV2Kind:
  7092. this._strideSize = 2;
  7093. break;
  7094. case VertexBuffer.ColorKind:
  7095. this._strideSize = 3;
  7096. break;
  7097. case VertexBuffer.MatricesIndicesKind:
  7098. this._strideSize = 4;
  7099. break;
  7100. case VertexBuffer.MatricesWeightsKind:
  7101. this._strideSize = 4;
  7102. break;
  7103. }
  7104. }
  7105. VertexBuffer.prototype.isUpdatable = function () {
  7106. return this._updatable;
  7107. };
  7108. VertexBuffer.prototype.getData = function () {
  7109. return this._data;
  7110. };
  7111. VertexBuffer.prototype.getBuffer = function () {
  7112. return this._buffer;
  7113. };
  7114. VertexBuffer.prototype.getStrideSize = function () {
  7115. return this._strideSize;
  7116. };
  7117. VertexBuffer.prototype.create = function (data) {
  7118. if (!data && this._buffer) {
  7119. return;
  7120. }
  7121. data = data || this._data;
  7122. if (!this._buffer) {
  7123. if (this._updatable) {
  7124. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7125. } else {
  7126. this._buffer = this._engine.createVertexBuffer(data);
  7127. }
  7128. }
  7129. if (this._updatable) {
  7130. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7131. this._data = data;
  7132. }
  7133. };
  7134. VertexBuffer.prototype.update = function (data) {
  7135. this.create(data);
  7136. };
  7137. VertexBuffer.prototype.updateDirectly = function (data) {
  7138. if (!this._buffer) {
  7139. return;
  7140. }
  7141. if (this._updatable) {
  7142. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7143. this._data = null;
  7144. }
  7145. };
  7146. VertexBuffer.prototype.dispose = function () {
  7147. if (!this._buffer) {
  7148. return;
  7149. }
  7150. if (this._engine._releaseBuffer(this._buffer)) {
  7151. this._buffer = null;
  7152. }
  7153. };
  7154. Object.defineProperty(VertexBuffer, "PositionKind", {
  7155. get: function () {
  7156. return VertexBuffer._PositionKind;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(VertexBuffer, "NormalKind", {
  7162. get: function () {
  7163. return VertexBuffer._NormalKind;
  7164. },
  7165. enumerable: true,
  7166. configurable: true
  7167. });
  7168. Object.defineProperty(VertexBuffer, "UVKind", {
  7169. get: function () {
  7170. return VertexBuffer._UVKind;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7176. get: function () {
  7177. return VertexBuffer._UV2Kind;
  7178. },
  7179. enumerable: true,
  7180. configurable: true
  7181. });
  7182. Object.defineProperty(VertexBuffer, "ColorKind", {
  7183. get: function () {
  7184. return VertexBuffer._ColorKind;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7190. get: function () {
  7191. return VertexBuffer._MatricesIndicesKind;
  7192. },
  7193. enumerable: true,
  7194. configurable: true
  7195. });
  7196. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7197. get: function () {
  7198. return VertexBuffer._MatricesWeightsKind;
  7199. },
  7200. enumerable: true,
  7201. configurable: true
  7202. });
  7203. VertexBuffer._PositionKind = "position";
  7204. VertexBuffer._NormalKind = "normal";
  7205. VertexBuffer._UVKind = "uv";
  7206. VertexBuffer._UV2Kind = "uv2";
  7207. VertexBuffer._ColorKind = "color";
  7208. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7209. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7210. return VertexBuffer;
  7211. })();
  7212. BABYLON.VertexBuffer = VertexBuffer;
  7213. })(BABYLON || (BABYLON = {}));
  7214. var __extends = this.__extends || function (d, b) {
  7215. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7216. function __() { this.constructor = d; }
  7217. __.prototype = b.prototype;
  7218. d.prototype = new __();
  7219. };
  7220. var BABYLON;
  7221. (function (BABYLON) {
  7222. var AbstractMesh = (function (_super) {
  7223. __extends(AbstractMesh, _super);
  7224. function AbstractMesh(name, scene) {
  7225. _super.call(this, name, scene);
  7226. this.position = new BABYLON.Vector3(0, 0, 0);
  7227. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7228. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7229. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7230. this.visibility = 1.0;
  7231. this.infiniteDistance = false;
  7232. this.isVisible = true;
  7233. this.isPickable = true;
  7234. this.showBoundingBox = false;
  7235. this.showSubMeshesBoundingBox = false;
  7236. this.onDispose = null;
  7237. this.checkCollisions = false;
  7238. this.isBlocker = false;
  7239. this.renderingGroupId = 0;
  7240. this.receiveShadows = false;
  7241. this.renderOutline = false;
  7242. this.outlineColor = BABYLON.Color3.Red();
  7243. this.outlineWidth = 0.02;
  7244. this.useOctreeForRenderingSelection = true;
  7245. this.useOctreeForPicking = true;
  7246. this.useOctreeForCollisions = true;
  7247. this.layerMask = 0xFFFFFFFF;
  7248. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7249. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7250. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7251. this._collider = new BABYLON.Collider();
  7252. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7253. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7254. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7255. this._localScaling = BABYLON.Matrix.Zero();
  7256. this._localRotation = BABYLON.Matrix.Zero();
  7257. this._localTranslation = BABYLON.Matrix.Zero();
  7258. this._localBillboard = BABYLON.Matrix.Zero();
  7259. this._localPivotScaling = BABYLON.Matrix.Zero();
  7260. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7261. this._localWorld = BABYLON.Matrix.Zero();
  7262. this._worldMatrix = BABYLON.Matrix.Zero();
  7263. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7264. this._absolutePosition = BABYLON.Vector3.Zero();
  7265. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7266. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7267. this._isDirty = false;
  7268. this._pivotMatrix = BABYLON.Matrix.Identity();
  7269. this._isDisposed = false;
  7270. this._renderId = 0;
  7271. this._intersectionsInProgress = new Array();
  7272. scene.meshes.push(this);
  7273. }
  7274. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7275. get: function () {
  7276. return AbstractMesh._BILLBOARDMODE_NONE;
  7277. },
  7278. enumerable: true,
  7279. configurable: true
  7280. });
  7281. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7282. get: function () {
  7283. return AbstractMesh._BILLBOARDMODE_X;
  7284. },
  7285. enumerable: true,
  7286. configurable: true
  7287. });
  7288. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7289. get: function () {
  7290. return AbstractMesh._BILLBOARDMODE_Y;
  7291. },
  7292. enumerable: true,
  7293. configurable: true
  7294. });
  7295. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7296. get: function () {
  7297. return AbstractMesh._BILLBOARDMODE_Z;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7303. get: function () {
  7304. return AbstractMesh._BILLBOARDMODE_ALL;
  7305. },
  7306. enumerable: true,
  7307. configurable: true
  7308. });
  7309. AbstractMesh.prototype.getTotalVertices = function () {
  7310. return 0;
  7311. };
  7312. AbstractMesh.prototype.getIndices = function () {
  7313. return null;
  7314. };
  7315. AbstractMesh.prototype.getVerticesData = function (kind) {
  7316. return null;
  7317. };
  7318. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7319. return false;
  7320. };
  7321. AbstractMesh.prototype.getBoundingInfo = function () {
  7322. if (!this._boundingInfo) {
  7323. this._updateBoundingInfo();
  7324. }
  7325. return this._boundingInfo;
  7326. };
  7327. AbstractMesh.prototype._preActivate = function () {
  7328. };
  7329. AbstractMesh.prototype._activate = function (renderId) {
  7330. this._renderId = renderId;
  7331. };
  7332. AbstractMesh.prototype.getWorldMatrix = function () {
  7333. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7334. this.computeWorldMatrix();
  7335. }
  7336. return this._worldMatrix;
  7337. };
  7338. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7339. get: function () {
  7340. return this._worldMatrix;
  7341. },
  7342. enumerable: true,
  7343. configurable: true
  7344. });
  7345. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7346. get: function () {
  7347. return this._absolutePosition;
  7348. },
  7349. enumerable: true,
  7350. configurable: true
  7351. });
  7352. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7353. if (!this.rotationQuaternion) {
  7354. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7355. this.rotation = BABYLON.Vector3.Zero();
  7356. }
  7357. if (!space || space == 0 /* LOCAL */) {
  7358. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7359. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7360. } else {
  7361. if (this.parent) {
  7362. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7363. invertParentWorldMatrix.invert();
  7364. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7365. }
  7366. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7367. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7368. }
  7369. };
  7370. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7371. var displacementVector = axis.scale(distance);
  7372. if (!space || space == 0 /* LOCAL */) {
  7373. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7374. this.setPositionWithLocalVector(tempV3);
  7375. } else {
  7376. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7377. }
  7378. };
  7379. AbstractMesh.prototype.getAbsolutePosition = function () {
  7380. this.computeWorldMatrix();
  7381. return this._absolutePosition;
  7382. };
  7383. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7384. if (!absolutePosition) {
  7385. return;
  7386. }
  7387. var absolutePositionX;
  7388. var absolutePositionY;
  7389. var absolutePositionZ;
  7390. if (absolutePosition.x === undefined) {
  7391. if (arguments.length < 3) {
  7392. return;
  7393. }
  7394. absolutePositionX = arguments[0];
  7395. absolutePositionY = arguments[1];
  7396. absolutePositionZ = arguments[2];
  7397. } else {
  7398. absolutePositionX = absolutePosition.x;
  7399. absolutePositionY = absolutePosition.y;
  7400. absolutePositionZ = absolutePosition.z;
  7401. }
  7402. if (this.parent) {
  7403. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7404. invertParentWorldMatrix.invert();
  7405. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7406. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7407. } else {
  7408. this.position.x = absolutePositionX;
  7409. this.position.y = absolutePositionY;
  7410. this.position.z = absolutePositionZ;
  7411. }
  7412. };
  7413. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7414. this._pivotMatrix = matrix;
  7415. this._cache.pivotMatrixUpdated = true;
  7416. };
  7417. AbstractMesh.prototype.getPivotMatrix = function () {
  7418. return this._pivotMatrix;
  7419. };
  7420. AbstractMesh.prototype._isSynchronized = function () {
  7421. if (this._isDirty) {
  7422. return false;
  7423. }
  7424. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7425. return false;
  7426. if (this._cache.pivotMatrixUpdated) {
  7427. return false;
  7428. }
  7429. if (this.infiniteDistance) {
  7430. return false;
  7431. }
  7432. if (!this._cache.position.equals(this.position))
  7433. return false;
  7434. if (this.rotationQuaternion) {
  7435. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7436. return false;
  7437. } else {
  7438. if (!this._cache.rotation.equals(this.rotation))
  7439. return false;
  7440. }
  7441. if (!this._cache.scaling.equals(this.scaling))
  7442. return false;
  7443. return true;
  7444. };
  7445. AbstractMesh.prototype._initCache = function () {
  7446. _super.prototype._initCache.call(this);
  7447. this._cache.localMatrixUpdated = false;
  7448. this._cache.position = BABYLON.Vector3.Zero();
  7449. this._cache.scaling = BABYLON.Vector3.Zero();
  7450. this._cache.rotation = BABYLON.Vector3.Zero();
  7451. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7452. };
  7453. AbstractMesh.prototype.markAsDirty = function (property) {
  7454. if (property === "rotation") {
  7455. this.rotationQuaternion = null;
  7456. }
  7457. this._currentRenderId = Number.MAX_VALUE;
  7458. this._isDirty = true;
  7459. };
  7460. AbstractMesh.prototype._updateBoundingInfo = function () {
  7461. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7462. this._boundingInfo._update(this.worldMatrixFromCache);
  7463. if (!this.subMeshes) {
  7464. return;
  7465. }
  7466. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7467. var subMesh = this.subMeshes[subIndex];
  7468. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7469. }
  7470. };
  7471. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7472. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7473. return this._worldMatrix;
  7474. }
  7475. this._cache.position.copyFrom(this.position);
  7476. this._cache.scaling.copyFrom(this.scaling);
  7477. this._cache.pivotMatrixUpdated = false;
  7478. this._currentRenderId = this.getScene().getRenderId();
  7479. this._isDirty = false;
  7480. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7481. if (this.rotationQuaternion) {
  7482. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7483. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7484. } else {
  7485. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7486. this._cache.rotation.copyFrom(this.rotation);
  7487. }
  7488. if (this.infiniteDistance && !this.parent) {
  7489. var camera = this.getScene().activeCamera;
  7490. var cameraWorldMatrix = camera.getWorldMatrix();
  7491. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7492. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7493. } else {
  7494. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7495. }
  7496. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7497. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7498. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7499. var localPosition = this.position.clone();
  7500. var zero = this.getScene().activeCamera.position.clone();
  7501. if (this.parent && this.parent.position) {
  7502. localPosition.addInPlace(this.parent.position);
  7503. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7504. }
  7505. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7506. zero = this.getScene().activeCamera.position;
  7507. } else {
  7508. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7509. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7510. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7511. zero.y = localPosition.y + 0.001;
  7512. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7513. zero.z = localPosition.z + 0.001;
  7514. }
  7515. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7516. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7517. this._localBillboard.invert();
  7518. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7519. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7520. }
  7521. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7522. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7523. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7524. } else {
  7525. this._worldMatrix.copyFrom(this._localWorld);
  7526. }
  7527. this._updateBoundingInfo();
  7528. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7529. return this._worldMatrix;
  7530. };
  7531. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7532. this.computeWorldMatrix();
  7533. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7534. };
  7535. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7536. this.computeWorldMatrix();
  7537. var invLocalWorldMatrix = this._localWorld.clone();
  7538. invLocalWorldMatrix.invert();
  7539. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7540. };
  7541. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7542. this.computeWorldMatrix();
  7543. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7544. };
  7545. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7546. yawCor = yawCor || 0;
  7547. pitchCor = pitchCor || 0;
  7548. rollCor = rollCor || 0;
  7549. var dv = targetPoint.subtract(this.position);
  7550. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7551. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7552. var pitch = Math.atan2(dv.y, len);
  7553. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7554. };
  7555. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7556. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7557. return false;
  7558. }
  7559. return true;
  7560. };
  7561. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7562. if (!this._boundingInfo || !mesh._boundingInfo) {
  7563. return false;
  7564. }
  7565. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7566. };
  7567. AbstractMesh.prototype.intersectsPoint = function (point) {
  7568. if (!this._boundingInfo) {
  7569. return false;
  7570. }
  7571. return this._boundingInfo.intersectsPoint(point);
  7572. };
  7573. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7574. var physicsEngine = this.getScene().getPhysicsEngine();
  7575. if (!physicsEngine) {
  7576. return;
  7577. }
  7578. if (impostor.impostor) {
  7579. options = impostor;
  7580. impostor = impostor.impostor;
  7581. }
  7582. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7583. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7584. physicsEngine._unregisterMesh(this);
  7585. return;
  7586. }
  7587. options.mass = options.mass || 0;
  7588. options.friction = options.friction || 0.2;
  7589. options.restitution = options.restitution || 0.9;
  7590. this._physicImpostor = impostor;
  7591. this._physicsMass = options.mass;
  7592. this._physicsFriction = options.friction;
  7593. this._physicRestitution = options.restitution;
  7594. physicsEngine._registerMesh(this, impostor, options);
  7595. };
  7596. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7597. if (!this._physicImpostor) {
  7598. return BABYLON.PhysicsEngine.NoImpostor;
  7599. }
  7600. return this._physicImpostor;
  7601. };
  7602. AbstractMesh.prototype.getPhysicsMass = function () {
  7603. if (!this._physicsMass) {
  7604. return 0;
  7605. }
  7606. return this._physicsMass;
  7607. };
  7608. AbstractMesh.prototype.getPhysicsFriction = function () {
  7609. if (!this._physicsFriction) {
  7610. return 0;
  7611. }
  7612. return this._physicsFriction;
  7613. };
  7614. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7615. if (!this._physicRestitution) {
  7616. return 0;
  7617. }
  7618. return this._physicRestitution;
  7619. };
  7620. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7621. if (!this._physicImpostor) {
  7622. return;
  7623. }
  7624. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7625. };
  7626. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7627. if (!this._physicImpostor) {
  7628. return;
  7629. }
  7630. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7631. };
  7632. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7633. if (!this._physicImpostor) {
  7634. return;
  7635. }
  7636. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7637. };
  7638. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7639. var globalPosition = this.getAbsolutePosition();
  7640. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7641. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7642. this._collider.radius = this.ellipsoid;
  7643. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7644. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7645. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7646. this.position.addInPlace(this._diffPositionForCollisions);
  7647. }
  7648. };
  7649. /**
  7650. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7651. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7652. */
  7653. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7654. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7655. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7656. if (!this._submeshesOctree) {
  7657. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7658. }
  7659. this.computeWorldMatrix(true);
  7660. var bbox = this.getBoundingInfo().boundingBox;
  7661. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7662. return this._submeshesOctree;
  7663. };
  7664. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7665. this._generatePointsArray();
  7666. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7667. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7668. subMesh._lastColliderWorldVertices = [];
  7669. subMesh._trianglePlanes = [];
  7670. var start = subMesh.verticesStart;
  7671. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7672. for (var i = start; i < end; i++) {
  7673. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7674. }
  7675. }
  7676. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7677. };
  7678. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7679. var subMeshes;
  7680. var len;
  7681. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7682. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7683. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7684. len = intersections.length;
  7685. subMeshes = intersections.data;
  7686. } else {
  7687. subMeshes = this.subMeshes;
  7688. len = subMeshes.length;
  7689. }
  7690. for (var index = 0; index < len; index++) {
  7691. var subMesh = subMeshes[index];
  7692. if (len > 1 && !subMesh._checkCollision(collider))
  7693. continue;
  7694. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7695. }
  7696. };
  7697. AbstractMesh.prototype._checkCollision = function (collider) {
  7698. if (!this._boundingInfo._checkCollision(collider))
  7699. return;
  7700. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7701. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7702. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7703. };
  7704. AbstractMesh.prototype._generatePointsArray = function () {
  7705. return false;
  7706. };
  7707. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7708. var pickingInfo = new BABYLON.PickingInfo();
  7709. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7710. return pickingInfo;
  7711. }
  7712. if (!this._generatePointsArray()) {
  7713. return pickingInfo;
  7714. }
  7715. var intersectInfo = null;
  7716. var subMeshes;
  7717. var len;
  7718. if (this._submeshesOctree && this.useOctreeForPicking) {
  7719. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7720. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7721. len = intersections.length;
  7722. subMeshes = intersections.data;
  7723. } else {
  7724. subMeshes = this.subMeshes;
  7725. len = subMeshes.length;
  7726. }
  7727. for (var index = 0; index < len; index++) {
  7728. var subMesh = subMeshes[index];
  7729. if (len > 1 && !subMesh.canIntersects(ray))
  7730. continue;
  7731. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7732. if (currentIntersectInfo) {
  7733. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7734. intersectInfo = currentIntersectInfo;
  7735. if (fastCheck) {
  7736. break;
  7737. }
  7738. }
  7739. }
  7740. }
  7741. if (intersectInfo) {
  7742. var world = this.getWorldMatrix();
  7743. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7744. var direction = ray.direction.clone();
  7745. direction.normalize();
  7746. direction = direction.scale(intersectInfo.distance);
  7747. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7748. var pickedPoint = worldOrigin.add(worldDirection);
  7749. pickingInfo.hit = true;
  7750. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7751. pickingInfo.pickedPoint = pickedPoint;
  7752. pickingInfo.pickedMesh = this;
  7753. pickingInfo.bu = intersectInfo.bu;
  7754. pickingInfo.bv = intersectInfo.bv;
  7755. pickingInfo.faceId = intersectInfo.faceId;
  7756. return pickingInfo;
  7757. }
  7758. return pickingInfo;
  7759. };
  7760. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7761. return null;
  7762. };
  7763. AbstractMesh.prototype.releaseSubMeshes = function () {
  7764. if (this.subMeshes) {
  7765. while (this.subMeshes.length) {
  7766. this.subMeshes[0].dispose();
  7767. }
  7768. } else {
  7769. this.subMeshes = new Array();
  7770. }
  7771. };
  7772. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7773. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7774. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7775. }
  7776. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7777. var other = this._intersectionsInProgress[index];
  7778. var pos = other._intersectionsInProgress.indexOf(this);
  7779. other._intersectionsInProgress.splice(pos, 1);
  7780. }
  7781. this._intersectionsInProgress = [];
  7782. this.releaseSubMeshes();
  7783. var index = this.getScene().meshes.indexOf(this);
  7784. if (index != -1) {
  7785. this.getScene().meshes.splice(index, 1);
  7786. }
  7787. if (!doNotRecurse) {
  7788. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7789. if (this.getScene().particleSystems[index].emitter == this) {
  7790. this.getScene().particleSystems[index].dispose();
  7791. index--;
  7792. }
  7793. }
  7794. var objects = this.getScene().meshes.slice(0);
  7795. for (index = 0; index < objects.length; index++) {
  7796. if (objects[index].parent == this) {
  7797. objects[index].dispose();
  7798. }
  7799. }
  7800. } else {
  7801. for (index = 0; index < this.getScene().meshes.length; index++) {
  7802. var obj = this.getScene().meshes[index];
  7803. if (obj.parent === this) {
  7804. obj.parent = null;
  7805. obj.computeWorldMatrix(true);
  7806. }
  7807. }
  7808. }
  7809. this._isDisposed = true;
  7810. if (this.onDispose) {
  7811. this.onDispose();
  7812. }
  7813. };
  7814. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7815. AbstractMesh._BILLBOARDMODE_X = 1;
  7816. AbstractMesh._BILLBOARDMODE_Y = 2;
  7817. AbstractMesh._BILLBOARDMODE_Z = 4;
  7818. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7819. return AbstractMesh;
  7820. })(BABYLON.Node);
  7821. BABYLON.AbstractMesh = AbstractMesh;
  7822. })(BABYLON || (BABYLON = {}));
  7823. var __extends = this.__extends || function (d, b) {
  7824. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7825. function __() { this.constructor = d; }
  7826. __.prototype = b.prototype;
  7827. d.prototype = new __();
  7828. };
  7829. var BABYLON;
  7830. (function (BABYLON) {
  7831. var _InstancesBatch = (function () {
  7832. function _InstancesBatch() {
  7833. this.mustReturn = false;
  7834. this.visibleInstances = new Array();
  7835. this.renderSelf = new Array();
  7836. }
  7837. return _InstancesBatch;
  7838. })();
  7839. BABYLON._InstancesBatch = _InstancesBatch;
  7840. var Mesh = (function (_super) {
  7841. __extends(Mesh, _super);
  7842. function Mesh(name, scene) {
  7843. _super.call(this, name, scene);
  7844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7845. this.instances = new Array();
  7846. this._onBeforeRenderCallbacks = new Array();
  7847. this._onAfterRenderCallbacks = new Array();
  7848. this._visibleInstances = {};
  7849. this._renderIdForInstances = new Array();
  7850. this._batchCache = new _InstancesBatch();
  7851. this._instancesBufferSize = 32 * 16 * 4;
  7852. }
  7853. Mesh.prototype.getTotalVertices = function () {
  7854. if (!this._geometry) {
  7855. return 0;
  7856. }
  7857. return this._geometry.getTotalVertices();
  7858. };
  7859. Mesh.prototype.getVerticesData = function (kind) {
  7860. if (!this._geometry) {
  7861. return null;
  7862. }
  7863. return this._geometry.getVerticesData(kind);
  7864. };
  7865. Mesh.prototype.getVertexBuffer = function (kind) {
  7866. if (!this._geometry) {
  7867. return undefined;
  7868. }
  7869. return this._geometry.getVertexBuffer(kind);
  7870. };
  7871. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7872. if (!this._geometry) {
  7873. if (this._delayInfo) {
  7874. return this._delayInfo.indexOf(kind) !== -1;
  7875. }
  7876. return false;
  7877. }
  7878. return this._geometry.isVerticesDataPresent(kind);
  7879. };
  7880. Mesh.prototype.getVerticesDataKinds = function () {
  7881. if (!this._geometry) {
  7882. var result = [];
  7883. if (this._delayInfo) {
  7884. for (var kind in this._delayInfo) {
  7885. result.push(kind);
  7886. }
  7887. }
  7888. return result;
  7889. }
  7890. return this._geometry.getVerticesDataKinds();
  7891. };
  7892. Mesh.prototype.getTotalIndices = function () {
  7893. if (!this._geometry) {
  7894. return 0;
  7895. }
  7896. return this._geometry.getTotalIndices();
  7897. };
  7898. Mesh.prototype.getIndices = function () {
  7899. if (!this._geometry) {
  7900. return [];
  7901. }
  7902. return this._geometry.getIndices();
  7903. };
  7904. Mesh.prototype.isReady = function () {
  7905. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7906. return false;
  7907. }
  7908. return _super.prototype.isReady.call(this);
  7909. };
  7910. Mesh.prototype.isDisposed = function () {
  7911. return this._isDisposed;
  7912. };
  7913. Mesh.prototype._preActivate = function () {
  7914. var sceneRenderId = this.getScene().getRenderId();
  7915. if (this._preActivateId == sceneRenderId) {
  7916. return;
  7917. }
  7918. this._preActivateId = sceneRenderId;
  7919. this._visibleInstances = null;
  7920. };
  7921. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7922. if (!this._visibleInstances) {
  7923. this._visibleInstances = {};
  7924. this._visibleInstances.defaultRenderId = renderId;
  7925. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7926. }
  7927. if (!this._visibleInstances[renderId]) {
  7928. this._visibleInstances[renderId] = new Array();
  7929. }
  7930. this._visibleInstances[renderId].push(instance);
  7931. };
  7932. Mesh.prototype.refreshBoundingInfo = function () {
  7933. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7934. if (data) {
  7935. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7936. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7937. }
  7938. if (this.subMeshes) {
  7939. for (var index = 0; index < this.subMeshes.length; index++) {
  7940. this.subMeshes[index].refreshBoundingInfo();
  7941. }
  7942. }
  7943. this._updateBoundingInfo();
  7944. };
  7945. Mesh.prototype._createGlobalSubMesh = function () {
  7946. var totalVertices = this.getTotalVertices();
  7947. if (!totalVertices || !this.getIndices()) {
  7948. return null;
  7949. }
  7950. this.releaseSubMeshes();
  7951. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7952. };
  7953. Mesh.prototype.subdivide = function (count) {
  7954. if (count < 1) {
  7955. return;
  7956. }
  7957. var totalIndices = this.getTotalIndices();
  7958. var subdivisionSize = (totalIndices / count) | 0;
  7959. var offset = 0;
  7960. while (subdivisionSize % 3 != 0) {
  7961. subdivisionSize++;
  7962. }
  7963. this.releaseSubMeshes();
  7964. for (var index = 0; index < count; index++) {
  7965. if (offset >= totalIndices) {
  7966. break;
  7967. }
  7968. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7969. offset += subdivisionSize;
  7970. }
  7971. this.synchronizeInstances();
  7972. };
  7973. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7974. if (kind instanceof Array) {
  7975. var temp = data;
  7976. data = kind;
  7977. kind = temp;
  7978. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  7979. }
  7980. if (!this._geometry) {
  7981. var vertexData = new BABYLON.VertexData();
  7982. vertexData.set(data, kind);
  7983. var scene = this.getScene();
  7984. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  7985. } else {
  7986. this._geometry.setVerticesData(kind, data, updatable);
  7987. }
  7988. };
  7989. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  7990. if (!this._geometry) {
  7991. return;
  7992. }
  7993. if (!makeItUnique) {
  7994. this._geometry.updateVerticesData(kind, data, updateExtends);
  7995. } else {
  7996. this.makeGeometryUnique();
  7997. this.updateVerticesData(kind, data, updateExtends, false);
  7998. }
  7999. };
  8000. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8001. if (!this._geometry) {
  8002. return;
  8003. }
  8004. if (!makeItUnique) {
  8005. this._geometry.updateVerticesDataDirectly(kind, data);
  8006. } else {
  8007. this.makeGeometryUnique();
  8008. this.updateVerticesDataDirectly(kind, data, false);
  8009. }
  8010. };
  8011. Mesh.prototype.makeGeometryUnique = function () {
  8012. if (!this._geometry) {
  8013. return;
  8014. }
  8015. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8016. geometry.applyToMesh(this);
  8017. };
  8018. Mesh.prototype.setIndices = function (indices) {
  8019. if (!this._geometry) {
  8020. var vertexData = new BABYLON.VertexData();
  8021. vertexData.indices = indices;
  8022. var scene = this.getScene();
  8023. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8024. } else {
  8025. this._geometry.setIndices(indices);
  8026. }
  8027. };
  8028. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  8029. var engine = this.getScene().getEngine();
  8030. var indexToBind = this._geometry.getIndexBuffer();
  8031. if (wireframe) {
  8032. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8033. }
  8034. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8035. };
  8036. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  8037. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8038. return;
  8039. }
  8040. var engine = this.getScene().getEngine();
  8041. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8042. };
  8043. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  8044. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8045. return;
  8046. }
  8047. var engine = this.getScene().getEngine();
  8048. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8049. };
  8050. Mesh.prototype.registerBeforeRender = function (func) {
  8051. this._onBeforeRenderCallbacks.push(func);
  8052. };
  8053. Mesh.prototype.unregisterBeforeRender = function (func) {
  8054. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8055. if (index > -1) {
  8056. this._onBeforeRenderCallbacks.splice(index, 1);
  8057. }
  8058. };
  8059. Mesh.prototype.registerAfterRender = function (func) {
  8060. this._onAfterRenderCallbacks.push(func);
  8061. };
  8062. Mesh.prototype.unregisterAfterRender = function (func) {
  8063. var index = this._onAfterRenderCallbacks.indexOf(func);
  8064. if (index > -1) {
  8065. this._onAfterRenderCallbacks.splice(index, 1);
  8066. }
  8067. };
  8068. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8069. var scene = this.getScene();
  8070. this._batchCache.mustReturn = false;
  8071. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8072. this._batchCache.visibleInstances[subMeshId] = null;
  8073. if (this._visibleInstances) {
  8074. var currentRenderId = scene.getRenderId();
  8075. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8076. var selfRenderId = this._renderId;
  8077. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8078. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8079. currentRenderId = this._visibleInstances.defaultRenderId;
  8080. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8081. }
  8082. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8083. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8084. this._batchCache.mustReturn = true;
  8085. return this._batchCache;
  8086. }
  8087. if (currentRenderId !== selfRenderId) {
  8088. this._batchCache.renderSelf[subMeshId] = false;
  8089. }
  8090. }
  8091. this._renderIdForInstances[subMeshId] = currentRenderId;
  8092. }
  8093. return this._batchCache;
  8094. };
  8095. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8096. var matricesCount = this.instances.length + 1;
  8097. var bufferSize = matricesCount * 16 * 4;
  8098. while (this._instancesBufferSize < bufferSize) {
  8099. this._instancesBufferSize *= 2;
  8100. }
  8101. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8102. if (this._worldMatricesInstancesBuffer) {
  8103. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8104. }
  8105. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8106. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8107. }
  8108. var offset = 0;
  8109. var instancesCount = 0;
  8110. var world = this.getWorldMatrix();
  8111. if (batch.renderSelf[subMesh._id]) {
  8112. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8113. offset += 16;
  8114. instancesCount++;
  8115. }
  8116. var visibleInstances = batch.visibleInstances[subMesh._id];
  8117. if (visibleInstances) {
  8118. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8119. var instance = visibleInstances[instanceIndex];
  8120. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8121. offset += 16;
  8122. instancesCount++;
  8123. }
  8124. }
  8125. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8126. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8127. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8128. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8129. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8130. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8131. this._draw(subMesh, !wireFrame, instancesCount);
  8132. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8133. };
  8134. Mesh.prototype.render = function (subMesh) {
  8135. var scene = this.getScene();
  8136. var batch = this._getInstancesRenderList(subMesh._id);
  8137. if (batch.mustReturn) {
  8138. return;
  8139. }
  8140. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8141. return;
  8142. }
  8143. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8144. this._onBeforeRenderCallbacks[callbackIndex]();
  8145. }
  8146. var engine = scene.getEngine();
  8147. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8148. var effectiveMaterial = subMesh.getMaterial();
  8149. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8150. return;
  8151. }
  8152. var savedDepthWrite = engine.getDepthWrite();
  8153. if (this.renderOutline) {
  8154. engine.setDepthWrite(false);
  8155. scene.getOutlineRenderer().render(subMesh, batch);
  8156. }
  8157. effectiveMaterial._preBind();
  8158. var effect = effectiveMaterial.getEffect();
  8159. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8160. this._bind(subMesh, effect, wireFrame);
  8161. var world = this.getWorldMatrix();
  8162. effectiveMaterial.bind(world, this);
  8163. if (hardwareInstancedRendering) {
  8164. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8165. } else {
  8166. if (batch.renderSelf[subMesh._id]) {
  8167. this._draw(subMesh, !wireFrame);
  8168. }
  8169. if (batch.visibleInstances[subMesh._id]) {
  8170. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8171. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8172. world = instance.getWorldMatrix();
  8173. effectiveMaterial.bindOnlyWorldMatrix(world);
  8174. this._draw(subMesh, !wireFrame);
  8175. }
  8176. }
  8177. }
  8178. effectiveMaterial.unbind();
  8179. if (this.renderOutline && savedDepthWrite) {
  8180. engine.setDepthWrite(true);
  8181. engine.setColorWrite(false);
  8182. scene.getOutlineRenderer().render(subMesh, batch);
  8183. engine.setColorWrite(true);
  8184. }
  8185. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8186. this._onAfterRenderCallbacks[callbackIndex]();
  8187. }
  8188. };
  8189. Mesh.prototype.getEmittedParticleSystems = function () {
  8190. var results = new Array();
  8191. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8192. var particleSystem = this.getScene().particleSystems[index];
  8193. if (particleSystem.emitter === this) {
  8194. results.push(particleSystem);
  8195. }
  8196. }
  8197. return results;
  8198. };
  8199. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8200. var results = new Array();
  8201. var descendants = this.getDescendants();
  8202. descendants.push(this);
  8203. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8204. var particleSystem = this.getScene().particleSystems[index];
  8205. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8206. results.push(particleSystem);
  8207. }
  8208. }
  8209. return results;
  8210. };
  8211. Mesh.prototype.getChildren = function () {
  8212. var results = [];
  8213. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8214. var mesh = this.getScene().meshes[index];
  8215. if (mesh.parent == this) {
  8216. results.push(mesh);
  8217. }
  8218. }
  8219. return results;
  8220. };
  8221. Mesh.prototype._checkDelayState = function () {
  8222. var _this = this;
  8223. var that = this;
  8224. var scene = this.getScene();
  8225. if (this._geometry) {
  8226. this._geometry.load(scene);
  8227. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8228. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8229. scene._addPendingData(that);
  8230. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8231. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8232. if (data instanceof ArrayBuffer) {
  8233. _this._delayLoadingFunction(data, _this);
  8234. } else {
  8235. _this._delayLoadingFunction(JSON.parse(data), _this);
  8236. }
  8237. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8238. scene._removePendingData(_this);
  8239. }, function () {
  8240. }, scene.database, getBinaryData);
  8241. }
  8242. };
  8243. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8244. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8245. return false;
  8246. }
  8247. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8248. return false;
  8249. }
  8250. this._checkDelayState();
  8251. return true;
  8252. };
  8253. Mesh.prototype.setMaterialByID = function (id) {
  8254. var materials = this.getScene().materials;
  8255. for (var index = 0; index < materials.length; index++) {
  8256. if (materials[index].id == id) {
  8257. this.material = materials[index];
  8258. return;
  8259. }
  8260. }
  8261. var multiMaterials = this.getScene().multiMaterials;
  8262. for (index = 0; index < multiMaterials.length; index++) {
  8263. if (multiMaterials[index].id == id) {
  8264. this.material = multiMaterials[index];
  8265. return;
  8266. }
  8267. }
  8268. };
  8269. Mesh.prototype.getAnimatables = function () {
  8270. var results = [];
  8271. if (this.material) {
  8272. results.push(this.material);
  8273. }
  8274. if (this.skeleton) {
  8275. results.push(this.skeleton);
  8276. }
  8277. return results;
  8278. };
  8279. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8280. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8281. return;
  8282. }
  8283. this._resetPointsArrayCache();
  8284. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8285. var temp = [];
  8286. for (var index = 0; index < data.length; index += 3) {
  8287. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8288. }
  8289. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8290. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8291. return;
  8292. }
  8293. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8294. for (index = 0; index < data.length; index += 3) {
  8295. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8296. }
  8297. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8298. };
  8299. Mesh.prototype._resetPointsArrayCache = function () {
  8300. this._positions = null;
  8301. };
  8302. Mesh.prototype._generatePointsArray = function () {
  8303. if (this._positions)
  8304. return true;
  8305. this._positions = [];
  8306. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8307. if (!data) {
  8308. return false;
  8309. }
  8310. for (var index = 0; index < data.length; index += 3) {
  8311. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8312. }
  8313. return true;
  8314. };
  8315. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8316. var result = new BABYLON.Mesh(name, this.getScene());
  8317. this._geometry.applyToMesh(result);
  8318. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8319. result.material = this.material;
  8320. if (newParent) {
  8321. result.parent = newParent;
  8322. }
  8323. if (!doNotCloneChildren) {
  8324. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8325. var mesh = this.getScene().meshes[index];
  8326. if (mesh.parent == this) {
  8327. mesh.clone(mesh.name, result);
  8328. }
  8329. }
  8330. }
  8331. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8332. var system = this.getScene().particleSystems[index];
  8333. if (system.emitter == this) {
  8334. system.clone(system.name, result);
  8335. }
  8336. }
  8337. result.computeWorldMatrix(true);
  8338. return result;
  8339. };
  8340. Mesh.prototype.dispose = function (doNotRecurse) {
  8341. if (this._geometry) {
  8342. this._geometry.releaseForMesh(this, true);
  8343. }
  8344. if (this._worldMatricesInstancesBuffer) {
  8345. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8346. this._worldMatricesInstancesBuffer = null;
  8347. }
  8348. while (this.instances.length) {
  8349. this.instances[0].dispose();
  8350. }
  8351. _super.prototype.dispose.call(this, doNotRecurse);
  8352. };
  8353. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8354. var _this = this;
  8355. var scene = this.getScene();
  8356. var onload = function (img) {
  8357. var canvas = document.createElement("canvas");
  8358. var context = canvas.getContext("2d");
  8359. var heightMapWidth = img.width;
  8360. var heightMapHeight = img.height;
  8361. canvas.width = heightMapWidth;
  8362. canvas.height = heightMapHeight;
  8363. context.drawImage(img, 0, 0);
  8364. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8365. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8366. };
  8367. BABYLON.Tools.LoadImage(url, onload, function () {
  8368. }, scene.database);
  8369. };
  8370. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8371. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8372. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8373. return;
  8374. }
  8375. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8376. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8377. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8378. var position = BABYLON.Vector3.Zero();
  8379. var normal = BABYLON.Vector3.Zero();
  8380. var uv = BABYLON.Vector2.Zero();
  8381. for (var index = 0; index < positions.length; index += 3) {
  8382. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8383. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8384. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8385. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8386. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8387. var pos = (u + v * heightMapWidth) * 4;
  8388. var r = buffer[pos] / 255.0;
  8389. var g = buffer[pos + 1] / 255.0;
  8390. var b = buffer[pos + 2] / 255.0;
  8391. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8392. normal.normalize();
  8393. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8394. position = position.add(normal);
  8395. position.toArray(positions, index);
  8396. }
  8397. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8398. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8399. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8400. };
  8401. Mesh.prototype.convertToFlatShadedMesh = function () {
  8402. var kinds = this.getVerticesDataKinds();
  8403. var vbs = [];
  8404. var data = [];
  8405. var newdata = [];
  8406. var updatableNormals = false;
  8407. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8408. var kind = kinds[kindIndex];
  8409. var vertexBuffer = this.getVertexBuffer(kind);
  8410. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8411. updatableNormals = vertexBuffer.isUpdatable();
  8412. kinds.splice(kindIndex, 1);
  8413. kindIndex--;
  8414. continue;
  8415. }
  8416. vbs[kind] = vertexBuffer;
  8417. data[kind] = vbs[kind].getData();
  8418. newdata[kind] = [];
  8419. }
  8420. var previousSubmeshes = this.subMeshes.slice(0);
  8421. var indices = this.getIndices();
  8422. var totalIndices = this.getTotalIndices();
  8423. for (index = 0; index < totalIndices; index++) {
  8424. var vertexIndex = indices[index];
  8425. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8426. kind = kinds[kindIndex];
  8427. var stride = vbs[kind].getStrideSize();
  8428. for (var offset = 0; offset < stride; offset++) {
  8429. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8430. }
  8431. }
  8432. }
  8433. var normals = [];
  8434. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8435. for (var index = 0; index < totalIndices; index += 3) {
  8436. indices[index] = index;
  8437. indices[index + 1] = index + 1;
  8438. indices[index + 2] = index + 2;
  8439. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8440. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8441. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8442. var p1p2 = p1.subtract(p2);
  8443. var p3p2 = p3.subtract(p2);
  8444. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8445. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8446. normals.push(normal.x);
  8447. normals.push(normal.y);
  8448. normals.push(normal.z);
  8449. }
  8450. }
  8451. this.setIndices(indices);
  8452. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8453. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8454. kind = kinds[kindIndex];
  8455. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8456. }
  8457. this.releaseSubMeshes();
  8458. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8459. var previousOne = previousSubmeshes[submeshIndex];
  8460. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8461. }
  8462. this.synchronizeInstances();
  8463. };
  8464. Mesh.prototype.createInstance = function (name) {
  8465. return new BABYLON.InstancedMesh(name, this);
  8466. };
  8467. Mesh.prototype.synchronizeInstances = function () {
  8468. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8469. var instance = this.instances[instanceIndex];
  8470. instance._syncSubMeshes();
  8471. }
  8472. };
  8473. Mesh.CreateBox = function (name, size, scene, updatable) {
  8474. var box = new BABYLON.Mesh(name, scene);
  8475. var vertexData = BABYLON.VertexData.CreateBox(size);
  8476. vertexData.applyToMesh(box, updatable);
  8477. return box;
  8478. };
  8479. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8480. var sphere = new BABYLON.Mesh(name, scene);
  8481. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8482. vertexData.applyToMesh(sphere, updatable);
  8483. return sphere;
  8484. };
  8485. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8486. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8487. if (scene !== undefined) {
  8488. updatable = scene;
  8489. }
  8490. scene = subdivisions;
  8491. subdivisions = 1;
  8492. }
  8493. var cylinder = new BABYLON.Mesh(name, scene);
  8494. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8495. vertexData.applyToMesh(cylinder, updatable);
  8496. return cylinder;
  8497. };
  8498. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8499. var torus = new BABYLON.Mesh(name, scene);
  8500. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8501. vertexData.applyToMesh(torus, updatable);
  8502. return torus;
  8503. };
  8504. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8505. var torusKnot = new BABYLON.Mesh(name, scene);
  8506. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8507. vertexData.applyToMesh(torusKnot, updatable);
  8508. return torusKnot;
  8509. };
  8510. Mesh.CreateLines = function (name, points, scene, updatable) {
  8511. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8512. var vertexData = BABYLON.VertexData.CreateLines(points);
  8513. vertexData.applyToMesh(lines, updatable);
  8514. return lines;
  8515. };
  8516. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8517. var plane = new BABYLON.Mesh(name, scene);
  8518. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8519. vertexData.applyToMesh(plane, updatable);
  8520. return plane;
  8521. };
  8522. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8523. var ground = new BABYLON.GroundMesh(name, scene);
  8524. ground._setReady(false);
  8525. ground._subdivisions = subdivisions;
  8526. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8527. vertexData.applyToMesh(ground, updatable);
  8528. ground._setReady(true);
  8529. return ground;
  8530. };
  8531. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8532. var tiledGround = new BABYLON.Mesh(name, scene);
  8533. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8534. vertexData.applyToMesh(tiledGround, updatable);
  8535. return tiledGround;
  8536. };
  8537. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8538. var ground = new BABYLON.GroundMesh(name, scene);
  8539. ground._subdivisions = subdivisions;
  8540. ground._setReady(false);
  8541. var onload = function (img) {
  8542. var canvas = document.createElement("canvas");
  8543. var context = canvas.getContext("2d");
  8544. var heightMapWidth = img.width;
  8545. var heightMapHeight = img.height;
  8546. canvas.width = heightMapWidth;
  8547. canvas.height = heightMapHeight;
  8548. context.drawImage(img, 0, 0);
  8549. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8550. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8551. vertexData.applyToMesh(ground, updatable);
  8552. ground._setReady(true);
  8553. };
  8554. BABYLON.Tools.LoadImage(url, onload, function () {
  8555. }, scene.database);
  8556. return ground;
  8557. };
  8558. Mesh.MinMax = function (meshes) {
  8559. var minVector = null;
  8560. var maxVector = null;
  8561. for (var i in meshes) {
  8562. var mesh = meshes[i];
  8563. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8564. if (!minVector) {
  8565. minVector = boundingBox.minimumWorld;
  8566. maxVector = boundingBox.maximumWorld;
  8567. continue;
  8568. }
  8569. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8570. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8571. }
  8572. return {
  8573. min: minVector,
  8574. max: maxVector
  8575. };
  8576. };
  8577. Mesh.Center = function (meshesOrMinMaxVector) {
  8578. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8579. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8580. };
  8581. return Mesh;
  8582. })(BABYLON.AbstractMesh);
  8583. BABYLON.Mesh = Mesh;
  8584. })(BABYLON || (BABYLON = {}));
  8585. var __extends = this.__extends || function (d, b) {
  8586. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8587. function __() { this.constructor = d; }
  8588. __.prototype = b.prototype;
  8589. d.prototype = new __();
  8590. };
  8591. var BABYLON;
  8592. (function (BABYLON) {
  8593. var GroundMesh = (function (_super) {
  8594. __extends(GroundMesh, _super);
  8595. function GroundMesh(name, scene) {
  8596. _super.call(this, name, scene);
  8597. this.generateOctree = false;
  8598. this._worldInverse = new BABYLON.Matrix();
  8599. }
  8600. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8601. get: function () {
  8602. return this._subdivisions;
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. GroundMesh.prototype.optimize = function (chunksCount) {
  8608. this.subdivide(this._subdivisions);
  8609. this.createOrUpdateSubmeshesOctree(32);
  8610. };
  8611. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8612. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8613. this.getWorldMatrix().invertToRef(this._worldInverse);
  8614. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8615. var pickInfo = this.intersects(ray);
  8616. if (pickInfo.hit) {
  8617. return pickInfo.pickedPoint.y;
  8618. }
  8619. return 0;
  8620. };
  8621. return GroundMesh;
  8622. })(BABYLON.Mesh);
  8623. BABYLON.GroundMesh = GroundMesh;
  8624. })(BABYLON || (BABYLON = {}));
  8625. var __extends = this.__extends || function (d, b) {
  8626. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8627. function __() { this.constructor = d; }
  8628. __.prototype = b.prototype;
  8629. d.prototype = new __();
  8630. };
  8631. var BABYLON;
  8632. (function (BABYLON) {
  8633. var InstancedMesh = (function (_super) {
  8634. __extends(InstancedMesh, _super);
  8635. function InstancedMesh(name, source) {
  8636. _super.call(this, name, source.getScene());
  8637. source.instances.push(this);
  8638. this._sourceMesh = source;
  8639. this.position.copyFrom(source.position);
  8640. this.rotation.copyFrom(source.rotation);
  8641. this.scaling.copyFrom(source.scaling);
  8642. if (source.rotationQuaternion) {
  8643. this.rotationQuaternion = source.rotationQuaternion.clone();
  8644. }
  8645. this.infiniteDistance = source.infiniteDistance;
  8646. this.setPivotMatrix(source.getPivotMatrix());
  8647. this.refreshBoundingInfo();
  8648. this._syncSubMeshes();
  8649. }
  8650. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8651. get: function () {
  8652. return this._sourceMesh.receiveShadows;
  8653. },
  8654. enumerable: true,
  8655. configurable: true
  8656. });
  8657. Object.defineProperty(InstancedMesh.prototype, "material", {
  8658. get: function () {
  8659. return this._sourceMesh.material;
  8660. },
  8661. enumerable: true,
  8662. configurable: true
  8663. });
  8664. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8665. get: function () {
  8666. return this._sourceMesh.visibility;
  8667. },
  8668. enumerable: true,
  8669. configurable: true
  8670. });
  8671. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8672. get: function () {
  8673. return this._sourceMesh.skeleton;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. InstancedMesh.prototype.getTotalVertices = function () {
  8679. return this._sourceMesh.getTotalVertices();
  8680. };
  8681. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8682. get: function () {
  8683. return this._sourceMesh;
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. InstancedMesh.prototype.getVerticesData = function (kind) {
  8689. return this._sourceMesh.getVerticesData(kind);
  8690. };
  8691. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8692. return this._sourceMesh.isVerticesDataPresent(kind);
  8693. };
  8694. InstancedMesh.prototype.getIndices = function () {
  8695. return this._sourceMesh.getIndices();
  8696. };
  8697. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8698. get: function () {
  8699. return this._sourceMesh._positions;
  8700. },
  8701. enumerable: true,
  8702. configurable: true
  8703. });
  8704. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8705. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8706. if (data) {
  8707. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8708. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8709. }
  8710. this._updateBoundingInfo();
  8711. };
  8712. InstancedMesh.prototype._preActivate = function () {
  8713. this.sourceMesh._preActivate();
  8714. };
  8715. InstancedMesh.prototype._activate = function (renderId) {
  8716. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8717. };
  8718. InstancedMesh.prototype._syncSubMeshes = function () {
  8719. this.releaseSubMeshes();
  8720. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8721. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8722. }
  8723. };
  8724. InstancedMesh.prototype._generatePointsArray = function () {
  8725. return this._sourceMesh._generatePointsArray();
  8726. };
  8727. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8728. var result = this._sourceMesh.createInstance(name);
  8729. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8730. this.refreshBoundingInfo();
  8731. if (newParent) {
  8732. result.parent = newParent;
  8733. }
  8734. if (!doNotCloneChildren) {
  8735. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8736. var mesh = this.getScene().meshes[index];
  8737. if (mesh.parent == this) {
  8738. mesh.clone(mesh.name, result);
  8739. }
  8740. }
  8741. }
  8742. result.computeWorldMatrix(true);
  8743. return result;
  8744. };
  8745. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8746. var index = this._sourceMesh.instances.indexOf(this);
  8747. this._sourceMesh.instances.splice(index, 1);
  8748. _super.prototype.dispose.call(this, doNotRecurse);
  8749. };
  8750. return InstancedMesh;
  8751. })(BABYLON.AbstractMesh);
  8752. BABYLON.InstancedMesh = InstancedMesh;
  8753. })(BABYLON || (BABYLON = {}));
  8754. var BABYLON;
  8755. (function (BABYLON) {
  8756. var SubMesh = (function () {
  8757. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8758. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8759. this.materialIndex = materialIndex;
  8760. this.verticesStart = verticesStart;
  8761. this.verticesCount = verticesCount;
  8762. this.indexStart = indexStart;
  8763. this.indexCount = indexCount;
  8764. this._renderId = 0;
  8765. this._mesh = mesh;
  8766. this._renderingMesh = renderingMesh || mesh;
  8767. mesh.subMeshes.push(this);
  8768. this._id = mesh.subMeshes.length - 1;
  8769. if (createBoundingBox) {
  8770. this.refreshBoundingInfo();
  8771. }
  8772. }
  8773. SubMesh.prototype.getBoundingInfo = function () {
  8774. return this._boundingInfo;
  8775. };
  8776. SubMesh.prototype.getMesh = function () {
  8777. return this._mesh;
  8778. };
  8779. SubMesh.prototype.getRenderingMesh = function () {
  8780. return this._renderingMesh;
  8781. };
  8782. SubMesh.prototype.getMaterial = function () {
  8783. var rootMaterial = this._renderingMesh.material;
  8784. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8785. var multiMaterial = rootMaterial;
  8786. return multiMaterial.getSubMaterial(this.materialIndex);
  8787. }
  8788. if (!rootMaterial) {
  8789. return this._mesh.getScene().defaultMaterial;
  8790. }
  8791. return rootMaterial;
  8792. };
  8793. SubMesh.prototype.refreshBoundingInfo = function () {
  8794. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8795. if (!data) {
  8796. this._boundingInfo = this._mesh._boundingInfo;
  8797. return;
  8798. }
  8799. var indices = this._renderingMesh.getIndices();
  8800. var extend;
  8801. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8802. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8803. } else {
  8804. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8805. }
  8806. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8807. };
  8808. SubMesh.prototype._checkCollision = function (collider) {
  8809. return this._boundingInfo._checkCollision(collider);
  8810. };
  8811. SubMesh.prototype.updateBoundingInfo = function (world) {
  8812. if (!this._boundingInfo) {
  8813. this.refreshBoundingInfo();
  8814. }
  8815. this._boundingInfo._update(world);
  8816. };
  8817. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8818. return this._boundingInfo.isInFrustum(frustumPlanes);
  8819. };
  8820. SubMesh.prototype.render = function () {
  8821. this._renderingMesh.render(this);
  8822. };
  8823. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8824. if (!this._linesIndexBuffer) {
  8825. var linesIndices = [];
  8826. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8827. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8828. }
  8829. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8830. this.linesIndexCount = linesIndices.length;
  8831. }
  8832. return this._linesIndexBuffer;
  8833. };
  8834. SubMesh.prototype.canIntersects = function (ray) {
  8835. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8836. };
  8837. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8838. var intersectInfo = null;
  8839. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8840. var p0 = positions[indices[index]];
  8841. var p1 = positions[indices[index + 1]];
  8842. var p2 = positions[indices[index + 2]];
  8843. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8844. if (currentIntersectInfo) {
  8845. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8846. intersectInfo = currentIntersectInfo;
  8847. intersectInfo.faceId = index / 3;
  8848. if (fastCheck) {
  8849. break;
  8850. }
  8851. }
  8852. }
  8853. }
  8854. return intersectInfo;
  8855. };
  8856. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8857. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8858. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8859. return result;
  8860. };
  8861. SubMesh.prototype.dispose = function () {
  8862. if (this._linesIndexBuffer) {
  8863. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8864. this._linesIndexBuffer = null;
  8865. }
  8866. var index = this._mesh.subMeshes.indexOf(this);
  8867. this._mesh.subMeshes.splice(index, 1);
  8868. };
  8869. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8870. var minVertexIndex = Number.MAX_VALUE;
  8871. var maxVertexIndex = -Number.MAX_VALUE;
  8872. renderingMesh = renderingMesh || mesh;
  8873. var indices = renderingMesh.getIndices();
  8874. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8875. var vertexIndex = indices[index];
  8876. if (vertexIndex < minVertexIndex)
  8877. minVertexIndex = vertexIndex;
  8878. if (vertexIndex > maxVertexIndex)
  8879. maxVertexIndex = vertexIndex;
  8880. }
  8881. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8882. };
  8883. return SubMesh;
  8884. })();
  8885. BABYLON.SubMesh = SubMesh;
  8886. })(BABYLON || (BABYLON = {}));
  8887. var BABYLON;
  8888. (function (BABYLON) {
  8889. var BaseTexture = (function () {
  8890. function BaseTexture(scene) {
  8891. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8892. this.hasAlpha = false;
  8893. this.getAlphaFromRGB = false;
  8894. this.level = 1;
  8895. this.isCube = false;
  8896. this.isRenderTarget = false;
  8897. this.animations = new Array();
  8898. this.coordinatesIndex = 0;
  8899. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8900. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8901. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8902. this.anisotropicFilteringLevel = 4;
  8903. this._scene = scene;
  8904. this._scene.textures.push(this);
  8905. }
  8906. BaseTexture.prototype.getScene = function () {
  8907. return this._scene;
  8908. };
  8909. BaseTexture.prototype.getTextureMatrix = function () {
  8910. return null;
  8911. };
  8912. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8913. return null;
  8914. };
  8915. BaseTexture.prototype.getInternalTexture = function () {
  8916. return this._texture;
  8917. };
  8918. BaseTexture.prototype.isReady = function () {
  8919. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8920. return true;
  8921. }
  8922. if (this._texture) {
  8923. return this._texture.isReady;
  8924. }
  8925. return false;
  8926. };
  8927. BaseTexture.prototype.getSize = function () {
  8928. if (this._texture._width) {
  8929. return { width: this._texture._width, height: this._texture._height };
  8930. }
  8931. if (this._texture._size) {
  8932. return { width: this._texture._size, height: this._texture._size };
  8933. }
  8934. return { width: 0, height: 0 };
  8935. };
  8936. BaseTexture.prototype.getBaseSize = function () {
  8937. if (!this.isReady())
  8938. return { width: 0, height: 0 };
  8939. if (this._texture._size) {
  8940. return { width: this._texture._size, height: this._texture._size };
  8941. }
  8942. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8943. };
  8944. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8945. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8946. for (var index = 0; index < texturesCache.length; index++) {
  8947. var texturesCacheEntry = texturesCache[index];
  8948. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8949. texturesCacheEntry.references++;
  8950. return texturesCacheEntry;
  8951. }
  8952. }
  8953. return null;
  8954. };
  8955. BaseTexture.prototype.delayLoad = function () {
  8956. };
  8957. BaseTexture.prototype.releaseInternalTexture = function () {
  8958. if (!this._texture) {
  8959. return;
  8960. }
  8961. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8962. this._texture.references--;
  8963. if (this._texture.references == 0) {
  8964. var index = texturesCache.indexOf(this._texture);
  8965. texturesCache.splice(index, 1);
  8966. this._scene.getEngine()._releaseTexture(this._texture);
  8967. delete this._texture;
  8968. }
  8969. };
  8970. BaseTexture.prototype.clone = function () {
  8971. return null;
  8972. };
  8973. BaseTexture.prototype.dispose = function () {
  8974. var index = this._scene.textures.indexOf(this);
  8975. if (index >= 0) {
  8976. this._scene.textures.splice(index, 1);
  8977. }
  8978. if (this._texture === undefined) {
  8979. return;
  8980. }
  8981. this.releaseInternalTexture();
  8982. if (this.onDispose) {
  8983. this.onDispose();
  8984. }
  8985. };
  8986. return BaseTexture;
  8987. })();
  8988. BABYLON.BaseTexture = BaseTexture;
  8989. })(BABYLON || (BABYLON = {}));
  8990. var BABYLON;
  8991. (function (BABYLON) {
  8992. var RenderingGroup = (function () {
  8993. function RenderingGroup(index, scene) {
  8994. this.index = index;
  8995. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  8996. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  8997. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  8998. this._scene = scene;
  8999. }
  9000. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9001. if (customRenderFunction) {
  9002. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9003. return true;
  9004. }
  9005. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9006. return false;
  9007. }
  9008. var engine = this._scene.getEngine();
  9009. var subIndex;
  9010. var submesh;
  9011. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9012. submesh = this._opaqueSubMeshes.data[subIndex];
  9013. this._activeVertices += submesh.verticesCount;
  9014. submesh.render();
  9015. }
  9016. engine.setAlphaTesting(true);
  9017. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9018. submesh = this._alphaTestSubMeshes.data[subIndex];
  9019. this._activeVertices += submesh.verticesCount;
  9020. submesh.render();
  9021. }
  9022. engine.setAlphaTesting(false);
  9023. if (beforeTransparents) {
  9024. beforeTransparents();
  9025. }
  9026. if (this._transparentSubMeshes.length) {
  9027. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9028. submesh = this._transparentSubMeshes.data[subIndex];
  9029. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9030. }
  9031. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9032. sortedArray.sort(function (a, b) {
  9033. if (a._distanceToCamera < b._distanceToCamera) {
  9034. return 1;
  9035. }
  9036. if (a._distanceToCamera > b._distanceToCamera) {
  9037. return -1;
  9038. }
  9039. return 0;
  9040. });
  9041. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9042. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9043. submesh = sortedArray[subIndex];
  9044. this._activeVertices += submesh.verticesCount;
  9045. submesh.render();
  9046. }
  9047. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9048. }
  9049. return true;
  9050. };
  9051. RenderingGroup.prototype.prepare = function () {
  9052. this._opaqueSubMeshes.reset();
  9053. this._transparentSubMeshes.reset();
  9054. this._alphaTestSubMeshes.reset();
  9055. };
  9056. RenderingGroup.prototype.dispatch = function (subMesh) {
  9057. var material = subMesh.getMaterial();
  9058. var mesh = subMesh.getMesh();
  9059. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9060. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9061. this._transparentSubMeshes.push(subMesh);
  9062. }
  9063. } else if (material.needAlphaTesting()) {
  9064. this._alphaTestSubMeshes.push(subMesh);
  9065. } else {
  9066. this._opaqueSubMeshes.push(subMesh);
  9067. }
  9068. };
  9069. return RenderingGroup;
  9070. })();
  9071. BABYLON.RenderingGroup = RenderingGroup;
  9072. })(BABYLON || (BABYLON = {}));
  9073. var BABYLON;
  9074. (function (BABYLON) {
  9075. var RenderingManager = (function () {
  9076. function RenderingManager(scene) {
  9077. this._renderingGroups = new Array();
  9078. this._scene = scene;
  9079. }
  9080. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9081. if (this._scene._activeParticleSystems.length === 0) {
  9082. return;
  9083. }
  9084. var beforeParticlesDate = new Date().getTime();
  9085. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9086. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9087. if (particleSystem.renderingGroupId !== index) {
  9088. continue;
  9089. }
  9090. this._clearDepthBuffer();
  9091. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9092. this._scene._activeParticles += particleSystem.render();
  9093. }
  9094. }
  9095. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  9096. };
  9097. RenderingManager.prototype._renderSprites = function (index) {
  9098. if (this._scene.spriteManagers.length === 0) {
  9099. return;
  9100. }
  9101. var beforeSpritessDate = new Date().getTime();
  9102. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9103. var spriteManager = this._scene.spriteManagers[id];
  9104. if (spriteManager.renderingGroupId === index) {
  9105. this._clearDepthBuffer();
  9106. spriteManager.render();
  9107. }
  9108. }
  9109. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  9110. };
  9111. RenderingManager.prototype._clearDepthBuffer = function () {
  9112. if (this._depthBufferAlreadyCleaned) {
  9113. return;
  9114. }
  9115. this._scene.getEngine().clear(0, false, true);
  9116. this._depthBufferAlreadyCleaned = true;
  9117. };
  9118. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9119. var _this = this;
  9120. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9121. this._depthBufferAlreadyCleaned = false;
  9122. var renderingGroup = this._renderingGroups[index];
  9123. if (renderingGroup) {
  9124. this._clearDepthBuffer();
  9125. if (!renderingGroup.render(customRenderFunction, function () {
  9126. if (renderSprites) {
  9127. _this._renderSprites(index);
  9128. }
  9129. })) {
  9130. this._renderingGroups.splice(index, 1);
  9131. }
  9132. } else if (renderSprites) {
  9133. this._renderSprites(index);
  9134. }
  9135. if (renderParticles) {
  9136. this._renderParticles(index, activeMeshes);
  9137. }
  9138. }
  9139. };
  9140. RenderingManager.prototype.reset = function () {
  9141. for (var index in this._renderingGroups) {
  9142. var renderingGroup = this._renderingGroups[index];
  9143. renderingGroup.prepare();
  9144. }
  9145. };
  9146. RenderingManager.prototype.dispatch = function (subMesh) {
  9147. var mesh = subMesh.getMesh();
  9148. var renderingGroupId = mesh.renderingGroupId || 0;
  9149. if (!this._renderingGroups[renderingGroupId]) {
  9150. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9151. }
  9152. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9153. };
  9154. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9155. return RenderingManager;
  9156. })();
  9157. BABYLON.RenderingManager = RenderingManager;
  9158. })(BABYLON || (BABYLON = {}));
  9159. var __extends = this.__extends || function (d, b) {
  9160. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9161. function __() { this.constructor = d; }
  9162. __.prototype = b.prototype;
  9163. d.prototype = new __();
  9164. };
  9165. var BABYLON;
  9166. (function (BABYLON) {
  9167. var Texture = (function (_super) {
  9168. __extends(Texture, _super);
  9169. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9170. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9171. if (typeof onLoad === "undefined") { onLoad = null; }
  9172. if (typeof onError === "undefined") { onError = null; }
  9173. if (typeof buffer === "undefined") { buffer = null; }
  9174. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9175. _super.call(this, scene);
  9176. this.uOffset = 0;
  9177. this.vOffset = 0;
  9178. this.uScale = 1.0;
  9179. this.vScale = 1.0;
  9180. this.uAng = 0;
  9181. this.vAng = 0;
  9182. this.wAng = 0;
  9183. this.name = url;
  9184. this.url = url;
  9185. this._noMipmap = noMipmap;
  9186. this._invertY = invertY;
  9187. this._samplingMode = samplingMode;
  9188. this._buffer = buffer;
  9189. this._deleteBuffer = deleteBuffer;
  9190. if (!url) {
  9191. return;
  9192. }
  9193. this._texture = this._getFromCache(url, noMipmap);
  9194. if (!this._texture) {
  9195. if (!scene.useDelayedTextureLoading) {
  9196. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9197. if (deleteBuffer) {
  9198. delete this._buffer;
  9199. }
  9200. } else {
  9201. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9202. }
  9203. }
  9204. }
  9205. Texture.prototype.delayLoad = function () {
  9206. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9207. return;
  9208. }
  9209. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9210. this._texture = this._getFromCache(this.url, this._noMipmap);
  9211. if (!this._texture) {
  9212. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9213. if (this._deleteBuffer) {
  9214. delete this._buffer;
  9215. }
  9216. }
  9217. };
  9218. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9219. x -= this.uOffset + 0.5;
  9220. y -= this.vOffset + 0.5;
  9221. z -= 0.5;
  9222. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9223. t.x *= this.uScale;
  9224. t.y *= this.vScale;
  9225. t.x += 0.5;
  9226. t.y += 0.5;
  9227. t.z += 0.5;
  9228. };
  9229. Texture.prototype.getTextureMatrix = function () {
  9230. 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) {
  9231. return this._cachedTextureMatrix;
  9232. }
  9233. this._cachedUOffset = this.uOffset;
  9234. this._cachedVOffset = this.vOffset;
  9235. this._cachedUScale = this.uScale;
  9236. this._cachedVScale = this.vScale;
  9237. this._cachedUAng = this.uAng;
  9238. this._cachedVAng = this.vAng;
  9239. this._cachedWAng = this.wAng;
  9240. if (!this._cachedTextureMatrix) {
  9241. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9242. this._rowGenerationMatrix = new BABYLON.Matrix();
  9243. this._t0 = BABYLON.Vector3.Zero();
  9244. this._t1 = BABYLON.Vector3.Zero();
  9245. this._t2 = BABYLON.Vector3.Zero();
  9246. }
  9247. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9248. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9249. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9250. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9251. this._t1.subtractInPlace(this._t0);
  9252. this._t2.subtractInPlace(this._t0);
  9253. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9254. this._cachedTextureMatrix.m[0] = this._t1.x;
  9255. this._cachedTextureMatrix.m[1] = this._t1.y;
  9256. this._cachedTextureMatrix.m[2] = this._t1.z;
  9257. this._cachedTextureMatrix.m[4] = this._t2.x;
  9258. this._cachedTextureMatrix.m[5] = this._t2.y;
  9259. this._cachedTextureMatrix.m[6] = this._t2.z;
  9260. this._cachedTextureMatrix.m[8] = this._t0.x;
  9261. this._cachedTextureMatrix.m[9] = this._t0.y;
  9262. this._cachedTextureMatrix.m[10] = this._t0.z;
  9263. return this._cachedTextureMatrix;
  9264. };
  9265. Texture.prototype.getReflectionTextureMatrix = function () {
  9266. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9267. return this._cachedTextureMatrix;
  9268. }
  9269. if (!this._cachedTextureMatrix) {
  9270. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9271. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9272. }
  9273. switch (this.coordinatesMode) {
  9274. case BABYLON.Texture.SPHERICAL_MODE:
  9275. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9276. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9277. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9278. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9279. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9280. break;
  9281. case BABYLON.Texture.PLANAR_MODE:
  9282. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9283. this._cachedTextureMatrix[0] = this.uScale;
  9284. this._cachedTextureMatrix[5] = this.vScale;
  9285. this._cachedTextureMatrix[12] = this.uOffset;
  9286. this._cachedTextureMatrix[13] = this.vOffset;
  9287. break;
  9288. case BABYLON.Texture.PROJECTION_MODE:
  9289. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9290. this._projectionModeMatrix.m[0] = 0.5;
  9291. this._projectionModeMatrix.m[5] = -0.5;
  9292. this._projectionModeMatrix.m[10] = 0.0;
  9293. this._projectionModeMatrix.m[12] = 0.5;
  9294. this._projectionModeMatrix.m[13] = 0.5;
  9295. this._projectionModeMatrix.m[14] = 1.0;
  9296. this._projectionModeMatrix.m[15] = 1.0;
  9297. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9298. break;
  9299. default:
  9300. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9301. break;
  9302. }
  9303. return this._cachedTextureMatrix;
  9304. };
  9305. Texture.prototype.clone = function () {
  9306. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9307. newTexture.hasAlpha = this.hasAlpha;
  9308. newTexture.level = this.level;
  9309. newTexture.wrapU = this.wrapU;
  9310. newTexture.wrapV = this.wrapV;
  9311. newTexture.coordinatesIndex = this.coordinatesIndex;
  9312. newTexture.coordinatesMode = this.coordinatesMode;
  9313. newTexture.uOffset = this.uOffset;
  9314. newTexture.vOffset = this.vOffset;
  9315. newTexture.uScale = this.uScale;
  9316. newTexture.vScale = this.vScale;
  9317. newTexture.uAng = this.uAng;
  9318. newTexture.vAng = this.vAng;
  9319. newTexture.wAng = this.wAng;
  9320. return newTexture;
  9321. };
  9322. Texture.NEAREST_SAMPLINGMODE = 1;
  9323. Texture.BILINEAR_SAMPLINGMODE = 2;
  9324. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9325. Texture.EXPLICIT_MODE = 0;
  9326. Texture.SPHERICAL_MODE = 1;
  9327. Texture.PLANAR_MODE = 2;
  9328. Texture.CUBIC_MODE = 3;
  9329. Texture.PROJECTION_MODE = 4;
  9330. Texture.SKYBOX_MODE = 5;
  9331. Texture.CLAMP_ADDRESSMODE = 0;
  9332. Texture.WRAP_ADDRESSMODE = 1;
  9333. Texture.MIRROR_ADDRESSMODE = 2;
  9334. return Texture;
  9335. })(BABYLON.BaseTexture);
  9336. BABYLON.Texture = Texture;
  9337. })(BABYLON || (BABYLON = {}));
  9338. var __extends = this.__extends || function (d, b) {
  9339. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9340. function __() { this.constructor = d; }
  9341. __.prototype = b.prototype;
  9342. d.prototype = new __();
  9343. };
  9344. var BABYLON;
  9345. (function (BABYLON) {
  9346. var CubeTexture = (function (_super) {
  9347. __extends(CubeTexture, _super);
  9348. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9349. _super.call(this, scene);
  9350. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9351. this.name = rootUrl;
  9352. this.url = rootUrl;
  9353. this._noMipmap = noMipmap;
  9354. this.hasAlpha = false;
  9355. this._texture = this._getFromCache(rootUrl, noMipmap);
  9356. if (!extensions) {
  9357. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9358. }
  9359. this._extensions = extensions;
  9360. if (!this._texture) {
  9361. if (!scene.useDelayedTextureLoading) {
  9362. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9363. } else {
  9364. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9365. }
  9366. }
  9367. this.isCube = true;
  9368. this._textureMatrix = BABYLON.Matrix.Identity();
  9369. }
  9370. CubeTexture.prototype.clone = function () {
  9371. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9372. newTexture.level = this.level;
  9373. newTexture.wrapU = this.wrapU;
  9374. newTexture.wrapV = this.wrapV;
  9375. newTexture.coordinatesIndex = this.coordinatesIndex;
  9376. newTexture.coordinatesMode = this.coordinatesMode;
  9377. return newTexture;
  9378. };
  9379. CubeTexture.prototype.delayLoad = function () {
  9380. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9381. return;
  9382. }
  9383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9384. this._texture = this._getFromCache(this.url, this._noMipmap);
  9385. if (!this._texture) {
  9386. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9387. }
  9388. };
  9389. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9390. return this._textureMatrix;
  9391. };
  9392. return CubeTexture;
  9393. })(BABYLON.BaseTexture);
  9394. BABYLON.CubeTexture = CubeTexture;
  9395. })(BABYLON || (BABYLON = {}));
  9396. var __extends = this.__extends || function (d, b) {
  9397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9398. function __() { this.constructor = d; }
  9399. __.prototype = b.prototype;
  9400. d.prototype = new __();
  9401. };
  9402. var BABYLON;
  9403. (function (BABYLON) {
  9404. var RenderTargetTexture = (function (_super) {
  9405. __extends(RenderTargetTexture, _super);
  9406. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9407. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9408. _super.call(this, null, scene, !generateMipMaps);
  9409. this.renderList = new Array();
  9410. this.renderParticles = true;
  9411. this.renderSprites = false;
  9412. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9413. this._currentRefreshId = -1;
  9414. this._refreshRate = 1;
  9415. this.name = name;
  9416. this.isRenderTarget = true;
  9417. this._size = size;
  9418. this._generateMipMaps = generateMipMaps;
  9419. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9420. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9421. this._renderingManager = new BABYLON.RenderingManager(scene);
  9422. }
  9423. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9424. this._currentRefreshId = -1;
  9425. };
  9426. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9427. get: function () {
  9428. return this._refreshRate;
  9429. },
  9430. set: function (value) {
  9431. this._refreshRate = value;
  9432. this.resetRefreshCounter();
  9433. },
  9434. enumerable: true,
  9435. configurable: true
  9436. });
  9437. RenderTargetTexture.prototype._shouldRender = function () {
  9438. if (this._currentRefreshId === -1) {
  9439. this._currentRefreshId = 1;
  9440. return true;
  9441. }
  9442. if (this.refreshRate == this._currentRefreshId) {
  9443. this._currentRefreshId = 1;
  9444. return true;
  9445. }
  9446. this._currentRefreshId++;
  9447. return false;
  9448. };
  9449. RenderTargetTexture.prototype.getRenderSize = function () {
  9450. return this._size;
  9451. };
  9452. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9453. this.releaseInternalTexture();
  9454. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9455. };
  9456. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9457. var scene = this.getScene();
  9458. var engine = scene.getEngine();
  9459. if (this._waitingRenderList) {
  9460. this.renderList = [];
  9461. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9462. var id = this._waitingRenderList[index];
  9463. this.renderList.push(scene.getMeshByID(id));
  9464. }
  9465. delete this._waitingRenderList;
  9466. }
  9467. if (!this.renderList) {
  9468. return;
  9469. }
  9470. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9471. engine.bindFramebuffer(this._texture);
  9472. }
  9473. engine.clear(scene.clearColor, true, true);
  9474. this._renderingManager.reset();
  9475. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9476. var mesh = this.renderList[meshIndex];
  9477. if (mesh) {
  9478. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9479. this.resetRefreshCounter();
  9480. continue;
  9481. }
  9482. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9483. mesh._activate(scene.getRenderId());
  9484. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9485. var subMesh = mesh.subMeshes[subIndex];
  9486. scene._activeVertices += subMesh.verticesCount;
  9487. this._renderingManager.dispatch(subMesh);
  9488. }
  9489. }
  9490. }
  9491. }
  9492. if (!this._doNotChangeAspectRatio) {
  9493. scene.updateTransformMatrix(true);
  9494. }
  9495. if (this.onBeforeRender) {
  9496. this.onBeforeRender();
  9497. }
  9498. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9499. if (useCameraPostProcess) {
  9500. scene.postProcessManager._finalizeFrame(false, this._texture);
  9501. }
  9502. if (this.onAfterRender) {
  9503. this.onAfterRender();
  9504. }
  9505. engine.unBindFramebuffer(this._texture);
  9506. if (!this._doNotChangeAspectRatio) {
  9507. scene.updateTransformMatrix(true);
  9508. }
  9509. };
  9510. RenderTargetTexture.prototype.clone = function () {
  9511. var textureSize = this.getSize();
  9512. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9513. newTexture.hasAlpha = this.hasAlpha;
  9514. newTexture.level = this.level;
  9515. newTexture.coordinatesMode = this.coordinatesMode;
  9516. newTexture.renderList = this.renderList.slice(0);
  9517. return newTexture;
  9518. };
  9519. return RenderTargetTexture;
  9520. })(BABYLON.Texture);
  9521. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9522. })(BABYLON || (BABYLON = {}));
  9523. var __extends = this.__extends || function (d, b) {
  9524. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9525. function __() { this.constructor = d; }
  9526. __.prototype = b.prototype;
  9527. d.prototype = new __();
  9528. };
  9529. var BABYLON;
  9530. (function (BABYLON) {
  9531. var MirrorTexture = (function (_super) {
  9532. __extends(MirrorTexture, _super);
  9533. function MirrorTexture(name, size, scene, generateMipMaps) {
  9534. var _this = this;
  9535. _super.call(this, name, size, scene, generateMipMaps, true);
  9536. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9537. this._transformMatrix = BABYLON.Matrix.Zero();
  9538. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9539. this.onBeforeRender = function () {
  9540. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9541. _this._savedViewMatrix = scene.getViewMatrix();
  9542. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9543. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9544. scene.clipPlane = _this.mirrorPlane;
  9545. scene.getEngine().cullBackFaces = false;
  9546. };
  9547. this.onAfterRender = function () {
  9548. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9549. scene.getEngine().cullBackFaces = true;
  9550. delete scene.clipPlane;
  9551. };
  9552. }
  9553. MirrorTexture.prototype.clone = function () {
  9554. var textureSize = this.getSize();
  9555. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9556. newTexture.hasAlpha = this.hasAlpha;
  9557. newTexture.level = this.level;
  9558. newTexture.mirrorPlane = this.mirrorPlane.clone();
  9559. newTexture.renderList = this.renderList.slice(0);
  9560. return newTexture;
  9561. };
  9562. return MirrorTexture;
  9563. })(BABYLON.RenderTargetTexture);
  9564. BABYLON.MirrorTexture = MirrorTexture;
  9565. })(BABYLON || (BABYLON = {}));
  9566. var __extends = this.__extends || function (d, b) {
  9567. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9568. function __() { this.constructor = d; }
  9569. __.prototype = b.prototype;
  9570. d.prototype = new __();
  9571. };
  9572. var BABYLON;
  9573. (function (BABYLON) {
  9574. var DynamicTexture = (function (_super) {
  9575. __extends(DynamicTexture, _super);
  9576. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  9577. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9578. _super.call(this, null, scene, !generateMipMaps);
  9579. this.name = name;
  9580. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9581. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9582. this._generateMipMaps = generateMipMaps;
  9583. if (options.getContext) {
  9584. this._canvas = options;
  9585. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9586. } else {
  9587. this._canvas = document.createElement("canvas");
  9588. if (options.width) {
  9589. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  9590. } else {
  9591. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  9592. }
  9593. }
  9594. var textureSize = this.getSize();
  9595. this._canvas.width = textureSize.width;
  9596. this._canvas.height = textureSize.height;
  9597. this._context = this._canvas.getContext("2d");
  9598. }
  9599. DynamicTexture.prototype.getContext = function () {
  9600. return this._context;
  9601. };
  9602. DynamicTexture.prototype.update = function (invertY) {
  9603. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  9604. };
  9605. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  9606. var size = this.getSize();
  9607. if (clearColor) {
  9608. this._context.fillStyle = clearColor;
  9609. this._context.fillRect(0, 0, size.width, size.height);
  9610. }
  9611. this._context.font = font;
  9612. if (x === null) {
  9613. var textSize = this._context.measureText(text);
  9614. x = (size.width - textSize.width) / 2;
  9615. }
  9616. this._context.fillStyle = color;
  9617. this._context.fillText(text, x, y);
  9618. this.update(invertY);
  9619. };
  9620. DynamicTexture.prototype.clone = function () {
  9621. var textureSize = this.getSize();
  9622. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9623. newTexture.hasAlpha = this.hasAlpha;
  9624. newTexture.level = this.level;
  9625. newTexture.wrapU = this.wrapU;
  9626. newTexture.wrapV = this.wrapV;
  9627. return newTexture;
  9628. };
  9629. return DynamicTexture;
  9630. })(BABYLON.Texture);
  9631. BABYLON.DynamicTexture = DynamicTexture;
  9632. })(BABYLON || (BABYLON = {}));
  9633. var __extends = this.__extends || function (d, b) {
  9634. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9635. function __() { this.constructor = d; }
  9636. __.prototype = b.prototype;
  9637. d.prototype = new __();
  9638. };
  9639. var BABYLON;
  9640. (function (BABYLON) {
  9641. var VideoTexture = (function (_super) {
  9642. __extends(VideoTexture, _super);
  9643. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  9644. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9645. var _this = this;
  9646. _super.call(this, null, scene, !generateMipMaps, invertY);
  9647. this._autoLaunch = true;
  9648. this.name = name;
  9649. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9650. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9651. var requiredWidth = size.width || size;
  9652. var requiredHeight = size.height || size;
  9653. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  9654. var textureSize = this.getSize();
  9655. this.video = document.createElement("video");
  9656. this.video.width = textureSize.width;
  9657. this.video.height = textureSize.height;
  9658. this.video.autoplay = false;
  9659. this.video.loop = true;
  9660. this.video.addEventListener("canplaythrough", function () {
  9661. if (_this._texture) {
  9662. _this._texture.isReady = true;
  9663. }
  9664. });
  9665. urls.forEach(function (url) {
  9666. var source = document.createElement("source");
  9667. source.src = url;
  9668. _this.video.appendChild(source);
  9669. });
  9670. this._lastUpdate = new Date().getTime();
  9671. }
  9672. VideoTexture.prototype.update = function () {
  9673. if (this._autoLaunch) {
  9674. this._autoLaunch = false;
  9675. this.video.play();
  9676. }
  9677. var now = new Date().getTime();
  9678. if (now - this._lastUpdate < 15) {
  9679. return false;
  9680. }
  9681. this._lastUpdate = now;
  9682. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  9683. return true;
  9684. };
  9685. return VideoTexture;
  9686. })(BABYLON.Texture);
  9687. BABYLON.VideoTexture = VideoTexture;
  9688. })(BABYLON || (BABYLON = {}));
  9689. var BABYLON;
  9690. (function (BABYLON) {
  9691. var EffectFallbacks = (function () {
  9692. function EffectFallbacks() {
  9693. this._defines = {};
  9694. this._currentRank = 32;
  9695. this._maxRank = -1;
  9696. }
  9697. EffectFallbacks.prototype.addFallback = function (rank, define) {
  9698. if (!this._defines[rank]) {
  9699. if (rank < this._currentRank) {
  9700. this._currentRank = rank;
  9701. }
  9702. if (rank > this._maxRank) {
  9703. this._maxRank = rank;
  9704. }
  9705. this._defines[rank] = new Array();
  9706. }
  9707. this._defines[rank].push(define);
  9708. };
  9709. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  9710. get: function () {
  9711. return this._currentRank <= this._maxRank;
  9712. },
  9713. enumerable: true,
  9714. configurable: true
  9715. });
  9716. EffectFallbacks.prototype.reduce = function (currentDefines) {
  9717. var currentFallbacks = this._defines[this._currentRank];
  9718. for (var index = 0; index < currentFallbacks.length; index++) {
  9719. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  9720. }
  9721. this._currentRank++;
  9722. return currentDefines;
  9723. };
  9724. return EffectFallbacks;
  9725. })();
  9726. BABYLON.EffectFallbacks = EffectFallbacks;
  9727. var Effect = (function () {
  9728. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  9729. var _this = this;
  9730. this._isReady = false;
  9731. this._compilationError = "";
  9732. this._valueCache = [];
  9733. this._engine = engine;
  9734. this.name = baseName;
  9735. this.defines = defines;
  9736. this._uniformsNames = uniformsNames.concat(samplers);
  9737. this._samplers = samplers;
  9738. this._attributesNames = attributesNames;
  9739. this.onError = onError;
  9740. this.onCompiled = onCompiled;
  9741. var vertexSource;
  9742. var fragmentSource;
  9743. if (baseName.vertexElement) {
  9744. vertexSource = document.getElementById(baseName.vertexElement);
  9745. if (!vertexSource) {
  9746. vertexSource = baseName.vertexElement;
  9747. }
  9748. } else {
  9749. vertexSource = baseName.vertex || baseName;
  9750. }
  9751. if (baseName.fragmentElement) {
  9752. fragmentSource = document.getElementById(baseName.fragmentElement);
  9753. if (!fragmentSource) {
  9754. fragmentSource = baseName.fragmentElement;
  9755. }
  9756. } else {
  9757. fragmentSource = baseName.fragment || baseName;
  9758. }
  9759. this._loadVertexShader(vertexSource, function (vertexCode) {
  9760. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  9761. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  9762. });
  9763. });
  9764. }
  9765. Effect.prototype.isReady = function () {
  9766. return this._isReady;
  9767. };
  9768. Effect.prototype.getProgram = function () {
  9769. return this._program;
  9770. };
  9771. Effect.prototype.getAttributesNames = function () {
  9772. return this._attributesNames;
  9773. };
  9774. Effect.prototype.getAttributeLocation = function (index) {
  9775. return this._attributes[index];
  9776. };
  9777. Effect.prototype.getAttributeLocationByName = function (name) {
  9778. var index = this._attributesNames.indexOf(name);
  9779. return this._attributes[index];
  9780. };
  9781. Effect.prototype.getAttributesCount = function () {
  9782. return this._attributes.length;
  9783. };
  9784. Effect.prototype.getUniformIndex = function (uniformName) {
  9785. return this._uniformsNames.indexOf(uniformName);
  9786. };
  9787. Effect.prototype.getUniform = function (uniformName) {
  9788. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  9789. };
  9790. Effect.prototype.getSamplers = function () {
  9791. return this._samplers;
  9792. };
  9793. Effect.prototype.getCompilationError = function () {
  9794. return this._compilationError;
  9795. };
  9796. Effect.prototype._loadVertexShader = function (vertex, callback) {
  9797. if (vertex instanceof HTMLElement) {
  9798. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  9799. callback(vertexCode);
  9800. return;
  9801. }
  9802. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  9803. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  9804. return;
  9805. }
  9806. var vertexShaderUrl;
  9807. if (vertex[0] === ".") {
  9808. vertexShaderUrl = vertex;
  9809. } else {
  9810. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  9811. }
  9812. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  9813. };
  9814. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  9815. if (fragment instanceof HTMLElement) {
  9816. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  9817. callback(fragmentCode);
  9818. return;
  9819. }
  9820. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  9821. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  9822. return;
  9823. }
  9824. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  9825. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  9826. return;
  9827. }
  9828. var fragmentShaderUrl;
  9829. if (fragment[0] === ".") {
  9830. fragmentShaderUrl = fragment;
  9831. } else {
  9832. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  9833. }
  9834. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  9835. };
  9836. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  9837. try {
  9838. var engine = this._engine;
  9839. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  9840. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  9841. this._attributes = engine.getAttributes(this._program, attributesNames);
  9842. for (var index = 0; index < this._samplers.length; index++) {
  9843. var sampler = this.getUniform(this._samplers[index]);
  9844. if (sampler == null) {
  9845. this._samplers.splice(index, 1);
  9846. index--;
  9847. }
  9848. }
  9849. engine.bindSamplers(this);
  9850. this._isReady = true;
  9851. if (this.onCompiled) {
  9852. this.onCompiled(this);
  9853. }
  9854. } catch (e) {
  9855. if (fallbacks && fallbacks.isMoreFallbacks) {
  9856. defines = fallbacks.reduce(defines);
  9857. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  9858. } else {
  9859. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  9860. BABYLON.Tools.Error("Defines: " + defines);
  9861. BABYLON.Tools.Error("Error: " + e.message);
  9862. this._compilationError = e.message;
  9863. if (this.onError) {
  9864. this.onError(this, this._compilationError);
  9865. }
  9866. }
  9867. }
  9868. };
  9869. Effect.prototype._bindTexture = function (channel, texture) {
  9870. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  9871. };
  9872. Effect.prototype.setTexture = function (channel, texture) {
  9873. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  9874. };
  9875. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9876. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  9877. };
  9878. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  9879. if (!this._valueCache[uniformName]) {
  9880. this._valueCache[uniformName] = [x, y];
  9881. return;
  9882. }
  9883. this._valueCache[uniformName][0] = x;
  9884. this._valueCache[uniformName][1] = y;
  9885. };
  9886. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  9887. if (!this._valueCache[uniformName]) {
  9888. this._valueCache[uniformName] = [x, y, z];
  9889. return;
  9890. }
  9891. this._valueCache[uniformName][0] = x;
  9892. this._valueCache[uniformName][1] = y;
  9893. this._valueCache[uniformName][2] = z;
  9894. };
  9895. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  9896. if (!this._valueCache[uniformName]) {
  9897. this._valueCache[uniformName] = [x, y, z, w];
  9898. return;
  9899. }
  9900. this._valueCache[uniformName][0] = x;
  9901. this._valueCache[uniformName][1] = y;
  9902. this._valueCache[uniformName][2] = z;
  9903. this._valueCache[uniformName][3] = w;
  9904. };
  9905. Effect.prototype.setArray = function (uniformName, array) {
  9906. this._engine.setArray(this.getUniform(uniformName), array);
  9907. return this;
  9908. };
  9909. Effect.prototype.setMatrices = function (uniformName, matrices) {
  9910. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  9911. return this;
  9912. };
  9913. Effect.prototype.setMatrix = function (uniformName, matrix) {
  9914. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  9915. return this;
  9916. };
  9917. Effect.prototype.setFloat = function (uniformName, value) {
  9918. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  9919. return this;
  9920. this._valueCache[uniformName] = value;
  9921. this._engine.setFloat(this.getUniform(uniformName), value);
  9922. return this;
  9923. };
  9924. Effect.prototype.setBool = function (uniformName, bool) {
  9925. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  9926. return this;
  9927. this._valueCache[uniformName] = bool;
  9928. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  9929. return this;
  9930. };
  9931. Effect.prototype.setVector2 = function (uniformName, vector2) {
  9932. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  9933. return this;
  9934. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  9935. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  9936. return this;
  9937. };
  9938. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  9939. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  9940. return this;
  9941. this._cacheFloat2(uniformName, x, y);
  9942. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  9943. return this;
  9944. };
  9945. Effect.prototype.setVector3 = function (uniformName, vector3) {
  9946. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  9947. return this;
  9948. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  9949. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  9950. return this;
  9951. };
  9952. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  9953. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  9954. return this;
  9955. this._cacheFloat3(uniformName, x, y, z);
  9956. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  9957. return this;
  9958. };
  9959. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  9960. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  9961. return this;
  9962. this._cacheFloat4(uniformName, x, y, z, w);
  9963. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  9964. return this;
  9965. };
  9966. Effect.prototype.setColor3 = function (uniformName, color3) {
  9967. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  9968. return this;
  9969. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  9970. this._engine.setColor3(this.getUniform(uniformName), color3);
  9971. return this;
  9972. };
  9973. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  9974. 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)
  9975. return this;
  9976. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  9977. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  9978. return this;
  9979. };
  9980. 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}",
  9981. 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}",
  9982. 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}",
  9983. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  9984. 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}",
  9985. 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}",
  9986. 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}",
  9987. 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}",
  9988. 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}",
  9989. 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}",
  9990. 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}",
  9991. 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}",
  9992. 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}",
  9993. 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}",
  9994. 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}",
  9995. 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}",
  9996. 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}",
  9997. 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\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}",
  9998. 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}",
  9999. 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}",
  10000. 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}",
  10001. 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}",
  10002. 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}",
  10003. 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}",
  10004. 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}",
  10005. 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}",
  10006. 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}",
  10007. 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}",
  10008. 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}",
  10009. };
  10010. return Effect;
  10011. })();
  10012. BABYLON.Effect = Effect;
  10013. })(BABYLON || (BABYLON = {}));
  10014. var BABYLON;
  10015. (function (BABYLON) {
  10016. var Material = (function () {
  10017. function Material(name, scene, doNotAdd) {
  10018. this.name = name;
  10019. this.checkReadyOnEveryCall = true;
  10020. this.checkReadyOnlyOnce = false;
  10021. this.state = "";
  10022. this.alpha = 1.0;
  10023. this.wireframe = false;
  10024. this.backFaceCulling = true;
  10025. this._wasPreviouslyReady = false;
  10026. this.id = name;
  10027. this._scene = scene;
  10028. if (!doNotAdd) {
  10029. scene.materials.push(this);
  10030. }
  10031. }
  10032. Material.prototype.isReady = function (mesh, useInstances) {
  10033. return true;
  10034. };
  10035. Material.prototype.getEffect = function () {
  10036. return this._effect;
  10037. };
  10038. Material.prototype.getScene = function () {
  10039. return this._scene;
  10040. };
  10041. Material.prototype.needAlphaBlending = function () {
  10042. return (this.alpha < 1.0);
  10043. };
  10044. Material.prototype.needAlphaTesting = function () {
  10045. return false;
  10046. };
  10047. Material.prototype.getAlphaTestTexture = function () {
  10048. return null;
  10049. };
  10050. Material.prototype.trackCreation = function (onCompiled, onError) {
  10051. };
  10052. Material.prototype._preBind = function () {
  10053. var engine = this._scene.getEngine();
  10054. engine.enableEffect(this._effect);
  10055. engine.setState(this.backFaceCulling);
  10056. };
  10057. Material.prototype.bind = function (world, mesh) {
  10058. };
  10059. Material.prototype.bindOnlyWorldMatrix = function (world) {
  10060. };
  10061. Material.prototype.unbind = function () {
  10062. };
  10063. Material.prototype.dispose = function (forceDisposeEffect) {
  10064. var index = this._scene.materials.indexOf(this);
  10065. this._scene.materials.splice(index, 1);
  10066. if (forceDisposeEffect && this._effect) {
  10067. this._scene.getEngine()._releaseEffect(this._effect);
  10068. this._effect = null;
  10069. }
  10070. if (this.onDispose) {
  10071. this.onDispose();
  10072. }
  10073. };
  10074. return Material;
  10075. })();
  10076. BABYLON.Material = Material;
  10077. })(BABYLON || (BABYLON = {}));
  10078. var __extends = this.__extends || function (d, b) {
  10079. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10080. function __() { this.constructor = d; }
  10081. __.prototype = b.prototype;
  10082. d.prototype = new __();
  10083. };
  10084. var BABYLON;
  10085. (function (BABYLON) {
  10086. var maxSimultaneousLights = 4;
  10087. var FresnelParameters = (function () {
  10088. function FresnelParameters() {
  10089. this.isEnabled = true;
  10090. this.leftColor = BABYLON.Color3.White();
  10091. this.rightColor = BABYLON.Color3.Black();
  10092. this.bias = 0;
  10093. this.power = 1;
  10094. }
  10095. return FresnelParameters;
  10096. })();
  10097. BABYLON.FresnelParameters = FresnelParameters;
  10098. var StandardMaterial = (function (_super) {
  10099. __extends(StandardMaterial, _super);
  10100. function StandardMaterial(name, scene) {
  10101. var _this = this;
  10102. _super.call(this, name, scene);
  10103. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10104. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10105. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10106. this.specularPower = 64;
  10107. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10108. this.useAlphaFromDiffuseTexture = false;
  10109. this.useSpecularOverAlpha = true;
  10110. this._cachedDefines = null;
  10111. this._renderTargets = new BABYLON.SmartArray(16);
  10112. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10113. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10114. this._scaledDiffuse = new BABYLON.Color3();
  10115. this._scaledSpecular = new BABYLON.Color3();
  10116. this.getRenderTargetTextures = function () {
  10117. _this._renderTargets.reset();
  10118. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10119. _this._renderTargets.push(_this.reflectionTexture);
  10120. }
  10121. return _this._renderTargets;
  10122. };
  10123. }
  10124. StandardMaterial.prototype.needAlphaBlending = function () {
  10125. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10126. };
  10127. StandardMaterial.prototype.needAlphaTesting = function () {
  10128. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10129. };
  10130. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10131. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10132. };
  10133. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10134. return this.diffuseTexture;
  10135. };
  10136. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10137. if (this.checkReadyOnlyOnce) {
  10138. if (this._wasPreviouslyReady) {
  10139. return true;
  10140. }
  10141. }
  10142. var scene = this.getScene();
  10143. if (!this.checkReadyOnEveryCall) {
  10144. if (this._renderId === scene.getRenderId()) {
  10145. return true;
  10146. }
  10147. }
  10148. var engine = scene.getEngine();
  10149. var defines = [];
  10150. var fallbacks = new BABYLON.EffectFallbacks();
  10151. if (scene.texturesEnabled) {
  10152. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10153. if (!this.diffuseTexture.isReady()) {
  10154. return false;
  10155. } else {
  10156. defines.push("#define DIFFUSE");
  10157. }
  10158. }
  10159. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10160. if (!this.ambientTexture.isReady()) {
  10161. return false;
  10162. } else {
  10163. defines.push("#define AMBIENT");
  10164. }
  10165. }
  10166. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10167. if (!this.opacityTexture.isReady()) {
  10168. return false;
  10169. } else {
  10170. defines.push("#define OPACITY");
  10171. if (this.opacityTexture.getAlphaFromRGB) {
  10172. defines.push("#define OPACITYRGB");
  10173. }
  10174. }
  10175. }
  10176. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10177. if (!this.reflectionTexture.isReady()) {
  10178. return false;
  10179. } else {
  10180. defines.push("#define REFLECTION");
  10181. fallbacks.addFallback(0, "REFLECTION");
  10182. }
  10183. }
  10184. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10185. if (!this.emissiveTexture.isReady()) {
  10186. return false;
  10187. } else {
  10188. defines.push("#define EMISSIVE");
  10189. }
  10190. }
  10191. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10192. if (!this.specularTexture.isReady()) {
  10193. return false;
  10194. } else {
  10195. defines.push("#define SPECULAR");
  10196. fallbacks.addFallback(0, "SPECULAR");
  10197. }
  10198. }
  10199. }
  10200. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10201. if (!this.bumpTexture.isReady()) {
  10202. return false;
  10203. } else {
  10204. defines.push("#define BUMP");
  10205. fallbacks.addFallback(0, "BUMP");
  10206. }
  10207. }
  10208. if (this.useSpecularOverAlpha) {
  10209. defines.push("#define SPECULAROVERALPHA");
  10210. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10211. }
  10212. if (scene.clipPlane) {
  10213. defines.push("#define CLIPPLANE");
  10214. }
  10215. if (engine.getAlphaTesting()) {
  10216. defines.push("#define ALPHATEST");
  10217. }
  10218. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10219. defines.push("#define ALPHAFROMDIFFUSE");
  10220. }
  10221. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10222. defines.push("#define FOG");
  10223. fallbacks.addFallback(1, "FOG");
  10224. }
  10225. var shadowsActivated = false;
  10226. var lightIndex = 0;
  10227. if (scene.lightsEnabled) {
  10228. for (var index = 0; index < scene.lights.length; index++) {
  10229. var light = scene.lights[index];
  10230. if (!light.isEnabled()) {
  10231. continue;
  10232. }
  10233. if (light._excludedMeshesIds.length > 0) {
  10234. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10235. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10236. if (excludedMesh) {
  10237. light.excludedMeshes.push(excludedMesh);
  10238. }
  10239. }
  10240. light._excludedMeshesIds = [];
  10241. }
  10242. if (light._includedOnlyMeshesIds.length > 0) {
  10243. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10244. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10245. if (includedOnlyMesh) {
  10246. light.includedOnlyMeshes.push(includedOnlyMesh);
  10247. }
  10248. }
  10249. light._includedOnlyMeshesIds = [];
  10250. }
  10251. if (!light.canAffectMesh(mesh)) {
  10252. continue;
  10253. }
  10254. defines.push("#define LIGHT" + lightIndex);
  10255. if (lightIndex > 0) {
  10256. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10257. }
  10258. var type;
  10259. if (light instanceof BABYLON.SpotLight) {
  10260. type = "#define SPOTLIGHT" + lightIndex;
  10261. } else if (light instanceof BABYLON.HemisphericLight) {
  10262. type = "#define HEMILIGHT" + lightIndex;
  10263. } else {
  10264. type = "#define POINTDIRLIGHT" + lightIndex;
  10265. }
  10266. defines.push(type);
  10267. if (lightIndex > 0) {
  10268. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10269. }
  10270. var shadowGenerator = light.getShadowGenerator();
  10271. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10272. defines.push("#define SHADOW" + lightIndex);
  10273. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10274. if (!shadowsActivated) {
  10275. defines.push("#define SHADOWS");
  10276. shadowsActivated = true;
  10277. }
  10278. if (shadowGenerator.useVarianceShadowMap) {
  10279. defines.push("#define SHADOWVSM" + lightIndex);
  10280. if (lightIndex > 0) {
  10281. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10282. }
  10283. }
  10284. if (shadowGenerator.usePoissonSampling) {
  10285. defines.push("#define SHADOWPCF" + lightIndex);
  10286. if (lightIndex > 0) {
  10287. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10288. }
  10289. }
  10290. }
  10291. lightIndex++;
  10292. if (lightIndex == maxSimultaneousLights)
  10293. break;
  10294. }
  10295. }
  10296. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10297. var fresnelRank = 1;
  10298. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10299. defines.push("#define DIFFUSEFRESNEL");
  10300. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10301. fresnelRank++;
  10302. }
  10303. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10304. defines.push("#define OPACITYFRESNEL");
  10305. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10306. fresnelRank++;
  10307. }
  10308. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10309. defines.push("#define REFLECTIONFRESNEL");
  10310. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10311. fresnelRank++;
  10312. }
  10313. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10314. defines.push("#define EMISSIVEFRESNEL");
  10315. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10316. fresnelRank++;
  10317. }
  10318. defines.push("#define FRESNEL");
  10319. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10320. }
  10321. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10322. if (mesh) {
  10323. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10324. attribs.push(BABYLON.VertexBuffer.UVKind);
  10325. defines.push("#define UV1");
  10326. }
  10327. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10328. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10329. defines.push("#define UV2");
  10330. }
  10331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10332. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10333. defines.push("#define VERTEXCOLOR");
  10334. }
  10335. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10336. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10337. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10338. defines.push("#define BONES");
  10339. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10340. defines.push("#define BONES4");
  10341. fallbacks.addFallback(0, "BONES4");
  10342. }
  10343. if (useInstances) {
  10344. defines.push("#define INSTANCES");
  10345. attribs.push("world0");
  10346. attribs.push("world1");
  10347. attribs.push("world2");
  10348. attribs.push("world3");
  10349. }
  10350. }
  10351. var join = defines.join("\n");
  10352. if (this._cachedDefines != join) {
  10353. this._cachedDefines = join;
  10354. var shaderName = "default";
  10355. if (!scene.getEngine().getCaps().standardDerivatives) {
  10356. shaderName = "legacydefault";
  10357. }
  10358. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10359. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10360. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10361. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10362. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10363. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10364. "vFogInfos", "vFogColor",
  10365. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10366. "mBones",
  10367. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10368. "darkness0", "darkness1", "darkness2", "darkness3",
  10369. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10370. ], [
  10371. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10372. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10373. ], join, fallbacks, this.onCompiled, this.onError);
  10374. }
  10375. if (!this._effect.isReady()) {
  10376. return false;
  10377. }
  10378. this._renderId = scene.getRenderId();
  10379. this._wasPreviouslyReady = true;
  10380. return true;
  10381. };
  10382. StandardMaterial.prototype.unbind = function () {
  10383. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10384. this._effect.setTexture("reflection2DSampler", null);
  10385. }
  10386. };
  10387. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10388. this._effect.setMatrix("world", world);
  10389. };
  10390. StandardMaterial.prototype.bind = function (world, mesh) {
  10391. var scene = this.getScene();
  10392. this.bindOnlyWorldMatrix(world);
  10393. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10394. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10395. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10396. }
  10397. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10398. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10399. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10400. }
  10401. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10402. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10403. }
  10404. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10405. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10406. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10407. }
  10408. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10409. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10410. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10411. }
  10412. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10413. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10414. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10415. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10416. }
  10417. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10418. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10419. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10420. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10421. }
  10422. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10423. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10424. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10425. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10426. }
  10427. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10428. if (this.reflectionTexture.isCube) {
  10429. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10430. } else {
  10431. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10432. }
  10433. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10434. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10435. }
  10436. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10437. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10438. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10439. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10440. }
  10441. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10442. this._effect.setTexture("specularSampler", this.specularTexture);
  10443. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10444. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10445. }
  10446. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10447. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10448. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10449. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10450. }
  10451. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10452. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10453. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10454. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10455. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10456. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10457. if (scene.lightsEnabled) {
  10458. var lightIndex = 0;
  10459. for (var index = 0; index < scene.lights.length; index++) {
  10460. var light = scene.lights[index];
  10461. if (!light.isEnabled()) {
  10462. continue;
  10463. }
  10464. if (!light.canAffectMesh(mesh)) {
  10465. continue;
  10466. }
  10467. if (light instanceof BABYLON.PointLight) {
  10468. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10469. } else if (light instanceof BABYLON.DirectionalLight) {
  10470. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10471. } else if (light instanceof BABYLON.SpotLight) {
  10472. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10473. } else if (light instanceof BABYLON.HemisphericLight) {
  10474. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10475. }
  10476. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10477. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10478. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10479. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10480. var shadowGenerator = light.getShadowGenerator();
  10481. if (mesh.receiveShadows && shadowGenerator) {
  10482. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10483. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10484. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10485. }
  10486. lightIndex++;
  10487. if (lightIndex == maxSimultaneousLights)
  10488. break;
  10489. }
  10490. }
  10491. if (scene.clipPlane) {
  10492. var clipPlane = scene.clipPlane;
  10493. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10494. }
  10495. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10496. this._effect.setMatrix("view", scene.getViewMatrix());
  10497. }
  10498. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10499. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10500. this._effect.setColor3("vFogColor", scene.fogColor);
  10501. }
  10502. };
  10503. StandardMaterial.prototype.getAnimatables = function () {
  10504. var results = [];
  10505. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10506. results.push(this.diffuseTexture);
  10507. }
  10508. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10509. results.push(this.ambientTexture);
  10510. }
  10511. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10512. results.push(this.opacityTexture);
  10513. }
  10514. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10515. results.push(this.reflectionTexture);
  10516. }
  10517. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10518. results.push(this.emissiveTexture);
  10519. }
  10520. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10521. results.push(this.specularTexture);
  10522. }
  10523. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10524. results.push(this.bumpTexture);
  10525. }
  10526. return results;
  10527. };
  10528. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10529. if (this.diffuseTexture) {
  10530. this.diffuseTexture.dispose();
  10531. }
  10532. if (this.ambientTexture) {
  10533. this.ambientTexture.dispose();
  10534. }
  10535. if (this.opacityTexture) {
  10536. this.opacityTexture.dispose();
  10537. }
  10538. if (this.reflectionTexture) {
  10539. this.reflectionTexture.dispose();
  10540. }
  10541. if (this.emissiveTexture) {
  10542. this.emissiveTexture.dispose();
  10543. }
  10544. if (this.specularTexture) {
  10545. this.specularTexture.dispose();
  10546. }
  10547. if (this.bumpTexture) {
  10548. this.bumpTexture.dispose();
  10549. }
  10550. _super.prototype.dispose.call(this, forceDisposeEffect);
  10551. };
  10552. StandardMaterial.prototype.clone = function (name) {
  10553. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10554. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10555. newStandardMaterial.alpha = this.alpha;
  10556. newStandardMaterial.wireframe = this.wireframe;
  10557. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  10558. if (this.diffuseTexture && this.diffuseTexture.clone) {
  10559. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  10560. }
  10561. if (this.ambientTexture && this.ambientTexture.clone) {
  10562. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  10563. }
  10564. if (this.opacityTexture && this.opacityTexture.clone) {
  10565. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  10566. }
  10567. if (this.reflectionTexture && this.reflectionTexture.clone) {
  10568. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  10569. }
  10570. if (this.emissiveTexture && this.emissiveTexture.clone) {
  10571. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  10572. }
  10573. if (this.specularTexture && this.specularTexture.clone) {
  10574. newStandardMaterial.specularTexture = this.specularTexture.clone();
  10575. }
  10576. if (this.bumpTexture && this.bumpTexture.clone) {
  10577. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  10578. }
  10579. newStandardMaterial.ambientColor = this.ambientColor.clone();
  10580. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  10581. newStandardMaterial.specularColor = this.specularColor.clone();
  10582. newStandardMaterial.specularPower = this.specularPower;
  10583. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  10584. return newStandardMaterial;
  10585. };
  10586. StandardMaterial.DiffuseTextureEnabled = true;
  10587. StandardMaterial.AmbientTextureEnabled = true;
  10588. StandardMaterial.OpacityTextureEnabled = true;
  10589. StandardMaterial.ReflectionTextureEnabled = true;
  10590. StandardMaterial.EmissiveTextureEnabled = true;
  10591. StandardMaterial.SpecularTextureEnabled = true;
  10592. StandardMaterial.BumpTextureEnabled = true;
  10593. return StandardMaterial;
  10594. })(BABYLON.Material);
  10595. BABYLON.StandardMaterial = StandardMaterial;
  10596. })(BABYLON || (BABYLON = {}));
  10597. var __extends = this.__extends || function (d, b) {
  10598. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10599. function __() { this.constructor = d; }
  10600. __.prototype = b.prototype;
  10601. d.prototype = new __();
  10602. };
  10603. var BABYLON;
  10604. (function (BABYLON) {
  10605. var MultiMaterial = (function (_super) {
  10606. __extends(MultiMaterial, _super);
  10607. function MultiMaterial(name, scene) {
  10608. _super.call(this, name, scene, true);
  10609. this.subMaterials = new Array();
  10610. scene.multiMaterials.push(this);
  10611. }
  10612. MultiMaterial.prototype.getSubMaterial = function (index) {
  10613. if (index < 0 || index >= this.subMaterials.length) {
  10614. return this.getScene().defaultMaterial;
  10615. }
  10616. return this.subMaterials[index];
  10617. };
  10618. MultiMaterial.prototype.isReady = function (mesh) {
  10619. for (var index = 0; index < this.subMaterials.length; index++) {
  10620. var subMaterial = this.subMaterials[index];
  10621. if (subMaterial) {
  10622. if (!this.subMaterials[index].isReady(mesh)) {
  10623. return false;
  10624. }
  10625. }
  10626. }
  10627. return true;
  10628. };
  10629. return MultiMaterial;
  10630. })(BABYLON.Material);
  10631. BABYLON.MultiMaterial = MultiMaterial;
  10632. })(BABYLON || (BABYLON = {}));
  10633. var BABYLON;
  10634. (function (BABYLON) {
  10635. var Database = (function () {
  10636. function Database(urlToScene, callbackManifestChecked) {
  10637. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  10638. this.callbackManifestChecked = callbackManifestChecked;
  10639. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  10640. this.db = null;
  10641. this.enableSceneOffline = false;
  10642. this.enableTexturesOffline = false;
  10643. this.manifestVersionFound = 0;
  10644. this.mustUpdateRessources = false;
  10645. this.hasReachedQuota = false;
  10646. this.checkManifestFile();
  10647. }
  10648. Database.prototype.checkManifestFile = function () {
  10649. var _this = this;
  10650. function noManifestFile() {
  10651. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  10652. that.enableSceneOffline = false;
  10653. that.enableTexturesOffline = false;
  10654. that.callbackManifestChecked(false);
  10655. }
  10656. var that = this;
  10657. var manifestURL = this.currentSceneUrl + ".manifest";
  10658. var xhr = new XMLHttpRequest();
  10659. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  10660. xhr.open("GET", manifestURLTimeStamped, true);
  10661. xhr.addEventListener("load", function () {
  10662. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10663. try {
  10664. var manifestFile = JSON.parse(xhr.response);
  10665. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  10666. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  10667. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  10668. _this.manifestVersionFound = manifestFile.version;
  10669. }
  10670. if (_this.callbackManifestChecked) {
  10671. _this.callbackManifestChecked(true);
  10672. }
  10673. } catch (ex) {
  10674. noManifestFile();
  10675. }
  10676. } else {
  10677. noManifestFile();
  10678. }
  10679. }, false);
  10680. xhr.addEventListener("error", function (event) {
  10681. noManifestFile();
  10682. }, false);
  10683. try {
  10684. xhr.send();
  10685. } catch (ex) {
  10686. BABYLON.Tools.Error("Error on XHR send request.");
  10687. that.callbackManifestChecked(false);
  10688. }
  10689. };
  10690. Database.prototype.openAsync = function (successCallback, errorCallback) {
  10691. var _this = this;
  10692. function handleError() {
  10693. that.isSupported = false;
  10694. if (errorCallback)
  10695. errorCallback();
  10696. }
  10697. var that = this;
  10698. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  10699. this.isSupported = false;
  10700. if (errorCallback)
  10701. errorCallback();
  10702. } else {
  10703. if (!this.db) {
  10704. this.hasReachedQuota = false;
  10705. this.isSupported = true;
  10706. var request = this.idbFactory.open("babylonjs", 1);
  10707. request.onerror = function (event) {
  10708. handleError();
  10709. };
  10710. request.onblocked = function (event) {
  10711. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  10712. handleError();
  10713. };
  10714. request.onsuccess = function (event) {
  10715. _this.db = request.result;
  10716. successCallback();
  10717. };
  10718. request.onupgradeneeded = function (event) {
  10719. _this.db = (event.target).result;
  10720. try {
  10721. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  10722. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  10723. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  10724. } catch (ex) {
  10725. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  10726. handleError();
  10727. }
  10728. };
  10729. } else {
  10730. if (successCallback)
  10731. successCallback();
  10732. }
  10733. }
  10734. };
  10735. Database.prototype.loadImageFromDB = function (url, image) {
  10736. var _this = this;
  10737. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  10738. var saveAndLoadImage = function () {
  10739. if (!_this.hasReachedQuota && _this.db !== null) {
  10740. _this._saveImageIntoDBAsync(completeURL, image);
  10741. } else {
  10742. image.src = url;
  10743. }
  10744. };
  10745. if (!this.mustUpdateRessources) {
  10746. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  10747. } else {
  10748. saveAndLoadImage();
  10749. }
  10750. };
  10751. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  10752. if (this.isSupported && this.db !== null) {
  10753. var texture;
  10754. var transaction = this.db.transaction(["textures"]);
  10755. transaction.onabort = function (event) {
  10756. image.src = url;
  10757. };
  10758. transaction.oncomplete = function (event) {
  10759. var blobTextureURL;
  10760. if (texture) {
  10761. var URL = window.URL || window.webkitURL;
  10762. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  10763. image.onerror = function () {
  10764. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  10765. image.src = url;
  10766. };
  10767. image.src = blobTextureURL;
  10768. } else {
  10769. notInDBCallback();
  10770. }
  10771. };
  10772. var getRequest = transaction.objectStore("textures").get(url);
  10773. getRequest.onsuccess = function (event) {
  10774. texture = (event.target).result;
  10775. };
  10776. getRequest.onerror = function (event) {
  10777. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  10778. image.src = url;
  10779. };
  10780. } else {
  10781. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10782. image.src = url;
  10783. }
  10784. };
  10785. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  10786. var _this = this;
  10787. if (this.isSupported) {
  10788. var generateBlobUrl = function () {
  10789. var blobTextureURL;
  10790. if (blob) {
  10791. var URL = window.URL || window.webkitURL;
  10792. try {
  10793. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  10794. } catch (ex) {
  10795. blobTextureURL = URL.createObjectURL(blob);
  10796. }
  10797. }
  10798. image.src = blobTextureURL;
  10799. };
  10800. if (BABYLON.Database.isUASupportingBlobStorage) {
  10801. var xhr = new XMLHttpRequest(), blob;
  10802. xhr.open("GET", url, true);
  10803. xhr.responseType = "blob";
  10804. xhr.addEventListener("load", function () {
  10805. if (xhr.status === 200) {
  10806. blob = xhr.response;
  10807. var transaction = _this.db.transaction(["textures"], "readwrite");
  10808. transaction.onabort = function (event) {
  10809. try {
  10810. if (event.srcElement.error.name === "QuotaExceededError") {
  10811. this.hasReachedQuota = true;
  10812. }
  10813. } catch (ex) {
  10814. }
  10815. generateBlobUrl();
  10816. };
  10817. transaction.oncomplete = function (event) {
  10818. generateBlobUrl();
  10819. };
  10820. var newTexture = { textureUrl: url, data: blob };
  10821. try {
  10822. var addRequest = transaction.objectStore("textures").put(newTexture);
  10823. addRequest.onsuccess = function (event) {
  10824. };
  10825. addRequest.onerror = function (event) {
  10826. generateBlobUrl();
  10827. };
  10828. } catch (ex) {
  10829. if (ex.code === 25) {
  10830. BABYLON.Database.isUASupportingBlobStorage = false;
  10831. }
  10832. image.src = url;
  10833. }
  10834. } else {
  10835. image.src = url;
  10836. }
  10837. }, false);
  10838. xhr.addEventListener("error", function (event) {
  10839. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  10840. image.src = url;
  10841. }, false);
  10842. xhr.send();
  10843. } else {
  10844. image.src = url;
  10845. }
  10846. } else {
  10847. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10848. image.src = url;
  10849. }
  10850. };
  10851. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  10852. var _this = this;
  10853. var updateVersion = function (event) {
  10854. _this._saveVersionIntoDBAsync(url, versionLoaded);
  10855. };
  10856. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  10857. };
  10858. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  10859. var _this = this;
  10860. if (this.isSupported) {
  10861. var version;
  10862. try {
  10863. var transaction = this.db.transaction(["versions"]);
  10864. transaction.oncomplete = function (event) {
  10865. if (version) {
  10866. if (_this.manifestVersionFound > version.data) {
  10867. _this.mustUpdateRessources = true;
  10868. updateInDBCallback();
  10869. } else {
  10870. callback(version.data);
  10871. }
  10872. } else {
  10873. _this.mustUpdateRessources = true;
  10874. updateInDBCallback();
  10875. }
  10876. };
  10877. transaction.onabort = function (event) {
  10878. callback(-1);
  10879. };
  10880. var getRequest = transaction.objectStore("versions").get(url);
  10881. getRequest.onsuccess = function (event) {
  10882. version = (event.target).result;
  10883. };
  10884. getRequest.onerror = function (event) {
  10885. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  10886. callback(-1);
  10887. };
  10888. } catch (ex) {
  10889. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  10890. callback(-1);
  10891. }
  10892. } else {
  10893. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10894. callback(-1);
  10895. }
  10896. };
  10897. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  10898. var _this = this;
  10899. if (this.isSupported && !this.hasReachedQuota) {
  10900. try {
  10901. var transaction = this.db.transaction(["versions"], "readwrite");
  10902. transaction.onabort = function (event) {
  10903. try {
  10904. if (event.srcElement.error.name === "QuotaExceededError") {
  10905. _this.hasReachedQuota = true;
  10906. }
  10907. } catch (ex) {
  10908. }
  10909. callback(-1);
  10910. };
  10911. transaction.oncomplete = function (event) {
  10912. callback(_this.manifestVersionFound);
  10913. };
  10914. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  10915. var addRequest = transaction.objectStore("versions").put(newVersion);
  10916. addRequest.onsuccess = function (event) {
  10917. };
  10918. addRequest.onerror = function (event) {
  10919. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  10920. };
  10921. } catch (ex) {
  10922. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  10923. callback(-1);
  10924. }
  10925. } else {
  10926. callback(-1);
  10927. }
  10928. };
  10929. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  10930. var _this = this;
  10931. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  10932. var saveAndLoadFile = function (event) {
  10933. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  10934. };
  10935. this._checkVersionFromDB(completeUrl, function (version) {
  10936. if (version !== -1) {
  10937. if (!_this.mustUpdateRessources) {
  10938. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  10939. } else {
  10940. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  10941. }
  10942. } else {
  10943. errorCallback();
  10944. }
  10945. });
  10946. };
  10947. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  10948. if (this.isSupported) {
  10949. var targetStore;
  10950. if (url.indexOf(".babylon") !== -1) {
  10951. targetStore = "scenes";
  10952. } else {
  10953. targetStore = "textures";
  10954. }
  10955. var file;
  10956. var transaction = this.db.transaction([targetStore]);
  10957. transaction.oncomplete = function (event) {
  10958. if (file) {
  10959. callback(file.data);
  10960. } else {
  10961. notInDBCallback();
  10962. }
  10963. };
  10964. transaction.onabort = function (event) {
  10965. notInDBCallback();
  10966. };
  10967. var getRequest = transaction.objectStore(targetStore).get(url);
  10968. getRequest.onsuccess = function (event) {
  10969. file = (event.target).result;
  10970. };
  10971. getRequest.onerror = function (event) {
  10972. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  10973. notInDBCallback();
  10974. };
  10975. } else {
  10976. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  10977. callback();
  10978. }
  10979. };
  10980. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  10981. var _this = this;
  10982. if (this.isSupported) {
  10983. var targetStore;
  10984. if (url.indexOf(".babylon") !== -1) {
  10985. targetStore = "scenes";
  10986. } else {
  10987. targetStore = "textures";
  10988. }
  10989. var xhr = new XMLHttpRequest(), fileData;
  10990. xhr.open("GET", url, true);
  10991. if (useArrayBuffer) {
  10992. xhr.responseType = "arraybuffer";
  10993. }
  10994. xhr.onprogress = progressCallback;
  10995. xhr.addEventListener("load", function () {
  10996. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  10997. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  10998. if (!_this.hasReachedQuota) {
  10999. var transaction = _this.db.transaction([targetStore], "readwrite");
  11000. transaction.onabort = function (event) {
  11001. try {
  11002. if (event.srcElement.error.name === "QuotaExceededError") {
  11003. this.hasReachedQuota = true;
  11004. }
  11005. } catch (ex) {
  11006. }
  11007. callback(fileData);
  11008. };
  11009. transaction.oncomplete = function (event) {
  11010. callback(fileData);
  11011. };
  11012. var newFile;
  11013. if (targetStore === "scenes") {
  11014. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11015. } else {
  11016. newFile = { textureUrl: url, data: fileData };
  11017. }
  11018. try {
  11019. var addRequest = transaction.objectStore(targetStore).put(newFile);
  11020. addRequest.onsuccess = function (event) {
  11021. };
  11022. addRequest.onerror = function (event) {
  11023. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  11024. };
  11025. } catch (ex) {
  11026. callback(fileData);
  11027. }
  11028. } else {
  11029. callback(fileData);
  11030. }
  11031. } else {
  11032. callback();
  11033. }
  11034. }, false);
  11035. xhr.addEventListener("error", function (event) {
  11036. BABYLON.Tools.Error("error on XHR request.");
  11037. callback();
  11038. }, false);
  11039. xhr.send();
  11040. } else {
  11041. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11042. callback();
  11043. }
  11044. };
  11045. Database.isUASupportingBlobStorage = true;
  11046. Database.parseURL = function (url) {
  11047. var a = document.createElement('a');
  11048. a.href = url;
  11049. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  11050. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  11051. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  11052. return absLocation;
  11053. };
  11054. Database.ReturnFullUrlLocation = function (url) {
  11055. if (url.indexOf("http:/") === -1) {
  11056. return (BABYLON.Database.parseURL(window.location.href) + url);
  11057. } else {
  11058. return url;
  11059. }
  11060. };
  11061. return Database;
  11062. })();
  11063. BABYLON.Database = Database;
  11064. })(BABYLON || (BABYLON = {}));
  11065. var BABYLON;
  11066. (function (BABYLON) {
  11067. var SpriteManager = (function () {
  11068. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  11069. this.name = name;
  11070. this.cellSize = cellSize;
  11071. this.sprites = new Array();
  11072. this.renderingGroupId = 0;
  11073. this._vertexDeclaration = [3, 4, 4, 4];
  11074. this._vertexStrideSize = 15 * 4;
  11075. this._capacity = capacity;
  11076. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11077. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11078. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11079. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11080. this._scene = scene;
  11081. this._scene.spriteManagers.push(this);
  11082. this._vertexDeclaration = [3, 4, 4, 4];
  11083. this._vertexStrideSize = 15 * 4;
  11084. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11085. var indices = [];
  11086. var index = 0;
  11087. for (var count = 0; count < capacity; count++) {
  11088. indices.push(index);
  11089. indices.push(index + 1);
  11090. indices.push(index + 2);
  11091. indices.push(index);
  11092. indices.push(index + 2);
  11093. indices.push(index + 3);
  11094. index += 4;
  11095. }
  11096. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11097. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11098. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11099. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11100. }
  11101. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11102. var arrayOffset = index * 15;
  11103. if (offsetX == 0)
  11104. offsetX = this._epsilon;
  11105. else if (offsetX == 1)
  11106. offsetX = 1 - this._epsilon;
  11107. if (offsetY == 0)
  11108. offsetY = this._epsilon;
  11109. else if (offsetY == 1)
  11110. offsetY = 1 - this._epsilon;
  11111. this._vertices[arrayOffset] = sprite.position.x;
  11112. this._vertices[arrayOffset + 1] = sprite.position.y;
  11113. this._vertices[arrayOffset + 2] = sprite.position.z;
  11114. this._vertices[arrayOffset + 3] = sprite.angle;
  11115. this._vertices[arrayOffset + 4] = sprite.size;
  11116. this._vertices[arrayOffset + 5] = offsetX;
  11117. this._vertices[arrayOffset + 6] = offsetY;
  11118. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11119. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11120. var offset = (sprite.cellIndex / rowSize) >> 0;
  11121. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11122. this._vertices[arrayOffset + 10] = offset;
  11123. this._vertices[arrayOffset + 11] = sprite.color.r;
  11124. this._vertices[arrayOffset + 12] = sprite.color.g;
  11125. this._vertices[arrayOffset + 13] = sprite.color.b;
  11126. this._vertices[arrayOffset + 14] = sprite.color.a;
  11127. };
  11128. SpriteManager.prototype.render = function () {
  11129. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11130. return;
  11131. var engine = this._scene.getEngine();
  11132. var baseSize = this._spriteTexture.getBaseSize();
  11133. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11134. var max = Math.min(this._capacity, this.sprites.length);
  11135. var rowSize = baseSize.width / this.cellSize;
  11136. var offset = 0;
  11137. for (var index = 0; index < max; index++) {
  11138. var sprite = this.sprites[index];
  11139. if (!sprite) {
  11140. continue;
  11141. }
  11142. sprite._animate(deltaTime);
  11143. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11144. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11145. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11146. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11147. }
  11148. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11149. var effect = this._effectBase;
  11150. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11151. effect = this._effectFog;
  11152. }
  11153. engine.enableEffect(effect);
  11154. var viewMatrix = this._scene.getViewMatrix();
  11155. effect.setTexture("diffuseSampler", this._spriteTexture);
  11156. effect.setMatrix("view", viewMatrix);
  11157. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11158. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11159. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11160. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11161. effect.setColor3("vFogColor", this._scene.fogColor);
  11162. }
  11163. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11164. effect.setBool("alphaTest", true);
  11165. engine.setColorWrite(false);
  11166. engine.draw(true, 0, max * 6);
  11167. engine.setColorWrite(true);
  11168. effect.setBool("alphaTest", false);
  11169. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11170. engine.draw(true, 0, max * 6);
  11171. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11172. };
  11173. SpriteManager.prototype.dispose = function () {
  11174. if (this._vertexBuffer) {
  11175. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11176. this._vertexBuffer = null;
  11177. }
  11178. if (this._indexBuffer) {
  11179. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11180. this._indexBuffer = null;
  11181. }
  11182. if (this._spriteTexture) {
  11183. this._spriteTexture.dispose();
  11184. this._spriteTexture = null;
  11185. }
  11186. var index = this._scene.spriteManagers.indexOf(this);
  11187. this._scene.spriteManagers.splice(index, 1);
  11188. if (this.onDispose) {
  11189. this.onDispose();
  11190. }
  11191. };
  11192. return SpriteManager;
  11193. })();
  11194. BABYLON.SpriteManager = SpriteManager;
  11195. })(BABYLON || (BABYLON = {}));
  11196. var BABYLON;
  11197. (function (BABYLON) {
  11198. var Sprite = (function () {
  11199. function Sprite(name, manager) {
  11200. this.name = name;
  11201. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11202. this.size = 1.0;
  11203. this.angle = 0;
  11204. this.cellIndex = 0;
  11205. this.invertU = 0;
  11206. this.invertV = 0;
  11207. this.animations = new Array();
  11208. this._animationStarted = false;
  11209. this._loopAnimation = false;
  11210. this._fromIndex = 0;
  11211. this._toIndex = 0;
  11212. this._delay = 0;
  11213. this._direction = 1;
  11214. this._frameCount = 0;
  11215. this._time = 0;
  11216. this._manager = manager;
  11217. this._manager.sprites.push(this);
  11218. this.position = BABYLON.Vector3.Zero();
  11219. }
  11220. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11221. this._fromIndex = from;
  11222. this._toIndex = to;
  11223. this._loopAnimation = loop;
  11224. this._delay = delay;
  11225. this._animationStarted = true;
  11226. this._direction = from < to ? 1 : -1;
  11227. this.cellIndex = from;
  11228. this._time = 0;
  11229. };
  11230. Sprite.prototype.stopAnimation = function () {
  11231. this._animationStarted = false;
  11232. };
  11233. Sprite.prototype._animate = function (deltaTime) {
  11234. if (!this._animationStarted)
  11235. return;
  11236. this._time += deltaTime;
  11237. if (this._time > this._delay) {
  11238. this._time = this._time % this._delay;
  11239. this.cellIndex += this._direction;
  11240. if (this.cellIndex == this._toIndex) {
  11241. if (this._loopAnimation) {
  11242. this.cellIndex = this._fromIndex;
  11243. } else {
  11244. this._animationStarted = false;
  11245. if (this.disposeWhenFinishedAnimating) {
  11246. this.dispose();
  11247. }
  11248. }
  11249. }
  11250. }
  11251. };
  11252. Sprite.prototype.dispose = function () {
  11253. for (var i = 0; i < this._manager.sprites.length; i++) {
  11254. if (this._manager.sprites[i] == this) {
  11255. this._manager.sprites.splice(i, 1);
  11256. }
  11257. }
  11258. };
  11259. return Sprite;
  11260. })();
  11261. BABYLON.Sprite = Sprite;
  11262. })(BABYLON || (BABYLON = {}));
  11263. var BABYLON;
  11264. (function (BABYLON) {
  11265. var Layer = (function () {
  11266. function Layer(name, imgUrl, scene, isBackground, color) {
  11267. this.name = name;
  11268. this._vertexDeclaration = [2];
  11269. this._vertexStrideSize = 2 * 4;
  11270. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11271. this.isBackground = isBackground === undefined ? true : isBackground;
  11272. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11273. this._scene = scene;
  11274. this._scene.layers.push(this);
  11275. var vertices = [];
  11276. vertices.push(1, 1);
  11277. vertices.push(-1, 1);
  11278. vertices.push(-1, -1);
  11279. vertices.push(1, -1);
  11280. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11281. var indices = [];
  11282. indices.push(0);
  11283. indices.push(1);
  11284. indices.push(2);
  11285. indices.push(0);
  11286. indices.push(2);
  11287. indices.push(3);
  11288. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11289. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11290. }
  11291. Layer.prototype.render = function () {
  11292. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11293. return;
  11294. var engine = this._scene.getEngine();
  11295. engine.enableEffect(this._effect);
  11296. engine.setState(false);
  11297. this._effect.setTexture("textureSampler", this.texture);
  11298. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11299. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11300. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11301. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11302. engine.draw(true, 0, 6);
  11303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11304. };
  11305. Layer.prototype.dispose = function () {
  11306. if (this._vertexBuffer) {
  11307. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11308. this._vertexBuffer = null;
  11309. }
  11310. if (this._indexBuffer) {
  11311. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11312. this._indexBuffer = null;
  11313. }
  11314. if (this.texture) {
  11315. this.texture.dispose();
  11316. this.texture = null;
  11317. }
  11318. var index = this._scene.layers.indexOf(this);
  11319. this._scene.layers.splice(index, 1);
  11320. if (this.onDispose) {
  11321. this.onDispose();
  11322. }
  11323. };
  11324. return Layer;
  11325. })();
  11326. BABYLON.Layer = Layer;
  11327. })(BABYLON || (BABYLON = {}));
  11328. var BABYLON;
  11329. (function (BABYLON) {
  11330. var Particle = (function () {
  11331. function Particle() {
  11332. this.position = BABYLON.Vector3.Zero();
  11333. this.direction = BABYLON.Vector3.Zero();
  11334. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11335. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11336. this.lifeTime = 1.0;
  11337. this.age = 0;
  11338. this.size = 0;
  11339. this.angle = 0;
  11340. this.angularSpeed = 0;
  11341. }
  11342. return Particle;
  11343. })();
  11344. BABYLON.Particle = Particle;
  11345. })(BABYLON || (BABYLON = {}));
  11346. var BABYLON;
  11347. (function (BABYLON) {
  11348. var randomNumber = function (min, max) {
  11349. if (min == max) {
  11350. return (min);
  11351. }
  11352. var random = Math.random();
  11353. return ((random * (max - min)) + min);
  11354. };
  11355. var ParticleSystem = (function () {
  11356. function ParticleSystem(name, capacity, scene, customEffect) {
  11357. var _this = this;
  11358. this.name = name;
  11359. this.renderingGroupId = 0;
  11360. this.emitter = null;
  11361. this.emitRate = 10;
  11362. this.manualEmitCount = -1;
  11363. this.updateSpeed = 0.01;
  11364. this.targetStopDuration = 0;
  11365. this.disposeOnStop = false;
  11366. this.minEmitPower = 1;
  11367. this.maxEmitPower = 1;
  11368. this.minLifeTime = 1;
  11369. this.maxLifeTime = 1;
  11370. this.minSize = 1;
  11371. this.maxSize = 1;
  11372. this.minAngularSpeed = 0;
  11373. this.maxAngularSpeed = 0;
  11374. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11375. this.forceDepthWrite = false;
  11376. this.gravity = BABYLON.Vector3.Zero();
  11377. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11378. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11379. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11380. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11381. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11382. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11383. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11384. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11385. this.particles = new Array();
  11386. this._vertexDeclaration = [3, 4, 4];
  11387. this._vertexStrideSize = 11 * 4;
  11388. this._stockParticles = new Array();
  11389. this._newPartsExcess = 0;
  11390. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11391. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11392. this._scaledDirection = BABYLON.Vector3.Zero();
  11393. this._scaledGravity = BABYLON.Vector3.Zero();
  11394. this._currentRenderId = -1;
  11395. this._started = false;
  11396. this._stopped = false;
  11397. this._actualFrame = 0;
  11398. this.id = name;
  11399. this._capacity = capacity;
  11400. this._scene = scene;
  11401. this._customEffect = customEffect;
  11402. scene.particleSystems.push(this);
  11403. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11404. var indices = [];
  11405. var index = 0;
  11406. for (var count = 0; count < capacity; count++) {
  11407. indices.push(index);
  11408. indices.push(index + 1);
  11409. indices.push(index + 2);
  11410. indices.push(index);
  11411. indices.push(index + 2);
  11412. indices.push(index + 3);
  11413. index += 4;
  11414. }
  11415. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11416. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11417. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11418. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11419. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11420. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11421. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11422. };
  11423. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11424. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11425. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11426. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11428. };
  11429. }
  11430. ParticleSystem.prototype.getCapacity = function () {
  11431. return this._capacity;
  11432. };
  11433. ParticleSystem.prototype.isAlive = function () {
  11434. return this._alive;
  11435. };
  11436. ParticleSystem.prototype.isStarted = function () {
  11437. return this._started;
  11438. };
  11439. ParticleSystem.prototype.start = function () {
  11440. this._started = true;
  11441. this._stopped = false;
  11442. this._actualFrame = 0;
  11443. };
  11444. ParticleSystem.prototype.stop = function () {
  11445. this._stopped = true;
  11446. };
  11447. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11448. var offset = index * 11;
  11449. this._vertices[offset] = particle.position.x;
  11450. this._vertices[offset + 1] = particle.position.y;
  11451. this._vertices[offset + 2] = particle.position.z;
  11452. this._vertices[offset + 3] = particle.color.r;
  11453. this._vertices[offset + 4] = particle.color.g;
  11454. this._vertices[offset + 5] = particle.color.b;
  11455. this._vertices[offset + 6] = particle.color.a;
  11456. this._vertices[offset + 7] = particle.angle;
  11457. this._vertices[offset + 8] = particle.size;
  11458. this._vertices[offset + 9] = offsetX;
  11459. this._vertices[offset + 10] = offsetY;
  11460. };
  11461. ParticleSystem.prototype._update = function (newParticles) {
  11462. this._alive = this.particles.length > 0;
  11463. for (var index = 0; index < this.particles.length; index++) {
  11464. var particle = this.particles[index];
  11465. particle.age += this._scaledUpdateSpeed;
  11466. if (particle.age >= particle.lifeTime) {
  11467. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11468. index--;
  11469. continue;
  11470. } else {
  11471. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11472. particle.color.addInPlace(this._scaledColorStep);
  11473. if (particle.color.a < 0)
  11474. particle.color.a = 0;
  11475. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11476. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11477. particle.position.addInPlace(this._scaledDirection);
  11478. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11479. particle.direction.addInPlace(this._scaledGravity);
  11480. }
  11481. }
  11482. var worldMatrix;
  11483. if (this.emitter.position) {
  11484. worldMatrix = this.emitter.getWorldMatrix();
  11485. } else {
  11486. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11487. }
  11488. for (index = 0; index < newParticles; index++) {
  11489. if (this.particles.length == this._capacity) {
  11490. break;
  11491. }
  11492. if (this._stockParticles.length !== 0) {
  11493. particle = this._stockParticles.pop();
  11494. particle.age = 0;
  11495. } else {
  11496. particle = new BABYLON.Particle();
  11497. }
  11498. this.particles.push(particle);
  11499. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11500. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11501. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11502. particle.size = randomNumber(this.minSize, this.maxSize);
  11503. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11504. this.startPositionFunction(worldMatrix, particle.position);
  11505. var step = randomNumber(0, 1.0);
  11506. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11507. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11508. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11509. }
  11510. };
  11511. ParticleSystem.prototype._getEffect = function () {
  11512. if (this._customEffect) {
  11513. return this._customEffect;
  11514. }
  11515. ;
  11516. var defines = [];
  11517. if (this._scene.clipPlane) {
  11518. defines.push("#define CLIPPLANE");
  11519. }
  11520. var join = defines.join("\n");
  11521. if (this._cachedDefines != join) {
  11522. this._cachedDefines = join;
  11523. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11524. }
  11525. return this._effect;
  11526. };
  11527. ParticleSystem.prototype.animate = function () {
  11528. if (!this._started)
  11529. return;
  11530. var effect = this._getEffect();
  11531. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11532. return;
  11533. if (this._currentRenderId === this._scene.getRenderId()) {
  11534. return;
  11535. }
  11536. this._currentRenderId = this._scene.getRenderId();
  11537. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11538. var emitCout;
  11539. if (this.manualEmitCount > -1) {
  11540. emitCout = this.manualEmitCount;
  11541. this.manualEmitCount = 0;
  11542. } else {
  11543. emitCout = this.emitRate;
  11544. }
  11545. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11546. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11547. if (this._newPartsExcess > 1.0) {
  11548. newParticles += this._newPartsExcess >> 0;
  11549. this._newPartsExcess -= this._newPartsExcess >> 0;
  11550. }
  11551. this._alive = false;
  11552. if (!this._stopped) {
  11553. this._actualFrame += this._scaledUpdateSpeed;
  11554. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11555. this.stop();
  11556. } else {
  11557. newParticles = 0;
  11558. }
  11559. this._update(newParticles);
  11560. if (this._stopped) {
  11561. if (!this._alive) {
  11562. this._started = false;
  11563. if (this.disposeOnStop) {
  11564. this._scene._toBeDisposed.push(this);
  11565. }
  11566. }
  11567. }
  11568. var offset = 0;
  11569. for (var index = 0; index < this.particles.length; index++) {
  11570. var particle = this.particles[index];
  11571. this._appendParticleVertex(offset++, particle, 0, 0);
  11572. this._appendParticleVertex(offset++, particle, 1, 0);
  11573. this._appendParticleVertex(offset++, particle, 1, 1);
  11574. this._appendParticleVertex(offset++, particle, 0, 1);
  11575. }
  11576. var engine = this._scene.getEngine();
  11577. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  11578. };
  11579. ParticleSystem.prototype.render = function () {
  11580. var effect = this._getEffect();
  11581. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  11582. return 0;
  11583. var engine = this._scene.getEngine();
  11584. engine.enableEffect(effect);
  11585. var viewMatrix = this._scene.getViewMatrix();
  11586. effect.setTexture("diffuseSampler", this.particleTexture);
  11587. effect.setMatrix("view", viewMatrix);
  11588. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11589. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  11590. if (this._scene.clipPlane) {
  11591. var clipPlane = this._scene.clipPlane;
  11592. var invView = viewMatrix.clone();
  11593. invView.invert();
  11594. effect.setMatrix("invView", invView);
  11595. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11596. }
  11597. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11598. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  11599. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  11600. } else {
  11601. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11602. }
  11603. if (this.forceDepthWrite) {
  11604. engine.setDepthWrite(true);
  11605. }
  11606. engine.draw(true, 0, this.particles.length * 6);
  11607. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11608. return this.particles.length;
  11609. };
  11610. ParticleSystem.prototype.dispose = function () {
  11611. if (this._vertexBuffer) {
  11612. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11613. this._vertexBuffer = null;
  11614. }
  11615. if (this._indexBuffer) {
  11616. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11617. this._indexBuffer = null;
  11618. }
  11619. if (this.particleTexture) {
  11620. this.particleTexture.dispose();
  11621. this.particleTexture = null;
  11622. }
  11623. var index = this._scene.particleSystems.indexOf(this);
  11624. this._scene.particleSystems.splice(index, 1);
  11625. if (this.onDispose) {
  11626. this.onDispose();
  11627. }
  11628. };
  11629. ParticleSystem.prototype.clone = function (name, newEmitter) {
  11630. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  11631. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  11632. if (newEmitter === undefined) {
  11633. newEmitter = this.emitter;
  11634. }
  11635. result.emitter = newEmitter;
  11636. if (this.particleTexture) {
  11637. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  11638. }
  11639. result.start();
  11640. return result;
  11641. };
  11642. ParticleSystem.BLENDMODE_ONEONE = 0;
  11643. ParticleSystem.BLENDMODE_STANDARD = 1;
  11644. return ParticleSystem;
  11645. })();
  11646. BABYLON.ParticleSystem = ParticleSystem;
  11647. })(BABYLON || (BABYLON = {}));
  11648. var BABYLON;
  11649. (function (BABYLON) {
  11650. var Animation = (function () {
  11651. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  11652. this.name = name;
  11653. this.targetProperty = targetProperty;
  11654. this.framePerSecond = framePerSecond;
  11655. this.dataType = dataType;
  11656. this.loopMode = loopMode;
  11657. this._offsetsCache = {};
  11658. this._highLimitsCache = {};
  11659. this._stopped = false;
  11660. this.targetPropertyPath = targetProperty.split(".");
  11661. this.dataType = dataType;
  11662. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  11663. }
  11664. Animation.prototype.isStopped = function () {
  11665. return this._stopped;
  11666. };
  11667. Animation.prototype.getKeys = function () {
  11668. return this._keys;
  11669. };
  11670. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  11671. return startValue + (endValue - startValue) * gradient;
  11672. };
  11673. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  11674. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  11675. };
  11676. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  11677. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  11678. };
  11679. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  11680. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  11681. };
  11682. Animation.prototype.clone = function () {
  11683. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  11684. clone.setKeys(this._keys);
  11685. return clone;
  11686. };
  11687. Animation.prototype.setKeys = function (values) {
  11688. this._keys = values.slice(0);
  11689. this._offsetsCache = {};
  11690. this._highLimitsCache = {};
  11691. };
  11692. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  11693. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  11694. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  11695. }
  11696. this.currentFrame = currentFrame;
  11697. for (var key = 0; key < this._keys.length; key++) {
  11698. if (this._keys[key + 1].frame >= currentFrame) {
  11699. var startValue = this._keys[key].value;
  11700. var endValue = this._keys[key + 1].value;
  11701. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  11702. switch (this.dataType) {
  11703. case Animation.ANIMATIONTYPE_FLOAT:
  11704. switch (loopMode) {
  11705. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11706. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11707. return this.floatInterpolateFunction(startValue, endValue, gradient);
  11708. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11709. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  11710. }
  11711. break;
  11712. case Animation.ANIMATIONTYPE_QUATERNION:
  11713. var quaternion = null;
  11714. switch (loopMode) {
  11715. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11716. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11717. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  11718. break;
  11719. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11720. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11721. break;
  11722. }
  11723. return quaternion;
  11724. case Animation.ANIMATIONTYPE_VECTOR3:
  11725. switch (loopMode) {
  11726. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11727. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11728. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  11729. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11730. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11731. }
  11732. case Animation.ANIMATIONTYPE_COLOR3:
  11733. switch (loopMode) {
  11734. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11735. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11736. return this.color3InterpolateFunction(startValue, endValue, gradient);
  11737. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11738. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  11739. }
  11740. case Animation.ANIMATIONTYPE_MATRIX:
  11741. switch (loopMode) {
  11742. case Animation.ANIMATIONLOOPMODE_CYCLE:
  11743. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  11744. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  11745. return startValue;
  11746. }
  11747. default:
  11748. break;
  11749. }
  11750. break;
  11751. }
  11752. }
  11753. return this._keys[this._keys.length - 1].value;
  11754. };
  11755. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  11756. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  11757. this._stopped = true;
  11758. return false;
  11759. }
  11760. var returnValue = true;
  11761. if (this._keys[0].frame != 0) {
  11762. var newKey = {
  11763. frame: 0,
  11764. value: this._keys[0].value
  11765. };
  11766. this._keys.splice(0, 0, newKey);
  11767. }
  11768. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  11769. from = this._keys[0].frame;
  11770. }
  11771. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  11772. to = this._keys[this._keys.length - 1].frame;
  11773. }
  11774. var range = to - from;
  11775. var offsetValue;
  11776. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  11777. if (ratio > range && !loop) {
  11778. returnValue = false;
  11779. highLimitValue = this._keys[this._keys.length - 1].value;
  11780. } else {
  11781. var highLimitValue = 0;
  11782. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  11783. var keyOffset = to.toString() + from.toString();
  11784. if (!this._offsetsCache[keyOffset]) {
  11785. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11786. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  11787. switch (this.dataType) {
  11788. case Animation.ANIMATIONTYPE_FLOAT:
  11789. this._offsetsCache[keyOffset] = toValue - fromValue;
  11790. break;
  11791. case Animation.ANIMATIONTYPE_QUATERNION:
  11792. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11793. break;
  11794. case Animation.ANIMATIONTYPE_VECTOR3:
  11795. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11796. case Animation.ANIMATIONTYPE_COLOR3:
  11797. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  11798. default:
  11799. break;
  11800. }
  11801. this._highLimitsCache[keyOffset] = toValue;
  11802. }
  11803. highLimitValue = this._highLimitsCache[keyOffset];
  11804. offsetValue = this._offsetsCache[keyOffset];
  11805. }
  11806. }
  11807. if (offsetValue === undefined) {
  11808. switch (this.dataType) {
  11809. case Animation.ANIMATIONTYPE_FLOAT:
  11810. offsetValue = 0;
  11811. break;
  11812. case Animation.ANIMATIONTYPE_QUATERNION:
  11813. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  11814. break;
  11815. case Animation.ANIMATIONTYPE_VECTOR3:
  11816. offsetValue = BABYLON.Vector3.Zero();
  11817. break;
  11818. case Animation.ANIMATIONTYPE_COLOR3:
  11819. offsetValue = BABYLON.Color3.Black();
  11820. }
  11821. }
  11822. var repeatCount = (ratio / range) >> 0;
  11823. var currentFrame = returnValue ? from + ratio % range : to;
  11824. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  11825. if (this.targetPropertyPath.length > 1) {
  11826. var property = this._target[this.targetPropertyPath[0]];
  11827. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  11828. property = property[this.targetPropertyPath[index]];
  11829. }
  11830. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  11831. } else {
  11832. this._target[this.targetPropertyPath[0]] = currentValue;
  11833. }
  11834. if (this._target.markAsDirty) {
  11835. this._target.markAsDirty(this.targetProperty);
  11836. }
  11837. if (!returnValue) {
  11838. this._stopped = true;
  11839. }
  11840. return returnValue;
  11841. };
  11842. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  11843. get: function () {
  11844. return Animation._ANIMATIONTYPE_FLOAT;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  11850. get: function () {
  11851. return Animation._ANIMATIONTYPE_VECTOR3;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  11857. get: function () {
  11858. return Animation._ANIMATIONTYPE_QUATERNION;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  11864. get: function () {
  11865. return Animation._ANIMATIONTYPE_MATRIX;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  11871. get: function () {
  11872. return Animation._ANIMATIONTYPE_COLOR3;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  11878. get: function () {
  11879. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  11885. get: function () {
  11886. return Animation._ANIMATIONLOOPMODE_CYCLE;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  11892. get: function () {
  11893. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Animation._ANIMATIONTYPE_FLOAT = 0;
  11899. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  11900. Animation._ANIMATIONTYPE_QUATERNION = 2;
  11901. Animation._ANIMATIONTYPE_MATRIX = 3;
  11902. Animation._ANIMATIONTYPE_COLOR3 = 4;
  11903. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  11904. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  11905. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  11906. return Animation;
  11907. })();
  11908. BABYLON.Animation = Animation;
  11909. })(BABYLON || (BABYLON = {}));
  11910. var BABYLON;
  11911. (function (BABYLON) {
  11912. var Animatable = (function () {
  11913. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  11914. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  11915. if (typeof toFrame === "undefined") { toFrame = 100; }
  11916. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  11917. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  11918. this.target = target;
  11919. this.fromFrame = fromFrame;
  11920. this.toFrame = toFrame;
  11921. this.loopAnimation = loopAnimation;
  11922. this.speedRatio = speedRatio;
  11923. this.onAnimationEnd = onAnimationEnd;
  11924. this._animations = new Array();
  11925. this._paused = false;
  11926. this.animationStarted = false;
  11927. if (animations) {
  11928. this.appendAnimations(target, animations);
  11929. }
  11930. this._scene = scene;
  11931. scene._activeAnimatables.push(this);
  11932. }
  11933. Animatable.prototype.appendAnimations = function (target, animations) {
  11934. for (var index = 0; index < animations.length; index++) {
  11935. var animation = animations[index];
  11936. animation._target = target;
  11937. this._animations.push(animation);
  11938. }
  11939. };
  11940. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  11941. var animations = this._animations;
  11942. for (var index = 0; index < animations.length; index++) {
  11943. if (animations[index].targetProperty === property) {
  11944. return animations[index];
  11945. }
  11946. }
  11947. return null;
  11948. };
  11949. Animatable.prototype.pause = function () {
  11950. this._paused = true;
  11951. };
  11952. Animatable.prototype.restart = function () {
  11953. this._paused = false;
  11954. };
  11955. Animatable.prototype.stop = function () {
  11956. var index = this._scene._activeAnimatables.indexOf(this);
  11957. if (index > -1) {
  11958. this._scene._activeAnimatables.splice(index, 1);
  11959. }
  11960. if (this.onAnimationEnd) {
  11961. this.onAnimationEnd();
  11962. }
  11963. };
  11964. Animatable.prototype._animate = function (delay) {
  11965. if (this._paused) {
  11966. return true;
  11967. }
  11968. if (!this._localDelayOffset) {
  11969. this._localDelayOffset = delay;
  11970. }
  11971. var running = false;
  11972. var animations = this._animations;
  11973. for (var index = 0; index < animations.length; index++) {
  11974. var animation = animations[index];
  11975. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  11976. running = running || isRunning;
  11977. }
  11978. if (!running && this.onAnimationEnd) {
  11979. this.onAnimationEnd();
  11980. }
  11981. return running;
  11982. };
  11983. return Animatable;
  11984. })();
  11985. BABYLON.Animatable = Animatable;
  11986. })(BABYLON || (BABYLON = {}));
  11987. var BABYLON;
  11988. (function (BABYLON) {
  11989. var Octree = (function () {
  11990. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  11991. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  11992. this.maxDepth = maxDepth;
  11993. this.dynamicContent = new Array();
  11994. this._maxBlockCapacity = maxBlockCapacity || 64;
  11995. this._selectionContent = new BABYLON.SmartArray(1024);
  11996. this._creationFunc = creationFunc;
  11997. }
  11998. Octree.prototype.update = function (worldMin, worldMax, entries) {
  11999. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12000. };
  12001. Octree.prototype.addMesh = function (entry) {
  12002. for (var index = 0; index < this.blocks.length; index++) {
  12003. var block = this.blocks[index];
  12004. block.addEntry(entry);
  12005. }
  12006. };
  12007. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12008. this._selectionContent.reset();
  12009. for (var index = 0; index < this.blocks.length; index++) {
  12010. var block = this.blocks[index];
  12011. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12012. }
  12013. if (allowDuplicate) {
  12014. this._selectionContent.concat(this.dynamicContent);
  12015. } else {
  12016. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12017. }
  12018. return this._selectionContent;
  12019. };
  12020. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12021. this._selectionContent.reset();
  12022. for (var index = 0; index < this.blocks.length; index++) {
  12023. var block = this.blocks[index];
  12024. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12025. }
  12026. if (allowDuplicate) {
  12027. this._selectionContent.concat(this.dynamicContent);
  12028. } else {
  12029. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12030. }
  12031. return this._selectionContent;
  12032. };
  12033. Octree.prototype.intersectsRay = function (ray) {
  12034. this._selectionContent.reset();
  12035. for (var index = 0; index < this.blocks.length; index++) {
  12036. var block = this.blocks[index];
  12037. block.intersectsRay(ray, this._selectionContent);
  12038. }
  12039. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12040. return this._selectionContent;
  12041. };
  12042. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12043. target.blocks = new Array();
  12044. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12045. for (var x = 0; x < 2; x++) {
  12046. for (var y = 0; y < 2; y++) {
  12047. for (var z = 0; z < 2; z++) {
  12048. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12049. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12050. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12051. block.addEntries(entries);
  12052. target.blocks.push(block);
  12053. }
  12054. }
  12055. }
  12056. };
  12057. Octree.CreationFuncForMeshes = function (entry, block) {
  12058. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12059. block.entries.push(entry);
  12060. }
  12061. };
  12062. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12063. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12064. block.entries.push(entry);
  12065. }
  12066. };
  12067. return Octree;
  12068. })();
  12069. BABYLON.Octree = Octree;
  12070. })(BABYLON || (BABYLON = {}));
  12071. var BABYLON;
  12072. (function (BABYLON) {
  12073. var OctreeBlock = (function () {
  12074. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12075. this.entries = new Array();
  12076. this._boundingVectors = new Array();
  12077. this._capacity = capacity;
  12078. this._depth = depth;
  12079. this._maxDepth = maxDepth;
  12080. this._creationFunc = creationFunc;
  12081. this._minPoint = minPoint;
  12082. this._maxPoint = maxPoint;
  12083. this._boundingVectors.push(minPoint.clone());
  12084. this._boundingVectors.push(maxPoint.clone());
  12085. this._boundingVectors.push(minPoint.clone());
  12086. this._boundingVectors[2].x = maxPoint.x;
  12087. this._boundingVectors.push(minPoint.clone());
  12088. this._boundingVectors[3].y = maxPoint.y;
  12089. this._boundingVectors.push(minPoint.clone());
  12090. this._boundingVectors[4].z = maxPoint.z;
  12091. this._boundingVectors.push(maxPoint.clone());
  12092. this._boundingVectors[5].z = minPoint.z;
  12093. this._boundingVectors.push(maxPoint.clone());
  12094. this._boundingVectors[6].x = minPoint.x;
  12095. this._boundingVectors.push(maxPoint.clone());
  12096. this._boundingVectors[7].y = minPoint.y;
  12097. }
  12098. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12099. get: function () {
  12100. return this._capacity;
  12101. },
  12102. enumerable: true,
  12103. configurable: true
  12104. });
  12105. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12106. get: function () {
  12107. return this._minPoint;
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12113. get: function () {
  12114. return this._maxPoint;
  12115. },
  12116. enumerable: true,
  12117. configurable: true
  12118. });
  12119. OctreeBlock.prototype.addEntry = function (entry) {
  12120. if (this.blocks) {
  12121. for (var index = 0; index < this.blocks.length; index++) {
  12122. var block = this.blocks[index];
  12123. block.addEntry(entry);
  12124. }
  12125. return;
  12126. }
  12127. this._creationFunc(entry, this);
  12128. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12129. this.createInnerBlocks();
  12130. }
  12131. };
  12132. OctreeBlock.prototype.addEntries = function (entries) {
  12133. for (var index = 0; index < entries.length; index++) {
  12134. var mesh = entries[index];
  12135. this.addEntry(mesh);
  12136. }
  12137. };
  12138. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12139. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12140. if (this.blocks) {
  12141. for (var index = 0; index < this.blocks.length; index++) {
  12142. var block = this.blocks[index];
  12143. block.select(frustumPlanes, selection, allowDuplicate);
  12144. }
  12145. return;
  12146. }
  12147. if (allowDuplicate) {
  12148. selection.concat(this.entries);
  12149. } else {
  12150. selection.concatWithNoDuplicate(this.entries);
  12151. }
  12152. }
  12153. };
  12154. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12155. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12156. if (this.blocks) {
  12157. for (var index = 0; index < this.blocks.length; index++) {
  12158. var block = this.blocks[index];
  12159. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12160. }
  12161. return;
  12162. }
  12163. if (allowDuplicate) {
  12164. selection.concat(this.entries);
  12165. } else {
  12166. selection.concatWithNoDuplicate(this.entries);
  12167. }
  12168. }
  12169. };
  12170. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12171. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12172. if (this.blocks) {
  12173. for (var index = 0; index < this.blocks.length; index++) {
  12174. var block = this.blocks[index];
  12175. block.intersectsRay(ray, selection);
  12176. }
  12177. return;
  12178. }
  12179. selection.concatWithNoDuplicate(this.entries);
  12180. }
  12181. };
  12182. OctreeBlock.prototype.createInnerBlocks = function () {
  12183. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12184. };
  12185. return OctreeBlock;
  12186. })();
  12187. BABYLON.OctreeBlock = OctreeBlock;
  12188. })(BABYLON || (BABYLON = {}));
  12189. var BABYLON;
  12190. (function (BABYLON) {
  12191. var Bone = (function () {
  12192. function Bone(name, skeleton, parentBone, matrix) {
  12193. this.name = name;
  12194. this.children = new Array();
  12195. this.animations = new Array();
  12196. this._worldTransform = new BABYLON.Matrix();
  12197. this._absoluteTransform = new BABYLON.Matrix();
  12198. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12199. this._skeleton = skeleton;
  12200. this._matrix = matrix;
  12201. this._baseMatrix = matrix;
  12202. skeleton.bones.push(this);
  12203. if (parentBone) {
  12204. this._parent = parentBone;
  12205. parentBone.children.push(this);
  12206. } else {
  12207. this._parent = null;
  12208. }
  12209. this._updateDifferenceMatrix();
  12210. }
  12211. Bone.prototype.getParent = function () {
  12212. return this._parent;
  12213. };
  12214. Bone.prototype.getLocalMatrix = function () {
  12215. return this._matrix;
  12216. };
  12217. Bone.prototype.getBaseMatrix = function () {
  12218. return this._baseMatrix;
  12219. };
  12220. Bone.prototype.getWorldMatrix = function () {
  12221. return this._worldTransform;
  12222. };
  12223. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12224. return this._invertedAbsoluteTransform;
  12225. };
  12226. Bone.prototype.getAbsoluteMatrix = function () {
  12227. var matrix = this._matrix.clone();
  12228. var parent = this._parent;
  12229. while (parent) {
  12230. matrix = matrix.multiply(parent.getLocalMatrix());
  12231. parent = parent.getParent();
  12232. }
  12233. return matrix;
  12234. };
  12235. Bone.prototype.updateMatrix = function (matrix) {
  12236. this._matrix = matrix;
  12237. this._skeleton._markAsDirty();
  12238. this._updateDifferenceMatrix();
  12239. };
  12240. Bone.prototype._updateDifferenceMatrix = function () {
  12241. if (this._parent) {
  12242. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12243. } else {
  12244. this._absoluteTransform.copyFrom(this._matrix);
  12245. }
  12246. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12247. for (var index = 0; index < this.children.length; index++) {
  12248. this.children[index]._updateDifferenceMatrix();
  12249. }
  12250. };
  12251. Bone.prototype.markAsDirty = function () {
  12252. this._skeleton._markAsDirty();
  12253. };
  12254. return Bone;
  12255. })();
  12256. BABYLON.Bone = Bone;
  12257. })(BABYLON || (BABYLON = {}));
  12258. var BABYLON;
  12259. (function (BABYLON) {
  12260. var Skeleton = (function () {
  12261. function Skeleton(name, id, scene) {
  12262. this.name = name;
  12263. this.id = id;
  12264. this.bones = new Array();
  12265. this._isDirty = true;
  12266. this._identity = BABYLON.Matrix.Identity();
  12267. this.bones = [];
  12268. this._scene = scene;
  12269. scene.skeletons.push(this);
  12270. }
  12271. Skeleton.prototype.getTransformMatrices = function () {
  12272. return this._transformMatrices;
  12273. };
  12274. Skeleton.prototype._markAsDirty = function () {
  12275. this._isDirty = true;
  12276. };
  12277. Skeleton.prototype.prepare = function () {
  12278. if (!this._isDirty) {
  12279. return;
  12280. }
  12281. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12282. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12283. }
  12284. for (var index = 0; index < this.bones.length; index++) {
  12285. var bone = this.bones[index];
  12286. var parentBone = bone.getParent();
  12287. if (parentBone) {
  12288. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12289. } else {
  12290. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12291. }
  12292. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12293. }
  12294. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12295. this._isDirty = false;
  12296. };
  12297. Skeleton.prototype.getAnimatables = function () {
  12298. if (!this._animatables || this._animatables.length != this.bones.length) {
  12299. this._animatables = [];
  12300. for (var index = 0; index < this.bones.length; index++) {
  12301. this._animatables.push(this.bones[index]);
  12302. }
  12303. }
  12304. return this._animatables;
  12305. };
  12306. Skeleton.prototype.clone = function (name, id) {
  12307. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12308. for (var index = 0; index < this.bones.length; index++) {
  12309. var source = this.bones[index];
  12310. var parentBone = null;
  12311. if (source.getParent()) {
  12312. var parentIndex = this.bones.indexOf(source.getParent());
  12313. parentBone = result.bones[parentIndex];
  12314. }
  12315. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12316. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12317. }
  12318. return result;
  12319. };
  12320. return Skeleton;
  12321. })();
  12322. BABYLON.Skeleton = Skeleton;
  12323. })(BABYLON || (BABYLON = {}));
  12324. var BABYLON;
  12325. (function (BABYLON) {
  12326. var PostProcess = (function () {
  12327. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12328. this.name = name;
  12329. this.width = -1;
  12330. this.height = -1;
  12331. this._reusable = false;
  12332. this._textures = new BABYLON.SmartArray(2);
  12333. this._currentRenderTextureInd = 0;
  12334. if (camera != null) {
  12335. this._camera = camera;
  12336. this._scene = camera.getScene();
  12337. camera.attachPostProcess(this);
  12338. this._engine = this._scene.getEngine();
  12339. } else {
  12340. this._engine = engine;
  12341. }
  12342. this._renderRatio = ratio;
  12343. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12344. this._reusable = reusable || false;
  12345. samplers = samplers || [];
  12346. samplers.push("textureSampler");
  12347. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12348. }
  12349. PostProcess.prototype.isReusable = function () {
  12350. return this._reusable;
  12351. };
  12352. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12353. camera = camera || this._camera;
  12354. var scene = camera.getScene();
  12355. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  12356. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  12357. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  12358. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  12359. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  12360. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12361. if (this._textures.length > 0) {
  12362. for (var i = 0; i < this._textures.length; i++) {
  12363. this._engine._releaseTexture(this._textures.data[i]);
  12364. }
  12365. this._textures.reset();
  12366. }
  12367. this.width = desiredWidth;
  12368. this.height = desiredHeight;
  12369. 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 }));
  12370. if (this._reusable) {
  12371. 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 }));
  12372. }
  12373. if (this.onSizeChanged) {
  12374. this.onSizeChanged();
  12375. }
  12376. }
  12377. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12378. if (this.onActivate) {
  12379. this.onActivate(camera);
  12380. }
  12381. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12382. if (this._reusable) {
  12383. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12384. }
  12385. };
  12386. PostProcess.prototype.apply = function () {
  12387. if (!this._effect.isReady())
  12388. return null;
  12389. this._engine.enableEffect(this._effect);
  12390. this._engine.setState(false);
  12391. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12392. this._engine.setDepthBuffer(false);
  12393. this._engine.setDepthWrite(false);
  12394. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12395. if (this.onApply) {
  12396. this.onApply(this._effect);
  12397. }
  12398. return this._effect;
  12399. };
  12400. PostProcess.prototype.dispose = function (camera) {
  12401. camera = camera || this._camera;
  12402. if (this._textures.length > 0) {
  12403. for (var i = 0; i < this._textures.length; i++) {
  12404. this._engine._releaseTexture(this._textures.data[i]);
  12405. }
  12406. this._textures.reset();
  12407. }
  12408. camera.detachPostProcess(this);
  12409. var index = camera._postProcesses.indexOf(this);
  12410. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12411. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12412. }
  12413. };
  12414. return PostProcess;
  12415. })();
  12416. BABYLON.PostProcess = PostProcess;
  12417. })(BABYLON || (BABYLON = {}));
  12418. var BABYLON;
  12419. (function (BABYLON) {
  12420. var PostProcessManager = (function () {
  12421. function PostProcessManager(scene) {
  12422. this._vertexDeclaration = [2];
  12423. this._vertexStrideSize = 2 * 4;
  12424. this._scene = scene;
  12425. var vertices = [];
  12426. vertices.push(1, 1);
  12427. vertices.push(-1, 1);
  12428. vertices.push(-1, -1);
  12429. vertices.push(1, -1);
  12430. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12431. var indices = [];
  12432. indices.push(0);
  12433. indices.push(1);
  12434. indices.push(2);
  12435. indices.push(0);
  12436. indices.push(2);
  12437. indices.push(3);
  12438. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12439. }
  12440. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12441. var postProcesses = this._scene.activeCamera._postProcesses;
  12442. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12443. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12444. return false;
  12445. }
  12446. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12447. return true;
  12448. };
  12449. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12450. var postProcesses = this._scene.activeCamera._postProcesses;
  12451. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12452. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12453. return;
  12454. }
  12455. var engine = this._scene.getEngine();
  12456. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12457. if (index < postProcessesTakenIndices.length - 1) {
  12458. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12459. } else {
  12460. if (targetTexture) {
  12461. engine.bindFramebuffer(targetTexture);
  12462. } else {
  12463. engine.restoreDefaultFramebuffer();
  12464. }
  12465. }
  12466. if (doNotPresent) {
  12467. break;
  12468. }
  12469. var pp = postProcesses[postProcessesTakenIndices[index]];
  12470. var effect = pp.apply();
  12471. if (effect) {
  12472. if (pp.onBeforeRender) {
  12473. pp.onBeforeRender(effect);
  12474. }
  12475. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12476. engine.draw(true, 0, 6);
  12477. }
  12478. }
  12479. engine.setDepthBuffer(true);
  12480. engine.setDepthWrite(true);
  12481. };
  12482. PostProcessManager.prototype.dispose = function () {
  12483. if (this._vertexBuffer) {
  12484. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12485. this._vertexBuffer = null;
  12486. }
  12487. if (this._indexBuffer) {
  12488. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12489. this._indexBuffer = null;
  12490. }
  12491. };
  12492. return PostProcessManager;
  12493. })();
  12494. BABYLON.PostProcessManager = PostProcessManager;
  12495. })(BABYLON || (BABYLON = {}));
  12496. var __extends = this.__extends || function (d, b) {
  12497. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12498. function __() { this.constructor = d; }
  12499. __.prototype = b.prototype;
  12500. d.prototype = new __();
  12501. };
  12502. var BABYLON;
  12503. (function (BABYLON) {
  12504. var PassPostProcess = (function (_super) {
  12505. __extends(PassPostProcess, _super);
  12506. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12507. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12508. }
  12509. return PassPostProcess;
  12510. })(BABYLON.PostProcess);
  12511. BABYLON.PassPostProcess = PassPostProcess;
  12512. })(BABYLON || (BABYLON = {}));
  12513. var __extends = this.__extends || function (d, b) {
  12514. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12515. function __() { this.constructor = d; }
  12516. __.prototype = b.prototype;
  12517. d.prototype = new __();
  12518. };
  12519. var BABYLON;
  12520. (function (BABYLON) {
  12521. var BlurPostProcess = (function (_super) {
  12522. __extends(BlurPostProcess, _super);
  12523. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12524. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12525. var _this = this;
  12526. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12527. this.direction = direction;
  12528. this.blurWidth = blurWidth;
  12529. this.onApply = function (effect) {
  12530. effect.setFloat2("screenSize", _this.width, _this.height);
  12531. effect.setVector2("direction", _this.direction);
  12532. effect.setFloat("blurWidth", _this.blurWidth);
  12533. };
  12534. }
  12535. return BlurPostProcess;
  12536. })(BABYLON.PostProcess);
  12537. BABYLON.BlurPostProcess = BlurPostProcess;
  12538. })(BABYLON || (BABYLON = {}));
  12539. var __extends = this.__extends || function (d, b) {
  12540. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12541. function __() { this.constructor = d; }
  12542. __.prototype = b.prototype;
  12543. d.prototype = new __();
  12544. };
  12545. var BABYLON;
  12546. (function (BABYLON) {
  12547. var FilterPostProcess = (function (_super) {
  12548. __extends(FilterPostProcess, _super);
  12549. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  12550. var _this = this;
  12551. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  12552. this.kernelMatrix = kernelMatrix;
  12553. this.onApply = function (effect) {
  12554. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  12555. };
  12556. }
  12557. return FilterPostProcess;
  12558. })(BABYLON.PostProcess);
  12559. BABYLON.FilterPostProcess = FilterPostProcess;
  12560. })(BABYLON || (BABYLON = {}));
  12561. var __extends = this.__extends || function (d, b) {
  12562. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12563. function __() { this.constructor = d; }
  12564. __.prototype = b.prototype;
  12565. d.prototype = new __();
  12566. };
  12567. var BABYLON;
  12568. (function (BABYLON) {
  12569. var RefractionPostProcess = (function (_super) {
  12570. __extends(RefractionPostProcess, _super);
  12571. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  12572. var _this = this;
  12573. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  12574. this.color = color;
  12575. this.depth = depth;
  12576. this.colorLevel = colorLevel;
  12577. this.onActivate = function (cam) {
  12578. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  12579. };
  12580. this.onApply = function (effect) {
  12581. effect.setColor3("baseColor", _this.color);
  12582. effect.setFloat("depth", _this.depth);
  12583. effect.setFloat("colorLevel", _this.colorLevel);
  12584. effect.setTexture("refractionSampler", _this._refRexture);
  12585. };
  12586. }
  12587. RefractionPostProcess.prototype.dispose = function (camera) {
  12588. if (this._refRexture) {
  12589. this._refRexture.dispose();
  12590. }
  12591. _super.prototype.dispose.call(this, camera);
  12592. };
  12593. return RefractionPostProcess;
  12594. })(BABYLON.PostProcess);
  12595. BABYLON.RefractionPostProcess = RefractionPostProcess;
  12596. })(BABYLON || (BABYLON = {}));
  12597. var __extends = this.__extends || function (d, b) {
  12598. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12599. function __() { this.constructor = d; }
  12600. __.prototype = b.prototype;
  12601. d.prototype = new __();
  12602. };
  12603. var BABYLON;
  12604. (function (BABYLON) {
  12605. var BlackAndWhitePostProcess = (function (_super) {
  12606. __extends(BlackAndWhitePostProcess, _super);
  12607. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12608. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  12609. }
  12610. return BlackAndWhitePostProcess;
  12611. })(BABYLON.PostProcess);
  12612. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  12613. })(BABYLON || (BABYLON = {}));
  12614. var __extends = this.__extends || function (d, b) {
  12615. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12616. function __() { this.constructor = d; }
  12617. __.prototype = b.prototype;
  12618. d.prototype = new __();
  12619. };
  12620. var BABYLON;
  12621. (function (BABYLON) {
  12622. var ConvolutionPostProcess = (function (_super) {
  12623. __extends(ConvolutionPostProcess, _super);
  12624. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  12625. var _this = this;
  12626. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  12627. this.kernel = kernel;
  12628. this.onApply = function (effect) {
  12629. effect.setFloat2("screenSize", _this.width, _this.height);
  12630. effect.setArray("kernel", _this.kernel);
  12631. };
  12632. }
  12633. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  12634. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  12635. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  12636. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  12637. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  12638. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  12639. return ConvolutionPostProcess;
  12640. })(BABYLON.PostProcess);
  12641. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  12642. })(BABYLON || (BABYLON = {}));
  12643. var __extends = this.__extends || function (d, b) {
  12644. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12645. function __() { this.constructor = d; }
  12646. __.prototype = b.prototype;
  12647. d.prototype = new __();
  12648. };
  12649. var BABYLON;
  12650. (function (BABYLON) {
  12651. var FxaaPostProcess = (function (_super) {
  12652. __extends(FxaaPostProcess, _super);
  12653. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12654. var _this = this;
  12655. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  12656. this.onSizeChanged = function () {
  12657. _this.texelWidth = 1.0 / _this.width;
  12658. _this.texelHeight = 1.0 / _this.height;
  12659. };
  12660. this.onApply = function (effect) {
  12661. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  12662. };
  12663. }
  12664. return FxaaPostProcess;
  12665. })(BABYLON.PostProcess);
  12666. BABYLON.FxaaPostProcess = FxaaPostProcess;
  12667. })(BABYLON || (BABYLON = {}));
  12668. var BABYLON;
  12669. (function (BABYLON) {
  12670. var LensFlare = (function () {
  12671. function LensFlare(size, position, color, imgUrl, system) {
  12672. this.size = size;
  12673. this.position = position;
  12674. this.dispose = function () {
  12675. if (this.texture) {
  12676. this.texture.dispose();
  12677. }
  12678. var index = this._system.lensFlares.indexOf(this);
  12679. this._system.lensFlares.splice(index, 1);
  12680. };
  12681. this.color = color || new BABYLON.Color3(1, 1, 1);
  12682. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  12683. this._system = system;
  12684. system.lensFlares.push(this);
  12685. }
  12686. return LensFlare;
  12687. })();
  12688. BABYLON.LensFlare = LensFlare;
  12689. })(BABYLON || (BABYLON = {}));
  12690. var BABYLON;
  12691. (function (BABYLON) {
  12692. var LensFlareSystem = (function () {
  12693. function LensFlareSystem(name, emitter, scene) {
  12694. this.name = name;
  12695. this.lensFlares = new Array();
  12696. this.borderLimit = 300;
  12697. this._vertexDeclaration = [2];
  12698. this._vertexStrideSize = 2 * 4;
  12699. this._isEnabled = true;
  12700. this._scene = scene;
  12701. this._emitter = emitter;
  12702. scene.lensFlareSystems.push(this);
  12703. this.meshesSelectionPredicate = function (m) {
  12704. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  12705. };
  12706. var vertices = [];
  12707. vertices.push(1, 1);
  12708. vertices.push(-1, 1);
  12709. vertices.push(-1, -1);
  12710. vertices.push(1, -1);
  12711. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12712. var indices = [];
  12713. indices.push(0);
  12714. indices.push(1);
  12715. indices.push(2);
  12716. indices.push(0);
  12717. indices.push(2);
  12718. indices.push(3);
  12719. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12720. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  12721. }
  12722. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  12723. get: function () {
  12724. return this._isEnabled;
  12725. },
  12726. set: function (value) {
  12727. this._isEnabled = value;
  12728. },
  12729. enumerable: true,
  12730. configurable: true
  12731. });
  12732. LensFlareSystem.prototype.getScene = function () {
  12733. return this._scene;
  12734. };
  12735. LensFlareSystem.prototype.getEmitter = function () {
  12736. return this._emitter;
  12737. };
  12738. LensFlareSystem.prototype.getEmitterPosition = function () {
  12739. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  12740. };
  12741. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  12742. var position = this.getEmitterPosition();
  12743. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  12744. this._positionX = position.x;
  12745. this._positionY = position.y;
  12746. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  12747. if (position.z > 0) {
  12748. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  12749. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  12750. return true;
  12751. }
  12752. }
  12753. return false;
  12754. };
  12755. LensFlareSystem.prototype._isVisible = function () {
  12756. if (!this._isEnabled) {
  12757. return false;
  12758. }
  12759. var emitterPosition = this.getEmitterPosition();
  12760. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  12761. var distance = direction.length();
  12762. direction.normalize();
  12763. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  12764. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  12765. return !pickInfo.hit || pickInfo.distance > distance;
  12766. };
  12767. LensFlareSystem.prototype.render = function () {
  12768. if (!this._effect.isReady())
  12769. return false;
  12770. var engine = this._scene.getEngine();
  12771. var viewport = this._scene.activeCamera.viewport;
  12772. var globalViewport = viewport.toGlobal(engine);
  12773. if (!this.computeEffectivePosition(globalViewport)) {
  12774. return false;
  12775. }
  12776. if (!this._isVisible()) {
  12777. return false;
  12778. }
  12779. var awayX;
  12780. var awayY;
  12781. if (this._positionX < this.borderLimit + globalViewport.x) {
  12782. awayX = this.borderLimit + globalViewport.x - this._positionX;
  12783. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  12784. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  12785. } else {
  12786. awayX = 0;
  12787. }
  12788. if (this._positionY < this.borderLimit + globalViewport.y) {
  12789. awayY = this.borderLimit + globalViewport.y - this._positionY;
  12790. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  12791. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  12792. } else {
  12793. awayY = 0;
  12794. }
  12795. var away = (awayX > awayY) ? awayX : awayY;
  12796. if (away > this.borderLimit) {
  12797. away = this.borderLimit;
  12798. }
  12799. var intensity = 1.0 - (away / this.borderLimit);
  12800. if (intensity < 0) {
  12801. return false;
  12802. }
  12803. if (intensity > 1.0) {
  12804. intensity = 1.0;
  12805. }
  12806. var centerX = globalViewport.x + globalViewport.width / 2;
  12807. var centerY = globalViewport.y + globalViewport.height / 2;
  12808. var distX = centerX - this._positionX;
  12809. var distY = centerY - this._positionY;
  12810. engine.enableEffect(this._effect);
  12811. engine.setState(false);
  12812. engine.setDepthBuffer(false);
  12813. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12814. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12815. for (var index = 0; index < this.lensFlares.length; index++) {
  12816. var flare = this.lensFlares[index];
  12817. var x = centerX - (distX * flare.position);
  12818. var y = centerY - (distY * flare.position);
  12819. var cw = flare.size;
  12820. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  12821. var cx = 2 * (x / globalViewport.width) - 1.0;
  12822. var cy = 1.0 - 2 * (y / globalViewport.height);
  12823. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  12824. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  12825. this._effect.setTexture("textureSampler", flare.texture);
  12826. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  12827. engine.draw(true, 0, 6);
  12828. }
  12829. engine.setDepthBuffer(true);
  12830. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12831. return true;
  12832. };
  12833. LensFlareSystem.prototype.dispose = function () {
  12834. if (this._vertexBuffer) {
  12835. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12836. this._vertexBuffer = null;
  12837. }
  12838. if (this._indexBuffer) {
  12839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12840. this._indexBuffer = null;
  12841. }
  12842. while (this.lensFlares.length) {
  12843. this.lensFlares[0].dispose();
  12844. }
  12845. var index = this._scene.lensFlareSystems.indexOf(this);
  12846. this._scene.lensFlareSystems.splice(index, 1);
  12847. };
  12848. return LensFlareSystem;
  12849. })();
  12850. BABYLON.LensFlareSystem = LensFlareSystem;
  12851. })(BABYLON || (BABYLON = {}));
  12852. var BABYLON;
  12853. (function (BABYLON) {
  12854. var IntersectionInfo = (function () {
  12855. function IntersectionInfo(bu, bv, distance) {
  12856. this.bu = bu;
  12857. this.bv = bv;
  12858. this.distance = distance;
  12859. this.faceId = 0;
  12860. }
  12861. return IntersectionInfo;
  12862. })();
  12863. BABYLON.IntersectionInfo = IntersectionInfo;
  12864. var PickingInfo = (function () {
  12865. function PickingInfo() {
  12866. this.hit = false;
  12867. this.distance = 0;
  12868. this.pickedPoint = null;
  12869. this.pickedMesh = null;
  12870. this.bu = 0;
  12871. this.bv = 0;
  12872. this.faceId = -1;
  12873. }
  12874. PickingInfo.prototype.getNormal = function () {
  12875. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12876. return null;
  12877. }
  12878. var indices = this.pickedMesh.getIndices();
  12879. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12880. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  12881. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  12882. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  12883. normal0 = normal0.scale(this.bu);
  12884. normal1 = normal1.scale(this.bv);
  12885. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  12886. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  12887. };
  12888. PickingInfo.prototype.getTextureCoordinates = function () {
  12889. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12890. return null;
  12891. }
  12892. var indices = this.pickedMesh.getIndices();
  12893. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  12894. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  12895. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  12896. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  12897. uv0 = uv0.scale(this.bu);
  12898. uv1 = uv1.scale(this.bv);
  12899. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  12900. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  12901. };
  12902. return PickingInfo;
  12903. })();
  12904. BABYLON.PickingInfo = PickingInfo;
  12905. })(BABYLON || (BABYLON = {}));
  12906. var BABYLON;
  12907. (function (BABYLON) {
  12908. var FilesInput = (function () {
  12909. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  12910. this.engine = p_engine;
  12911. this.canvas = p_canvas;
  12912. this.currentScene = p_scene;
  12913. this.sceneLoadedCallback = p_sceneLoadedCallback;
  12914. this.progressCallback = p_progressCallback;
  12915. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  12916. this.textureLoadingCallback = p_textureLoadingCallback;
  12917. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  12918. }
  12919. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  12920. var _this = this;
  12921. if (p_elementToMonitor) {
  12922. this.elementToMonitor = p_elementToMonitor;
  12923. this.elementToMonitor.addEventListener("dragenter", function (e) {
  12924. _this.drag(e);
  12925. }, false);
  12926. this.elementToMonitor.addEventListener("dragover", function (e) {
  12927. _this.drag(e);
  12928. }, false);
  12929. this.elementToMonitor.addEventListener("drop", function (e) {
  12930. _this.drop(e);
  12931. }, false);
  12932. }
  12933. };
  12934. FilesInput.prototype.renderFunction = function () {
  12935. if (this.additionnalRenderLoopLogicCallback) {
  12936. this.additionnalRenderLoopLogicCallback();
  12937. }
  12938. if (this.currentScene) {
  12939. if (this.textureLoadingCallback) {
  12940. var remaining = this.currentScene.getWaitingItemsCount();
  12941. if (remaining > 0) {
  12942. this.textureLoadingCallback(remaining);
  12943. }
  12944. }
  12945. this.currentScene.render();
  12946. }
  12947. };
  12948. FilesInput.prototype.drag = function (e) {
  12949. e.stopPropagation();
  12950. e.preventDefault();
  12951. };
  12952. FilesInput.prototype.drop = function (eventDrop) {
  12953. eventDrop.stopPropagation();
  12954. eventDrop.preventDefault();
  12955. this.loadFiles(eventDrop);
  12956. };
  12957. FilesInput.prototype.loadFiles = function (event) {
  12958. var _this = this;
  12959. var that = this;
  12960. if (this.startingProcessingFilesCallback)
  12961. this.startingProcessingFilesCallback();
  12962. var sceneFileToLoad;
  12963. var filesToLoad;
  12964. if (event && event.dataTransfer && event.dataTransfer.files) {
  12965. filesToLoad = event.dataTransfer.files;
  12966. }
  12967. if (event && event.target && event.target.files) {
  12968. filesToLoad = event.target.files;
  12969. }
  12970. if (filesToLoad && filesToLoad.length > 0) {
  12971. for (var i = 0; i < filesToLoad.length; i++) {
  12972. switch (filesToLoad[i].type) {
  12973. case "image/jpeg":
  12974. case "image/png":
  12975. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  12976. break;
  12977. case "image/targa":
  12978. case "image/vnd.ms-dds":
  12979. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  12980. break;
  12981. default:
  12982. 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) {
  12983. sceneFileToLoad = filesToLoad[i];
  12984. }
  12985. break;
  12986. }
  12987. }
  12988. if (sceneFileToLoad) {
  12989. if (this.currentScene) {
  12990. this.engine.stopRenderLoop();
  12991. this.currentScene.dispose();
  12992. }
  12993. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  12994. that.currentScene = newScene;
  12995. that.currentScene.executeWhenReady(function () {
  12996. if (that.currentScene.activeCamera) {
  12997. that.currentScene.activeCamera.attachControl(that.canvas);
  12998. }
  12999. if (that.sceneLoadedCallback) {
  13000. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13001. }
  13002. that.engine.runRenderLoop(function () {
  13003. that.renderFunction();
  13004. });
  13005. });
  13006. }, function (progress) {
  13007. if (_this.progressCallback) {
  13008. _this.progressCallback(progress);
  13009. }
  13010. });
  13011. } else {
  13012. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13013. }
  13014. }
  13015. };
  13016. FilesInput.FilesTextures = new Array();
  13017. FilesInput.FilesToLoad = new Array();
  13018. return FilesInput;
  13019. })();
  13020. BABYLON.FilesInput = FilesInput;
  13021. })(BABYLON || (BABYLON = {}));
  13022. var BABYLON;
  13023. (function (BABYLON) {
  13024. var OimoJSPlugin = (function () {
  13025. function OimoJSPlugin() {
  13026. this._registeredMeshes = [];
  13027. /**
  13028. * Update the body position according to the mesh position
  13029. * @param mesh
  13030. */
  13031. this.updateBodyPosition = function (mesh) {
  13032. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13033. var registeredMesh = this._registeredMeshes[index];
  13034. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13035. var body = registeredMesh.body.body;
  13036. var center = mesh.getBoundingInfo().boundingBox.center;
  13037. body.setPosition(center.x, center.y, center.z);
  13038. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13039. return;
  13040. }
  13041. if (registeredMesh.mesh.parent === mesh) {
  13042. mesh.computeWorldMatrix(true);
  13043. registeredMesh.mesh.computeWorldMatrix(true);
  13044. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13045. var absoluteRotation = mesh.rotation;
  13046. body = registeredMesh.body.body;
  13047. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13048. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13049. return;
  13050. }
  13051. }
  13052. };
  13053. }
  13054. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13055. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13056. };
  13057. OimoJSPlugin.prototype.initialize = function (iterations) {
  13058. this._world = new OIMO.World();
  13059. this._world.clear();
  13060. };
  13061. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13062. this._world.gravity = gravity;
  13063. };
  13064. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13065. var body = null;
  13066. this.unregisterMesh(mesh);
  13067. mesh.computeWorldMatrix(true);
  13068. switch (impostor) {
  13069. case BABYLON.PhysicsEngine.SphereImpostor:
  13070. var bbox = mesh.getBoundingInfo().boundingBox;
  13071. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13072. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13073. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13074. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13075. var deltaPosition = mesh.position.subtract(bbox.center);
  13076. body = new OIMO.Body({
  13077. type: 'sphere',
  13078. size: [size],
  13079. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13080. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13081. move: options.mass != 0,
  13082. config: [options.mass, options.friction, options.restitution],
  13083. world: this._world
  13084. });
  13085. this._registeredMeshes.push({
  13086. mesh: mesh,
  13087. body: body,
  13088. delta: deltaPosition
  13089. });
  13090. break;
  13091. case BABYLON.PhysicsEngine.PlaneImpostor:
  13092. case BABYLON.PhysicsEngine.BoxImpostor:
  13093. bbox = mesh.getBoundingInfo().boundingBox;
  13094. var min = bbox.minimumWorld;
  13095. var max = bbox.maximumWorld;
  13096. var box = max.subtract(min);
  13097. var sizeX = this._checkWithEpsilon(box.x);
  13098. var sizeY = this._checkWithEpsilon(box.y);
  13099. var sizeZ = this._checkWithEpsilon(box.z);
  13100. var deltaPosition = mesh.position.subtract(bbox.center);
  13101. body = new OIMO.Body({
  13102. type: 'box',
  13103. size: [sizeX, sizeY, sizeZ],
  13104. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13105. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13106. move: options.mass != 0,
  13107. config: [options.mass, options.friction, options.restitution],
  13108. world: this._world
  13109. });
  13110. this._registeredMeshes.push({
  13111. mesh: mesh,
  13112. body: body,
  13113. delta: deltaPosition
  13114. });
  13115. break;
  13116. }
  13117. return body;
  13118. };
  13119. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13120. var types = [], sizes = [], positions = [], rotations = [];
  13121. var initialMesh = parts[0].mesh;
  13122. for (var index = 0; index < parts.length; index++) {
  13123. var part = parts[index];
  13124. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13125. types.push(bodyParameters.type);
  13126. sizes.push.apply(sizes, bodyParameters.size);
  13127. positions.push.apply(positions, bodyParameters.pos);
  13128. rotations.push.apply(rotations, bodyParameters.rot);
  13129. }
  13130. var body = new OIMO.Body({
  13131. type: types,
  13132. size: sizes,
  13133. pos: positions,
  13134. rot: rotations,
  13135. move: options.mass != 0,
  13136. config: [options.mass, options.friction, options.restitution],
  13137. world: this._world
  13138. });
  13139. this._registeredMeshes.push({
  13140. mesh: initialMesh,
  13141. body: body
  13142. });
  13143. return body;
  13144. };
  13145. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13146. var bodyParameters = null;
  13147. var mesh = part.mesh;
  13148. switch (part.impostor) {
  13149. case BABYLON.PhysicsEngine.SphereImpostor:
  13150. var bbox = mesh.getBoundingInfo().boundingBox;
  13151. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13152. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13153. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13154. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13155. bodyParameters = {
  13156. type: 'sphere',
  13157. /* bug with oimo : sphere needs 3 sizes in this case */
  13158. size: [size, -1, -1],
  13159. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13160. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13161. };
  13162. break;
  13163. case BABYLON.PhysicsEngine.PlaneImpostor:
  13164. case BABYLON.PhysicsEngine.BoxImpostor:
  13165. bbox = mesh.getBoundingInfo().boundingBox;
  13166. var min = bbox.minimumWorld;
  13167. var max = bbox.maximumWorld;
  13168. var box = max.subtract(min);
  13169. var sizeX = this._checkWithEpsilon(box.x);
  13170. var sizeY = this._checkWithEpsilon(box.y);
  13171. var sizeZ = this._checkWithEpsilon(box.z);
  13172. var relativePosition = mesh.position;
  13173. bodyParameters = {
  13174. type: 'box',
  13175. size: [sizeX, sizeY, sizeZ],
  13176. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13177. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13178. };
  13179. break;
  13180. }
  13181. return bodyParameters;
  13182. };
  13183. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13184. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13185. var registeredMesh = this._registeredMeshes[index];
  13186. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13187. if (registeredMesh.body) {
  13188. this._world.removeRigidBody(registeredMesh.body.body);
  13189. this._unbindBody(registeredMesh.body);
  13190. }
  13191. this._registeredMeshes.splice(index, 1);
  13192. return;
  13193. }
  13194. }
  13195. };
  13196. OimoJSPlugin.prototype._unbindBody = function (body) {
  13197. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13198. var registeredMesh = this._registeredMeshes[index];
  13199. if (registeredMesh.body === body) {
  13200. registeredMesh.body = null;
  13201. }
  13202. }
  13203. };
  13204. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13205. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13206. var registeredMesh = this._registeredMeshes[index];
  13207. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13208. var mass = registeredMesh.body.body.massInfo.mass;
  13209. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13210. return;
  13211. }
  13212. }
  13213. };
  13214. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13215. var body1 = null, body2 = null;
  13216. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13217. var registeredMesh = this._registeredMeshes[index];
  13218. if (registeredMesh.mesh === mesh1) {
  13219. body1 = registeredMesh.body.body;
  13220. } else if (registeredMesh.mesh === mesh2) {
  13221. body2 = registeredMesh.body.body;
  13222. }
  13223. }
  13224. if (!body1 || !body2) {
  13225. return false;
  13226. }
  13227. if (!options) {
  13228. options = {};
  13229. }
  13230. new OIMO.Link({
  13231. type: options.type,
  13232. body1: body1,
  13233. body2: body2,
  13234. min: options.min,
  13235. max: options.max,
  13236. axe1: options.axe1,
  13237. axe2: options.axe2,
  13238. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13239. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13240. collision: options.collision,
  13241. spring: options.spring,
  13242. world: this._world
  13243. });
  13244. return true;
  13245. };
  13246. OimoJSPlugin.prototype.dispose = function () {
  13247. this._world.clear();
  13248. while (this._registeredMeshes.length) {
  13249. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13250. }
  13251. };
  13252. OimoJSPlugin.prototype.isSupported = function () {
  13253. return OIMO !== undefined;
  13254. };
  13255. OimoJSPlugin.prototype._getLastShape = function (body) {
  13256. var lastShape = body.shapes;
  13257. while (lastShape.next) {
  13258. lastShape = lastShape.next;
  13259. }
  13260. return lastShape;
  13261. };
  13262. OimoJSPlugin.prototype.runOneStep = function (time) {
  13263. this._world.step();
  13264. var i = this._registeredMeshes.length;
  13265. var m;
  13266. while (i--) {
  13267. var body = this._registeredMeshes[i].body.body;
  13268. var mesh = this._registeredMeshes[i].mesh;
  13269. var delta = this._registeredMeshes[i].delta;
  13270. if (!body.sleeping) {
  13271. if (body.shapes.next) {
  13272. var parentShape = this._getLastShape(body);
  13273. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13274. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13275. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13276. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13277. if (!mesh.rotationQuaternion) {
  13278. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13279. }
  13280. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13281. } else {
  13282. m = body.getMatrix();
  13283. mtx = BABYLON.Matrix.FromArray(m);
  13284. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13285. if (!delta) {
  13286. mesh.position.x = bodyX;
  13287. mesh.position.y = bodyY;
  13288. mesh.position.z = bodyZ;
  13289. } else {
  13290. mesh.position.x = bodyX + delta.x;
  13291. mesh.position.y = bodyY + delta.y;
  13292. mesh.position.z = bodyZ + delta.z;
  13293. }
  13294. if (!mesh.rotationQuaternion) {
  13295. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13296. }
  13297. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13298. }
  13299. }
  13300. }
  13301. };
  13302. return OimoJSPlugin;
  13303. })();
  13304. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13305. })(BABYLON || (BABYLON = {}));
  13306. var BABYLON;
  13307. (function (BABYLON) {
  13308. var PhysicsEngine = (function () {
  13309. function PhysicsEngine(plugin) {
  13310. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13311. }
  13312. PhysicsEngine.prototype._initialize = function (gravity) {
  13313. this._currentPlugin.initialize();
  13314. this._setGravity(gravity);
  13315. };
  13316. PhysicsEngine.prototype._runOneStep = function (delta) {
  13317. if (delta > 0.1) {
  13318. delta = 0.1;
  13319. } else if (delta <= 0) {
  13320. delta = 1.0 / 60.0;
  13321. }
  13322. this._currentPlugin.runOneStep(delta);
  13323. };
  13324. PhysicsEngine.prototype._setGravity = function (gravity) {
  13325. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13326. this._currentPlugin.setGravity(this.gravity);
  13327. };
  13328. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13329. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13330. };
  13331. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13332. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13333. };
  13334. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13335. this._currentPlugin.unregisterMesh(mesh);
  13336. };
  13337. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13338. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13339. };
  13340. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13341. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13342. };
  13343. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13344. this._currentPlugin.updateBodyPosition(mesh);
  13345. };
  13346. PhysicsEngine.prototype.dispose = function () {
  13347. this._currentPlugin.dispose();
  13348. };
  13349. PhysicsEngine.prototype.isSupported = function () {
  13350. return this._currentPlugin.isSupported();
  13351. };
  13352. PhysicsEngine.NoImpostor = 0;
  13353. PhysicsEngine.SphereImpostor = 1;
  13354. PhysicsEngine.BoxImpostor = 2;
  13355. PhysicsEngine.PlaneImpostor = 3;
  13356. PhysicsEngine.CompoundImpostor = 4;
  13357. PhysicsEngine.MeshImpostor = 4;
  13358. PhysicsEngine.CapsuleImpostor = 5;
  13359. PhysicsEngine.ConeImpostor = 6;
  13360. PhysicsEngine.CylinderImpostor = 7;
  13361. PhysicsEngine.ConvexHullImpostor = 8;
  13362. PhysicsEngine.Epsilon = 0.001;
  13363. return PhysicsEngine;
  13364. })();
  13365. BABYLON.PhysicsEngine = PhysicsEngine;
  13366. })(BABYLON || (BABYLON = {}));
  13367. var BABYLON;
  13368. (function (BABYLON) {
  13369. var serializeLight = function (light) {
  13370. var serializationObject = {};
  13371. serializationObject.name = light.name;
  13372. serializationObject.id = light.id;
  13373. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13374. if (light instanceof BABYLON.PointLight) {
  13375. serializationObject.type = 0;
  13376. serializationObject.position = light.position.asArray();
  13377. } else if (light instanceof BABYLON.DirectionalLight) {
  13378. serializationObject.type = 1;
  13379. var directionalLight = light;
  13380. serializationObject.position = directionalLight.position.asArray();
  13381. serializationObject.direction = directionalLight.direction.asArray();
  13382. } else if (light instanceof BABYLON.SpotLight) {
  13383. serializationObject.type = 2;
  13384. var spotLight = light;
  13385. serializationObject.position = spotLight.position.asArray();
  13386. serializationObject.direction = spotLight.position.asArray();
  13387. serializationObject.angle = spotLight.angle;
  13388. serializationObject.exponent = spotLight.exponent;
  13389. } else if (light instanceof BABYLON.HemisphericLight) {
  13390. serializationObject.type = 3;
  13391. var hemisphericLight = light;
  13392. serializationObject.direction = hemisphericLight.direction.asArray();
  13393. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13394. }
  13395. if (light.intensity) {
  13396. serializationObject.intensity = light.intensity;
  13397. }
  13398. serializationObject.range = light.range;
  13399. serializationObject.diffuse = light.diffuse.asArray();
  13400. serializationObject.specular = light.specular.asArray();
  13401. return serializationObject;
  13402. };
  13403. var serializeFresnelParameter = function (fresnelParameter) {
  13404. var serializationObject = {};
  13405. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13406. serializationObject.leftColor = fresnelParameter.leftColor;
  13407. serializationObject.rightColor = fresnelParameter.rightColor;
  13408. serializationObject.bias = fresnelParameter.bias;
  13409. serializationObject.power = fresnelParameter.power;
  13410. return serializationObject;
  13411. };
  13412. var serializeCamera = function (camera) {
  13413. var serializationObject = {};
  13414. serializationObject.name = camera.name;
  13415. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13416. serializationObject.id = camera.id;
  13417. serializationObject.position = camera.position.asArray();
  13418. if (camera.parent) {
  13419. serializationObject.parentId = camera.parent.id;
  13420. }
  13421. serializationObject.rotation = camera.rotation.asArray();
  13422. if (camera.lockedTarget && camera.lockedTarget.id) {
  13423. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13424. }
  13425. serializationObject.fov = camera.fov;
  13426. serializationObject.minZ = camera.minZ;
  13427. serializationObject.maxZ = camera.maxZ;
  13428. serializationObject.speed = camera.speed;
  13429. serializationObject.inertia = camera.inertia;
  13430. serializationObject.checkCollisions = camera.checkCollisions;
  13431. serializationObject.applyGravity = camera.applyGravity;
  13432. if (camera.ellipsoid) {
  13433. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13434. }
  13435. appendAnimations(camera, serializationObject);
  13436. serializationObject.layerMask = camera.layerMask;
  13437. return serializationObject;
  13438. };
  13439. var appendAnimations = function (source, destination) {
  13440. if (source.animations) {
  13441. destination.animations = [];
  13442. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13443. var animation = source.animations[animationIndex];
  13444. destination.animations.push(serializeAnimation(animation));
  13445. }
  13446. }
  13447. };
  13448. var serializeAnimation = function (animation) {
  13449. var serializationObject = {};
  13450. serializationObject.name = animation.name;
  13451. serializationObject.property = animation.targetProperty;
  13452. serializationObject.framePerSecond = animation.framePerSecond;
  13453. serializationObject.dataType = animation.dataType;
  13454. serializationObject.loopBehavior = animation.loopMode;
  13455. var dataType = animation.dataType;
  13456. serializationObject.keys = [];
  13457. var keys = animation.getKeys();
  13458. for (var index = 0; index < keys.length; index++) {
  13459. var animationKey = keys[index];
  13460. var key = {};
  13461. key.frame = animationKey.frame;
  13462. switch (dataType) {
  13463. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13464. key.values = [animationKey.value];
  13465. break;
  13466. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13467. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13468. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13469. key.values = animationKey.value.asArray();
  13470. break;
  13471. }
  13472. serializationObject.keys.push(key);
  13473. }
  13474. return serializationObject;
  13475. };
  13476. var serializeMultiMaterial = function (material) {
  13477. var serializationObject = {};
  13478. serializationObject.name = material.name;
  13479. serializationObject.id = material.id;
  13480. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13481. serializationObject.materials = [];
  13482. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13483. var subMat = material.subMaterials[matIndex];
  13484. if (subMat) {
  13485. serializationObject.materials.push(subMat.id);
  13486. } else {
  13487. serializationObject.materials.push(null);
  13488. }
  13489. }
  13490. return serializationObject;
  13491. };
  13492. var serializeMaterial = function (material) {
  13493. var serializationObject = {};
  13494. serializationObject.name = material.name;
  13495. serializationObject.ambient = material.ambientColor.asArray();
  13496. serializationObject.diffuse = material.diffuseColor.asArray();
  13497. serializationObject.specular = material.specularColor.asArray();
  13498. serializationObject.specularPower = material.specularPower;
  13499. serializationObject.emissive = material.emissiveColor.asArray();
  13500. serializationObject.alpha = material.alpha;
  13501. serializationObject.id = material.id;
  13502. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13503. serializationObject.backFaceCulling = material.backFaceCulling;
  13504. if (material.diffuseTexture) {
  13505. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13506. }
  13507. if (material.diffuseFresnelParameters) {
  13508. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13509. }
  13510. if (material.ambientTexture) {
  13511. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13512. }
  13513. if (material.opacityTexture) {
  13514. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13515. }
  13516. if (material.opacityFresnelParameters) {
  13517. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13518. }
  13519. if (material.reflectionTexture) {
  13520. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13521. }
  13522. if (material.reflectionFresnelParameters) {
  13523. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13524. }
  13525. if (material.emissiveTexture) {
  13526. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13527. }
  13528. if (material.emissiveFresnelParameters) {
  13529. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13530. }
  13531. if (material.specularTexture) {
  13532. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  13533. }
  13534. if (material.bumpTexture) {
  13535. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  13536. }
  13537. return serializationObject;
  13538. };
  13539. var serializeTexture = function (texture) {
  13540. var serializationObject = {};
  13541. if (!texture.name) {
  13542. return null;
  13543. }
  13544. if (texture instanceof BABYLON.CubeTexture) {
  13545. serializationObject.name = texture.name;
  13546. serializationObject.hasAlpha = texture.hasAlpha;
  13547. serializationObject.level = texture.level;
  13548. serializationObject.coordinatesMode = texture.coordinatesMode;
  13549. return serializationObject;
  13550. }
  13551. if (texture instanceof BABYLON.MirrorTexture) {
  13552. var mirrorTexture = texture;
  13553. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  13554. serializationObject.renderList = [];
  13555. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  13556. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  13557. }
  13558. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  13559. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  13560. var renderTargetTexture = texture;
  13561. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  13562. serializationObject.renderList = [];
  13563. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  13564. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  13565. }
  13566. }
  13567. var regularTexture = texture;
  13568. serializationObject.name = texture.name;
  13569. serializationObject.hasAlpha = texture.hasAlpha;
  13570. serializationObject.level = texture.level;
  13571. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  13572. serializationObject.coordinatesMode = texture.coordinatesMode;
  13573. serializationObject.uOffset = regularTexture.uOffset;
  13574. serializationObject.vOffset = regularTexture.vOffset;
  13575. serializationObject.uScale = regularTexture.uScale;
  13576. serializationObject.vScale = regularTexture.vScale;
  13577. serializationObject.uAng = regularTexture.uAng;
  13578. serializationObject.vAng = regularTexture.vAng;
  13579. serializationObject.wAng = regularTexture.wAng;
  13580. serializationObject.wrapU = texture.wrapU;
  13581. serializationObject.wrapV = texture.wrapV;
  13582. appendAnimations(texture, serializationObject);
  13583. return serializationObject;
  13584. };
  13585. var serializeSkeleton = function (skeleton) {
  13586. var serializationObject = {};
  13587. serializationObject.name = skeleton.name;
  13588. serializationObject.id = skeleton.id;
  13589. serializationObject.bones = [];
  13590. for (var index = 0; index < skeleton.bones.length; index++) {
  13591. var bone = skeleton.bones[index];
  13592. var serializedBone = {
  13593. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  13594. name: bone.name,
  13595. matrix: bone.getLocalMatrix().toArray()
  13596. };
  13597. serializationObject.bones.push(serializedBone);
  13598. if (bone.animations && bone.animations.length > 0) {
  13599. serializedBone.animation = serializeAnimation(bone.animations[0]);
  13600. }
  13601. }
  13602. return serializationObject;
  13603. };
  13604. var serializeParticleSystem = function (particleSystem) {
  13605. var serializationObject = {};
  13606. serializationObject.emitterId = particleSystem.emitter.id;
  13607. serializationObject.capacity = particleSystem.getCapacity();
  13608. if (particleSystem.particleTexture) {
  13609. serializationObject.textureName = particleSystem.particleTexture.name;
  13610. }
  13611. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  13612. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  13613. serializationObject.minSize = particleSystem.minSize;
  13614. serializationObject.maxSize = particleSystem.maxSize;
  13615. serializationObject.minLifeTime = particleSystem.minLifeTime;
  13616. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  13617. serializationObject.emitRate = particleSystem.emitRate;
  13618. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  13619. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  13620. serializationObject.gravity = particleSystem.gravity.asArray();
  13621. serializationObject.direction1 = particleSystem.direction1.asArray();
  13622. serializationObject.direction2 = particleSystem.direction2.asArray();
  13623. serializationObject.color1 = particleSystem.color1.asArray();
  13624. serializationObject.color2 = particleSystem.color2.asArray();
  13625. serializationObject.colorDead = particleSystem.colorDead.asArray();
  13626. serializationObject.updateSpeed = particleSystem.updateSpeed;
  13627. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  13628. serializationObject.textureMask = particleSystem.textureMask.asArray();
  13629. serializationObject.blendMode = particleSystem.blendMode;
  13630. return serializationObject;
  13631. };
  13632. var serializeLensFlareSystem = function (lensFlareSystem) {
  13633. var serializationObject = {};
  13634. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  13635. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  13636. serializationObject.flares = [];
  13637. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  13638. var flare = lensFlareSystem.lensFlares[index];
  13639. serializationObject.flares.push({
  13640. size: flare.size,
  13641. position: flare.position,
  13642. color: flare.color.asArray(),
  13643. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  13644. });
  13645. }
  13646. return serializationObject;
  13647. };
  13648. var serializeShadowGenerator = function (light) {
  13649. var serializationObject = {};
  13650. var shadowGenerator = light.getShadowGenerator();
  13651. serializationObject.lightId = light.id;
  13652. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  13653. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  13654. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  13655. serializationObject.renderList = [];
  13656. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  13657. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  13658. serializationObject.renderList.push(mesh.id);
  13659. }
  13660. return serializationObject;
  13661. };
  13662. var serializedGeometries = [];
  13663. var serializeGeometry = function (geometry, serializationGeometries) {
  13664. if (serializedGeometries[geometry.id]) {
  13665. return;
  13666. }
  13667. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  13668. serializationGeometries.boxes.push(serializeBox(geometry));
  13669. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  13670. serializationGeometries.spheres.push(serializeSphere(geometry));
  13671. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  13672. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  13673. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  13674. serializationGeometries.toruses.push(serializeTorus(geometry));
  13675. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  13676. serializationGeometries.grounds.push(serializeGround(geometry));
  13677. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  13678. serializationGeometries.planes.push(serializePlane(geometry));
  13679. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  13680. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  13681. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  13682. throw new Error("Unknow primitive type");
  13683. } else {
  13684. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  13685. }
  13686. serializedGeometries[geometry.id] = true;
  13687. };
  13688. var serializeGeometryBase = function (geometry) {
  13689. var serializationObject = {};
  13690. serializationObject.id = geometry.id;
  13691. if (BABYLON.Tags.HasTags(geometry)) {
  13692. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  13693. }
  13694. return serializationObject;
  13695. };
  13696. var serializeVertexData = function (vertexData) {
  13697. var serializationObject = serializeGeometryBase(vertexData);
  13698. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13699. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13700. }
  13701. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13702. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13703. }
  13704. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13705. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13706. }
  13707. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13708. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  13709. }
  13710. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13711. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  13712. }
  13713. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  13714. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  13715. serializationObject.matricesIndices._isExpanded = true;
  13716. }
  13717. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13718. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  13719. }
  13720. serializationObject.indices = vertexData.getIndices();
  13721. return serializationObject;
  13722. };
  13723. var serializePrimitive = function (primitive) {
  13724. var serializationObject = serializeGeometryBase(primitive);
  13725. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  13726. return serializationObject;
  13727. };
  13728. var serializeBox = function (box) {
  13729. var serializationObject = serializePrimitive(box);
  13730. serializationObject.size = box.size;
  13731. return serializationObject;
  13732. };
  13733. var serializeSphere = function (sphere) {
  13734. var serializationObject = serializePrimitive(sphere);
  13735. serializationObject.segments = sphere.segments;
  13736. serializationObject.diameter = sphere.diameter;
  13737. return serializationObject;
  13738. };
  13739. var serializeCylinder = function (cylinder) {
  13740. var serializationObject = serializePrimitive(cylinder);
  13741. serializationObject.height = cylinder.height;
  13742. serializationObject.diameterTop = cylinder.diameterTop;
  13743. serializationObject.diameterBottom = cylinder.diameterBottom;
  13744. serializationObject.tessellation = cylinder.tessellation;
  13745. return serializationObject;
  13746. };
  13747. var serializeTorus = function (torus) {
  13748. var serializationObject = serializePrimitive(torus);
  13749. serializationObject.diameter = torus.diameter;
  13750. serializationObject.thickness = torus.thickness;
  13751. serializationObject.tessellation = torus.tessellation;
  13752. return serializationObject;
  13753. };
  13754. var serializeGround = function (ground) {
  13755. var serializationObject = serializePrimitive(ground);
  13756. serializationObject.width = ground.width;
  13757. serializationObject.height = ground.height;
  13758. serializationObject.subdivisions = ground.subdivisions;
  13759. return serializationObject;
  13760. };
  13761. var serializePlane = function (plane) {
  13762. var serializationObject = serializePrimitive(plane);
  13763. serializationObject.size = plane.size;
  13764. return serializationObject;
  13765. };
  13766. var serializeTorusKnot = function (torusKnot) {
  13767. var serializationObject = serializePrimitive(torusKnot);
  13768. serializationObject.radius = torusKnot.radius;
  13769. serializationObject.tube = torusKnot.tube;
  13770. serializationObject.radialSegments = torusKnot.radialSegments;
  13771. serializationObject.tubularSegments = torusKnot.tubularSegments;
  13772. serializationObject.p = torusKnot.p;
  13773. serializationObject.q = torusKnot.q;
  13774. return serializationObject;
  13775. };
  13776. var serializeMesh = function (mesh, serializationScene) {
  13777. var serializationObject = {};
  13778. serializationObject.name = mesh.name;
  13779. serializationObject.id = mesh.id;
  13780. if (BABYLON.Tags.HasTags(mesh)) {
  13781. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  13782. }
  13783. serializationObject.position = mesh.position.asArray();
  13784. if (mesh.rotationQuaternion) {
  13785. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  13786. } else if (mesh.rotation) {
  13787. serializationObject.rotation = mesh.rotation.asArray();
  13788. }
  13789. serializationObject.scaling = mesh.scaling.asArray();
  13790. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  13791. serializationObject.isEnabled = mesh.isEnabled();
  13792. serializationObject.isVisible = mesh.isVisible;
  13793. serializationObject.infiniteDistance = mesh.infiniteDistance;
  13794. serializationObject.pickable = mesh.isPickable;
  13795. serializationObject.receiveShadows = mesh.receiveShadows;
  13796. serializationObject.billboardMode = mesh.billboardMode;
  13797. serializationObject.visibility = mesh.visibility;
  13798. serializationObject.checkCollisions = mesh.checkCollisions;
  13799. if (mesh.parent) {
  13800. serializationObject.parentId = mesh.parent.id;
  13801. }
  13802. var geometry = mesh._geometry;
  13803. if (geometry) {
  13804. var geometryId = geometry.id;
  13805. serializationObject.geometryId = geometryId;
  13806. if (!mesh.getScene().getGeometryByID(geometryId)) {
  13807. serializeGeometry(geometry, serializationScene.geometries);
  13808. }
  13809. serializationObject.subMeshes = [];
  13810. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13811. var subMesh = mesh.subMeshes[subIndex];
  13812. serializationObject.subMeshes.push({
  13813. materialIndex: subMesh.materialIndex,
  13814. verticesStart: subMesh.verticesStart,
  13815. verticesCount: subMesh.verticesCount,
  13816. indexStart: subMesh.indexStart,
  13817. indexCount: subMesh.indexCount
  13818. });
  13819. }
  13820. }
  13821. if (mesh.material) {
  13822. serializationObject.materialId = mesh.material.id;
  13823. } else {
  13824. mesh.material = null;
  13825. }
  13826. if (mesh.skeleton) {
  13827. serializationObject.skeletonId = mesh.skeleton.id;
  13828. }
  13829. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  13830. serializationObject.physicsMass = mesh.getPhysicsMass();
  13831. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  13832. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  13833. switch (mesh.getPhysicsImpostor()) {
  13834. case BABYLON.PhysicsEngine.BoxImpostor:
  13835. serializationObject.physicsImpostor = 1;
  13836. break;
  13837. case BABYLON.PhysicsEngine.SphereImpostor:
  13838. serializationObject.physicsImpostor = 2;
  13839. break;
  13840. }
  13841. }
  13842. serializationObject.instances = [];
  13843. for (var index = 0; index < mesh.instances.length; index++) {
  13844. var instance = mesh.instances[index];
  13845. var serializationInstance = {
  13846. name: instance.name,
  13847. position: instance.position,
  13848. rotation: instance.rotation,
  13849. rotationQuaternion: instance.rotationQuaternion,
  13850. scaling: instance.scaling
  13851. };
  13852. serializationObject.instances.push(serializationInstance);
  13853. appendAnimations(instance, serializationInstance);
  13854. }
  13855. appendAnimations(mesh, serializationObject);
  13856. serializationObject.layerMask = mesh.layerMask;
  13857. return serializationObject;
  13858. };
  13859. var SceneSerializer = (function () {
  13860. function SceneSerializer() {
  13861. }
  13862. SceneSerializer.Serialize = function (scene) {
  13863. var serializationObject = {};
  13864. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  13865. serializationObject.autoClear = scene.autoClear;
  13866. serializationObject.clearColor = scene.clearColor.asArray();
  13867. serializationObject.ambientColor = scene.ambientColor.asArray();
  13868. serializationObject.gravity = scene.gravity.asArray();
  13869. if (scene.fogMode && scene.fogMode !== 0) {
  13870. serializationObject.fogMode = scene.fogMode;
  13871. serializationObject.fogColor = scene.fogColor.asArray();
  13872. serializationObject.fogStart = scene.fogStart;
  13873. serializationObject.fogEnd = scene.fogEnd;
  13874. serializationObject.fogDensity = scene.fogDensity;
  13875. }
  13876. serializationObject.lights = [];
  13877. for (var index = 0; index < scene.lights.length; index++) {
  13878. var light = scene.lights[index];
  13879. serializationObject.lights.push(serializeLight(light));
  13880. }
  13881. serializationObject.cameras = [];
  13882. for (index = 0; index < scene.cameras.length; index++) {
  13883. var camera = scene.cameras[index];
  13884. if (camera instanceof BABYLON.FreeCamera) {
  13885. serializationObject.cameras.push(serializeCamera(camera));
  13886. }
  13887. }
  13888. if (scene.activeCamera) {
  13889. serializationObject.activeCameraID = scene.activeCamera.id;
  13890. }
  13891. serializationObject.materials = [];
  13892. serializationObject.multiMaterials = [];
  13893. for (index = 0; index < scene.materials.length; index++) {
  13894. var material = scene.materials[index];
  13895. if (material instanceof BABYLON.StandardMaterial) {
  13896. serializationObject.materials.push(serializeMaterial(material));
  13897. } else if (material instanceof BABYLON.MultiMaterial) {
  13898. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  13899. }
  13900. }
  13901. serializationObject.skeletons = [];
  13902. for (index = 0; index < scene.skeletons.length; index++) {
  13903. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  13904. }
  13905. serializationObject.geometries = {};
  13906. serializationObject.geometries.boxes = [];
  13907. serializationObject.geometries.spheres = [];
  13908. serializationObject.geometries.cylinders = [];
  13909. serializationObject.geometries.toruses = [];
  13910. serializationObject.geometries.grounds = [];
  13911. serializationObject.geometries.planes = [];
  13912. serializationObject.geometries.torusKnots = [];
  13913. serializationObject.geometries.vertexData = [];
  13914. serializedGeometries = [];
  13915. var geometries = scene.getGeometries();
  13916. for (var index = 0; index < geometries.length; index++) {
  13917. var geometry = geometries[index];
  13918. if (geometry.isReady()) {
  13919. serializeGeometry(geometry, serializationObject.geometries);
  13920. }
  13921. }
  13922. serializationObject.meshes = [];
  13923. for (index = 0; index < scene.meshes.length; index++) {
  13924. var abstractMesh = scene.meshes[index];
  13925. if (abstractMesh instanceof BABYLON.Mesh) {
  13926. var mesh = abstractMesh;
  13927. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  13928. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  13929. }
  13930. }
  13931. }
  13932. serializationObject.particleSystems = [];
  13933. for (index = 0; index < scene.particleSystems.length; index++) {
  13934. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  13935. }
  13936. serializationObject.lensFlareSystems = [];
  13937. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  13938. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  13939. }
  13940. serializationObject.shadowGenerators = [];
  13941. for (index = 0; index < scene.lights.length; index++) {
  13942. light = scene.lights[index];
  13943. if (light.getShadowGenerator()) {
  13944. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  13945. }
  13946. }
  13947. return serializationObject;
  13948. };
  13949. return SceneSerializer;
  13950. })();
  13951. BABYLON.SceneSerializer = SceneSerializer;
  13952. })(BABYLON || (BABYLON = {}));
  13953. var BABYLON;
  13954. (function (BABYLON) {
  13955. var SceneLoader = (function () {
  13956. function SceneLoader() {
  13957. }
  13958. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  13959. get: function () {
  13960. return SceneLoader._ForceFullSceneLoadingForIncremental;
  13961. },
  13962. set: function (value) {
  13963. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  13964. },
  13965. enumerable: true,
  13966. configurable: true
  13967. });
  13968. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  13969. get: function () {
  13970. return SceneLoader._ShowLoadingScreen;
  13971. },
  13972. set: function (value) {
  13973. SceneLoader._ShowLoadingScreen = value;
  13974. },
  13975. enumerable: true,
  13976. configurable: true
  13977. });
  13978. SceneLoader._getPluginForFilename = function (sceneFilename) {
  13979. var dotPosition = sceneFilename.lastIndexOf(".");
  13980. var extension = sceneFilename.substring(dotPosition).toLowerCase();
  13981. for (var index = 0; index < this._registeredPlugins.length; index++) {
  13982. var plugin = this._registeredPlugins[index];
  13983. if (plugin.extensions.indexOf(extension) !== -1) {
  13984. return plugin;
  13985. }
  13986. }
  13987. return this._registeredPlugins[this._registeredPlugins.length - 1];
  13988. };
  13989. SceneLoader.RegisterPlugin = function (plugin) {
  13990. plugin.extensions = plugin.extensions.toLowerCase();
  13991. SceneLoader._registeredPlugins.push(plugin);
  13992. };
  13993. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  13994. var _this = this;
  13995. var manifestChecked = function (success) {
  13996. scene.database = database;
  13997. var plugin = _this._getPluginForFilename(sceneFilename);
  13998. var importMeshFromData = function (data) {
  13999. var meshes = [];
  14000. var particleSystems = [];
  14001. var skeletons = [];
  14002. try {
  14003. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14004. if (onerror) {
  14005. onerror(scene);
  14006. }
  14007. return;
  14008. }
  14009. } catch (e) {
  14010. if (onerror) {
  14011. onerror(scene);
  14012. }
  14013. return;
  14014. }
  14015. if (onsuccess) {
  14016. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14017. onsuccess(meshes, particleSystems, skeletons);
  14018. }
  14019. };
  14020. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14021. importMeshFromData(sceneFilename.substr(5));
  14022. return;
  14023. }
  14024. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14025. importMeshFromData(data);
  14026. }, progressCallBack, database);
  14027. };
  14028. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14029. };
  14030. /**
  14031. * Load a scene
  14032. * @param rootUrl a string that defines the root url for scene and resources
  14033. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14034. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14035. */
  14036. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14037. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14038. };
  14039. /**
  14040. * Append a scene
  14041. * @param rootUrl a string that defines the root url for scene and resources
  14042. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14043. * @param scene is the instance of BABYLON.Scene to append to
  14044. */
  14045. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14046. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14047. var database;
  14048. if (SceneLoader.ShowLoadingScreen) {
  14049. scene.getEngine().displayLoadingUI();
  14050. }
  14051. var loadSceneFromData = function (data) {
  14052. scene.database = database;
  14053. if (!plugin.load(scene, data, rootUrl)) {
  14054. if (onerror) {
  14055. onerror(scene);
  14056. }
  14057. scene.getEngine().hideLoadingUI();
  14058. return;
  14059. }
  14060. if (onsuccess) {
  14061. onsuccess(scene);
  14062. }
  14063. if (SceneLoader.ShowLoadingScreen) {
  14064. scene.executeWhenReady(function () {
  14065. scene.getEngine().hideLoadingUI();
  14066. });
  14067. }
  14068. };
  14069. var manifestChecked = function (success) {
  14070. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14071. };
  14072. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14073. loadSceneFromData(sceneFilename.substr(5));
  14074. return;
  14075. }
  14076. if (rootUrl.indexOf("file:") === -1) {
  14077. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14078. } else {
  14079. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14080. }
  14081. };
  14082. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14083. SceneLoader._ShowLoadingScreen = true;
  14084. SceneLoader._registeredPlugins = new Array();
  14085. return SceneLoader;
  14086. })();
  14087. BABYLON.SceneLoader = SceneLoader;
  14088. ;
  14089. })(BABYLON || (BABYLON = {}));
  14090. var BABYLON;
  14091. (function (BABYLON) {
  14092. (function (Internals) {
  14093. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14094. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14095. texture.name = parsedTexture.name;
  14096. texture.hasAlpha = parsedTexture.hasAlpha;
  14097. texture.level = parsedTexture.level;
  14098. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14099. return texture;
  14100. };
  14101. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14102. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14103. return null;
  14104. }
  14105. if (parsedTexture.isCube) {
  14106. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14107. }
  14108. var texture;
  14109. if (parsedTexture.mirrorPlane) {
  14110. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14111. texture._waitingRenderList = parsedTexture.renderList;
  14112. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14113. } else if (parsedTexture.isRenderTarget) {
  14114. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14115. texture._waitingRenderList = parsedTexture.renderList;
  14116. } else {
  14117. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14118. }
  14119. texture.name = parsedTexture.name;
  14120. texture.hasAlpha = parsedTexture.hasAlpha;
  14121. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14122. texture.level = parsedTexture.level;
  14123. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14124. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14125. texture.uOffset = parsedTexture.uOffset;
  14126. texture.vOffset = parsedTexture.vOffset;
  14127. texture.uScale = parsedTexture.uScale;
  14128. texture.vScale = parsedTexture.vScale;
  14129. texture.uAng = parsedTexture.uAng;
  14130. texture.vAng = parsedTexture.vAng;
  14131. texture.wAng = parsedTexture.wAng;
  14132. texture.wrapU = parsedTexture.wrapU;
  14133. texture.wrapV = parsedTexture.wrapV;
  14134. if (parsedTexture.animations) {
  14135. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14136. var parsedAnimation = parsedTexture.animations[animationIndex];
  14137. texture.animations.push(parseAnimation(parsedAnimation));
  14138. }
  14139. }
  14140. return texture;
  14141. };
  14142. var parseSkeleton = function (parsedSkeleton, scene) {
  14143. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14144. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14145. var parsedBone = parsedSkeleton.bones[index];
  14146. var parentBone = null;
  14147. if (parsedBone.parentBoneIndex > -1) {
  14148. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14149. }
  14150. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14151. if (parsedBone.animation) {
  14152. bone.animations.push(parseAnimation(parsedBone.animation));
  14153. }
  14154. }
  14155. return skeleton;
  14156. };
  14157. var parseFresnelParameters = function (parsedFresnelParameters) {
  14158. var fresnelParameters = new BABYLON.FresnelParameters();
  14159. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14160. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14161. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14162. fresnelParameters.bias = parsedFresnelParameters.bias;
  14163. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14164. return fresnelParameters;
  14165. };
  14166. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14167. var material;
  14168. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14169. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14170. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14171. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14172. material.specularPower = parsedMaterial.specularPower;
  14173. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14174. material.alpha = parsedMaterial.alpha;
  14175. material.id = parsedMaterial.id;
  14176. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14177. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14178. material.wireframe = parsedMaterial.wireframe;
  14179. if (parsedMaterial.diffuseTexture) {
  14180. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14181. }
  14182. if (parsedMaterial.diffuseFresnelParameters) {
  14183. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14184. }
  14185. if (parsedMaterial.ambientTexture) {
  14186. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14187. }
  14188. if (parsedMaterial.opacityTexture) {
  14189. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14190. }
  14191. if (parsedMaterial.opacityFresnelParameters) {
  14192. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14193. }
  14194. if (parsedMaterial.reflectionTexture) {
  14195. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14196. }
  14197. if (parsedMaterial.reflectionFresnelParameters) {
  14198. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14199. }
  14200. if (parsedMaterial.emissiveTexture) {
  14201. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14202. }
  14203. if (parsedMaterial.emissiveFresnelParameters) {
  14204. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14205. }
  14206. if (parsedMaterial.specularTexture) {
  14207. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14208. }
  14209. if (parsedMaterial.bumpTexture) {
  14210. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14211. }
  14212. return material;
  14213. };
  14214. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14215. for (var index = 0; index < parsedData.materials.length; index++) {
  14216. var parsedMaterial = parsedData.materials[index];
  14217. if (parsedMaterial.id === id) {
  14218. return parseMaterial(parsedMaterial, scene, rootUrl);
  14219. }
  14220. }
  14221. return null;
  14222. };
  14223. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14224. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14225. multiMaterial.id = parsedMultiMaterial.id;
  14226. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14227. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14228. var subMatId = parsedMultiMaterial.materials[matIndex];
  14229. if (subMatId) {
  14230. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14231. } else {
  14232. multiMaterial.subMaterials.push(null);
  14233. }
  14234. }
  14235. return multiMaterial;
  14236. };
  14237. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14238. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14239. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14240. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14241. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14242. var parsedFlare = parsedLensFlareSystem.flares[index];
  14243. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14244. }
  14245. return lensFlareSystem;
  14246. };
  14247. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14248. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14249. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14250. if (parsedParticleSystem.textureName) {
  14251. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14252. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14253. }
  14254. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14255. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14256. particleSystem.minSize = parsedParticleSystem.minSize;
  14257. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14258. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14259. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14260. particleSystem.emitter = emitter;
  14261. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14262. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14263. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14264. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14265. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14266. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14267. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14268. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14269. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14270. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14271. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14272. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14273. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14274. particleSystem.start();
  14275. return particleSystem;
  14276. };
  14277. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14278. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14279. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14280. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14281. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14282. shadowGenerator.getShadowMap().renderList.push(mesh);
  14283. }
  14284. if (parsedShadowGenerator.usePoissonSampling) {
  14285. shadowGenerator.usePoissonSampling = true;
  14286. } else {
  14287. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14288. }
  14289. return shadowGenerator;
  14290. };
  14291. var parseAnimation = function (parsedAnimation) {
  14292. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14293. var dataType = parsedAnimation.dataType;
  14294. var keys = [];
  14295. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14296. var key = parsedAnimation.keys[index];
  14297. var data;
  14298. switch (dataType) {
  14299. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14300. data = key.values[0];
  14301. break;
  14302. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14303. data = BABYLON.Quaternion.FromArray(key.values);
  14304. break;
  14305. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14306. data = BABYLON.Matrix.FromArray(key.values);
  14307. break;
  14308. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14309. default:
  14310. data = BABYLON.Vector3.FromArray(key.values);
  14311. break;
  14312. }
  14313. keys.push({
  14314. frame: key.frame,
  14315. value: data
  14316. });
  14317. }
  14318. animation.setKeys(keys);
  14319. return animation;
  14320. };
  14321. var parseLight = function (parsedLight, scene) {
  14322. var light;
  14323. switch (parsedLight.type) {
  14324. case 0:
  14325. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14326. break;
  14327. case 1:
  14328. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14329. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14330. break;
  14331. case 2:
  14332. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14333. break;
  14334. case 3:
  14335. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14336. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14337. break;
  14338. }
  14339. light.id = parsedLight.id;
  14340. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14341. if (parsedLight.intensity !== undefined) {
  14342. light.intensity = parsedLight.intensity;
  14343. }
  14344. if (parsedLight.range) {
  14345. light.range = parsedLight.range;
  14346. }
  14347. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14348. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14349. if (parsedLight.excludedMeshesIds) {
  14350. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14351. }
  14352. if (parsedLight.includedOnlyMeshesIds) {
  14353. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14354. }
  14355. if (parsedLight.animations) {
  14356. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14357. var parsedAnimation = parsedLight.animations[animationIndex];
  14358. light.animations.push(parseAnimation(parsedAnimation));
  14359. }
  14360. }
  14361. if (parsedLight.autoAnimate) {
  14362. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14363. }
  14364. };
  14365. var parseCamera = function (parsedCamera, scene) {
  14366. var camera;
  14367. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  14368. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  14369. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  14370. var alpha = parsedCamera.alpha;
  14371. var beta = parsedCamera.beta;
  14372. var radius = parsedCamera.radius;
  14373. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  14374. var eye_space = parsedCamera.eye_space;
  14375. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  14376. } else {
  14377. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  14378. }
  14379. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  14380. var eye_space = parsedCamera.eye_space;
  14381. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  14382. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  14383. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  14384. } else if (parsedCamera.type === "FollowCamera") {
  14385. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  14386. camera.heightOffset = parsedCamera.heightOffset;
  14387. camera.radius = parsedCamera.radius;
  14388. camera.rotationOffset = parsedCamera.rotationOffset;
  14389. if (lockedTargetMesh)
  14390. camera.target = lockedTargetMesh;
  14391. } else if (parsedCamera.type === "GamepadCamera") {
  14392. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  14393. } else if (parsedCamera.type === "OculusCamera") {
  14394. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  14395. } else if (parsedCamera.type === "TouchCamera") {
  14396. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  14397. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  14398. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  14399. } else if (parsedCamera.type === "WebVRCamera") {
  14400. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  14401. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  14402. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  14403. } else {
  14404. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  14405. }
  14406. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  14407. camera.lockedTarget = lockedTargetMesh;
  14408. }
  14409. camera.id = parsedCamera.id;
  14410. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14411. if (parsedCamera.parentId) {
  14412. camera._waitingParentId = parsedCamera.parentId;
  14413. }
  14414. if (parsedCamera.target) {
  14415. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14416. } else {
  14417. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14418. }
  14419. camera.fov = parsedCamera.fov;
  14420. camera.minZ = parsedCamera.minZ;
  14421. camera.maxZ = parsedCamera.maxZ;
  14422. camera.speed = parsedCamera.speed;
  14423. camera.inertia = parsedCamera.inertia;
  14424. camera.checkCollisions = parsedCamera.checkCollisions;
  14425. camera.applyGravity = parsedCamera.applyGravity;
  14426. if (parsedCamera.ellipsoid) {
  14427. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14428. }
  14429. if (parsedCamera.animations) {
  14430. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14431. var parsedAnimation = parsedCamera.animations[animationIndex];
  14432. camera.animations.push(parseAnimation(parsedAnimation));
  14433. }
  14434. }
  14435. if (parsedCamera.autoAnimate) {
  14436. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14437. }
  14438. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14439. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14440. } else {
  14441. camera.layerMask = 0xFFFFFFFF;
  14442. }
  14443. return camera;
  14444. };
  14445. var parseGeometry = function (parsedGeometry, scene) {
  14446. var id = parsedGeometry.id;
  14447. return scene.getGeometryByID(id);
  14448. };
  14449. var parseBox = function (parsedBox, scene) {
  14450. if (parseGeometry(parsedBox, scene)) {
  14451. return null;
  14452. }
  14453. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14454. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14455. scene.pushGeometry(box, true);
  14456. return box;
  14457. };
  14458. var parseSphere = function (parsedSphere, scene) {
  14459. if (parseGeometry(parsedSphere, scene)) {
  14460. return null;
  14461. }
  14462. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14463. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14464. scene.pushGeometry(sphere, true);
  14465. return sphere;
  14466. };
  14467. var parseCylinder = function (parsedCylinder, scene) {
  14468. if (parseGeometry(parsedCylinder, scene)) {
  14469. return null;
  14470. }
  14471. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14472. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14473. scene.pushGeometry(cylinder, true);
  14474. return cylinder;
  14475. };
  14476. var parseTorus = function (parsedTorus, scene) {
  14477. if (parseGeometry(parsedTorus, scene)) {
  14478. return null;
  14479. }
  14480. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14481. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14482. scene.pushGeometry(torus, true);
  14483. return torus;
  14484. };
  14485. var parseGround = function (parsedGround, scene) {
  14486. if (parseGeometry(parsedGround, scene)) {
  14487. return null;
  14488. }
  14489. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14490. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14491. scene.pushGeometry(ground, true);
  14492. return ground;
  14493. };
  14494. var parsePlane = function (parsedPlane, scene) {
  14495. if (parseGeometry(parsedPlane, scene)) {
  14496. return null;
  14497. }
  14498. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14499. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14500. scene.pushGeometry(plane, true);
  14501. return plane;
  14502. };
  14503. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14504. if (parseGeometry(parsedTorusKnot, scene)) {
  14505. return null;
  14506. }
  14507. 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);
  14508. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14509. scene.pushGeometry(torusKnot, true);
  14510. return torusKnot;
  14511. };
  14512. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14513. if (parseGeometry(parsedVertexData, scene)) {
  14514. return null;
  14515. }
  14516. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14517. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14518. if (parsedVertexData.delayLoadingFile) {
  14519. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14520. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14521. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14522. geometry._delayInfo = [];
  14523. if (parsedVertexData.hasUVs) {
  14524. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14525. }
  14526. if (parsedVertexData.hasUVs2) {
  14527. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14528. }
  14529. if (parsedVertexData.hasColors) {
  14530. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14531. }
  14532. if (parsedVertexData.hasMatricesIndices) {
  14533. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14534. }
  14535. if (parsedVertexData.hasMatricesWeights) {
  14536. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14537. }
  14538. geometry._delayLoadingFunction = importVertexData;
  14539. } else {
  14540. importVertexData(parsedVertexData, geometry);
  14541. }
  14542. scene.pushGeometry(geometry, true);
  14543. return geometry;
  14544. };
  14545. var parseMesh = function (parsedMesh, scene, rootUrl) {
  14546. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  14547. mesh.id = parsedMesh.id;
  14548. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  14549. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  14550. if (parsedMesh.rotationQuaternion) {
  14551. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  14552. } else if (parsedMesh.rotation) {
  14553. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  14554. }
  14555. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  14556. if (parsedMesh.localMatrix) {
  14557. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  14558. } else if (parsedMesh.pivotMatrix) {
  14559. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  14560. }
  14561. mesh.setEnabled(parsedMesh.isEnabled);
  14562. mesh.isVisible = parsedMesh.isVisible;
  14563. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  14564. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  14565. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  14566. if (parsedMesh.pickable !== undefined) {
  14567. mesh.isPickable = parsedMesh.pickable;
  14568. }
  14569. mesh.receiveShadows = parsedMesh.receiveShadows;
  14570. mesh.billboardMode = parsedMesh.billboardMode;
  14571. if (parsedMesh.visibility !== undefined) {
  14572. mesh.visibility = parsedMesh.visibility;
  14573. }
  14574. mesh.checkCollisions = parsedMesh.checkCollisions;
  14575. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  14576. if (parsedMesh.parentId) {
  14577. mesh._waitingParentId = parsedMesh.parentId;
  14578. }
  14579. if (parsedMesh.delayLoadingFile) {
  14580. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14581. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  14582. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  14583. if (parsedMesh._binaryInfo) {
  14584. mesh._binaryInfo = parsedMesh._binaryInfo;
  14585. }
  14586. mesh._delayInfo = [];
  14587. if (parsedMesh.hasUVs) {
  14588. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14589. }
  14590. if (parsedMesh.hasUVs2) {
  14591. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14592. }
  14593. if (parsedMesh.hasColors) {
  14594. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  14595. }
  14596. if (parsedMesh.hasMatricesIndices) {
  14597. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14598. }
  14599. if (parsedMesh.hasMatricesWeights) {
  14600. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14601. }
  14602. mesh._delayLoadingFunction = importGeometry;
  14603. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  14604. mesh._checkDelayState();
  14605. }
  14606. } else {
  14607. importGeometry(parsedMesh, mesh);
  14608. }
  14609. if (parsedMesh.materialId) {
  14610. mesh.setMaterialByID(parsedMesh.materialId);
  14611. } else {
  14612. mesh.material = null;
  14613. }
  14614. if (parsedMesh.skeletonId > -1) {
  14615. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  14616. }
  14617. if (parsedMesh.physicsImpostor) {
  14618. if (!scene.isPhysicsEnabled()) {
  14619. scene.enablePhysics();
  14620. }
  14621. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  14622. }
  14623. if (parsedMesh.animations) {
  14624. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14625. var parsedAnimation = parsedMesh.animations[animationIndex];
  14626. mesh.animations.push(parseAnimation(parsedAnimation));
  14627. }
  14628. }
  14629. if (parsedMesh.autoAnimate) {
  14630. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  14631. }
  14632. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  14633. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  14634. } else {
  14635. mesh.layerMask = 0xFFFFFFFF;
  14636. }
  14637. if (parsedMesh.instances) {
  14638. for (var index = 0; index < parsedMesh.instances.length; index++) {
  14639. var parsedInstance = parsedMesh.instances[index];
  14640. var instance = mesh.createInstance(parsedInstance.name);
  14641. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  14642. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  14643. if (parsedInstance.rotationQuaternion) {
  14644. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  14645. } else if (parsedInstance.rotation) {
  14646. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  14647. }
  14648. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  14649. instance.checkCollisions = mesh.checkCollisions;
  14650. if (parsedMesh.animations) {
  14651. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  14652. parsedAnimation = parsedMesh.animations[animationIndex];
  14653. instance.animations.push(parseAnimation(parsedAnimation));
  14654. }
  14655. }
  14656. }
  14657. }
  14658. return mesh;
  14659. };
  14660. var isDescendantOf = function (mesh, names, hierarchyIds) {
  14661. names = (names instanceof Array) ? names : [names];
  14662. for (var i in names) {
  14663. if (mesh.name === names[i]) {
  14664. hierarchyIds.push(mesh.id);
  14665. return true;
  14666. }
  14667. }
  14668. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  14669. hierarchyIds.push(mesh.id);
  14670. return true;
  14671. }
  14672. return false;
  14673. };
  14674. var importVertexData = function (parsedVertexData, geometry) {
  14675. var vertexData = new BABYLON.VertexData();
  14676. var positions = parsedVertexData.positions;
  14677. if (positions) {
  14678. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  14679. }
  14680. var normals = parsedVertexData.normals;
  14681. if (normals) {
  14682. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  14683. }
  14684. var uvs = parsedVertexData.uvs;
  14685. if (uvs) {
  14686. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  14687. }
  14688. var uv2s = parsedVertexData.uv2s;
  14689. if (uv2s) {
  14690. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  14691. }
  14692. var colors = parsedVertexData.colors;
  14693. if (colors) {
  14694. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  14695. }
  14696. var matricesIndices = parsedVertexData.matricesIndices;
  14697. if (matricesIndices) {
  14698. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  14699. }
  14700. var matricesWeights = parsedVertexData.matricesWeights;
  14701. if (matricesWeights) {
  14702. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  14703. }
  14704. var indices = parsedVertexData.indices;
  14705. if (indices) {
  14706. vertexData.indices = indices;
  14707. }
  14708. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  14709. };
  14710. var importGeometry = function (parsedGeometry, mesh) {
  14711. var scene = mesh.getScene();
  14712. var geometryId = parsedGeometry.geometryId;
  14713. if (geometryId) {
  14714. var geometry = scene.getGeometryByID(geometryId);
  14715. if (geometry) {
  14716. geometry.applyToMesh(mesh);
  14717. }
  14718. } else if (parsedGeometry instanceof ArrayBuffer) {
  14719. var binaryInfo = mesh._binaryInfo;
  14720. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  14721. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  14722. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  14723. }
  14724. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  14725. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  14726. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  14727. }
  14728. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  14729. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  14730. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  14731. }
  14732. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  14733. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  14734. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  14735. }
  14736. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  14737. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  14738. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  14739. }
  14740. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  14741. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  14742. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  14743. }
  14744. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  14745. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  14746. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  14747. }
  14748. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  14749. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  14750. mesh.setIndices(indicesData);
  14751. }
  14752. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  14753. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  14754. mesh.subMeshes = [];
  14755. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  14756. var materialIndex = subMeshesData[(i * 5) + 0];
  14757. var verticesStart = subMeshesData[(i * 5) + 1];
  14758. var verticesCount = subMeshesData[(i * 5) + 2];
  14759. var indexStart = subMeshesData[(i * 5) + 3];
  14760. var indexCount = subMeshesData[(i * 5) + 4];
  14761. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  14762. }
  14763. }
  14764. return;
  14765. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  14766. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  14767. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  14768. if (parsedGeometry.uvs) {
  14769. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  14770. }
  14771. if (parsedGeometry.uvs2) {
  14772. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  14773. }
  14774. if (parsedGeometry.colors) {
  14775. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  14776. }
  14777. if (parsedGeometry.matricesIndices) {
  14778. if (!parsedGeometry.matricesIndices._isExpanded) {
  14779. var floatIndices = [];
  14780. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  14781. var matricesIndex = parsedGeometry.matricesIndices[i];
  14782. floatIndices.push(matricesIndex & 0x000000FF);
  14783. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  14784. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  14785. floatIndices.push(matricesIndex >> 24);
  14786. }
  14787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  14788. } else {
  14789. delete parsedGeometry.matricesIndices._isExpanded;
  14790. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  14791. }
  14792. }
  14793. if (parsedGeometry.matricesWeights) {
  14794. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  14795. }
  14796. mesh.setIndices(parsedGeometry.indices);
  14797. }
  14798. if (parsedGeometry.subMeshes) {
  14799. mesh.subMeshes = [];
  14800. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  14801. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  14802. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  14803. }
  14804. }
  14805. if (mesh._shouldGenerateFlatShading) {
  14806. mesh.convertToFlatShadedMesh();
  14807. delete mesh._shouldGenerateFlatShading;
  14808. }
  14809. mesh.computeWorldMatrix(true);
  14810. if (scene._selectionOctree) {
  14811. scene._selectionOctree.addMesh(mesh);
  14812. }
  14813. };
  14814. BABYLON.SceneLoader.RegisterPlugin({
  14815. extensions: ".babylon",
  14816. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  14817. var parsedData = JSON.parse(data);
  14818. var loadedSkeletonsIds = [];
  14819. var loadedMaterialsIds = [];
  14820. var hierarchyIds = [];
  14821. for (var index = 0; index < parsedData.meshes.length; index++) {
  14822. var parsedMesh = parsedData.meshes[index];
  14823. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  14824. if (meshesNames instanceof Array) {
  14825. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  14826. }
  14827. if (parsedMesh.materialId) {
  14828. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  14829. if (!materialFound) {
  14830. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  14831. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  14832. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  14833. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14834. var subMatId = parsedMultiMaterial.materials[matIndex];
  14835. loadedMaterialsIds.push(subMatId);
  14836. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  14837. }
  14838. loadedMaterialsIds.push(parsedMultiMaterial.id);
  14839. parseMultiMaterial(parsedMultiMaterial, scene);
  14840. materialFound = true;
  14841. break;
  14842. }
  14843. }
  14844. }
  14845. if (!materialFound) {
  14846. loadedMaterialsIds.push(parsedMesh.materialId);
  14847. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  14848. }
  14849. }
  14850. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  14851. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  14852. if (!skeletonAlreadyLoaded) {
  14853. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  14854. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  14855. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  14856. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  14857. loadedSkeletonsIds.push(parsedSkeleton.id);
  14858. }
  14859. }
  14860. }
  14861. }
  14862. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  14863. meshes.push(mesh);
  14864. }
  14865. }
  14866. for (index = 0; index < scene.meshes.length; index++) {
  14867. var currentMesh = scene.meshes[index];
  14868. if (currentMesh._waitingParentId) {
  14869. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  14870. currentMesh._waitingParentId = undefined;
  14871. }
  14872. }
  14873. if (parsedData.particleSystems) {
  14874. for (index = 0; index < parsedData.particleSystems.length; index++) {
  14875. var parsedParticleSystem = parsedData.particleSystems[index];
  14876. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  14877. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  14878. }
  14879. }
  14880. }
  14881. return true;
  14882. },
  14883. load: function (scene, data, rootUrl) {
  14884. var parsedData = JSON.parse(data);
  14885. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  14886. scene.autoClear = parsedData.autoClear;
  14887. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  14888. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  14889. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  14890. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  14891. scene.fogMode = parsedData.fogMode;
  14892. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  14893. scene.fogStart = parsedData.fogStart;
  14894. scene.fogEnd = parsedData.fogEnd;
  14895. scene.fogDensity = parsedData.fogDensity;
  14896. }
  14897. for (var index = 0; index < parsedData.lights.length; index++) {
  14898. var parsedLight = parsedData.lights[index];
  14899. parseLight(parsedLight, scene);
  14900. }
  14901. if (parsedData.materials) {
  14902. for (index = 0; index < parsedData.materials.length; index++) {
  14903. var parsedMaterial = parsedData.materials[index];
  14904. parseMaterial(parsedMaterial, scene, rootUrl);
  14905. }
  14906. }
  14907. if (parsedData.multiMaterials) {
  14908. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  14909. var parsedMultiMaterial = parsedData.multiMaterials[index];
  14910. parseMultiMaterial(parsedMultiMaterial, scene);
  14911. }
  14912. }
  14913. if (parsedData.skeletons) {
  14914. for (index = 0; index < parsedData.skeletons.length; index++) {
  14915. var parsedSkeleton = parsedData.skeletons[index];
  14916. parseSkeleton(parsedSkeleton, scene);
  14917. }
  14918. }
  14919. var geometries = parsedData.geometries;
  14920. if (geometries) {
  14921. var boxes = geometries.boxes;
  14922. if (boxes) {
  14923. for (index = 0; index < boxes.length; index++) {
  14924. var parsedBox = boxes[index];
  14925. parseBox(parsedBox, scene);
  14926. }
  14927. }
  14928. var spheres = geometries.spheres;
  14929. if (spheres) {
  14930. for (index = 0; index < spheres.length; index++) {
  14931. var parsedSphere = spheres[index];
  14932. parseSphere(parsedSphere, scene);
  14933. }
  14934. }
  14935. var cylinders = geometries.cylinders;
  14936. if (cylinders) {
  14937. for (index = 0; index < cylinders.length; index++) {
  14938. var parsedCylinder = cylinders[index];
  14939. parseCylinder(parsedCylinder, scene);
  14940. }
  14941. }
  14942. var toruses = geometries.toruses;
  14943. if (toruses) {
  14944. for (index = 0; index < toruses.length; index++) {
  14945. var parsedTorus = toruses[index];
  14946. parseTorus(parsedTorus, scene);
  14947. }
  14948. }
  14949. var grounds = geometries.grounds;
  14950. if (grounds) {
  14951. for (index = 0; index < grounds.length; index++) {
  14952. var parsedGround = grounds[index];
  14953. parseGround(parsedGround, scene);
  14954. }
  14955. }
  14956. var planes = geometries.planes;
  14957. if (planes) {
  14958. for (index = 0; index < planes.length; index++) {
  14959. var parsedPlane = planes[index];
  14960. parsePlane(parsedPlane, scene);
  14961. }
  14962. }
  14963. var torusKnots = geometries.torusKnots;
  14964. if (torusKnots) {
  14965. for (index = 0; index < torusKnots.length; index++) {
  14966. var parsedTorusKnot = torusKnots[index];
  14967. parseTorusKnot(parsedTorusKnot, scene);
  14968. }
  14969. }
  14970. var vertexData = geometries.vertexData;
  14971. if (vertexData) {
  14972. for (index = 0; index < vertexData.length; index++) {
  14973. var parsedVertexData = vertexData[index];
  14974. parseVertexData(parsedVertexData, scene, rootUrl);
  14975. }
  14976. }
  14977. }
  14978. for (index = 0; index < parsedData.meshes.length; index++) {
  14979. var parsedMesh = parsedData.meshes[index];
  14980. parseMesh(parsedMesh, scene, rootUrl);
  14981. }
  14982. for (index = 0; index < parsedData.cameras.length; index++) {
  14983. var parsedCamera = parsedData.cameras[index];
  14984. parseCamera(parsedCamera, scene);
  14985. }
  14986. if (parsedData.activeCameraID) {
  14987. scene.setActiveCameraByID(parsedData.activeCameraID);
  14988. }
  14989. for (index = 0; index < scene.cameras.length; index++) {
  14990. var camera = scene.cameras[index];
  14991. if (camera._waitingParentId) {
  14992. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  14993. camera._waitingParentId = undefined;
  14994. }
  14995. }
  14996. for (index = 0; index < scene.meshes.length; index++) {
  14997. var mesh = scene.meshes[index];
  14998. if (mesh._waitingParentId) {
  14999. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15000. mesh._waitingParentId = undefined;
  15001. }
  15002. }
  15003. if (parsedData.particleSystems) {
  15004. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15005. var parsedParticleSystem = parsedData.particleSystems[index];
  15006. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15007. }
  15008. }
  15009. if (parsedData.lensFlareSystems) {
  15010. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15011. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15012. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15013. }
  15014. }
  15015. if (parsedData.shadowGenerators) {
  15016. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15017. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15018. parseShadowGenerator(parsedShadowGenerator, scene);
  15019. }
  15020. }
  15021. return true;
  15022. }
  15023. });
  15024. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15025. var Internals = BABYLON.Internals;
  15026. })(BABYLON || (BABYLON = {}));
  15027. var BABYLON;
  15028. (function (BABYLON) {
  15029. var currentCSGMeshId = 0;
  15030. var Vertex = (function () {
  15031. function Vertex(pos, normal, uv) {
  15032. this.pos = pos;
  15033. this.normal = normal;
  15034. this.uv = uv;
  15035. }
  15036. Vertex.prototype.clone = function () {
  15037. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15038. };
  15039. Vertex.prototype.flip = function () {
  15040. this.normal = this.normal.scale(-1);
  15041. };
  15042. Vertex.prototype.interpolate = function (other, t) {
  15043. 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));
  15044. };
  15045. return Vertex;
  15046. })();
  15047. var Plane = (function () {
  15048. function Plane(normal, w) {
  15049. this.normal = normal;
  15050. this.w = w;
  15051. }
  15052. Plane.FromPoints = function (a, b, c) {
  15053. var v0 = c.subtract(a);
  15054. var v1 = b.subtract(a);
  15055. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15056. return null;
  15057. }
  15058. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15059. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15060. };
  15061. Plane.prototype.clone = function () {
  15062. return new Plane(this.normal.clone(), this.w);
  15063. };
  15064. Plane.prototype.flip = function () {
  15065. this.normal.scaleInPlace(-1);
  15066. this.w = -this.w;
  15067. };
  15068. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15069. var COPLANAR = 0;
  15070. var FRONT = 1;
  15071. var BACK = 2;
  15072. var SPANNING = 3;
  15073. var polygonType = 0;
  15074. var types = [];
  15075. for (var i = 0; i < polygon.vertices.length; i++) {
  15076. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15077. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15078. polygonType |= type;
  15079. types.push(type);
  15080. }
  15081. switch (polygonType) {
  15082. case COPLANAR:
  15083. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15084. break;
  15085. case FRONT:
  15086. front.push(polygon);
  15087. break;
  15088. case BACK:
  15089. back.push(polygon);
  15090. break;
  15091. case SPANNING:
  15092. var f = [], b = [];
  15093. for (i = 0; i < polygon.vertices.length; i++) {
  15094. var j = (i + 1) % polygon.vertices.length;
  15095. var ti = types[i], tj = types[j];
  15096. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15097. if (ti != BACK)
  15098. f.push(vi);
  15099. if (ti != FRONT)
  15100. b.push(ti != BACK ? vi.clone() : vi);
  15101. if ((ti | tj) == SPANNING) {
  15102. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15103. var v = vi.interpolate(vj, t);
  15104. f.push(v);
  15105. b.push(v.clone());
  15106. }
  15107. }
  15108. if (f.length >= 3) {
  15109. var poly = new Polygon(f, polygon.shared);
  15110. if (poly.plane)
  15111. front.push(poly);
  15112. }
  15113. if (b.length >= 3) {
  15114. poly = new Polygon(b, polygon.shared);
  15115. if (poly.plane)
  15116. back.push(poly);
  15117. }
  15118. break;
  15119. }
  15120. };
  15121. Plane.EPSILON = 1e-5;
  15122. return Plane;
  15123. })();
  15124. var Polygon = (function () {
  15125. function Polygon(vertices, shared) {
  15126. this.vertices = vertices;
  15127. this.shared = shared;
  15128. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15129. }
  15130. Polygon.prototype.clone = function () {
  15131. var vertices = this.vertices.map(function (v) {
  15132. return v.clone();
  15133. });
  15134. return new Polygon(vertices, this.shared);
  15135. };
  15136. Polygon.prototype.flip = function () {
  15137. this.vertices.reverse().map(function (v) {
  15138. v.flip();
  15139. });
  15140. this.plane.flip();
  15141. };
  15142. return Polygon;
  15143. })();
  15144. var Node = (function () {
  15145. function Node(polygons) {
  15146. this.plane = null;
  15147. this.front = null;
  15148. this.back = null;
  15149. this.polygons = [];
  15150. if (polygons) {
  15151. this.build(polygons);
  15152. }
  15153. }
  15154. Node.prototype.clone = function () {
  15155. var node = new Node();
  15156. node.plane = this.plane && this.plane.clone();
  15157. node.front = this.front && this.front.clone();
  15158. node.back = this.back && this.back.clone();
  15159. node.polygons = this.polygons.map(function (p) {
  15160. return p.clone();
  15161. });
  15162. return node;
  15163. };
  15164. Node.prototype.invert = function () {
  15165. for (var i = 0; i < this.polygons.length; i++) {
  15166. this.polygons[i].flip();
  15167. }
  15168. if (this.plane) {
  15169. this.plane.flip();
  15170. }
  15171. if (this.front) {
  15172. this.front.invert();
  15173. }
  15174. if (this.back) {
  15175. this.back.invert();
  15176. }
  15177. var temp = this.front;
  15178. this.front = this.back;
  15179. this.back = temp;
  15180. };
  15181. Node.prototype.clipPolygons = function (polygons) {
  15182. if (!this.plane)
  15183. return polygons.slice();
  15184. var front = [], back = [];
  15185. for (var i = 0; i < polygons.length; i++) {
  15186. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15187. }
  15188. if (this.front) {
  15189. front = this.front.clipPolygons(front);
  15190. }
  15191. if (this.back) {
  15192. back = this.back.clipPolygons(back);
  15193. } else {
  15194. back = [];
  15195. }
  15196. return front.concat(back);
  15197. };
  15198. Node.prototype.clipTo = function (bsp) {
  15199. this.polygons = bsp.clipPolygons(this.polygons);
  15200. if (this.front)
  15201. this.front.clipTo(bsp);
  15202. if (this.back)
  15203. this.back.clipTo(bsp);
  15204. };
  15205. Node.prototype.allPolygons = function () {
  15206. var polygons = this.polygons.slice();
  15207. if (this.front)
  15208. polygons = polygons.concat(this.front.allPolygons());
  15209. if (this.back)
  15210. polygons = polygons.concat(this.back.allPolygons());
  15211. return polygons;
  15212. };
  15213. Node.prototype.build = function (polygons) {
  15214. if (!polygons.length)
  15215. return;
  15216. if (!this.plane)
  15217. this.plane = polygons[0].plane.clone();
  15218. var front = [], back = [];
  15219. for (var i = 0; i < polygons.length; i++) {
  15220. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15221. }
  15222. if (front.length) {
  15223. if (!this.front)
  15224. this.front = new Node();
  15225. this.front.build(front);
  15226. }
  15227. if (back.length) {
  15228. if (!this.back)
  15229. this.back = new Node();
  15230. this.back.build(back);
  15231. }
  15232. };
  15233. return Node;
  15234. })();
  15235. var CSG = (function () {
  15236. function CSG() {
  15237. this.polygons = new Array();
  15238. }
  15239. CSG.FromMesh = function (mesh) {
  15240. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15241. if (mesh instanceof BABYLON.Mesh) {
  15242. mesh.computeWorldMatrix(true);
  15243. var matrix = mesh.getWorldMatrix();
  15244. var meshPosition = mesh.position.clone();
  15245. var meshRotation = mesh.rotation.clone();
  15246. var meshScaling = mesh.scaling.clone();
  15247. } else {
  15248. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15249. }
  15250. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15251. var subMeshes = mesh.subMeshes;
  15252. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15253. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15254. vertices = [];
  15255. for (var j = 0; j < 3; j++) {
  15256. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15257. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15258. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15259. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15260. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15261. vertex = new Vertex(position, normal, uv);
  15262. vertices.push(vertex);
  15263. }
  15264. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15265. if (polygon.plane)
  15266. polygons.push(polygon);
  15267. }
  15268. }
  15269. var csg = CSG.FromPolygons(polygons);
  15270. csg.matrix = matrix;
  15271. csg.position = meshPosition;
  15272. csg.rotation = meshRotation;
  15273. csg.scaling = meshScaling;
  15274. currentCSGMeshId++;
  15275. return csg;
  15276. };
  15277. CSG.FromPolygons = function (polygons) {
  15278. var csg = new BABYLON.CSG();
  15279. csg.polygons = polygons;
  15280. return csg;
  15281. };
  15282. CSG.prototype.clone = function () {
  15283. var csg = new BABYLON.CSG();
  15284. csg.polygons = this.polygons.map(function (p) {
  15285. return p.clone();
  15286. });
  15287. csg.copyTransformAttributes(this);
  15288. return csg;
  15289. };
  15290. CSG.prototype.toPolygons = function () {
  15291. return this.polygons;
  15292. };
  15293. CSG.prototype.union = function (csg) {
  15294. var a = new Node(this.clone().polygons);
  15295. var b = new Node(csg.clone().polygons);
  15296. a.clipTo(b);
  15297. b.clipTo(a);
  15298. b.invert();
  15299. b.clipTo(a);
  15300. b.invert();
  15301. a.build(b.allPolygons());
  15302. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15303. };
  15304. CSG.prototype.unionInPlace = function (csg) {
  15305. var a = new Node(this.polygons);
  15306. var b = new Node(csg.polygons);
  15307. a.clipTo(b);
  15308. b.clipTo(a);
  15309. b.invert();
  15310. b.clipTo(a);
  15311. b.invert();
  15312. a.build(b.allPolygons());
  15313. this.polygons = a.allPolygons();
  15314. };
  15315. CSG.prototype.subtract = function (csg) {
  15316. var a = new Node(this.clone().polygons);
  15317. var b = new Node(csg.clone().polygons);
  15318. a.invert();
  15319. a.clipTo(b);
  15320. b.clipTo(a);
  15321. b.invert();
  15322. b.clipTo(a);
  15323. b.invert();
  15324. a.build(b.allPolygons());
  15325. a.invert();
  15326. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15327. };
  15328. CSG.prototype.subtractInPlace = function (csg) {
  15329. var a = new Node(this.polygons);
  15330. var b = new Node(csg.polygons);
  15331. a.invert();
  15332. a.clipTo(b);
  15333. b.clipTo(a);
  15334. b.invert();
  15335. b.clipTo(a);
  15336. b.invert();
  15337. a.build(b.allPolygons());
  15338. a.invert();
  15339. this.polygons = a.allPolygons();
  15340. };
  15341. CSG.prototype.intersect = function (csg) {
  15342. var a = new Node(this.clone().polygons);
  15343. var b = new Node(csg.clone().polygons);
  15344. a.invert();
  15345. b.clipTo(a);
  15346. b.invert();
  15347. a.clipTo(b);
  15348. b.clipTo(a);
  15349. a.build(b.allPolygons());
  15350. a.invert();
  15351. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15352. };
  15353. CSG.prototype.intersectInPlace = function (csg) {
  15354. var a = new Node(this.polygons);
  15355. var b = new Node(csg.polygons);
  15356. a.invert();
  15357. b.clipTo(a);
  15358. b.invert();
  15359. a.clipTo(b);
  15360. b.clipTo(a);
  15361. a.build(b.allPolygons());
  15362. a.invert();
  15363. this.polygons = a.allPolygons();
  15364. };
  15365. CSG.prototype.inverse = function () {
  15366. var csg = this.clone();
  15367. csg.inverseInPlace();
  15368. return csg;
  15369. };
  15370. CSG.prototype.inverseInPlace = function () {
  15371. this.polygons.map(function (p) {
  15372. p.flip();
  15373. });
  15374. };
  15375. CSG.prototype.copyTransformAttributes = function (csg) {
  15376. this.matrix = csg.matrix;
  15377. this.position = csg.position;
  15378. this.rotation = csg.rotation;
  15379. this.scaling = csg.scaling;
  15380. return this;
  15381. };
  15382. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15383. var matrix = this.matrix.clone();
  15384. matrix.invert();
  15385. 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;
  15386. if (keepSubMeshes) {
  15387. polygons.sort(function (a, b) {
  15388. if (a.shared.meshId === b.shared.meshId) {
  15389. return a.shared.subMeshId - b.shared.subMeshId;
  15390. } else {
  15391. return a.shared.meshId - b.shared.meshId;
  15392. }
  15393. });
  15394. }
  15395. for (var i = 0, il = polygons.length; i < il; i++) {
  15396. polygon = polygons[i];
  15397. if (!subMesh_dict[polygon.shared.meshId]) {
  15398. subMesh_dict[polygon.shared.meshId] = {};
  15399. }
  15400. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15401. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15402. indexStart: +Infinity,
  15403. indexEnd: -Infinity,
  15404. materialIndex: polygon.shared.materialIndex
  15405. };
  15406. }
  15407. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15408. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15409. polygonIndices[0] = 0;
  15410. polygonIndices[1] = j - 1;
  15411. polygonIndices[2] = j;
  15412. for (var k = 0; k < 3; k++) {
  15413. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15414. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15415. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15416. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15417. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15418. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15419. 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)) {
  15420. vertices.push(vertex.x, vertex.y, vertex.z);
  15421. uvs.push(uv.x, uv.y);
  15422. normals.push(normal.x, normal.y, normal.z);
  15423. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15424. }
  15425. indices.push(vertex_idx);
  15426. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15427. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15428. currentIndex++;
  15429. }
  15430. }
  15431. }
  15432. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15433. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15434. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15435. mesh.setIndices(indices);
  15436. if (keepSubMeshes) {
  15437. var materialIndexOffset = 0, materialMaxIndex;
  15438. mesh.subMeshes.length = 0;
  15439. for (var m in subMesh_dict) {
  15440. materialMaxIndex = -1;
  15441. for (var sm in subMesh_dict[m]) {
  15442. subMesh_obj = subMesh_dict[m][sm];
  15443. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15444. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15445. }
  15446. materialIndexOffset += ++materialMaxIndex;
  15447. }
  15448. }
  15449. return mesh;
  15450. };
  15451. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15452. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15453. mesh.material = material;
  15454. mesh.position.copyFrom(this.position);
  15455. mesh.rotation.copyFrom(this.rotation);
  15456. mesh.scaling.copyFrom(this.scaling);
  15457. mesh.computeWorldMatrix(true);
  15458. return mesh;
  15459. };
  15460. return CSG;
  15461. })();
  15462. BABYLON.CSG = CSG;
  15463. })(BABYLON || (BABYLON = {}));
  15464. var __extends = this.__extends || function (d, b) {
  15465. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15466. function __() { this.constructor = d; }
  15467. __.prototype = b.prototype;
  15468. d.prototype = new __();
  15469. };
  15470. var BABYLON;
  15471. (function (BABYLON) {
  15472. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15473. __extends(OculusDistortionCorrectionPostProcess, _super);
  15474. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15475. var _this = this;
  15476. _super.call(this, name, "oculusDistortionCorrection", [
  15477. 'LensCenter',
  15478. 'Scale',
  15479. 'ScaleIn',
  15480. 'HmdWarpParam'
  15481. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15482. this._isRightEye = isRightEye;
  15483. this._distortionFactors = cameraSettings.DistortionK;
  15484. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15485. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15486. this.onSizeChanged = function () {
  15487. _this.aspectRatio = _this.width * .5 / _this.height;
  15488. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15489. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15490. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15491. };
  15492. this.onApply = function (effect) {
  15493. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15494. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15495. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15496. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15497. };
  15498. }
  15499. return OculusDistortionCorrectionPostProcess;
  15500. })(BABYLON.PostProcess);
  15501. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15502. })(BABYLON || (BABYLON = {}));
  15503. var BABYLON;
  15504. (function (BABYLON) {
  15505. (function (JoystickAxis) {
  15506. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15507. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15508. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15509. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15510. var JoystickAxis = BABYLON.JoystickAxis;
  15511. var VirtualJoystick = (function () {
  15512. function VirtualJoystick(leftJoystick) {
  15513. var _this = this;
  15514. if (leftJoystick) {
  15515. this._leftJoystick = true;
  15516. } else {
  15517. this._leftJoystick = false;
  15518. }
  15519. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15520. VirtualJoystick._globalJoystickIndex++;
  15521. this._axisTargetedByLeftAndRight = 0 /* X */;
  15522. this._axisTargetedByUpAndDown = 1 /* Y */;
  15523. this.reverseLeftRight = false;
  15524. this.reverseUpDown = false;
  15525. this._touches = new BABYLON.VirtualJoystick.Collection();
  15526. this.deltaPosition = BABYLON.Vector3.Zero();
  15527. this._joystickSensibility = 25;
  15528. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15529. this._rotationSpeed = 25;
  15530. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  15531. this._rotateOnAxisRelativeToMesh = false;
  15532. if (!VirtualJoystick.vjCanvas) {
  15533. window.addEventListener("resize", function () {
  15534. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15535. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15536. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  15537. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  15538. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  15539. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  15540. }, false);
  15541. VirtualJoystick.vjCanvas = document.createElement("canvas");
  15542. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  15543. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  15544. VirtualJoystick.vjCanvas.width = window.innerWidth;
  15545. VirtualJoystick.vjCanvas.height = window.innerHeight;
  15546. VirtualJoystick.vjCanvas.style.width = "100%";
  15547. VirtualJoystick.vjCanvas.style.height = "100%";
  15548. VirtualJoystick.vjCanvas.style.position = "absolute";
  15549. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  15550. VirtualJoystick.vjCanvas.style.top = "0px";
  15551. VirtualJoystick.vjCanvas.style.left = "0px";
  15552. VirtualJoystick.vjCanvas.style.zIndex = "5";
  15553. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  15554. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  15555. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  15556. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15557. document.body.appendChild(VirtualJoystick.vjCanvas);
  15558. }
  15559. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  15560. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  15561. this.pressed = false;
  15562. this._joystickColor = "cyan";
  15563. this._joystickPointerID = -1;
  15564. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  15565. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  15566. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  15567. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  15568. _this._onPointerDown(evt);
  15569. }, false);
  15570. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  15571. _this._onPointerMove(evt);
  15572. }, false);
  15573. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  15574. _this._onPointerUp(evt);
  15575. }, false);
  15576. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  15577. _this._onPointerUp(evt);
  15578. }, false);
  15579. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  15580. evt.preventDefault();
  15581. }, false);
  15582. requestAnimationFrame(function () {
  15583. _this._drawVirtualJoystick();
  15584. });
  15585. }
  15586. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  15587. this._joystickSensibility = newJoystickSensibility;
  15588. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15589. };
  15590. VirtualJoystick.prototype._onPointerDown = function (e) {
  15591. var positionOnScreenCondition;
  15592. e.preventDefault();
  15593. if (this._leftJoystick === true) {
  15594. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  15595. } else {
  15596. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  15597. }
  15598. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  15599. this._joystickPointerID = e.pointerId;
  15600. this._joystickPointerStartPos.x = e.clientX;
  15601. this._joystickPointerStartPos.y = e.clientY;
  15602. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  15603. this._deltaJoystickVector.x = 0;
  15604. this._deltaJoystickVector.y = 0;
  15605. this.pressed = true;
  15606. this._touches.add(e.pointerId.toString(), e);
  15607. } else {
  15608. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  15609. this._action();
  15610. this._touches.add(e.pointerId.toString(), e);
  15611. }
  15612. }
  15613. };
  15614. VirtualJoystick.prototype._onPointerMove = function (e) {
  15615. if (this._joystickPointerID == e.pointerId) {
  15616. this._joystickPointerPos.x = e.clientX;
  15617. this._joystickPointerPos.y = e.clientY;
  15618. this._deltaJoystickVector = this._joystickPointerPos.clone();
  15619. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  15620. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  15621. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  15622. switch (this._axisTargetedByLeftAndRight) {
  15623. case 0 /* X */:
  15624. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  15625. break;
  15626. case 1 /* Y */:
  15627. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  15628. break;
  15629. case 2 /* Z */:
  15630. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  15631. break;
  15632. }
  15633. var directionUpDown = this.reverseUpDown ? 1 : -1;
  15634. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  15635. switch (this._axisTargetedByUpAndDown) {
  15636. case 0 /* X */:
  15637. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  15638. break;
  15639. case 1 /* Y */:
  15640. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  15641. break;
  15642. case 2 /* Z */:
  15643. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  15644. break;
  15645. }
  15646. } else {
  15647. if (this._touches.item(e.pointerId.toString())) {
  15648. this._touches.item(e.pointerId.toString()).x = e.clientX;
  15649. this._touches.item(e.pointerId.toString()).y = e.clientY;
  15650. }
  15651. }
  15652. };
  15653. VirtualJoystick.prototype._onPointerUp = function (e) {
  15654. this._clearCanvas();
  15655. if (this._joystickPointerID == e.pointerId) {
  15656. this._joystickPointerID = -1;
  15657. this.pressed = false;
  15658. }
  15659. this._deltaJoystickVector.x = 0;
  15660. this._deltaJoystickVector.y = 0;
  15661. this._touches.remove(e.pointerId.toString());
  15662. };
  15663. /**
  15664. * Change the color of the virtual joystick
  15665. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  15666. */
  15667. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  15668. this._joystickColor = newColor;
  15669. };
  15670. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  15671. this._action = action;
  15672. };
  15673. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  15674. switch (axis) {
  15675. case 0 /* X */:
  15676. case 1 /* Y */:
  15677. case 2 /* Z */:
  15678. this._axisTargetedByLeftAndRight = axis;
  15679. break;
  15680. default:
  15681. this._axisTargetedByLeftAndRight = 0 /* X */;
  15682. break;
  15683. }
  15684. };
  15685. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  15686. switch (axis) {
  15687. case 0 /* X */:
  15688. case 1 /* Y */:
  15689. case 2 /* Z */:
  15690. this._axisTargetedByUpAndDown = axis;
  15691. break;
  15692. default:
  15693. this._axisTargetedByUpAndDown = 1 /* Y */;
  15694. break;
  15695. }
  15696. };
  15697. VirtualJoystick.prototype._clearCanvas = function () {
  15698. if (this._leftJoystick) {
  15699. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  15700. } else {
  15701. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  15702. }
  15703. };
  15704. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  15705. var _this = this;
  15706. if (this.pressed) {
  15707. this._clearCanvas();
  15708. this._touches.forEach(function (touch) {
  15709. if (touch.pointerId === _this._joystickPointerID) {
  15710. VirtualJoystick.vjCanvasContext.beginPath();
  15711. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15712. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15713. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  15714. VirtualJoystick.vjCanvasContext.stroke();
  15715. VirtualJoystick.vjCanvasContext.beginPath();
  15716. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15717. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  15718. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  15719. VirtualJoystick.vjCanvasContext.stroke();
  15720. VirtualJoystick.vjCanvasContext.beginPath();
  15721. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  15722. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  15723. VirtualJoystick.vjCanvasContext.stroke();
  15724. } else {
  15725. VirtualJoystick.vjCanvasContext.beginPath();
  15726. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  15727. VirtualJoystick.vjCanvasContext.beginPath();
  15728. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  15729. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  15730. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  15731. VirtualJoystick.vjCanvasContext.stroke();
  15732. }
  15733. ;
  15734. });
  15735. }
  15736. requestAnimationFrame(function () {
  15737. _this._drawVirtualJoystick();
  15738. });
  15739. };
  15740. VirtualJoystick.prototype.releaseCanvas = function () {
  15741. if (VirtualJoystick.vjCanvas) {
  15742. document.body.removeChild(VirtualJoystick.vjCanvas);
  15743. VirtualJoystick.vjCanvas = null;
  15744. }
  15745. };
  15746. VirtualJoystick._globalJoystickIndex = 0;
  15747. return VirtualJoystick;
  15748. })();
  15749. BABYLON.VirtualJoystick = VirtualJoystick;
  15750. })(BABYLON || (BABYLON = {}));
  15751. var BABYLON;
  15752. (function (BABYLON) {
  15753. (function (VirtualJoystick) {
  15754. var Collection = (function () {
  15755. function Collection() {
  15756. this._count = 0;
  15757. this._collection = new Array();
  15758. }
  15759. Collection.prototype.Count = function () {
  15760. return this._count;
  15761. };
  15762. Collection.prototype.add = function (key, item) {
  15763. if (this._collection[key] != undefined) {
  15764. return undefined;
  15765. }
  15766. this._collection[key] = item;
  15767. return ++this._count;
  15768. };
  15769. Collection.prototype.remove = function (key) {
  15770. if (this._collection[key] == undefined) {
  15771. return undefined;
  15772. }
  15773. delete this._collection[key];
  15774. return --this._count;
  15775. };
  15776. Collection.prototype.item = function (key) {
  15777. return this._collection[key];
  15778. };
  15779. Collection.prototype.forEach = function (block) {
  15780. var key;
  15781. for (key in this._collection) {
  15782. if (this._collection.hasOwnProperty(key)) {
  15783. block(this._collection[key]);
  15784. }
  15785. }
  15786. };
  15787. return Collection;
  15788. })();
  15789. VirtualJoystick.Collection = Collection;
  15790. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  15791. var VirtualJoystick = BABYLON.VirtualJoystick;
  15792. })(BABYLON || (BABYLON = {}));
  15793. var __extends = this.__extends || function (d, b) {
  15794. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15795. function __() { this.constructor = d; }
  15796. __.prototype = b.prototype;
  15797. d.prototype = new __();
  15798. };
  15799. var BABYLON;
  15800. (function (BABYLON) {
  15801. var OculusRiftDevKit2013_Metric = {
  15802. HResolution: 1280,
  15803. VResolution: 800,
  15804. HScreenSize: 0.149759993,
  15805. VScreenSize: 0.0935999975,
  15806. VScreenCenter: 0.0467999987,
  15807. EyeToScreenDistance: 0.0410000011,
  15808. LensSeparationDistance: 0.0635000020,
  15809. InterpupillaryDistance: 0.0640000030,
  15810. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  15811. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  15812. PostProcessScaleFactor: 1.714605507808412,
  15813. LensCenterOffset: 0.151976421
  15814. };
  15815. var _OculusInnerCamera = (function (_super) {
  15816. __extends(_OculusInnerCamera, _super);
  15817. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  15818. _super.call(this, name, position, scene);
  15819. this._workMatrix = new BABYLON.Matrix();
  15820. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  15821. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  15822. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  15823. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  15824. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  15825. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  15826. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  15827. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  15828. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  15829. }
  15830. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  15831. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  15832. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  15833. return this._projectionMatrix;
  15834. };
  15835. _OculusInnerCamera.prototype._getViewMatrix = function () {
  15836. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15837. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15838. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  15839. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15840. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  15841. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  15842. return this._viewMatrix;
  15843. };
  15844. return _OculusInnerCamera;
  15845. })(BABYLON.FreeCamera);
  15846. var OculusCamera = (function (_super) {
  15847. __extends(OculusCamera, _super);
  15848. function OculusCamera(name, position, scene) {
  15849. _super.call(this, name, position, scene);
  15850. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  15851. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  15852. this.subCameras.push(this._leftCamera);
  15853. this.subCameras.push(this._rightCamera);
  15854. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15855. }
  15856. OculusCamera.prototype._update = function () {
  15857. this._leftCamera.position.copyFrom(this.position);
  15858. this._rightCamera.position.copyFrom(this.position);
  15859. this._updateCamera(this._leftCamera);
  15860. this._updateCamera(this._rightCamera);
  15861. _super.prototype._update.call(this);
  15862. };
  15863. OculusCamera.prototype._updateCamera = function (camera) {
  15864. camera.minZ = this.minZ;
  15865. camera.maxZ = this.maxZ;
  15866. camera.rotation.x = this.rotation.x;
  15867. camera.rotation.y = this.rotation.y;
  15868. camera.rotation.z = this.rotation.z;
  15869. };
  15870. OculusCamera.prototype._onOrientationEvent = function (evt) {
  15871. var yaw = evt.alpha / 180 * Math.PI;
  15872. var pitch = evt.beta / 180 * Math.PI;
  15873. var roll = evt.gamma / 180 * Math.PI;
  15874. if (!this._offsetOrientation) {
  15875. this._offsetOrientation = {
  15876. yaw: yaw,
  15877. pitch: pitch,
  15878. roll: roll
  15879. };
  15880. return;
  15881. } else {
  15882. this.rotation.y += yaw - this._offsetOrientation.yaw;
  15883. this.rotation.x += pitch - this._offsetOrientation.pitch;
  15884. this.rotation.z += this._offsetOrientation.roll - roll;
  15885. this._offsetOrientation.yaw = yaw;
  15886. this._offsetOrientation.pitch = pitch;
  15887. this._offsetOrientation.roll = roll;
  15888. }
  15889. };
  15890. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  15891. _super.prototype.attachControl.call(this, element, noPreventDefault);
  15892. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15893. };
  15894. OculusCamera.prototype.detachControl = function (element) {
  15895. _super.prototype.detachControl.call(this, element);
  15896. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15897. };
  15898. return OculusCamera;
  15899. })(BABYLON.FreeCamera);
  15900. BABYLON.OculusCamera = OculusCamera;
  15901. })(BABYLON || (BABYLON = {}));
  15902. var __extends = this.__extends || function (d, b) {
  15903. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15904. function __() { this.constructor = d; }
  15905. __.prototype = b.prototype;
  15906. d.prototype = new __();
  15907. };
  15908. var BABYLON;
  15909. (function (BABYLON) {
  15910. var VirtualJoysticksCamera = (function (_super) {
  15911. __extends(VirtualJoysticksCamera, _super);
  15912. function VirtualJoysticksCamera(name, position, scene) {
  15913. _super.call(this, name, position, scene);
  15914. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  15915. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  15916. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  15917. this._leftjoystick.setJoystickSensibility(0.15);
  15918. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  15919. this._rightjoystick.setAxisForUpDown(0 /* X */);
  15920. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  15921. this._rightjoystick.reverseUpDown = true;
  15922. this._rightjoystick.setJoystickSensibility(0.05);
  15923. this._rightjoystick.setJoystickColor("yellow");
  15924. }
  15925. VirtualJoysticksCamera.prototype._checkInputs = function () {
  15926. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  15927. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  15928. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  15929. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  15930. if (!this._leftjoystick.pressed) {
  15931. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  15932. }
  15933. if (!this._rightjoystick.pressed) {
  15934. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  15935. }
  15936. };
  15937. VirtualJoysticksCamera.prototype.dispose = function () {
  15938. this._leftjoystick.releaseCanvas();
  15939. _super.prototype.dispose.call(this);
  15940. };
  15941. return VirtualJoysticksCamera;
  15942. })(BABYLON.FreeCamera);
  15943. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  15944. })(BABYLON || (BABYLON = {}));
  15945. var __extends = this.__extends || function (d, b) {
  15946. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15947. function __() { this.constructor = d; }
  15948. __.prototype = b.prototype;
  15949. d.prototype = new __();
  15950. };
  15951. var BABYLON;
  15952. (function (BABYLON) {
  15953. var ShaderMaterial = (function (_super) {
  15954. __extends(ShaderMaterial, _super);
  15955. function ShaderMaterial(name, scene, shaderPath, options) {
  15956. _super.call(this, name, scene);
  15957. this._textures = new Array();
  15958. this._floats = new Array();
  15959. this._floatsArrays = {};
  15960. this._colors3 = new Array();
  15961. this._colors4 = new Array();
  15962. this._vectors2 = new Array();
  15963. this._vectors3 = new Array();
  15964. this._matrices = new Array();
  15965. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  15966. this._shaderPath = shaderPath;
  15967. options.needAlphaBlending = options.needAlphaBlending || false;
  15968. options.needAlphaTesting = options.needAlphaTesting || false;
  15969. options.attributes = options.attributes || ["position", "normal", "uv"];
  15970. options.uniforms = options.uniforms || ["worldViewProjection"];
  15971. options.samplers = options.samplers || [];
  15972. this._options = options;
  15973. }
  15974. ShaderMaterial.prototype.needAlphaBlending = function () {
  15975. return this._options.needAlphaBlending;
  15976. };
  15977. ShaderMaterial.prototype.needAlphaTesting = function () {
  15978. return this._options.needAlphaTesting;
  15979. };
  15980. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  15981. if (this._options.uniforms.indexOf(uniformName) === -1) {
  15982. this._options.uniforms.push(uniformName);
  15983. }
  15984. };
  15985. ShaderMaterial.prototype.setTexture = function (name, texture) {
  15986. if (this._options.samplers.indexOf(name) === -1) {
  15987. this._options.samplers.push(name);
  15988. }
  15989. this._textures[name] = texture;
  15990. return this;
  15991. };
  15992. ShaderMaterial.prototype.setFloat = function (name, value) {
  15993. this._checkUniform(name);
  15994. this._floats[name] = value;
  15995. return this;
  15996. };
  15997. ShaderMaterial.prototype.setFloats = function (name, value) {
  15998. this._checkUniform(name);
  15999. this._floatsArrays[name] = value;
  16000. return this;
  16001. };
  16002. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16003. this._checkUniform(name);
  16004. this._colors3[name] = value;
  16005. return this;
  16006. };
  16007. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16008. this._checkUniform(name);
  16009. this._colors4[name] = value;
  16010. return this;
  16011. };
  16012. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16013. this._checkUniform(name);
  16014. this._vectors2[name] = value;
  16015. return this;
  16016. };
  16017. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16018. this._checkUniform(name);
  16019. this._vectors3[name] = value;
  16020. return this;
  16021. };
  16022. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16023. this._checkUniform(name);
  16024. this._matrices[name] = value;
  16025. return this;
  16026. };
  16027. ShaderMaterial.prototype.isReady = function () {
  16028. var engine = this.getScene().getEngine();
  16029. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16030. if (!this._effect.isReady()) {
  16031. return false;
  16032. }
  16033. return true;
  16034. };
  16035. ShaderMaterial.prototype.bind = function (world) {
  16036. if (this._options.uniforms.indexOf("world") !== -1) {
  16037. this._effect.setMatrix("world", world);
  16038. }
  16039. if (this._options.uniforms.indexOf("view") !== -1) {
  16040. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16041. }
  16042. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16043. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16044. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16045. }
  16046. if (this._options.uniforms.indexOf("projection") !== -1) {
  16047. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16048. }
  16049. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16050. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16051. }
  16052. for (var name in this._textures) {
  16053. this._effect.setTexture(name, this._textures[name]);
  16054. }
  16055. for (name in this._floats) {
  16056. this._effect.setFloat(name, this._floats[name]);
  16057. }
  16058. for (name in this._floatsArrays) {
  16059. this._effect.setArray(name, this._floatsArrays[name]);
  16060. }
  16061. for (name in this._colors3) {
  16062. this._effect.setColor3(name, this._colors3[name]);
  16063. }
  16064. for (name in this._colors4) {
  16065. var color = this._colors4[name];
  16066. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16067. }
  16068. for (name in this._vectors2) {
  16069. this._effect.setVector2(name, this._vectors2[name]);
  16070. }
  16071. for (name in this._vectors3) {
  16072. this._effect.setVector3(name, this._vectors3[name]);
  16073. }
  16074. for (name in this._matrices) {
  16075. this._effect.setMatrix(name, this._matrices[name]);
  16076. }
  16077. };
  16078. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16079. for (var name in this._textures) {
  16080. this._textures[name].dispose();
  16081. }
  16082. this._textures = [];
  16083. _super.prototype.dispose.call(this, forceDisposeEffect);
  16084. };
  16085. return ShaderMaterial;
  16086. })(BABYLON.Material);
  16087. BABYLON.ShaderMaterial = ShaderMaterial;
  16088. })(BABYLON || (BABYLON = {}));
  16089. var BABYLON;
  16090. (function (BABYLON) {
  16091. var VertexData = (function () {
  16092. function VertexData() {
  16093. }
  16094. VertexData.prototype.set = function (data, kind) {
  16095. switch (kind) {
  16096. case BABYLON.VertexBuffer.PositionKind:
  16097. this.positions = data;
  16098. break;
  16099. case BABYLON.VertexBuffer.NormalKind:
  16100. this.normals = data;
  16101. break;
  16102. case BABYLON.VertexBuffer.UVKind:
  16103. this.uvs = data;
  16104. break;
  16105. case BABYLON.VertexBuffer.UV2Kind:
  16106. this.uv2s = data;
  16107. break;
  16108. case BABYLON.VertexBuffer.ColorKind:
  16109. this.colors = data;
  16110. break;
  16111. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16112. this.matricesIndices = data;
  16113. break;
  16114. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16115. this.matricesWeights = data;
  16116. break;
  16117. }
  16118. };
  16119. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16120. this._applyTo(mesh, updatable);
  16121. };
  16122. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16123. this._applyTo(geometry, updatable);
  16124. };
  16125. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16126. this._update(mesh);
  16127. };
  16128. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16129. this._update(geometry);
  16130. };
  16131. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16132. if (this.positions) {
  16133. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16134. }
  16135. if (this.normals) {
  16136. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16137. }
  16138. if (this.uvs) {
  16139. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16140. }
  16141. if (this.uv2s) {
  16142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16143. }
  16144. if (this.colors) {
  16145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16146. }
  16147. if (this.matricesIndices) {
  16148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16149. }
  16150. if (this.matricesWeights) {
  16151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16152. }
  16153. if (this.indices) {
  16154. meshOrGeometry.setIndices(this.indices);
  16155. }
  16156. };
  16157. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16158. if (this.positions) {
  16159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16160. }
  16161. if (this.normals) {
  16162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16163. }
  16164. if (this.uvs) {
  16165. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16166. }
  16167. if (this.uv2s) {
  16168. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16169. }
  16170. if (this.colors) {
  16171. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16172. }
  16173. if (this.matricesIndices) {
  16174. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16175. }
  16176. if (this.matricesWeights) {
  16177. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16178. }
  16179. if (this.indices) {
  16180. meshOrGeometry.setIndices(this.indices);
  16181. }
  16182. };
  16183. VertexData.prototype.transform = function (matrix) {
  16184. var transformed = BABYLON.Vector3.Zero();
  16185. if (this.positions) {
  16186. var position = BABYLON.Vector3.Zero();
  16187. for (var index = 0; index < this.positions.length; index += 3) {
  16188. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16189. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16190. this.positions[index] = transformed.x;
  16191. this.positions[index + 1] = transformed.y;
  16192. this.positions[index + 2] = transformed.z;
  16193. }
  16194. }
  16195. if (this.normals) {
  16196. var normal = BABYLON.Vector3.Zero();
  16197. for (index = 0; index < this.normals.length; index += 3) {
  16198. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16199. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16200. this.normals[index] = transformed.x;
  16201. this.normals[index + 1] = transformed.y;
  16202. this.normals[index + 2] = transformed.z;
  16203. }
  16204. }
  16205. };
  16206. VertexData.prototype.merge = function (other) {
  16207. if (other.indices) {
  16208. if (!this.indices) {
  16209. this.indices = [];
  16210. }
  16211. var offset = this.positions ? this.positions.length / 3 : 0;
  16212. for (var index = 0; index < other.indices.length; index++) {
  16213. this.indices.push(other.indices[index] + offset);
  16214. }
  16215. }
  16216. if (other.positions) {
  16217. if (!this.positions) {
  16218. this.positions = [];
  16219. }
  16220. for (index = 0; index < other.positions.length; index++) {
  16221. this.positions.push(other.positions[index]);
  16222. }
  16223. }
  16224. if (other.normals) {
  16225. if (!this.normals) {
  16226. this.normals = [];
  16227. }
  16228. for (index = 0; index < other.normals.length; index++) {
  16229. this.normals.push(other.normals[index]);
  16230. }
  16231. }
  16232. if (other.uvs) {
  16233. if (!this.uvs) {
  16234. this.uvs = [];
  16235. }
  16236. for (index = 0; index < other.uvs.length; index++) {
  16237. this.uvs.push(other.uvs[index]);
  16238. }
  16239. }
  16240. if (other.uv2s) {
  16241. if (!this.uv2s) {
  16242. this.uv2s = [];
  16243. }
  16244. for (index = 0; index < other.uv2s.length; index++) {
  16245. this.uv2s.push(other.uv2s[index]);
  16246. }
  16247. }
  16248. if (other.matricesIndices) {
  16249. if (!this.matricesIndices) {
  16250. this.matricesIndices = [];
  16251. }
  16252. for (index = 0; index < other.matricesIndices.length; index++) {
  16253. this.matricesIndices.push(other.matricesIndices[index]);
  16254. }
  16255. }
  16256. if (other.matricesWeights) {
  16257. if (!this.matricesWeights) {
  16258. this.matricesWeights = [];
  16259. }
  16260. for (index = 0; index < other.matricesWeights.length; index++) {
  16261. this.matricesWeights.push(other.matricesWeights[index]);
  16262. }
  16263. }
  16264. if (other.colors) {
  16265. if (!this.colors) {
  16266. this.colors = [];
  16267. }
  16268. for (index = 0; index < other.colors.length; index++) {
  16269. this.colors.push(other.colors[index]);
  16270. }
  16271. }
  16272. };
  16273. VertexData.ExtractFromMesh = function (mesh) {
  16274. return VertexData._ExtractFrom(mesh);
  16275. };
  16276. VertexData.ExtractFromGeometry = function (geometry) {
  16277. return VertexData._ExtractFrom(geometry);
  16278. };
  16279. VertexData._ExtractFrom = function (meshOrGeometry) {
  16280. var result = new BABYLON.VertexData();
  16281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16282. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16283. }
  16284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16285. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16286. }
  16287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16288. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16289. }
  16290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16291. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16292. }
  16293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16294. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16295. }
  16296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16297. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16298. }
  16299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16300. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16301. }
  16302. result.indices = meshOrGeometry.getIndices();
  16303. return result;
  16304. };
  16305. VertexData.CreateBox = function (size) {
  16306. var normalsSource = [
  16307. new BABYLON.Vector3(0, 0, 1),
  16308. new BABYLON.Vector3(0, 0, -1),
  16309. new BABYLON.Vector3(1, 0, 0),
  16310. new BABYLON.Vector3(-1, 0, 0),
  16311. new BABYLON.Vector3(0, 1, 0),
  16312. new BABYLON.Vector3(0, -1, 0)
  16313. ];
  16314. var indices = [];
  16315. var positions = [];
  16316. var normals = [];
  16317. var uvs = [];
  16318. size = size || 1;
  16319. for (var index = 0; index < normalsSource.length; index++) {
  16320. var normal = normalsSource[index];
  16321. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16322. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16323. var verticesLength = positions.length / 3;
  16324. indices.push(verticesLength);
  16325. indices.push(verticesLength + 1);
  16326. indices.push(verticesLength + 2);
  16327. indices.push(verticesLength);
  16328. indices.push(verticesLength + 2);
  16329. indices.push(verticesLength + 3);
  16330. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16331. positions.push(vertex.x, vertex.y, vertex.z);
  16332. normals.push(normal.x, normal.y, normal.z);
  16333. uvs.push(1.0, 1.0);
  16334. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16335. positions.push(vertex.x, vertex.y, vertex.z);
  16336. normals.push(normal.x, normal.y, normal.z);
  16337. uvs.push(0.0, 1.0);
  16338. vertex = normal.add(side1).add(side2).scale(size / 2);
  16339. positions.push(vertex.x, vertex.y, vertex.z);
  16340. normals.push(normal.x, normal.y, normal.z);
  16341. uvs.push(0.0, 0.0);
  16342. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16343. positions.push(vertex.x, vertex.y, vertex.z);
  16344. normals.push(normal.x, normal.y, normal.z);
  16345. uvs.push(1.0, 0.0);
  16346. }
  16347. var vertexData = new BABYLON.VertexData();
  16348. vertexData.indices = indices;
  16349. vertexData.positions = positions;
  16350. vertexData.normals = normals;
  16351. vertexData.uvs = uvs;
  16352. return vertexData;
  16353. };
  16354. VertexData.CreateSphere = function (segments, diameter) {
  16355. segments = segments || 32;
  16356. diameter = diameter || 1;
  16357. var radius = diameter / 2;
  16358. var totalZRotationSteps = 2 + segments;
  16359. var totalYRotationSteps = 2 * totalZRotationSteps;
  16360. var indices = [];
  16361. var positions = [];
  16362. var normals = [];
  16363. var uvs = [];
  16364. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16365. var normalizedZ = zRotationStep / totalZRotationSteps;
  16366. var angleZ = (normalizedZ * Math.PI);
  16367. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16368. var normalizedY = yRotationStep / totalYRotationSteps;
  16369. var angleY = normalizedY * Math.PI * 2;
  16370. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16371. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16372. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16373. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16374. var vertex = complete.scale(radius);
  16375. var normal = BABYLON.Vector3.Normalize(vertex);
  16376. positions.push(vertex.x, vertex.y, vertex.z);
  16377. normals.push(normal.x, normal.y, normal.z);
  16378. uvs.push(normalizedZ, normalizedY);
  16379. }
  16380. if (zRotationStep > 0) {
  16381. var verticesCount = positions.length / 3;
  16382. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16383. indices.push((firstIndex));
  16384. indices.push((firstIndex + 1));
  16385. indices.push(firstIndex + totalYRotationSteps + 1);
  16386. indices.push((firstIndex + totalYRotationSteps + 1));
  16387. indices.push((firstIndex + 1));
  16388. indices.push((firstIndex + totalYRotationSteps + 2));
  16389. }
  16390. }
  16391. }
  16392. var vertexData = new BABYLON.VertexData();
  16393. vertexData.indices = indices;
  16394. vertexData.positions = positions;
  16395. vertexData.normals = normals;
  16396. vertexData.uvs = uvs;
  16397. return vertexData;
  16398. };
  16399. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  16400. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  16401. var radiusTop = diameterTop / 2;
  16402. var radiusBottom = diameterBottom / 2;
  16403. var indices = [];
  16404. var positions = [];
  16405. var normals = [];
  16406. var uvs = [];
  16407. height = height || 1;
  16408. diameterTop = diameterTop || 0.5;
  16409. diameterBottom = diameterBottom || 1;
  16410. tessellation = tessellation || 16;
  16411. subdivisions = subdivisions || 1;
  16412. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  16413. var getCircleVector = function (i) {
  16414. var angle = (i * 2.0 * Math.PI / tessellation);
  16415. var dx = Math.cos(angle);
  16416. var dz = Math.sin(angle);
  16417. return new BABYLON.Vector3(dx, 0, dz);
  16418. };
  16419. var createCylinderCap = function (isTop) {
  16420. var radius = isTop ? radiusTop : radiusBottom;
  16421. if (radius == 0) {
  16422. return;
  16423. }
  16424. var vbase = positions.length / 3;
  16425. var offset = new BABYLON.Vector3(0, height / 2, 0);
  16426. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  16427. if (!isTop) {
  16428. offset.scaleInPlace(-1);
  16429. textureScale.x = -textureScale.x;
  16430. }
  16431. for (i = 0; i < tessellation; i++) {
  16432. var circleVector = getCircleVector(i);
  16433. var position = circleVector.scale(radius).add(offset);
  16434. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  16435. positions.push(position.x, position.y, position.z);
  16436. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16437. }
  16438. for (var i = 0; i < tessellation - 2; i++) {
  16439. if (!isTop) {
  16440. indices.push(vbase);
  16441. indices.push(vbase + (i + 2) % tessellation);
  16442. indices.push(vbase + (i + 1) % tessellation);
  16443. } else {
  16444. indices.push(vbase);
  16445. indices.push(vbase + (i + 1) % tessellation);
  16446. indices.push(vbase + (i + 2) % tessellation);
  16447. }
  16448. }
  16449. };
  16450. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  16451. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  16452. var stride = tessellation + 1;
  16453. for (var i = 0; i <= tessellation; i++) {
  16454. var circleVector = getCircleVector(i);
  16455. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  16456. var position, radius = radiusBottom;
  16457. for (var s = 0; s <= subdivisions; s++) {
  16458. position = circleVector.scale(radius);
  16459. position.addInPlace(base.add(offset.scale(s)));
  16460. textureCoordinate.y += 1 / subdivisions;
  16461. radius += (radiusTop - radiusBottom) / subdivisions;
  16462. positions.push(position.x, position.y, position.z);
  16463. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16464. }
  16465. }
  16466. subdivisions += 1;
  16467. for (var s = 0; s < subdivisions - 1; s++) {
  16468. for (var i = 0; i <= tessellation; i++) {
  16469. indices.push(i * subdivisions + s);
  16470. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16471. indices.push(i * subdivisions + (s + 1));
  16472. indices.push(i * subdivisions + (s + 1));
  16473. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  16474. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  16475. }
  16476. }
  16477. createCylinderCap(true);
  16478. createCylinderCap(false);
  16479. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16480. var vertexData = new BABYLON.VertexData();
  16481. vertexData.indices = indices;
  16482. vertexData.positions = positions;
  16483. vertexData.normals = normals;
  16484. vertexData.uvs = uvs;
  16485. return vertexData;
  16486. };
  16487. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  16488. var indices = [];
  16489. var positions = [];
  16490. var normals = [];
  16491. var uvs = [];
  16492. diameter = diameter || 1;
  16493. thickness = thickness || 0.5;
  16494. tessellation = tessellation || 16;
  16495. var stride = tessellation + 1;
  16496. for (var i = 0; i <= tessellation; i++) {
  16497. var u = i / tessellation;
  16498. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  16499. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  16500. for (var j = 0; j <= tessellation; j++) {
  16501. var v = 1 - j / tessellation;
  16502. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  16503. var dx = Math.cos(innerAngle);
  16504. var dy = Math.sin(innerAngle);
  16505. var normal = new BABYLON.Vector3(dx, dy, 0);
  16506. var position = normal.scale(thickness / 2);
  16507. var textureCoordinate = new BABYLON.Vector2(u, v);
  16508. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  16509. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  16510. positions.push(position.x, position.y, position.z);
  16511. normals.push(normal.x, normal.y, normal.z);
  16512. uvs.push(textureCoordinate.x, textureCoordinate.y);
  16513. var nextI = (i + 1) % stride;
  16514. var nextJ = (j + 1) % stride;
  16515. indices.push(i * stride + j);
  16516. indices.push(i * stride + nextJ);
  16517. indices.push(nextI * stride + j);
  16518. indices.push(i * stride + nextJ);
  16519. indices.push(nextI * stride + nextJ);
  16520. indices.push(nextI * stride + j);
  16521. }
  16522. }
  16523. var vertexData = new BABYLON.VertexData();
  16524. vertexData.indices = indices;
  16525. vertexData.positions = positions;
  16526. vertexData.normals = normals;
  16527. vertexData.uvs = uvs;
  16528. return vertexData;
  16529. };
  16530. VertexData.CreateLines = function (points) {
  16531. var indices = [];
  16532. var positions = [];
  16533. for (var index = 0; index < points.length; index++) {
  16534. positions.push(points[index].x, points[index].y, points[index].z);
  16535. if (index > 0) {
  16536. indices.push(index - 1);
  16537. indices.push(index);
  16538. }
  16539. }
  16540. var vertexData = new BABYLON.VertexData();
  16541. vertexData.indices = indices;
  16542. vertexData.positions = positions;
  16543. return vertexData;
  16544. };
  16545. VertexData.CreateGround = function (width, height, subdivisions) {
  16546. var indices = [];
  16547. var positions = [];
  16548. var normals = [];
  16549. var uvs = [];
  16550. var row, col;
  16551. width = width || 1;
  16552. height = height || 1;
  16553. subdivisions = subdivisions || 1;
  16554. for (row = 0; row <= subdivisions; row++) {
  16555. for (col = 0; col <= subdivisions; col++) {
  16556. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16557. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16558. positions.push(position.x, position.y, position.z);
  16559. normals.push(normal.x, normal.y, normal.z);
  16560. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16561. }
  16562. }
  16563. for (row = 0; row < subdivisions; row++) {
  16564. for (col = 0; col < subdivisions; col++) {
  16565. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16566. indices.push(col + 1 + row * (subdivisions + 1));
  16567. indices.push(col + row * (subdivisions + 1));
  16568. indices.push(col + (row + 1) * (subdivisions + 1));
  16569. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16570. indices.push(col + row * (subdivisions + 1));
  16571. }
  16572. }
  16573. var vertexData = new BABYLON.VertexData();
  16574. vertexData.indices = indices;
  16575. vertexData.positions = positions;
  16576. vertexData.normals = normals;
  16577. vertexData.uvs = uvs;
  16578. return vertexData;
  16579. };
  16580. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  16581. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  16582. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  16583. var indices = [];
  16584. var positions = [];
  16585. var normals = [];
  16586. var uvs = [];
  16587. var row, col, tileRow, tileCol;
  16588. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  16589. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  16590. precision.w = (precision.w < 1) ? 1 : precision.w;
  16591. precision.h = (precision.h < 1) ? 1 : precision.h;
  16592. var tileSize = {
  16593. 'w': (xmax - xmin) / subdivisions.w,
  16594. 'h': (zmax - zmin) / subdivisions.h
  16595. };
  16596. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  16597. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  16598. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  16599. }
  16600. }
  16601. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  16602. var base = positions.length / 3;
  16603. var rowLength = precision.w + 1;
  16604. for (row = 0; row < precision.h; row++) {
  16605. for (col = 0; col < precision.w; col++) {
  16606. var square = [
  16607. base + col + row * rowLength,
  16608. base + (col + 1) + row * rowLength,
  16609. base + (col + 1) + (row + 1) * rowLength,
  16610. base + col + (row + 1) * rowLength
  16611. ];
  16612. indices.push(square[1]);
  16613. indices.push(square[2]);
  16614. indices.push(square[3]);
  16615. indices.push(square[0]);
  16616. indices.push(square[1]);
  16617. indices.push(square[3]);
  16618. }
  16619. }
  16620. var position = BABYLON.Vector3.Zero();
  16621. var normal = new BABYLON.Vector3(0, 1.0, 0);
  16622. for (row = 0; row <= precision.h; row++) {
  16623. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  16624. for (col = 0; col <= precision.w; col++) {
  16625. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  16626. position.y = 0;
  16627. positions.push(position.x, position.y, position.z);
  16628. normals.push(normal.x, normal.y, normal.z);
  16629. uvs.push(col / precision.w, row / precision.h);
  16630. }
  16631. }
  16632. }
  16633. var vertexData = new BABYLON.VertexData();
  16634. vertexData.indices = indices;
  16635. vertexData.positions = positions;
  16636. vertexData.normals = normals;
  16637. vertexData.uvs = uvs;
  16638. return vertexData;
  16639. };
  16640. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  16641. var indices = [];
  16642. var positions = [];
  16643. var normals = [];
  16644. var uvs = [];
  16645. var row, col;
  16646. for (row = 0; row <= subdivisions; row++) {
  16647. for (col = 0; col <= subdivisions; col++) {
  16648. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  16649. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  16650. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  16651. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  16652. var r = buffer[pos] / 255.0;
  16653. var g = buffer[pos + 1] / 255.0;
  16654. var b = buffer[pos + 2] / 255.0;
  16655. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  16656. position.y = minHeight + (maxHeight - minHeight) * gradient;
  16657. positions.push(position.x, position.y, position.z);
  16658. normals.push(0, 0, 0);
  16659. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  16660. }
  16661. }
  16662. for (row = 0; row < subdivisions; row++) {
  16663. for (col = 0; col < subdivisions; col++) {
  16664. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16665. indices.push(col + 1 + row * (subdivisions + 1));
  16666. indices.push(col + row * (subdivisions + 1));
  16667. indices.push(col + (row + 1) * (subdivisions + 1));
  16668. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  16669. indices.push(col + row * (subdivisions + 1));
  16670. }
  16671. }
  16672. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16673. var vertexData = new BABYLON.VertexData();
  16674. vertexData.indices = indices;
  16675. vertexData.positions = positions;
  16676. vertexData.normals = normals;
  16677. vertexData.uvs = uvs;
  16678. return vertexData;
  16679. };
  16680. VertexData.CreatePlane = function (size) {
  16681. var indices = [];
  16682. var positions = [];
  16683. var normals = [];
  16684. var uvs = [];
  16685. size = size || 1;
  16686. var halfSize = size / 2.0;
  16687. positions.push(-halfSize, -halfSize, 0);
  16688. normals.push(0, 0, -1.0);
  16689. uvs.push(0.0, 0.0);
  16690. positions.push(halfSize, -halfSize, 0);
  16691. normals.push(0, 0, -1.0);
  16692. uvs.push(1.0, 0.0);
  16693. positions.push(halfSize, halfSize, 0);
  16694. normals.push(0, 0, -1.0);
  16695. uvs.push(1.0, 1.0);
  16696. positions.push(-halfSize, halfSize, 0);
  16697. normals.push(0, 0, -1.0);
  16698. uvs.push(0.0, 1.0);
  16699. indices.push(0);
  16700. indices.push(1);
  16701. indices.push(2);
  16702. indices.push(0);
  16703. indices.push(2);
  16704. indices.push(3);
  16705. var vertexData = new BABYLON.VertexData();
  16706. vertexData.indices = indices;
  16707. vertexData.positions = positions;
  16708. vertexData.normals = normals;
  16709. vertexData.uvs = uvs;
  16710. return vertexData;
  16711. };
  16712. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  16713. var indices = [];
  16714. var positions = [];
  16715. var normals = [];
  16716. var uvs = [];
  16717. radius = radius || 2;
  16718. tube = tube || 0.5;
  16719. radialSegments = radialSegments || 32;
  16720. tubularSegments = tubularSegments || 32;
  16721. p = p || 2;
  16722. q = q || 3;
  16723. var getPos = function (angle) {
  16724. var cu = Math.cos(angle);
  16725. var su = Math.sin(angle);
  16726. var quOverP = q / p * angle;
  16727. var cs = Math.cos(quOverP);
  16728. var tx = radius * (2 + cs) * 0.5 * cu;
  16729. var ty = radius * (2 + cs) * su * 0.5;
  16730. var tz = radius * Math.sin(quOverP) * 0.5;
  16731. return new BABYLON.Vector3(tx, ty, tz);
  16732. };
  16733. for (var i = 0; i <= radialSegments; i++) {
  16734. var modI = i % radialSegments;
  16735. var u = modI / radialSegments * 2 * p * Math.PI;
  16736. var p1 = getPos(u);
  16737. var p2 = getPos(u + 0.01);
  16738. var tang = p2.subtract(p1);
  16739. var n = p2.add(p1);
  16740. var bitan = BABYLON.Vector3.Cross(tang, n);
  16741. n = BABYLON.Vector3.Cross(bitan, tang);
  16742. bitan.normalize();
  16743. n.normalize();
  16744. for (var j = 0; j < tubularSegments; j++) {
  16745. var modJ = j % tubularSegments;
  16746. var v = modJ / tubularSegments * 2 * Math.PI;
  16747. var cx = -tube * Math.cos(v);
  16748. var cy = tube * Math.sin(v);
  16749. positions.push(p1.x + cx * n.x + cy * bitan.x);
  16750. positions.push(p1.y + cx * n.y + cy * bitan.y);
  16751. positions.push(p1.z + cx * n.z + cy * bitan.z);
  16752. uvs.push(i / radialSegments);
  16753. uvs.push(j / tubularSegments);
  16754. }
  16755. }
  16756. for (i = 0; i < radialSegments; i++) {
  16757. for (j = 0; j < tubularSegments; j++) {
  16758. var jNext = (j + 1) % tubularSegments;
  16759. var a = i * tubularSegments + j;
  16760. var b = (i + 1) * tubularSegments + j;
  16761. var c = (i + 1) * tubularSegments + jNext;
  16762. var d = i * tubularSegments + jNext;
  16763. indices.push(d);
  16764. indices.push(b);
  16765. indices.push(a);
  16766. indices.push(d);
  16767. indices.push(c);
  16768. indices.push(b);
  16769. }
  16770. }
  16771. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16772. var vertexData = new BABYLON.VertexData();
  16773. vertexData.indices = indices;
  16774. vertexData.positions = positions;
  16775. vertexData.normals = normals;
  16776. vertexData.uvs = uvs;
  16777. return vertexData;
  16778. };
  16779. VertexData.ComputeNormals = function (positions, indices, normals) {
  16780. var positionVectors = [];
  16781. var facesOfVertices = [];
  16782. var index;
  16783. for (index = 0; index < positions.length; index += 3) {
  16784. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  16785. positionVectors.push(vector3);
  16786. facesOfVertices.push([]);
  16787. }
  16788. var facesNormals = [];
  16789. for (index = 0; index < indices.length / 3; index++) {
  16790. var i1 = indices[index * 3];
  16791. var i2 = indices[index * 3 + 1];
  16792. var i3 = indices[index * 3 + 2];
  16793. var p1 = positionVectors[i1];
  16794. var p2 = positionVectors[i2];
  16795. var p3 = positionVectors[i3];
  16796. var p1p2 = p1.subtract(p2);
  16797. var p3p2 = p3.subtract(p2);
  16798. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16799. facesOfVertices[i1].push(index);
  16800. facesOfVertices[i2].push(index);
  16801. facesOfVertices[i3].push(index);
  16802. }
  16803. for (index = 0; index < positionVectors.length; index++) {
  16804. var faces = facesOfVertices[index];
  16805. var normal = BABYLON.Vector3.Zero();
  16806. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  16807. normal.addInPlace(facesNormals[faces[faceIndex]]);
  16808. }
  16809. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  16810. normals[index * 3] = normal.x;
  16811. normals[index * 3 + 1] = normal.y;
  16812. normals[index * 3 + 2] = normal.z;
  16813. }
  16814. };
  16815. return VertexData;
  16816. })();
  16817. BABYLON.VertexData = VertexData;
  16818. })(BABYLON || (BABYLON = {}));
  16819. var __extends = this.__extends || function (d, b) {
  16820. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16821. function __() { this.constructor = d; }
  16822. __.prototype = b.prototype;
  16823. d.prototype = new __();
  16824. };
  16825. var BABYLON;
  16826. (function (BABYLON) {
  16827. var buildCamera = function (that, name) {
  16828. that._leftCamera.isIntermediate = true;
  16829. that.subCameras.push(that._leftCamera);
  16830. that.subCameras.push(that._rightCamera);
  16831. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  16832. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  16833. that._anaglyphPostProcess.onApply = function (effect) {
  16834. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  16835. };
  16836. that._update();
  16837. };
  16838. var AnaglyphArcRotateCamera = (function (_super) {
  16839. __extends(AnaglyphArcRotateCamera, _super);
  16840. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  16841. _super.call(this, name, alpha, beta, radius, target, scene);
  16842. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16843. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  16844. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  16845. buildCamera(this, name);
  16846. }
  16847. AnaglyphArcRotateCamera.prototype._update = function () {
  16848. this._updateCamera(this._leftCamera);
  16849. this._updateCamera(this._rightCamera);
  16850. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  16851. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  16852. _super.prototype._update.call(this);
  16853. };
  16854. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  16855. camera.beta = this.beta;
  16856. camera.radius = this.radius;
  16857. camera.minZ = this.minZ;
  16858. camera.maxZ = this.maxZ;
  16859. camera.fov = this.fov;
  16860. camera.target = this.target;
  16861. };
  16862. return AnaglyphArcRotateCamera;
  16863. })(BABYLON.ArcRotateCamera);
  16864. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  16865. var AnaglyphFreeCamera = (function (_super) {
  16866. __extends(AnaglyphFreeCamera, _super);
  16867. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  16868. _super.call(this, name, position, scene);
  16869. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  16870. this._transformMatrix = new BABYLON.Matrix();
  16871. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  16872. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  16873. buildCamera(this, name);
  16874. }
  16875. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  16876. var target = this.getTarget();
  16877. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  16878. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  16879. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  16880. };
  16881. AnaglyphFreeCamera.prototype._update = function () {
  16882. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  16883. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  16884. this._updateCamera(this._leftCamera);
  16885. this._updateCamera(this._rightCamera);
  16886. _super.prototype._update.call(this);
  16887. };
  16888. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  16889. camera.minZ = this.minZ;
  16890. camera.maxZ = this.maxZ;
  16891. camera.fov = this.fov;
  16892. camera.viewport = this.viewport;
  16893. camera.setTarget(this.getTarget());
  16894. };
  16895. return AnaglyphFreeCamera;
  16896. })(BABYLON.FreeCamera);
  16897. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  16898. })(BABYLON || (BABYLON = {}));
  16899. var __extends = this.__extends || function (d, b) {
  16900. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16901. function __() { this.constructor = d; }
  16902. __.prototype = b.prototype;
  16903. d.prototype = new __();
  16904. };
  16905. var BABYLON;
  16906. (function (BABYLON) {
  16907. var AnaglyphPostProcess = (function (_super) {
  16908. __extends(AnaglyphPostProcess, _super);
  16909. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16910. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  16911. }
  16912. return AnaglyphPostProcess;
  16913. })(BABYLON.PostProcess);
  16914. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  16915. })(BABYLON || (BABYLON = {}));
  16916. var BABYLON;
  16917. (function (BABYLON) {
  16918. var Tags = (function () {
  16919. function Tags() {
  16920. }
  16921. Tags.EnableFor = function (obj) {
  16922. obj._tags = obj._tags || {};
  16923. obj.hasTags = function () {
  16924. return Tags.HasTags(obj);
  16925. };
  16926. obj.addTags = function (tagsString) {
  16927. return Tags.AddTagsTo(obj, tagsString);
  16928. };
  16929. obj.removeTags = function (tagsString) {
  16930. return Tags.RemoveTagsFrom(obj, tagsString);
  16931. };
  16932. obj.matchesTagsQuery = function (tagsQuery) {
  16933. return Tags.MatchesQuery(obj, tagsQuery);
  16934. };
  16935. };
  16936. Tags.DisableFor = function (obj) {
  16937. delete obj._tags;
  16938. delete obj.hasTags;
  16939. delete obj.addTags;
  16940. delete obj.removeTags;
  16941. delete obj.matchesTagsQuery;
  16942. };
  16943. Tags.HasTags = function (obj) {
  16944. if (!obj._tags) {
  16945. return false;
  16946. }
  16947. return !BABYLON.Tools.IsEmpty(obj._tags);
  16948. };
  16949. Tags.GetTags = function (obj) {
  16950. if (!obj._tags) {
  16951. return null;
  16952. }
  16953. return obj._tags;
  16954. };
  16955. Tags.AddTagsTo = function (obj, tagsString) {
  16956. if (!tagsString) {
  16957. return;
  16958. }
  16959. var tags = tagsString.split(" ");
  16960. for (var t in tags) {
  16961. Tags._AddTagTo(obj, tags[t]);
  16962. }
  16963. };
  16964. Tags._AddTagTo = function (obj, tag) {
  16965. tag = tag.trim();
  16966. if (tag === "" || tag === "true" || tag === "false") {
  16967. return;
  16968. }
  16969. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  16970. return;
  16971. }
  16972. Tags.EnableFor(obj);
  16973. obj._tags[tag] = true;
  16974. };
  16975. Tags.RemoveTagsFrom = function (obj, tagsString) {
  16976. if (!Tags.HasTags(obj)) {
  16977. return;
  16978. }
  16979. var tags = tagsString.split(" ");
  16980. for (var t in tags) {
  16981. Tags._RemoveTagFrom(obj, tags[t]);
  16982. }
  16983. };
  16984. Tags._RemoveTagFrom = function (obj, tag) {
  16985. delete obj._tags[tag];
  16986. };
  16987. Tags.MatchesQuery = function (obj, tagsQuery) {
  16988. if (tagsQuery === undefined) {
  16989. return true;
  16990. }
  16991. if (tagsQuery === "") {
  16992. return Tags.HasTags(obj);
  16993. }
  16994. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  16995. return Tags.HasTags(obj) && obj._tags[r];
  16996. });
  16997. };
  16998. return Tags;
  16999. })();
  17000. BABYLON.Tags = Tags;
  17001. })(BABYLON || (BABYLON = {}));
  17002. var BABYLON;
  17003. (function (BABYLON) {
  17004. (function (Internals) {
  17005. var AndOrNotEvaluator = (function () {
  17006. function AndOrNotEvaluator() {
  17007. }
  17008. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17009. if (!query.match(/\([^\(\)]*\)/g)) {
  17010. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17011. } else {
  17012. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17013. r = r.slice(1, r.length - 1);
  17014. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17015. });
  17016. }
  17017. if (query === "true") {
  17018. return true;
  17019. }
  17020. if (query === "false") {
  17021. return false;
  17022. }
  17023. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17024. };
  17025. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17026. evaluateCallback = evaluateCallback || (function (r) {
  17027. return r === "true" ? true : false;
  17028. });
  17029. var result;
  17030. var or = parenthesisContent.split("||");
  17031. for (var i in or) {
  17032. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17033. var and = ori.split("&&");
  17034. if (and.length > 1) {
  17035. for (var j = 0; j < and.length; ++j) {
  17036. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17037. if (andj !== "true" && andj !== "false") {
  17038. if (andj[0] === "!") {
  17039. result = !evaluateCallback(andj.substring(1));
  17040. } else {
  17041. result = evaluateCallback(andj);
  17042. }
  17043. } else {
  17044. result = andj === "true" ? true : false;
  17045. }
  17046. if (!result) {
  17047. ori = "false";
  17048. break;
  17049. }
  17050. }
  17051. }
  17052. if (result || ori === "true") {
  17053. result = true;
  17054. break;
  17055. }
  17056. if (ori !== "true" && ori !== "false") {
  17057. if (ori[0] === "!") {
  17058. result = !evaluateCallback(ori.substring(1));
  17059. } else {
  17060. result = evaluateCallback(ori);
  17061. }
  17062. } else {
  17063. result = ori === "true" ? true : false;
  17064. }
  17065. }
  17066. return result ? "true" : "false";
  17067. };
  17068. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17069. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17070. r = r.replace(/[\s]/g, function () {
  17071. return "";
  17072. });
  17073. return r.length % 2 ? "!" : "";
  17074. });
  17075. booleanString = booleanString.trim();
  17076. if (booleanString === "!true") {
  17077. booleanString = "false";
  17078. } else if (booleanString === "!false") {
  17079. booleanString = "true";
  17080. }
  17081. return booleanString;
  17082. };
  17083. return AndOrNotEvaluator;
  17084. })();
  17085. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17086. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17087. var Internals = BABYLON.Internals;
  17088. })(BABYLON || (BABYLON = {}));
  17089. var BABYLON;
  17090. (function (BABYLON) {
  17091. var PostProcessRenderPass = (function () {
  17092. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17093. this._enabled = true;
  17094. this._refCount = 0;
  17095. this._name = name;
  17096. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17097. this.setRenderList(renderList);
  17098. this._renderTexture.onBeforeRender = beforeRender;
  17099. this._renderTexture.onAfterRender = afterRender;
  17100. this._scene = scene;
  17101. }
  17102. PostProcessRenderPass.prototype._incRefCount = function () {
  17103. if (this._refCount === 0) {
  17104. this._scene.customRenderTargets.push(this._renderTexture);
  17105. }
  17106. return ++this._refCount;
  17107. };
  17108. PostProcessRenderPass.prototype._decRefCount = function () {
  17109. this._refCount--;
  17110. if (this._refCount <= 0) {
  17111. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17112. }
  17113. return this._refCount;
  17114. };
  17115. PostProcessRenderPass.prototype._update = function () {
  17116. this.setRenderList(this._renderList);
  17117. };
  17118. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17119. this._renderTexture.renderList = renderList;
  17120. };
  17121. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17122. return this._renderTexture;
  17123. };
  17124. return PostProcessRenderPass;
  17125. })();
  17126. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17127. })(BABYLON || (BABYLON = {}));
  17128. var BABYLON;
  17129. (function (BABYLON) {
  17130. var PostProcessRenderEffect = (function () {
  17131. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17132. this._engine = engine;
  17133. this._name = name;
  17134. this._singleInstance = singleInstance || true;
  17135. this._getPostProcess = getPostProcess;
  17136. this._cameras = [];
  17137. this._postProcesses = [];
  17138. this._indicesForCamera = [];
  17139. this._renderPasses = [];
  17140. this._renderEffectAsPasses = [];
  17141. }
  17142. PostProcessRenderEffect.prototype._update = function () {
  17143. for (var renderPassName in this._renderPasses) {
  17144. this._renderPasses[renderPassName]._update();
  17145. }
  17146. };
  17147. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17148. this._renderPasses[renderPass._name] = renderPass;
  17149. this._linkParameters();
  17150. };
  17151. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17152. delete this._renderPasses[renderPass._name];
  17153. this._linkParameters();
  17154. };
  17155. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17156. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17157. this._linkParameters();
  17158. };
  17159. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17160. for (var renderPassName in this._renderPasses) {
  17161. if (renderPassName === passName) {
  17162. return this._renderPasses[passName];
  17163. }
  17164. }
  17165. };
  17166. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17167. this._renderPasses.length = 0;
  17168. this._linkParameters();
  17169. };
  17170. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17171. var cameraKey;
  17172. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17173. for (var i = 0; i < _cam.length; i++) {
  17174. var camera = _cam[i];
  17175. var cameraName = camera.name;
  17176. if (this._singleInstance) {
  17177. cameraKey = 0;
  17178. } else {
  17179. cameraKey = cameraName;
  17180. }
  17181. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  17182. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17183. if (!this._indicesForCamera[cameraName]) {
  17184. this._indicesForCamera[cameraName] = [];
  17185. }
  17186. this._indicesForCamera[cameraName].push(index);
  17187. if (this._cameras.indexOf(camera) === -1) {
  17188. this._cameras[cameraName] = camera;
  17189. }
  17190. for (var passName in this._renderPasses) {
  17191. this._renderPasses[passName]._incRefCount();
  17192. }
  17193. }
  17194. this._linkParameters();
  17195. };
  17196. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17197. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17198. for (var i = 0; i < _cam.length; i++) {
  17199. var camera = _cam[i];
  17200. var cameraName = camera.name;
  17201. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17202. var index = this._cameras.indexOf(cameraName);
  17203. this._indicesForCamera.splice(index, 1);
  17204. this._cameras.splice(index, 1);
  17205. for (var passName in this._renderPasses) {
  17206. this._renderPasses[passName]._decRefCount();
  17207. }
  17208. }
  17209. };
  17210. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17211. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17212. for (var i = 0; i < _cam.length; i++) {
  17213. var camera = _cam[i];
  17214. var cameraName = camera.name;
  17215. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17216. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17217. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17218. }
  17219. }
  17220. for (var passName in this._renderPasses) {
  17221. this._renderPasses[passName]._incRefCount();
  17222. }
  17223. }
  17224. };
  17225. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17226. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17227. for (var i = 0; i < _cam.length; i++) {
  17228. var camera = _cam[i];
  17229. var cameraName = camera.Name;
  17230. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17231. for (var passName in this._renderPasses) {
  17232. this._renderPasses[passName]._decRefCount();
  17233. }
  17234. }
  17235. };
  17236. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17237. if (this._singleInstance) {
  17238. return this._postProcesses[0];
  17239. } else {
  17240. return this._postProcesses[camera.name];
  17241. }
  17242. };
  17243. PostProcessRenderEffect.prototype._linkParameters = function () {
  17244. var _this = this;
  17245. for (var index in this._postProcesses) {
  17246. if (this.applyParameters) {
  17247. this.applyParameters(this._postProcesses[index]);
  17248. }
  17249. this._postProcesses[index].onBeforeRender = function (effect) {
  17250. _this._linkTextures(effect);
  17251. };
  17252. }
  17253. };
  17254. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17255. for (var renderPassName in this._renderPasses) {
  17256. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17257. }
  17258. for (var renderEffectName in this._renderEffectAsPasses) {
  17259. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17260. }
  17261. };
  17262. return PostProcessRenderEffect;
  17263. })();
  17264. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17265. })(BABYLON || (BABYLON = {}));
  17266. var BABYLON;
  17267. (function (BABYLON) {
  17268. var PostProcessRenderPipeline = (function () {
  17269. function PostProcessRenderPipeline(engine, name) {
  17270. this._engine = engine;
  17271. this._name = name;
  17272. this._renderEffects = [];
  17273. this._renderEffectsForIsolatedPass = [];
  17274. this._cameras = [];
  17275. }
  17276. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17277. this._renderEffects[renderEffect._name] = renderEffect;
  17278. };
  17279. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17280. var renderEffects = this._renderEffects[renderEffectName];
  17281. if (!renderEffects) {
  17282. return;
  17283. }
  17284. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17285. };
  17286. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17287. var renderEffects = this._renderEffects[renderEffectName];
  17288. if (!renderEffects) {
  17289. return;
  17290. }
  17291. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17292. };
  17293. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17294. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17295. var indicesToDelete = [];
  17296. for (var i = 0; i < _cam.length; i++) {
  17297. var camera = _cam[i];
  17298. var cameraName = camera.name;
  17299. if (this._cameras.indexOf(camera) === -1) {
  17300. this._cameras[cameraName] = camera;
  17301. } else if (unique) {
  17302. indicesToDelete.push(i);
  17303. }
  17304. }
  17305. for (var i = 0; i < indicesToDelete.length; i++) {
  17306. cameras.splice(indicesToDelete[i], 1);
  17307. }
  17308. for (var renderEffectName in this._renderEffects) {
  17309. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17310. }
  17311. };
  17312. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17313. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17314. for (var renderEffectName in this._renderEffects) {
  17315. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17316. }
  17317. for (var i = 0; i < _cam.length; i++) {
  17318. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17319. }
  17320. };
  17321. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17322. var _this = this;
  17323. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17324. var pass = null;
  17325. for (var renderEffectName in this._renderEffects) {
  17326. pass = this._renderEffects[renderEffectName].getPass(passName);
  17327. if (pass != null) {
  17328. break;
  17329. }
  17330. }
  17331. if (pass === null) {
  17332. return;
  17333. }
  17334. for (var renderEffectName in this._renderEffects) {
  17335. this._renderEffects[renderEffectName]._disable(_cam);
  17336. }
  17337. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17338. for (var i = 0; i < _cam.length; i++) {
  17339. var camera = _cam[i];
  17340. var cameraName = camera.name;
  17341. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17342. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17343. });
  17344. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17345. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17346. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17347. }
  17348. };
  17349. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17350. var _this = this;
  17351. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17352. for (var i = 0; i < _cam.length; i++) {
  17353. var camera = _cam[i];
  17354. var cameraName = camera.name;
  17355. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17356. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17357. });
  17358. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17359. }
  17360. for (var renderEffectName in this._renderEffects) {
  17361. this._renderEffects[renderEffectName]._enable(_cam);
  17362. }
  17363. };
  17364. PostProcessRenderPipeline.prototype._update = function () {
  17365. for (var renderEffectName in this._renderEffects) {
  17366. this._renderEffects[renderEffectName]._update();
  17367. }
  17368. for (var i = 0; i < this._cameras.length; i++) {
  17369. var cameraName = this._cameras[i].name;
  17370. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17371. this._renderEffectsForIsolatedPass[cameraName]._update();
  17372. }
  17373. }
  17374. };
  17375. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17376. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17377. return PostProcessRenderPipeline;
  17378. })();
  17379. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17380. })(BABYLON || (BABYLON = {}));
  17381. var BABYLON;
  17382. (function (BABYLON) {
  17383. var PostProcessRenderPipelineManager = (function () {
  17384. function PostProcessRenderPipelineManager() {
  17385. this._renderPipelines = new Array();
  17386. }
  17387. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17388. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17389. };
  17390. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17391. var renderPipeline = this._renderPipelines[renderPipelineName];
  17392. if (!renderPipeline) {
  17393. return;
  17394. }
  17395. renderPipeline._attachCameras(cameras, unique);
  17396. };
  17397. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  17398. var renderPipeline = this._renderPipelines[renderPipelineName];
  17399. if (!renderPipeline) {
  17400. return;
  17401. }
  17402. renderPipeline._detachCameras(cameras);
  17403. };
  17404. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17405. var renderPipeline = this._renderPipelines[renderPipelineName];
  17406. if (!renderPipeline) {
  17407. return;
  17408. }
  17409. renderPipeline._enableEffect(renderEffectName, cameras);
  17410. };
  17411. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  17412. var renderPipeline = this._renderPipelines[renderPipelineName];
  17413. if (!renderPipeline) {
  17414. return;
  17415. }
  17416. renderPipeline._disableEffect(renderEffectName, cameras);
  17417. };
  17418. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  17419. var renderPipeline = this._renderPipelines[renderPipelineName];
  17420. if (!renderPipeline) {
  17421. return;
  17422. }
  17423. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  17424. };
  17425. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  17426. var renderPipeline = this._renderPipelines[renderPipelineName];
  17427. if (!renderPipeline) {
  17428. return;
  17429. }
  17430. renderPipeline._disableDisplayOnlyPass(cameras);
  17431. };
  17432. PostProcessRenderPipelineManager.prototype.update = function () {
  17433. for (var renderPipelineName in this._renderPipelines) {
  17434. this._renderPipelines[renderPipelineName]._update();
  17435. }
  17436. };
  17437. return PostProcessRenderPipelineManager;
  17438. })();
  17439. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  17440. })(BABYLON || (BABYLON = {}));
  17441. var __extends = this.__extends || function (d, b) {
  17442. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17443. function __() { this.constructor = d; }
  17444. __.prototype = b.prototype;
  17445. d.prototype = new __();
  17446. };
  17447. var BABYLON;
  17448. (function (BABYLON) {
  17449. var DisplayPassPostProcess = (function (_super) {
  17450. __extends(DisplayPassPostProcess, _super);
  17451. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17452. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  17453. }
  17454. return DisplayPassPostProcess;
  17455. })(BABYLON.PostProcess);
  17456. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  17457. })(BABYLON || (BABYLON = {}));
  17458. var BABYLON;
  17459. (function (BABYLON) {
  17460. var BoundingBoxRenderer = (function () {
  17461. function BoundingBoxRenderer(scene) {
  17462. this.frontColor = new BABYLON.Color3(1, 1, 1);
  17463. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  17464. this.showBackLines = true;
  17465. this.renderList = new BABYLON.SmartArray(32);
  17466. this._scene = scene;
  17467. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  17468. attributes: ["position"],
  17469. uniforms: ["worldViewProjection", "color"]
  17470. });
  17471. var engine = this._scene.getEngine();
  17472. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  17473. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  17474. 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]);
  17475. }
  17476. BoundingBoxRenderer.prototype.reset = function () {
  17477. this.renderList.reset();
  17478. };
  17479. BoundingBoxRenderer.prototype.render = function () {
  17480. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  17481. return;
  17482. }
  17483. var engine = this._scene.getEngine();
  17484. engine.setDepthWrite(false);
  17485. this._colorShader._preBind();
  17486. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  17487. var boundingBox = this.renderList.data[boundingBoxIndex];
  17488. var min = boundingBox.minimum;
  17489. var max = boundingBox.maximum;
  17490. var diff = max.subtract(min);
  17491. var median = min.add(diff.scale(0.5));
  17492. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  17493. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  17494. if (this.showBackLines) {
  17495. engine.setDepthFunctionToGreaterOrEqual();
  17496. this._colorShader.setColor4("color", this.backColor.toColor4());
  17497. this._colorShader.bind(worldMatrix);
  17498. engine.draw(false, 0, 24);
  17499. }
  17500. engine.setDepthFunctionToLess();
  17501. this._colorShader.setColor4("color", this.frontColor.toColor4());
  17502. this._colorShader.bind(worldMatrix);
  17503. engine.draw(false, 0, 24);
  17504. }
  17505. this._colorShader.unbind();
  17506. engine.setDepthFunctionToLessOrEqual();
  17507. engine.setDepthWrite(true);
  17508. };
  17509. BoundingBoxRenderer.prototype.dispose = function () {
  17510. this._colorShader.dispose();
  17511. this._vb.dispose();
  17512. this._scene.getEngine()._releaseBuffer(this._ib);
  17513. };
  17514. return BoundingBoxRenderer;
  17515. })();
  17516. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  17517. })(BABYLON || (BABYLON = {}));
  17518. /**
  17519. * Based on jsTGALoader - Javascript loader for TGA file
  17520. * By Vincent Thibault
  17521. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  17522. */
  17523. var BABYLON;
  17524. (function (BABYLON) {
  17525. (function (Internals) {
  17526. var TGATools = (function () {
  17527. function TGATools() {
  17528. }
  17529. TGATools.GetTGAHeader = function (data) {
  17530. var offset = 0;
  17531. var header = {
  17532. id_length: data[offset++],
  17533. colormap_type: data[offset++],
  17534. image_type: data[offset++],
  17535. colormap_index: data[offset++] | data[offset++] << 8,
  17536. colormap_length: data[offset++] | data[offset++] << 8,
  17537. colormap_size: data[offset++],
  17538. origin: [
  17539. data[offset++] | data[offset++] << 8,
  17540. data[offset++] | data[offset++] << 8
  17541. ],
  17542. width: data[offset++] | data[offset++] << 8,
  17543. height: data[offset++] | data[offset++] << 8,
  17544. pixel_size: data[offset++],
  17545. flags: data[offset++]
  17546. };
  17547. return header;
  17548. };
  17549. TGATools.UploadContent = function (gl, data) {
  17550. if (data.length < 19) {
  17551. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  17552. return;
  17553. }
  17554. var offset = 18;
  17555. var header = TGATools.GetTGAHeader(data);
  17556. if (header.id_length + offset > data.length) {
  17557. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  17558. return;
  17559. }
  17560. offset += header.id_length;
  17561. var use_rle = false;
  17562. var use_pal = false;
  17563. var use_rgb = false;
  17564. var use_grey = false;
  17565. switch (header.image_type) {
  17566. case TGATools._TYPE_RLE_INDEXED:
  17567. use_rle = true;
  17568. case TGATools._TYPE_INDEXED:
  17569. use_pal = true;
  17570. break;
  17571. case TGATools._TYPE_RLE_RGB:
  17572. use_rle = true;
  17573. case TGATools._TYPE_RGB:
  17574. use_rgb = true;
  17575. break;
  17576. case TGATools._TYPE_RLE_GREY:
  17577. use_rle = true;
  17578. case TGATools._TYPE_GREY:
  17579. use_grey = true;
  17580. break;
  17581. }
  17582. var pixel_data;
  17583. var numAlphaBits = header.flags & 0xf;
  17584. var pixel_size = header.pixel_size >> 3;
  17585. var pixel_total = header.width * header.height * pixel_size;
  17586. var palettes;
  17587. if (use_pal) {
  17588. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  17589. }
  17590. if (use_rle) {
  17591. pixel_data = new Uint8Array(pixel_total);
  17592. var c, count, i;
  17593. var localOffset = 0;
  17594. var pixels = new Uint8Array(pixel_size);
  17595. while (offset < pixel_total && localOffset < pixel_total) {
  17596. c = data[offset++];
  17597. count = (c & 0x7f) + 1;
  17598. if (c & 0x80) {
  17599. for (i = 0; i < pixel_size; ++i) {
  17600. pixels[i] = data[offset++];
  17601. }
  17602. for (i = 0; i < count; ++i) {
  17603. pixel_data.set(pixels, localOffset + i * pixel_size);
  17604. }
  17605. localOffset += pixel_size * count;
  17606. } else {
  17607. count *= pixel_size;
  17608. for (i = 0; i < count; ++i) {
  17609. pixel_data[localOffset + i] = data[offset++];
  17610. }
  17611. localOffset += count;
  17612. }
  17613. }
  17614. } else {
  17615. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  17616. }
  17617. var x_start, y_start, x_step, y_step, y_end, x_end;
  17618. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  17619. default:
  17620. case TGATools._ORIGIN_UL:
  17621. x_start = 0;
  17622. x_step = 1;
  17623. x_end = header.width;
  17624. y_start = 0;
  17625. y_step = 1;
  17626. y_end = header.height;
  17627. break;
  17628. case TGATools._ORIGIN_BL:
  17629. x_start = 0;
  17630. x_step = 1;
  17631. x_end = header.width;
  17632. y_start = header.height - 1;
  17633. y_step = -1;
  17634. y_end = -1;
  17635. break;
  17636. case TGATools._ORIGIN_UR:
  17637. x_start = header.width - 1;
  17638. x_step = -1;
  17639. x_end = -1;
  17640. y_start = 0;
  17641. y_step = 1;
  17642. y_end = header.height;
  17643. break;
  17644. case TGATools._ORIGIN_BR:
  17645. x_start = header.width - 1;
  17646. x_step = -1;
  17647. x_end = -1;
  17648. y_start = header.height - 1;
  17649. y_step = -1;
  17650. y_end = -1;
  17651. break;
  17652. }
  17653. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  17654. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  17655. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  17656. };
  17657. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17658. var image = pixel_data, colormap = palettes;
  17659. var width = header.width, height = header.height;
  17660. var color, i = 0, x, y;
  17661. var imageData = new Uint8Array(width * height * 4);
  17662. for (y = y_start; y !== y_end; y += y_step) {
  17663. for (x = x_start; x !== x_end; x += x_step, i++) {
  17664. color = image[i];
  17665. imageData[(x + width * y) * 4 + 3] = 255;
  17666. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  17667. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  17668. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  17669. }
  17670. }
  17671. return imageData;
  17672. };
  17673. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17674. var image = pixel_data;
  17675. var width = header.width, height = header.height;
  17676. var color, i = 0, x, y;
  17677. var imageData = new Uint8Array(width * height * 4);
  17678. for (y = y_start; y !== y_end; y += y_step) {
  17679. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17680. color = image[i + 0] + (image[i + 1] << 8);
  17681. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  17682. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  17683. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  17684. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  17685. }
  17686. }
  17687. return imageData;
  17688. };
  17689. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17690. var image = pixel_data;
  17691. var width = header.width, height = header.height;
  17692. var i = 0, x, y;
  17693. var imageData = new Uint8Array(width * height * 4);
  17694. for (y = y_start; y !== y_end; y += y_step) {
  17695. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  17696. imageData[(x + width * y) * 4 + 3] = 255;
  17697. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17698. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17699. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17700. }
  17701. }
  17702. return imageData;
  17703. };
  17704. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17705. var image = pixel_data;
  17706. var width = header.width, height = header.height;
  17707. var i = 0, x, y;
  17708. var imageData = new Uint8Array(width * height * 4);
  17709. for (y = y_start; y !== y_end; y += y_step) {
  17710. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  17711. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17712. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  17713. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  17714. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  17715. }
  17716. }
  17717. return imageData;
  17718. };
  17719. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17720. var image = pixel_data;
  17721. var width = header.width, height = header.height;
  17722. var color, i = 0, x, y;
  17723. var imageData = new Uint8Array(width * height * 4);
  17724. for (y = y_start; y !== y_end; y += y_step) {
  17725. for (x = x_start; x !== x_end; x += x_step, i++) {
  17726. color = image[i];
  17727. imageData[(x + width * y) * 4 + 0] = color;
  17728. imageData[(x + width * y) * 4 + 1] = color;
  17729. imageData[(x + width * y) * 4 + 2] = color;
  17730. imageData[(x + width * y) * 4 + 3] = 255;
  17731. }
  17732. }
  17733. return imageData;
  17734. };
  17735. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  17736. var image = pixel_data;
  17737. var width = header.width, height = header.height;
  17738. var i = 0, x, y;
  17739. var imageData = new Uint8Array(width * height * 4);
  17740. for (y = y_start; y !== y_end; y += y_step) {
  17741. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  17742. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  17743. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  17744. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  17745. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  17746. }
  17747. }
  17748. return imageData;
  17749. };
  17750. TGATools._TYPE_NO_DATA = 0;
  17751. TGATools._TYPE_INDEXED = 1;
  17752. TGATools._TYPE_RGB = 2;
  17753. TGATools._TYPE_GREY = 3;
  17754. TGATools._TYPE_RLE_INDEXED = 9;
  17755. TGATools._TYPE_RLE_RGB = 10;
  17756. TGATools._TYPE_RLE_GREY = 11;
  17757. TGATools._ORIGIN_MASK = 0x30;
  17758. TGATools._ORIGIN_SHIFT = 0x04;
  17759. TGATools._ORIGIN_BL = 0x00;
  17760. TGATools._ORIGIN_BR = 0x01;
  17761. TGATools._ORIGIN_UL = 0x02;
  17762. TGATools._ORIGIN_UR = 0x03;
  17763. return TGATools;
  17764. })();
  17765. Internals.TGATools = TGATools;
  17766. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17767. var Internals = BABYLON.Internals;
  17768. })(BABYLON || (BABYLON = {}));
  17769. var BABYLON;
  17770. (function (BABYLON) {
  17771. (function (Internals) {
  17772. var DDS_MAGIC = 0x20534444;
  17773. 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;
  17774. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  17775. 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;
  17776. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  17777. function FourCCToInt32(value) {
  17778. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  17779. }
  17780. function Int32ToFourCC(value) {
  17781. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  17782. }
  17783. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  17784. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  17785. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  17786. var headerLengthInt = 31;
  17787. var off_magic = 0;
  17788. var off_size = 1;
  17789. var off_flags = 2;
  17790. var off_height = 3;
  17791. var off_width = 4;
  17792. var off_mipmapCount = 7;
  17793. var off_pfFlags = 20;
  17794. var off_pfFourCC = 21;
  17795. var off_RGBbpp = 22;
  17796. var off_RMask = 23;
  17797. var off_GMask = 24;
  17798. var off_BMask = 25;
  17799. var off_AMask = 26;
  17800. var off_caps1 = 27;
  17801. var off_caps2 = 28;
  17802. ;
  17803. var DDSTools = (function () {
  17804. function DDSTools() {
  17805. }
  17806. DDSTools.GetDDSInfo = function (arrayBuffer) {
  17807. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  17808. var mipmapCount = 1;
  17809. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  17810. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17811. }
  17812. return {
  17813. width: header[off_width],
  17814. height: header[off_height],
  17815. mipmapCount: mipmapCount,
  17816. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  17817. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  17818. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  17819. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  17820. };
  17821. };
  17822. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17823. var byteArray = new Uint8Array(dataLength);
  17824. var srcData = new Uint8Array(arrayBuffer);
  17825. var index = 0;
  17826. for (var y = height - 1; y >= 0; y--) {
  17827. for (var x = 0; x < width; x++) {
  17828. var srcPos = dataOffset + (x + y * width) * 4;
  17829. byteArray[index + 2] = srcData[srcPos];
  17830. byteArray[index + 1] = srcData[srcPos + 1];
  17831. byteArray[index] = srcData[srcPos + 2];
  17832. byteArray[index + 3] = srcData[srcPos + 3];
  17833. index += 4;
  17834. }
  17835. }
  17836. return byteArray;
  17837. };
  17838. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17839. var byteArray = new Uint8Array(dataLength);
  17840. var srcData = new Uint8Array(arrayBuffer);
  17841. var index = 0;
  17842. for (var y = height - 1; y >= 0; y--) {
  17843. for (var x = 0; x < width; x++) {
  17844. var srcPos = dataOffset + (x + y * width) * 3;
  17845. byteArray[index + 2] = srcData[srcPos];
  17846. byteArray[index + 1] = srcData[srcPos + 1];
  17847. byteArray[index] = srcData[srcPos + 2];
  17848. index += 3;
  17849. }
  17850. }
  17851. return byteArray;
  17852. };
  17853. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  17854. var byteArray = new Uint8Array(dataLength);
  17855. var srcData = new Uint8Array(arrayBuffer);
  17856. var index = 0;
  17857. for (var y = height - 1; y >= 0; y--) {
  17858. for (var x = 0; x < width; x++) {
  17859. var srcPos = dataOffset + (x + y * width);
  17860. byteArray[index] = srcData[srcPos];
  17861. index++;
  17862. }
  17863. }
  17864. return byteArray;
  17865. };
  17866. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  17867. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  17868. if (header[off_magic] != DDS_MAGIC) {
  17869. BABYLON.Tools.Error("Invalid magic number in DDS header");
  17870. return;
  17871. }
  17872. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  17873. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  17874. return;
  17875. }
  17876. if (info.isFourCC) {
  17877. fourCC = header[off_pfFourCC];
  17878. switch (fourCC) {
  17879. case FOURCC_DXT1:
  17880. blockBytes = 8;
  17881. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17882. break;
  17883. case FOURCC_DXT3:
  17884. blockBytes = 16;
  17885. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17886. break;
  17887. case FOURCC_DXT5:
  17888. blockBytes = 16;
  17889. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17890. break;
  17891. default:
  17892. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  17893. return;
  17894. }
  17895. }
  17896. mipmapCount = 1;
  17897. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  17898. mipmapCount = Math.max(1, header[off_mipmapCount]);
  17899. }
  17900. var bpp = header[off_RGBbpp];
  17901. for (var face = 0; face < faces; face++) {
  17902. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  17903. width = header[off_width];
  17904. height = header[off_height];
  17905. dataOffset = header[off_size] + 4;
  17906. for (i = 0; i < mipmapCount; ++i) {
  17907. if (info.isRGB) {
  17908. if (bpp == 24) {
  17909. dataLength = width * height * 3;
  17910. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17911. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  17912. } else {
  17913. dataLength = width * height * 4;
  17914. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17915. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  17916. }
  17917. } else if (info.isLuminance) {
  17918. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  17919. var unpaddedRowSize = width;
  17920. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  17921. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  17922. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  17923. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  17924. } else {
  17925. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  17926. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  17927. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  17928. }
  17929. dataOffset += dataLength;
  17930. width *= 0.5;
  17931. height *= 0.5;
  17932. width = Math.max(1.0, width);
  17933. height = Math.max(1.0, height);
  17934. }
  17935. }
  17936. };
  17937. return DDSTools;
  17938. })();
  17939. Internals.DDSTools = DDSTools;
  17940. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17941. var Internals = BABYLON.Internals;
  17942. })(BABYLON || (BABYLON = {}));
  17943. var BABYLON;
  17944. (function (BABYLON) {
  17945. var SmartArray = (function () {
  17946. function SmartArray(capacity) {
  17947. this.length = 0;
  17948. this._duplicateId = 0;
  17949. this.data = new Array(capacity);
  17950. this._id = SmartArray._GlobalId++;
  17951. }
  17952. SmartArray.prototype.push = function (value) {
  17953. this.data[this.length++] = value;
  17954. if (this.length > this.data.length) {
  17955. this.data.length *= 2;
  17956. }
  17957. if (!value.__smartArrayFlags) {
  17958. value.__smartArrayFlags = {};
  17959. }
  17960. value.__smartArrayFlags[this._id] = this._duplicateId;
  17961. };
  17962. SmartArray.prototype.pushNoDuplicate = function (value) {
  17963. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  17964. return;
  17965. }
  17966. this.push(value);
  17967. };
  17968. SmartArray.prototype.sort = function (compareFn) {
  17969. this.data.sort(compareFn);
  17970. };
  17971. SmartArray.prototype.reset = function () {
  17972. this.length = 0;
  17973. this._duplicateId++;
  17974. };
  17975. SmartArray.prototype.concat = function (array) {
  17976. if (array.length === 0) {
  17977. return;
  17978. }
  17979. if (this.length + array.length > this.data.length) {
  17980. this.data.length = (this.length + array.length) * 2;
  17981. }
  17982. for (var index = 0; index < array.length; index++) {
  17983. this.data[this.length++] = (array.data || array)[index];
  17984. }
  17985. };
  17986. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  17987. if (array.length === 0) {
  17988. return;
  17989. }
  17990. if (this.length + array.length > this.data.length) {
  17991. this.data.length = (this.length + array.length) * 2;
  17992. }
  17993. for (var index = 0; index < array.length; index++) {
  17994. var item = (array.data || array)[index];
  17995. this.pushNoDuplicate(item);
  17996. }
  17997. };
  17998. SmartArray.prototype.indexOf = function (value) {
  17999. var position = this.data.indexOf(value);
  18000. if (position >= this.length) {
  18001. return -1;
  18002. }
  18003. return position;
  18004. };
  18005. SmartArray._GlobalId = 0;
  18006. return SmartArray;
  18007. })();
  18008. BABYLON.SmartArray = SmartArray;
  18009. })(BABYLON || (BABYLON = {}));
  18010. var BABYLON;
  18011. (function (BABYLON) {
  18012. var CannonJSPlugin = (function () {
  18013. function CannonJSPlugin() {
  18014. this._registeredMeshes = [];
  18015. this._physicsMaterials = [];
  18016. this.updateBodyPosition = function (mesh) {
  18017. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18018. var registeredMesh = this._registeredMeshes[index];
  18019. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18020. var body = registeredMesh.body.body;
  18021. var center = mesh.getBoundingInfo().boundingBox.center;
  18022. body.position.set(center.x, center.z, center.y);
  18023. body.quaternion.x = mesh.rotationQuaternion.x;
  18024. body.quaternion.z = mesh.rotationQuaternion.y;
  18025. body.quaternion.y = mesh.rotationQuaternion.z;
  18026. body.quaternion.w = -mesh.rotationQuaternion.w;
  18027. return;
  18028. }
  18029. }
  18030. };
  18031. }
  18032. CannonJSPlugin.prototype.initialize = function (iterations) {
  18033. if (typeof iterations === "undefined") { iterations = 10; }
  18034. this._world = new CANNON.World();
  18035. this._world.broadphase = new CANNON.NaiveBroadphase();
  18036. this._world.solver.iterations = iterations;
  18037. };
  18038. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18039. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18040. };
  18041. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18042. this._world.step(delta);
  18043. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18044. var registeredMesh = this._registeredMeshes[index];
  18045. if (registeredMesh.isChild) {
  18046. continue;
  18047. }
  18048. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18049. var deltaPos = registeredMesh.delta;
  18050. if (deltaPos) {
  18051. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18052. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18053. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18054. } else {
  18055. registeredMesh.mesh.position.x = bodyX;
  18056. registeredMesh.mesh.position.y = bodyZ;
  18057. registeredMesh.mesh.position.z = bodyY;
  18058. }
  18059. if (!registeredMesh.mesh.rotationQuaternion) {
  18060. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18061. }
  18062. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18063. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18064. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18065. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18066. }
  18067. };
  18068. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18069. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18070. };
  18071. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18072. this.unregisterMesh(mesh);
  18073. mesh.computeWorldMatrix(true);
  18074. switch (impostor) {
  18075. case BABYLON.PhysicsEngine.SphereImpostor:
  18076. var bbox = mesh.getBoundingInfo().boundingBox;
  18077. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18078. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18079. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18080. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18081. case BABYLON.PhysicsEngine.BoxImpostor:
  18082. bbox = mesh.getBoundingInfo().boundingBox;
  18083. var min = bbox.minimumWorld;
  18084. var max = bbox.maximumWorld;
  18085. var box = max.subtract(min).scale(0.5);
  18086. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18087. case BABYLON.PhysicsEngine.PlaneImpostor:
  18088. return this._createPlane(mesh, options);
  18089. case BABYLON.PhysicsEngine.MeshImpostor:
  18090. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18091. var rawFaces = mesh.getIndices();
  18092. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18093. }
  18094. return null;
  18095. };
  18096. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18097. var shape = new CANNON.Sphere(radius);
  18098. if (!options) {
  18099. return shape;
  18100. }
  18101. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18102. };
  18103. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18104. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18105. if (!options) {
  18106. return shape;
  18107. }
  18108. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18109. };
  18110. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18111. var shape = new CANNON.Plane();
  18112. if (!options) {
  18113. return shape;
  18114. }
  18115. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18116. };
  18117. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18118. var verts = [], faces = [];
  18119. mesh.computeWorldMatrix(true);
  18120. for (var i = 0; i < rawVerts.length; i += 3) {
  18121. var transformed = BABYLON.Vector3.Zero();
  18122. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18123. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18124. }
  18125. for (var j = 0; j < rawFaces.length; j += 3) {
  18126. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18127. }
  18128. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18129. if (!options) {
  18130. return shape;
  18131. }
  18132. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18133. };
  18134. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18135. var index;
  18136. var mat;
  18137. for (index = 0; index < this._physicsMaterials.length; index++) {
  18138. mat = this._physicsMaterials[index];
  18139. if (mat.friction === friction && mat.restitution === restitution) {
  18140. return mat;
  18141. }
  18142. }
  18143. var currentMat = new CANNON.Material();
  18144. currentMat.friction = friction;
  18145. currentMat.restitution = restitution;
  18146. this._physicsMaterials.push(currentMat);
  18147. for (index = 0; index < this._physicsMaterials.length; index++) {
  18148. mat = this._physicsMaterials[index];
  18149. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18150. contactMaterial.contactEquationStiffness = 1e10;
  18151. contactMaterial.contactEquationRegularizationTime = 10;
  18152. this._world.addContactMaterial(contactMaterial);
  18153. }
  18154. return currentMat;
  18155. };
  18156. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18157. var initialRotation = null;
  18158. if (mesh.rotationQuaternion) {
  18159. initialRotation = mesh.rotationQuaternion.clone();
  18160. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18161. }
  18162. var bbox = mesh.getBoundingInfo().boundingBox;
  18163. var deltaPosition = mesh.position.subtract(bbox.center);
  18164. var material = this._addMaterial(friction, restitution);
  18165. var body = new CANNON.RigidBody(mass, shape, material);
  18166. if (initialRotation) {
  18167. body.quaternion.x = initialRotation.x;
  18168. body.quaternion.z = initialRotation.y;
  18169. body.quaternion.y = initialRotation.z;
  18170. body.quaternion.w = -initialRotation.w;
  18171. }
  18172. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18173. this._world.add(body);
  18174. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18175. return body;
  18176. };
  18177. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18178. var compoundShape = new CANNON.Compound();
  18179. for (var index = 0; index < parts.length; index++) {
  18180. var mesh = parts[index].mesh;
  18181. var shape = this.registerMesh(mesh, parts[index].impostor);
  18182. if (index == 0) {
  18183. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18184. } else {
  18185. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18186. }
  18187. }
  18188. var initialMesh = parts[0].mesh;
  18189. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18190. body.parts = parts;
  18191. return body;
  18192. };
  18193. CannonJSPlugin.prototype._unbindBody = function (body) {
  18194. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18195. var registeredMesh = this._registeredMeshes[index];
  18196. if (registeredMesh.body === body) {
  18197. registeredMesh.body = null;
  18198. registeredMesh.delta = 0;
  18199. }
  18200. }
  18201. };
  18202. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18203. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18204. var registeredMesh = this._registeredMeshes[index];
  18205. if (registeredMesh.mesh === mesh) {
  18206. if (registeredMesh.body) {
  18207. this._world.remove(registeredMesh.body);
  18208. this._unbindBody(registeredMesh.body);
  18209. }
  18210. this._registeredMeshes.splice(index, 1);
  18211. return;
  18212. }
  18213. }
  18214. };
  18215. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18216. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18217. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18218. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18219. var registeredMesh = this._registeredMeshes[index];
  18220. if (registeredMesh.mesh === mesh) {
  18221. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18222. return;
  18223. }
  18224. }
  18225. };
  18226. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18227. var body1 = null, body2 = null;
  18228. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18229. var registeredMesh = this._registeredMeshes[index];
  18230. if (registeredMesh.mesh === mesh1) {
  18231. body1 = registeredMesh.body;
  18232. } else if (registeredMesh.mesh === mesh2) {
  18233. body2 = registeredMesh.body;
  18234. }
  18235. }
  18236. if (!body1 || !body2) {
  18237. return false;
  18238. }
  18239. 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));
  18240. this._world.addConstraint(constraint);
  18241. return true;
  18242. };
  18243. CannonJSPlugin.prototype.dispose = function () {
  18244. while (this._registeredMeshes.length) {
  18245. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18246. }
  18247. };
  18248. CannonJSPlugin.prototype.isSupported = function () {
  18249. return window.CANNON !== undefined;
  18250. };
  18251. return CannonJSPlugin;
  18252. })();
  18253. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18254. })(BABYLON || (BABYLON = {}));
  18255. var __extends = this.__extends || function (d, b) {
  18256. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18257. function __() { this.constructor = d; }
  18258. __.prototype = b.prototype;
  18259. d.prototype = new __();
  18260. };
  18261. var BABYLON;
  18262. (function (BABYLON) {
  18263. var Condition = (function () {
  18264. function Condition(actionManager) {
  18265. this._actionManager = actionManager;
  18266. }
  18267. Condition.prototype.isValid = function () {
  18268. return true;
  18269. };
  18270. Condition.prototype._getProperty = function (propertyPath) {
  18271. return this._actionManager._getProperty(propertyPath);
  18272. };
  18273. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18274. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18275. };
  18276. return Condition;
  18277. })();
  18278. BABYLON.Condition = Condition;
  18279. var ValueCondition = (function (_super) {
  18280. __extends(ValueCondition, _super);
  18281. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18282. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18283. _super.call(this, actionManager);
  18284. this.propertyPath = propertyPath;
  18285. this.value = value;
  18286. this.operator = operator;
  18287. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18288. this._property = this._getProperty(this.propertyPath);
  18289. }
  18290. Object.defineProperty(ValueCondition, "IsEqual", {
  18291. get: function () {
  18292. return ValueCondition._IsEqual;
  18293. },
  18294. enumerable: true,
  18295. configurable: true
  18296. });
  18297. Object.defineProperty(ValueCondition, "IsDifferent", {
  18298. get: function () {
  18299. return ValueCondition._IsDifferent;
  18300. },
  18301. enumerable: true,
  18302. configurable: true
  18303. });
  18304. Object.defineProperty(ValueCondition, "IsGreater", {
  18305. get: function () {
  18306. return ValueCondition._IsGreater;
  18307. },
  18308. enumerable: true,
  18309. configurable: true
  18310. });
  18311. Object.defineProperty(ValueCondition, "IsLesser", {
  18312. get: function () {
  18313. return ValueCondition._IsLesser;
  18314. },
  18315. enumerable: true,
  18316. configurable: true
  18317. });
  18318. ValueCondition.prototype.isValid = function () {
  18319. switch (this.operator) {
  18320. case ValueCondition.IsGreater:
  18321. return this._target[this._property] > this.value;
  18322. case ValueCondition.IsLesser:
  18323. return this._target[this._property] < this.value;
  18324. case ValueCondition.IsEqual:
  18325. case ValueCondition.IsDifferent:
  18326. var check;
  18327. if (this.value.equals) {
  18328. check = this.value.equals(this._target[this._property]);
  18329. } else {
  18330. check = this.value === this._target[this._property];
  18331. }
  18332. return this.operator === ValueCondition.IsEqual ? check : !check;
  18333. }
  18334. return false;
  18335. };
  18336. ValueCondition._IsEqual = 0;
  18337. ValueCondition._IsDifferent = 1;
  18338. ValueCondition._IsGreater = 2;
  18339. ValueCondition._IsLesser = 3;
  18340. return ValueCondition;
  18341. })(Condition);
  18342. BABYLON.ValueCondition = ValueCondition;
  18343. var PredicateCondition = (function (_super) {
  18344. __extends(PredicateCondition, _super);
  18345. function PredicateCondition(actionManager, predicate) {
  18346. _super.call(this, actionManager);
  18347. this.predicate = predicate;
  18348. }
  18349. PredicateCondition.prototype.isValid = function () {
  18350. return this.predicate();
  18351. };
  18352. return PredicateCondition;
  18353. })(Condition);
  18354. BABYLON.PredicateCondition = PredicateCondition;
  18355. var StateCondition = (function (_super) {
  18356. __extends(StateCondition, _super);
  18357. function StateCondition(actionManager, target, value) {
  18358. _super.call(this, actionManager);
  18359. this.value = value;
  18360. this._target = target;
  18361. }
  18362. StateCondition.prototype.isValid = function () {
  18363. return this._target.state === this.value;
  18364. };
  18365. return StateCondition;
  18366. })(Condition);
  18367. BABYLON.StateCondition = StateCondition;
  18368. })(BABYLON || (BABYLON = {}));
  18369. var BABYLON;
  18370. (function (BABYLON) {
  18371. var Action = (function () {
  18372. function Action(triggerOptions, condition) {
  18373. this.triggerOptions = triggerOptions;
  18374. if (triggerOptions.parameter) {
  18375. this.trigger = triggerOptions.trigger;
  18376. this._triggerParameter = triggerOptions.parameter;
  18377. } else {
  18378. this.trigger = triggerOptions;
  18379. }
  18380. this._nextActiveAction = this;
  18381. this._condition = condition;
  18382. }
  18383. Action.prototype._prepare = function () {
  18384. };
  18385. Action.prototype.getTriggerParameter = function () {
  18386. return this._triggerParameter;
  18387. };
  18388. Action.prototype._executeCurrent = function (evt) {
  18389. if (this._condition) {
  18390. var currentRenderId = this._actionManager.getScene().getRenderId();
  18391. if (this._condition._evaluationId === currentRenderId) {
  18392. if (!this._condition._currentResult) {
  18393. return;
  18394. }
  18395. } else {
  18396. this._condition._evaluationId = currentRenderId;
  18397. if (!this._condition.isValid()) {
  18398. this._condition._currentResult = false;
  18399. return;
  18400. }
  18401. this._condition._currentResult = true;
  18402. }
  18403. }
  18404. this._nextActiveAction.execute(evt);
  18405. if (this._nextActiveAction._child) {
  18406. if (!this._nextActiveAction._child._actionManager) {
  18407. this._nextActiveAction._child._actionManager = this._actionManager;
  18408. }
  18409. this._nextActiveAction = this._nextActiveAction._child;
  18410. } else {
  18411. this._nextActiveAction = this;
  18412. }
  18413. };
  18414. Action.prototype.execute = function (evt) {
  18415. };
  18416. Action.prototype.then = function (action) {
  18417. this._child = action;
  18418. action._actionManager = this._actionManager;
  18419. action._prepare();
  18420. return action;
  18421. };
  18422. Action.prototype._getProperty = function (propertyPath) {
  18423. return this._actionManager._getProperty(propertyPath);
  18424. };
  18425. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  18426. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18427. };
  18428. return Action;
  18429. })();
  18430. BABYLON.Action = Action;
  18431. })(BABYLON || (BABYLON = {}));
  18432. var BABYLON;
  18433. (function (BABYLON) {
  18434. var ActionEvent = (function () {
  18435. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  18436. this.source = source;
  18437. this.pointerX = pointerX;
  18438. this.pointerY = pointerY;
  18439. this.meshUnderPointer = meshUnderPointer;
  18440. this.sourceEvent = sourceEvent;
  18441. }
  18442. ActionEvent.CreateNew = function (source) {
  18443. var scene = source.getScene();
  18444. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  18445. };
  18446. ActionEvent.CreateNewFromScene = function (scene, evt) {
  18447. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  18448. };
  18449. return ActionEvent;
  18450. })();
  18451. BABYLON.ActionEvent = ActionEvent;
  18452. var ActionManager = (function () {
  18453. function ActionManager(scene) {
  18454. this.actions = new Array();
  18455. this._scene = scene;
  18456. scene._actionManagers.push(this);
  18457. }
  18458. Object.defineProperty(ActionManager, "NothingTrigger", {
  18459. get: function () {
  18460. return ActionManager._NothingTrigger;
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. Object.defineProperty(ActionManager, "OnPickTrigger", {
  18466. get: function () {
  18467. return ActionManager._OnPickTrigger;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  18473. get: function () {
  18474. return ActionManager._OnLeftPickTrigger;
  18475. },
  18476. enumerable: true,
  18477. configurable: true
  18478. });
  18479. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  18480. get: function () {
  18481. return ActionManager._OnRightPickTrigger;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  18487. get: function () {
  18488. return ActionManager._OnCenterPickTrigger;
  18489. },
  18490. enumerable: true,
  18491. configurable: true
  18492. });
  18493. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  18494. get: function () {
  18495. return ActionManager._OnPointerOverTrigger;
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  18501. get: function () {
  18502. return ActionManager._OnPointerOutTrigger;
  18503. },
  18504. enumerable: true,
  18505. configurable: true
  18506. });
  18507. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  18508. get: function () {
  18509. return ActionManager._OnEveryFrameTrigger;
  18510. },
  18511. enumerable: true,
  18512. configurable: true
  18513. });
  18514. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  18515. get: function () {
  18516. return ActionManager._OnIntersectionEnterTrigger;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  18522. get: function () {
  18523. return ActionManager._OnIntersectionExitTrigger;
  18524. },
  18525. enumerable: true,
  18526. configurable: true
  18527. });
  18528. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  18529. get: function () {
  18530. return ActionManager._OnKeyDownTrigger;
  18531. },
  18532. enumerable: true,
  18533. configurable: true
  18534. });
  18535. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  18536. get: function () {
  18537. return ActionManager._OnKeyUpTrigger;
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. ActionManager.prototype.dispose = function () {
  18543. var index = this._scene._actionManagers.indexOf(this);
  18544. if (index > -1) {
  18545. this._scene._actionManagers.splice(index, 1);
  18546. }
  18547. };
  18548. ActionManager.prototype.getScene = function () {
  18549. return this._scene;
  18550. };
  18551. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  18552. for (var index = 0; index < this.actions.length; index++) {
  18553. var action = this.actions[index];
  18554. if (triggers.indexOf(action.trigger) > -1) {
  18555. return true;
  18556. }
  18557. }
  18558. return false;
  18559. };
  18560. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  18561. get: function () {
  18562. for (var index = 0; index < this.actions.length; index++) {
  18563. var action = this.actions[index];
  18564. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  18565. return true;
  18566. }
  18567. }
  18568. return false;
  18569. },
  18570. enumerable: true,
  18571. configurable: true
  18572. });
  18573. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  18574. get: function () {
  18575. for (var index = 0; index < this.actions.length; index++) {
  18576. var action = this.actions[index];
  18577. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  18578. return true;
  18579. }
  18580. }
  18581. return false;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. ActionManager.prototype.registerAction = function (action) {
  18587. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  18588. if (this.getScene().actionManager !== this) {
  18589. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  18590. return null;
  18591. }
  18592. }
  18593. this.actions.push(action);
  18594. action._actionManager = this;
  18595. action._prepare();
  18596. return action;
  18597. };
  18598. ActionManager.prototype.processTrigger = function (trigger, evt) {
  18599. for (var index = 0; index < this.actions.length; index++) {
  18600. var action = this.actions[index];
  18601. if (action.trigger === trigger) {
  18602. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  18603. var parameter = action.getTriggerParameter();
  18604. if (parameter) {
  18605. if (evt.sourceEvent.key !== parameter) {
  18606. continue;
  18607. }
  18608. }
  18609. }
  18610. action._executeCurrent(evt);
  18611. }
  18612. }
  18613. };
  18614. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  18615. var properties = propertyPath.split(".");
  18616. for (var index = 0; index < properties.length - 1; index++) {
  18617. target = target[properties[index]];
  18618. }
  18619. return target;
  18620. };
  18621. ActionManager.prototype._getProperty = function (propertyPath) {
  18622. var properties = propertyPath.split(".");
  18623. return properties[properties.length - 1];
  18624. };
  18625. ActionManager._NothingTrigger = 0;
  18626. ActionManager._OnPickTrigger = 1;
  18627. ActionManager._OnLeftPickTrigger = 2;
  18628. ActionManager._OnRightPickTrigger = 3;
  18629. ActionManager._OnCenterPickTrigger = 4;
  18630. ActionManager._OnPointerOverTrigger = 5;
  18631. ActionManager._OnPointerOutTrigger = 6;
  18632. ActionManager._OnEveryFrameTrigger = 7;
  18633. ActionManager._OnIntersectionEnterTrigger = 8;
  18634. ActionManager._OnIntersectionExitTrigger = 9;
  18635. ActionManager._OnKeyDownTrigger = 10;
  18636. ActionManager._OnKeyUpTrigger = 11;
  18637. return ActionManager;
  18638. })();
  18639. BABYLON.ActionManager = ActionManager;
  18640. })(BABYLON || (BABYLON = {}));
  18641. var __extends = this.__extends || function (d, b) {
  18642. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18643. function __() { this.constructor = d; }
  18644. __.prototype = b.prototype;
  18645. d.prototype = new __();
  18646. };
  18647. var BABYLON;
  18648. (function (BABYLON) {
  18649. var InterpolateValueAction = (function (_super) {
  18650. __extends(InterpolateValueAction, _super);
  18651. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  18652. if (typeof duration === "undefined") { duration = 1000; }
  18653. _super.call(this, triggerOptions, condition);
  18654. this.propertyPath = propertyPath;
  18655. this.value = value;
  18656. this.duration = duration;
  18657. this.stopOtherAnimations = stopOtherAnimations;
  18658. this._target = target;
  18659. }
  18660. InterpolateValueAction.prototype._prepare = function () {
  18661. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18662. this._property = this._getProperty(this.propertyPath);
  18663. };
  18664. InterpolateValueAction.prototype.execute = function () {
  18665. var scene = this._actionManager.getScene();
  18666. var keys = [
  18667. {
  18668. frame: 0,
  18669. value: this._target[this._property]
  18670. }, {
  18671. frame: 100,
  18672. value: this.value
  18673. }
  18674. ];
  18675. var dataType;
  18676. if (typeof this.value === "number") {
  18677. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  18678. } else if (this.value instanceof BABYLON.Color3) {
  18679. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  18680. } else if (this.value instanceof BABYLON.Vector3) {
  18681. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  18682. } else if (this.value instanceof BABYLON.Matrix) {
  18683. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  18684. } else if (this.value instanceof BABYLON.Quaternion) {
  18685. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  18686. } else {
  18687. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  18688. return;
  18689. }
  18690. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  18691. animation.setKeys(keys);
  18692. if (this.stopOtherAnimations) {
  18693. scene.stopAnimation(this._target);
  18694. }
  18695. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  18696. };
  18697. return InterpolateValueAction;
  18698. })(BABYLON.Action);
  18699. BABYLON.InterpolateValueAction = InterpolateValueAction;
  18700. })(BABYLON || (BABYLON = {}));
  18701. var __extends = this.__extends || function (d, b) {
  18702. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18703. function __() { this.constructor = d; }
  18704. __.prototype = b.prototype;
  18705. d.prototype = new __();
  18706. };
  18707. var BABYLON;
  18708. (function (BABYLON) {
  18709. var SwitchBooleanAction = (function (_super) {
  18710. __extends(SwitchBooleanAction, _super);
  18711. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  18712. _super.call(this, triggerOptions, condition);
  18713. this.propertyPath = propertyPath;
  18714. this._target = target;
  18715. }
  18716. SwitchBooleanAction.prototype._prepare = function () {
  18717. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18718. this._property = this._getProperty(this.propertyPath);
  18719. };
  18720. SwitchBooleanAction.prototype.execute = function () {
  18721. this._target[this._property] = !this._target[this._property];
  18722. };
  18723. return SwitchBooleanAction;
  18724. })(BABYLON.Action);
  18725. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  18726. var SetStateAction = (function (_super) {
  18727. __extends(SetStateAction, _super);
  18728. function SetStateAction(triggerOptions, target, value, condition) {
  18729. _super.call(this, triggerOptions, condition);
  18730. this.value = value;
  18731. this._target = target;
  18732. }
  18733. SetStateAction.prototype.execute = function () {
  18734. this._target.state = this.value;
  18735. };
  18736. return SetStateAction;
  18737. })(BABYLON.Action);
  18738. BABYLON.SetStateAction = SetStateAction;
  18739. var SetValueAction = (function (_super) {
  18740. __extends(SetValueAction, _super);
  18741. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  18742. _super.call(this, triggerOptions, condition);
  18743. this.propertyPath = propertyPath;
  18744. this.value = value;
  18745. this._target = target;
  18746. }
  18747. SetValueAction.prototype._prepare = function () {
  18748. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18749. this._property = this._getProperty(this.propertyPath);
  18750. };
  18751. SetValueAction.prototype.execute = function () {
  18752. this._target[this._property] = this.value;
  18753. };
  18754. return SetValueAction;
  18755. })(BABYLON.Action);
  18756. BABYLON.SetValueAction = SetValueAction;
  18757. var IncrementValueAction = (function (_super) {
  18758. __extends(IncrementValueAction, _super);
  18759. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  18760. _super.call(this, triggerOptions, condition);
  18761. this.propertyPath = propertyPath;
  18762. this.value = value;
  18763. this._target = target;
  18764. }
  18765. IncrementValueAction.prototype._prepare = function () {
  18766. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  18767. this._property = this._getProperty(this.propertyPath);
  18768. if (typeof this._target[this._property] !== "number") {
  18769. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  18770. }
  18771. };
  18772. IncrementValueAction.prototype.execute = function () {
  18773. this._target[this._property] += this.value;
  18774. };
  18775. return IncrementValueAction;
  18776. })(BABYLON.Action);
  18777. BABYLON.IncrementValueAction = IncrementValueAction;
  18778. var PlayAnimationAction = (function (_super) {
  18779. __extends(PlayAnimationAction, _super);
  18780. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  18781. _super.call(this, triggerOptions, condition);
  18782. this.from = from;
  18783. this.to = to;
  18784. this.loop = loop;
  18785. this._target = target;
  18786. }
  18787. PlayAnimationAction.prototype._prepare = function () {
  18788. };
  18789. PlayAnimationAction.prototype.execute = function () {
  18790. var scene = this._actionManager.getScene();
  18791. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  18792. };
  18793. return PlayAnimationAction;
  18794. })(BABYLON.Action);
  18795. BABYLON.PlayAnimationAction = PlayAnimationAction;
  18796. var StopAnimationAction = (function (_super) {
  18797. __extends(StopAnimationAction, _super);
  18798. function StopAnimationAction(triggerOptions, target, condition) {
  18799. _super.call(this, triggerOptions, condition);
  18800. this._target = target;
  18801. }
  18802. StopAnimationAction.prototype._prepare = function () {
  18803. };
  18804. StopAnimationAction.prototype.execute = function () {
  18805. var scene = this._actionManager.getScene();
  18806. scene.stopAnimation(this._target);
  18807. };
  18808. return StopAnimationAction;
  18809. })(BABYLON.Action);
  18810. BABYLON.StopAnimationAction = StopAnimationAction;
  18811. var DoNothingAction = (function (_super) {
  18812. __extends(DoNothingAction, _super);
  18813. function DoNothingAction(triggerOptions, condition) {
  18814. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  18815. _super.call(this, triggerOptions, condition);
  18816. }
  18817. DoNothingAction.prototype.execute = function () {
  18818. };
  18819. return DoNothingAction;
  18820. })(BABYLON.Action);
  18821. BABYLON.DoNothingAction = DoNothingAction;
  18822. var CombineAction = (function (_super) {
  18823. __extends(CombineAction, _super);
  18824. function CombineAction(triggerOptions, children, condition) {
  18825. _super.call(this, triggerOptions, condition);
  18826. this.children = children;
  18827. }
  18828. CombineAction.prototype._prepare = function () {
  18829. for (var index = 0; index < this.children.length; index++) {
  18830. this.children[index]._actionManager = this._actionManager;
  18831. this.children[index]._prepare();
  18832. }
  18833. };
  18834. CombineAction.prototype.execute = function (evt) {
  18835. for (var index = 0; index < this.children.length; index++) {
  18836. this.children[index].execute(evt);
  18837. }
  18838. };
  18839. return CombineAction;
  18840. })(BABYLON.Action);
  18841. BABYLON.CombineAction = CombineAction;
  18842. var ExecuteCodeAction = (function (_super) {
  18843. __extends(ExecuteCodeAction, _super);
  18844. function ExecuteCodeAction(triggerOptions, func, condition) {
  18845. _super.call(this, triggerOptions, condition);
  18846. this.func = func;
  18847. }
  18848. ExecuteCodeAction.prototype.execute = function (evt) {
  18849. this.func(evt);
  18850. };
  18851. return ExecuteCodeAction;
  18852. })(BABYLON.Action);
  18853. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  18854. var SetParentAction = (function (_super) {
  18855. __extends(SetParentAction, _super);
  18856. function SetParentAction(triggerOptions, target, parent, condition) {
  18857. _super.call(this, triggerOptions, condition);
  18858. this._target = target;
  18859. this._parent = parent;
  18860. }
  18861. SetParentAction.prototype._prepare = function () {
  18862. };
  18863. SetParentAction.prototype.execute = function () {
  18864. if (this._target.parent === this._parent) {
  18865. return;
  18866. }
  18867. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  18868. invertParentWorldMatrix.invert();
  18869. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  18870. this._target.parent = this._parent;
  18871. };
  18872. return SetParentAction;
  18873. })(BABYLON.Action);
  18874. BABYLON.SetParentAction = SetParentAction;
  18875. })(BABYLON || (BABYLON = {}));
  18876. var __extends = this.__extends || function (d, b) {
  18877. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18878. function __() { this.constructor = d; }
  18879. __.prototype = b.prototype;
  18880. d.prototype = new __();
  18881. };
  18882. var BABYLON;
  18883. (function (BABYLON) {
  18884. var Geometry = (function () {
  18885. function Geometry(id, scene, vertexData, updatable, mesh) {
  18886. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18887. this._totalVertices = 0;
  18888. this._indices = [];
  18889. this.id = id;
  18890. this._engine = scene.getEngine();
  18891. this._meshes = [];
  18892. this._scene = scene;
  18893. if (vertexData) {
  18894. this.setAllVerticesData(vertexData, updatable);
  18895. } else {
  18896. this._totalVertices = 0;
  18897. this._indices = [];
  18898. }
  18899. if (mesh) {
  18900. this.applyToMesh(mesh);
  18901. }
  18902. }
  18903. Geometry.prototype.getScene = function () {
  18904. return this._scene;
  18905. };
  18906. Geometry.prototype.getEngine = function () {
  18907. return this._engine;
  18908. };
  18909. Geometry.prototype.isReady = function () {
  18910. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  18911. };
  18912. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  18913. vertexData.applyToGeometry(this, updatable);
  18914. };
  18915. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  18916. this._vertexBuffers = this._vertexBuffers || {};
  18917. if (this._vertexBuffers[kind]) {
  18918. this._vertexBuffers[kind].dispose();
  18919. }
  18920. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  18921. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18922. var stride = this._vertexBuffers[kind].getStrideSize();
  18923. this._totalVertices = data.length / stride;
  18924. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18925. var meshes = this._meshes;
  18926. var numOfMeshes = meshes.length;
  18927. for (var index = 0; index < numOfMeshes; index++) {
  18928. var mesh = meshes[index];
  18929. mesh._resetPointsArrayCache();
  18930. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18931. mesh._createGlobalSubMesh();
  18932. mesh.computeWorldMatrix(true);
  18933. }
  18934. }
  18935. };
  18936. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  18937. var vertexBuffer = this.getVertexBuffer(kind);
  18938. if (!vertexBuffer) {
  18939. return;
  18940. }
  18941. vertexBuffer.updateDirectly(data);
  18942. };
  18943. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  18944. var vertexBuffer = this.getVertexBuffer(kind);
  18945. if (!vertexBuffer) {
  18946. return;
  18947. }
  18948. vertexBuffer.update(data);
  18949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  18950. var extend;
  18951. if (updateExtends) {
  18952. var stride = vertexBuffer.getStrideSize();
  18953. this._totalVertices = data.length / stride;
  18954. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  18955. }
  18956. var meshes = this._meshes;
  18957. var numOfMeshes = meshes.length;
  18958. for (var index = 0; index < numOfMeshes; index++) {
  18959. var mesh = meshes[index];
  18960. mesh._resetPointsArrayCache();
  18961. if (updateExtends) {
  18962. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18963. }
  18964. }
  18965. }
  18966. };
  18967. Geometry.prototype.getTotalVertices = function () {
  18968. if (!this.isReady()) {
  18969. return 0;
  18970. }
  18971. return this._totalVertices;
  18972. };
  18973. Geometry.prototype.getVerticesData = function (kind) {
  18974. var vertexBuffer = this.getVertexBuffer(kind);
  18975. if (!vertexBuffer) {
  18976. return null;
  18977. }
  18978. return vertexBuffer.getData();
  18979. };
  18980. Geometry.prototype.getVertexBuffer = function (kind) {
  18981. if (!this.isReady()) {
  18982. return null;
  18983. }
  18984. return this._vertexBuffers[kind];
  18985. };
  18986. Geometry.prototype.getVertexBuffers = function () {
  18987. if (!this.isReady()) {
  18988. return null;
  18989. }
  18990. return this._vertexBuffers;
  18991. };
  18992. Geometry.prototype.isVerticesDataPresent = function (kind) {
  18993. if (!this._vertexBuffers) {
  18994. if (this._delayInfo) {
  18995. return this._delayInfo.indexOf(kind) !== -1;
  18996. }
  18997. return false;
  18998. }
  18999. return this._vertexBuffers[kind] !== undefined;
  19000. };
  19001. Geometry.prototype.getVerticesDataKinds = function () {
  19002. var result = [];
  19003. if (!this._vertexBuffers && this._delayInfo) {
  19004. for (var kind in this._delayInfo) {
  19005. result.push(kind);
  19006. }
  19007. } else {
  19008. for (kind in this._vertexBuffers) {
  19009. result.push(kind);
  19010. }
  19011. }
  19012. return result;
  19013. };
  19014. Geometry.prototype.setIndices = function (indices) {
  19015. if (this._indexBuffer) {
  19016. this._engine._releaseBuffer(this._indexBuffer);
  19017. }
  19018. this._indices = indices;
  19019. if (this._meshes.length !== 0 && this._indices) {
  19020. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19021. }
  19022. var meshes = this._meshes;
  19023. var numOfMeshes = meshes.length;
  19024. for (var index = 0; index < numOfMeshes; index++) {
  19025. meshes[index]._createGlobalSubMesh();
  19026. }
  19027. };
  19028. Geometry.prototype.getTotalIndices = function () {
  19029. if (!this.isReady()) {
  19030. return 0;
  19031. }
  19032. return this._indices.length;
  19033. };
  19034. Geometry.prototype.getIndices = function () {
  19035. if (!this.isReady()) {
  19036. return null;
  19037. }
  19038. return this._indices;
  19039. };
  19040. Geometry.prototype.getIndexBuffer = function () {
  19041. if (!this.isReady()) {
  19042. return null;
  19043. }
  19044. return this._indexBuffer;
  19045. };
  19046. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19047. var meshes = this._meshes;
  19048. var index = meshes.indexOf(mesh);
  19049. if (index === -1) {
  19050. return;
  19051. }
  19052. for (var kind in this._vertexBuffers) {
  19053. this._vertexBuffers[kind].dispose();
  19054. }
  19055. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19056. this._indexBuffer = null;
  19057. }
  19058. meshes.splice(index, 1);
  19059. mesh._geometry = null;
  19060. if (meshes.length == 0 && shouldDispose) {
  19061. this.dispose();
  19062. }
  19063. };
  19064. Geometry.prototype.applyToMesh = function (mesh) {
  19065. if (mesh._geometry === this) {
  19066. return;
  19067. }
  19068. var previousGeometry = mesh._geometry;
  19069. if (previousGeometry) {
  19070. previousGeometry.releaseForMesh(mesh);
  19071. }
  19072. var meshes = this._meshes;
  19073. mesh._geometry = this;
  19074. this._scene.pushGeometry(this);
  19075. meshes.push(mesh);
  19076. if (this.isReady()) {
  19077. this._applyToMesh(mesh);
  19078. } else {
  19079. mesh._boundingInfo = this._boundingInfo;
  19080. }
  19081. };
  19082. Geometry.prototype._applyToMesh = function (mesh) {
  19083. var numOfMeshes = this._meshes.length;
  19084. for (var kind in this._vertexBuffers) {
  19085. if (numOfMeshes === 1) {
  19086. this._vertexBuffers[kind].create();
  19087. }
  19088. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19089. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19090. mesh._resetPointsArrayCache();
  19091. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19092. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19093. mesh._createGlobalSubMesh();
  19094. }
  19095. }
  19096. if (numOfMeshes === 1 && this._indices) {
  19097. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19098. }
  19099. if (this._indexBuffer) {
  19100. this._indexBuffer.references = numOfMeshes;
  19101. }
  19102. };
  19103. Geometry.prototype.load = function (scene, onLoaded) {
  19104. var _this = this;
  19105. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19106. return;
  19107. }
  19108. if (this.isReady()) {
  19109. if (onLoaded) {
  19110. onLoaded();
  19111. }
  19112. return;
  19113. }
  19114. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19115. scene._addPendingData(this);
  19116. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19117. _this._delayLoadingFunction(JSON.parse(data), _this);
  19118. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19119. _this._delayInfo = [];
  19120. scene._removePendingData(_this);
  19121. var meshes = _this._meshes;
  19122. var numOfMeshes = meshes.length;
  19123. for (var index = 0; index < numOfMeshes; index++) {
  19124. _this._applyToMesh(meshes[index]);
  19125. }
  19126. if (onLoaded) {
  19127. onLoaded();
  19128. }
  19129. }, function () {
  19130. }, scene.database);
  19131. };
  19132. Geometry.prototype.dispose = function () {
  19133. var meshes = this._meshes;
  19134. var numOfMeshes = meshes.length;
  19135. for (var index = 0; index < numOfMeshes; index++) {
  19136. this.releaseForMesh(meshes[index]);
  19137. }
  19138. this._meshes = [];
  19139. for (var kind in this._vertexBuffers) {
  19140. this._vertexBuffers[kind].dispose();
  19141. }
  19142. this._vertexBuffers = [];
  19143. this._totalVertices = 0;
  19144. if (this._indexBuffer) {
  19145. this._engine._releaseBuffer(this._indexBuffer);
  19146. }
  19147. this._indexBuffer = null;
  19148. this._indices = [];
  19149. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19150. this.delayLoadingFile = null;
  19151. this._delayLoadingFunction = null;
  19152. this._delayInfo = [];
  19153. this._boundingInfo = null;
  19154. var geometries = this._scene.getGeometries();
  19155. index = geometries.indexOf(this);
  19156. if (index > -1) {
  19157. geometries.splice(index, 1);
  19158. }
  19159. };
  19160. Geometry.prototype.copy = function (id) {
  19161. var vertexData = new BABYLON.VertexData();
  19162. vertexData.indices = [];
  19163. var indices = this.getIndices();
  19164. for (var index = 0; index < indices.length; index++) {
  19165. vertexData.indices.push(indices[index]);
  19166. }
  19167. var updatable = false;
  19168. var stopChecking = false;
  19169. for (var kind in this._vertexBuffers) {
  19170. vertexData.set(this.getVerticesData(kind), kind);
  19171. if (!stopChecking) {
  19172. updatable = this.getVertexBuffer(kind).isUpdatable();
  19173. stopChecking = !updatable;
  19174. }
  19175. }
  19176. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19177. geometry.delayLoadState = this.delayLoadState;
  19178. geometry.delayLoadingFile = this.delayLoadingFile;
  19179. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19180. for (kind in this._delayInfo) {
  19181. geometry._delayInfo = geometry._delayInfo || [];
  19182. geometry._delayInfo.push(kind);
  19183. }
  19184. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19185. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19186. return geometry;
  19187. };
  19188. Geometry.ExtractFromMesh = function (mesh, id) {
  19189. var geometry = mesh._geometry;
  19190. if (!geometry) {
  19191. return null;
  19192. }
  19193. return geometry.copy(id);
  19194. };
  19195. Geometry.RandomId = function () {
  19196. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19197. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19198. return v.toString(16);
  19199. });
  19200. };
  19201. return Geometry;
  19202. })();
  19203. BABYLON.Geometry = Geometry;
  19204. (function (Geometry) {
  19205. (function (Primitives) {
  19206. var _Primitive = (function (_super) {
  19207. __extends(_Primitive, _super);
  19208. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19209. this._beingRegenerated = true;
  19210. this._canBeRegenerated = canBeRegenerated;
  19211. _super.call(this, id, scene, vertexData, false, mesh);
  19212. this._beingRegenerated = false;
  19213. }
  19214. _Primitive.prototype.canBeRegenerated = function () {
  19215. return this._canBeRegenerated;
  19216. };
  19217. _Primitive.prototype.regenerate = function () {
  19218. if (!this._canBeRegenerated) {
  19219. return;
  19220. }
  19221. this._beingRegenerated = true;
  19222. this.setAllVerticesData(this._regenerateVertexData(), false);
  19223. this._beingRegenerated = false;
  19224. };
  19225. _Primitive.prototype.asNewGeometry = function (id) {
  19226. return _super.prototype.copy.call(this, id);
  19227. };
  19228. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19229. if (!this._beingRegenerated) {
  19230. return;
  19231. }
  19232. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19233. };
  19234. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19235. if (!this._beingRegenerated) {
  19236. return;
  19237. }
  19238. _super.prototype.setVerticesData.call(this, kind, data, false);
  19239. };
  19240. _Primitive.prototype._regenerateVertexData = function () {
  19241. throw new Error("Abstract method");
  19242. };
  19243. _Primitive.prototype.copy = function (id) {
  19244. throw new Error("Must be overriden in sub-classes.");
  19245. };
  19246. return _Primitive;
  19247. })(Geometry);
  19248. Primitives._Primitive = _Primitive;
  19249. var Box = (function (_super) {
  19250. __extends(Box, _super);
  19251. function Box(id, scene, size, canBeRegenerated, mesh) {
  19252. this.size = size;
  19253. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19254. }
  19255. Box.prototype._regenerateVertexData = function () {
  19256. return BABYLON.VertexData.CreateBox(this.size);
  19257. };
  19258. Box.prototype.copy = function (id) {
  19259. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19260. };
  19261. return Box;
  19262. })(_Primitive);
  19263. Primitives.Box = Box;
  19264. var Sphere = (function (_super) {
  19265. __extends(Sphere, _super);
  19266. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19267. this.segments = segments;
  19268. this.diameter = diameter;
  19269. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19270. }
  19271. Sphere.prototype._regenerateVertexData = function () {
  19272. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19273. };
  19274. Sphere.prototype.copy = function (id) {
  19275. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19276. };
  19277. return Sphere;
  19278. })(_Primitive);
  19279. Primitives.Sphere = Sphere;
  19280. var Cylinder = (function (_super) {
  19281. __extends(Cylinder, _super);
  19282. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19283. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19284. this.height = height;
  19285. this.diameterTop = diameterTop;
  19286. this.diameterBottom = diameterBottom;
  19287. this.tessellation = tessellation;
  19288. this.subdivisions = subdivisions;
  19289. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19290. }
  19291. Cylinder.prototype._regenerateVertexData = function () {
  19292. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19293. };
  19294. Cylinder.prototype.copy = function (id) {
  19295. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19296. };
  19297. return Cylinder;
  19298. })(_Primitive);
  19299. Primitives.Cylinder = Cylinder;
  19300. var Torus = (function (_super) {
  19301. __extends(Torus, _super);
  19302. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19303. this.diameter = diameter;
  19304. this.thickness = thickness;
  19305. this.tessellation = tessellation;
  19306. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19307. }
  19308. Torus.prototype._regenerateVertexData = function () {
  19309. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19310. };
  19311. Torus.prototype.copy = function (id) {
  19312. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19313. };
  19314. return Torus;
  19315. })(_Primitive);
  19316. Primitives.Torus = Torus;
  19317. var Ground = (function (_super) {
  19318. __extends(Ground, _super);
  19319. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19320. this.width = width;
  19321. this.height = height;
  19322. this.subdivisions = subdivisions;
  19323. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19324. }
  19325. Ground.prototype._regenerateVertexData = function () {
  19326. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19327. };
  19328. Ground.prototype.copy = function (id) {
  19329. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19330. };
  19331. return Ground;
  19332. })(_Primitive);
  19333. Primitives.Ground = Ground;
  19334. var TiledGround = (function (_super) {
  19335. __extends(TiledGround, _super);
  19336. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19337. this.xmin = xmin;
  19338. this.zmin = zmin;
  19339. this.xmax = xmax;
  19340. this.zmax = zmax;
  19341. this.subdivisions = subdivisions;
  19342. this.precision = precision;
  19343. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19344. }
  19345. TiledGround.prototype._regenerateVertexData = function () {
  19346. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19347. };
  19348. TiledGround.prototype.copy = function (id) {
  19349. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19350. };
  19351. return TiledGround;
  19352. })(_Primitive);
  19353. Primitives.TiledGround = TiledGround;
  19354. var Plane = (function (_super) {
  19355. __extends(Plane, _super);
  19356. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19357. this.size = size;
  19358. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19359. }
  19360. Plane.prototype._regenerateVertexData = function () {
  19361. return BABYLON.VertexData.CreatePlane(this.size);
  19362. };
  19363. Plane.prototype.copy = function (id) {
  19364. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19365. };
  19366. return Plane;
  19367. })(_Primitive);
  19368. Primitives.Plane = Plane;
  19369. var TorusKnot = (function (_super) {
  19370. __extends(TorusKnot, _super);
  19371. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19372. this.radius = radius;
  19373. this.tube = tube;
  19374. this.radialSegments = radialSegments;
  19375. this.tubularSegments = tubularSegments;
  19376. this.p = p;
  19377. this.q = q;
  19378. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19379. }
  19380. TorusKnot.prototype._regenerateVertexData = function () {
  19381. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19382. };
  19383. TorusKnot.prototype.copy = function (id) {
  19384. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19385. };
  19386. return TorusKnot;
  19387. })(_Primitive);
  19388. Primitives.TorusKnot = TorusKnot;
  19389. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19390. var Primitives = Geometry.Primitives;
  19391. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19392. var Geometry = BABYLON.Geometry;
  19393. })(BABYLON || (BABYLON = {}));
  19394. var __extends = this.__extends || function (d, b) {
  19395. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19396. function __() { this.constructor = d; }
  19397. __.prototype = b.prototype;
  19398. d.prototype = new __();
  19399. };
  19400. var BABYLON;
  19401. (function (BABYLON) {
  19402. var Gamepads = (function () {
  19403. function Gamepads(ongamedpadconnected) {
  19404. var _this = this;
  19405. this.babylonGamepads = [];
  19406. this.oneGamepadConnected = false;
  19407. this.isMonitoring = false;
  19408. this.gamepadEventSupported = 'GamepadEvent' in window;
  19409. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  19410. 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=";
  19411. this._callbackGamepadConnected = ongamedpadconnected;
  19412. if (this.gamepadSupportAvailable) {
  19413. if (this.gamepadEventSupported) {
  19414. window.addEventListener('gamepadconnected', function (evt) {
  19415. _this._onGamepadConnected(evt);
  19416. }, false);
  19417. window.addEventListener('gamepaddisconnected', function (evt) {
  19418. _this._onGamepadDisconnected(evt);
  19419. }, false);
  19420. } else {
  19421. this._startMonitoringGamepads();
  19422. }
  19423. if (!this.oneGamepadConnected) {
  19424. this._insertGamepadDOMInstructions();
  19425. }
  19426. } else {
  19427. this._insertGamepadDOMNotSupported();
  19428. }
  19429. }
  19430. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  19431. Gamepads.gamepadDOMInfo = document.createElement("div");
  19432. var buttonAImage = document.createElement("img");
  19433. buttonAImage.src = this.buttonADataURL;
  19434. var spanMessage = document.createElement("span");
  19435. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  19436. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  19437. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19438. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19439. Gamepads.gamepadDOMInfo.style.width = "100%";
  19440. Gamepads.gamepadDOMInfo.style.height = "48px";
  19441. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19442. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19443. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19444. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19445. buttonAImage.style.position = "relative";
  19446. buttonAImage.style.bottom = "8px";
  19447. spanMessage.style.position = "relative";
  19448. spanMessage.style.fontSize = "32px";
  19449. spanMessage.style.bottom = "32px";
  19450. spanMessage.style.color = "green";
  19451. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19452. };
  19453. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  19454. Gamepads.gamepadDOMInfo = document.createElement("div");
  19455. var spanMessage = document.createElement("span");
  19456. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  19457. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  19458. Gamepads.gamepadDOMInfo.style.position = "absolute";
  19459. Gamepads.gamepadDOMInfo.style.width = "100%";
  19460. Gamepads.gamepadDOMInfo.style.height = "40px";
  19461. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  19462. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  19463. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  19464. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  19465. spanMessage.style.position = "relative";
  19466. spanMessage.style.fontSize = "32px";
  19467. spanMessage.style.color = "red";
  19468. document.body.appendChild(Gamepads.gamepadDOMInfo);
  19469. };
  19470. Gamepads.prototype.dispose = function () {
  19471. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19472. };
  19473. Gamepads.prototype._onGamepadConnected = function (evt) {
  19474. var newGamepad = this._addNewGamepad(evt.gamepad);
  19475. if (this._callbackGamepadConnected)
  19476. this._callbackGamepadConnected(newGamepad);
  19477. this._startMonitoringGamepads();
  19478. };
  19479. Gamepads.prototype._addNewGamepad = function (gamepad) {
  19480. if (!this.oneGamepadConnected) {
  19481. this.oneGamepadConnected = true;
  19482. if (Gamepads.gamepadDOMInfo) {
  19483. document.body.removeChild(Gamepads.gamepadDOMInfo);
  19484. Gamepads.gamepadDOMInfo = null;
  19485. }
  19486. }
  19487. var newGamepad;
  19488. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  19489. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  19490. } else {
  19491. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  19492. }
  19493. this.babylonGamepads.push(newGamepad);
  19494. return newGamepad;
  19495. };
  19496. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  19497. for (var i in this.babylonGamepads) {
  19498. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  19499. this.babylonGamepads.splice(i, 1);
  19500. break;
  19501. }
  19502. }
  19503. if (this.babylonGamepads.length == 0) {
  19504. this._stopMonitoringGamepads();
  19505. }
  19506. };
  19507. Gamepads.prototype._startMonitoringGamepads = function () {
  19508. if (!this.isMonitoring) {
  19509. this.isMonitoring = true;
  19510. this._checkGamepadsStatus();
  19511. }
  19512. };
  19513. Gamepads.prototype._stopMonitoringGamepads = function () {
  19514. this.isMonitoring = false;
  19515. };
  19516. Gamepads.prototype._checkGamepadsStatus = function () {
  19517. var _this = this;
  19518. this._updateGamepadObjects();
  19519. for (var i in this.babylonGamepads) {
  19520. this.babylonGamepads[i].update();
  19521. }
  19522. if (this.isMonitoring) {
  19523. if (window.requestAnimationFrame) {
  19524. window.requestAnimationFrame(function () {
  19525. _this._checkGamepadsStatus();
  19526. });
  19527. } else if (window.mozRequestAnimationFrame) {
  19528. window.mozRequestAnimationFrame(function () {
  19529. _this._checkGamepadsStatus();
  19530. });
  19531. } else if (window.webkitRequestAnimationFrame) {
  19532. window.webkitRequestAnimationFrame(function () {
  19533. _this._checkGamepadsStatus();
  19534. });
  19535. }
  19536. }
  19537. };
  19538. Gamepads.prototype._updateGamepadObjects = function () {
  19539. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  19540. for (var i = 0; i < gamepads.length; i++) {
  19541. if (gamepads[i]) {
  19542. if (!(gamepads[i].index in this.babylonGamepads)) {
  19543. var newGamepad = this._addNewGamepad(gamepads[i]);
  19544. if (this._callbackGamepadConnected) {
  19545. this._callbackGamepadConnected(newGamepad);
  19546. }
  19547. } else {
  19548. this.babylonGamepads[i].browserGamepad = gamepads[i];
  19549. }
  19550. }
  19551. }
  19552. };
  19553. return Gamepads;
  19554. })();
  19555. BABYLON.Gamepads = Gamepads;
  19556. var StickValues = (function () {
  19557. function StickValues(x, y) {
  19558. this.x = x;
  19559. this.y = y;
  19560. }
  19561. return StickValues;
  19562. })();
  19563. BABYLON.StickValues = StickValues;
  19564. var Gamepad = (function () {
  19565. function Gamepad(id, index, browserGamepad) {
  19566. this.id = id;
  19567. this.index = index;
  19568. this.browserGamepad = browserGamepad;
  19569. if (this.browserGamepad.axes.length >= 2) {
  19570. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19571. }
  19572. if (this.browserGamepad.axes.length >= 4) {
  19573. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19574. }
  19575. }
  19576. Gamepad.prototype.onleftstickchanged = function (callback) {
  19577. this._onleftstickchanged = callback;
  19578. };
  19579. Gamepad.prototype.onrightstickchanged = function (callback) {
  19580. this._onrightstickchanged = callback;
  19581. };
  19582. Object.defineProperty(Gamepad.prototype, "leftStick", {
  19583. get: function () {
  19584. return this._leftStick;
  19585. },
  19586. set: function (newValues) {
  19587. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  19588. this._onleftstickchanged(newValues);
  19589. }
  19590. this._leftStick = newValues;
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. Object.defineProperty(Gamepad.prototype, "rightStick", {
  19596. get: function () {
  19597. return this._rightStick;
  19598. },
  19599. set: function (newValues) {
  19600. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  19601. this._onrightstickchanged(newValues);
  19602. }
  19603. this._rightStick = newValues;
  19604. },
  19605. enumerable: true,
  19606. configurable: true
  19607. });
  19608. Gamepad.prototype.update = function () {
  19609. if (this._leftStick) {
  19610. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  19611. }
  19612. if (this._rightStick) {
  19613. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  19614. }
  19615. };
  19616. return Gamepad;
  19617. })();
  19618. BABYLON.Gamepad = Gamepad;
  19619. var GenericPad = (function (_super) {
  19620. __extends(GenericPad, _super);
  19621. function GenericPad(id, index, gamepad) {
  19622. _super.call(this, id, index, gamepad);
  19623. this.id = id;
  19624. this.index = index;
  19625. this.gamepad = gamepad;
  19626. this._buttons = new Array(gamepad.buttons.length);
  19627. }
  19628. GenericPad.prototype.onbuttondown = function (callback) {
  19629. this._onbuttondown = callback;
  19630. };
  19631. GenericPad.prototype.onbuttonup = function (callback) {
  19632. this._onbuttonup = callback;
  19633. };
  19634. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  19635. if (newValue !== currentValue) {
  19636. if (this._onbuttondown && newValue === 1) {
  19637. this._onbuttondown(buttonIndex);
  19638. }
  19639. if (this._onbuttonup && newValue === 0) {
  19640. this._onbuttonup(buttonIndex);
  19641. }
  19642. }
  19643. return newValue;
  19644. };
  19645. GenericPad.prototype.update = function () {
  19646. _super.prototype.update.call(this);
  19647. for (var index = 0; index < this._buttons.length; index++) {
  19648. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  19649. }
  19650. };
  19651. return GenericPad;
  19652. })(Gamepad);
  19653. BABYLON.GenericPad = GenericPad;
  19654. (function (Xbox360Button) {
  19655. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  19656. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  19657. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  19658. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  19659. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  19660. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  19661. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  19662. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  19663. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  19664. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  19665. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  19666. var Xbox360Button = BABYLON.Xbox360Button;
  19667. (function (Xbox360Dpad) {
  19668. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  19669. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  19670. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  19671. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  19672. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  19673. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  19674. var Xbox360Pad = (function (_super) {
  19675. __extends(Xbox360Pad, _super);
  19676. function Xbox360Pad() {
  19677. _super.apply(this, arguments);
  19678. this._leftTrigger = 0;
  19679. this._rightTrigger = 0;
  19680. this._buttonA = 0;
  19681. this._buttonB = 0;
  19682. this._buttonX = 0;
  19683. this._buttonY = 0;
  19684. this._buttonBack = 0;
  19685. this._buttonStart = 0;
  19686. this._buttonLB = 0;
  19687. this._buttonRB = 0;
  19688. this._buttonLeftStick = 0;
  19689. this._buttonRightStick = 0;
  19690. this._dPadUp = 0;
  19691. this._dPadDown = 0;
  19692. this._dPadLeft = 0;
  19693. this._dPadRight = 0;
  19694. }
  19695. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  19696. this._onlefttriggerchanged = callback;
  19697. };
  19698. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  19699. this._onrighttriggerchanged = callback;
  19700. };
  19701. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  19702. get: function () {
  19703. return this._leftTrigger;
  19704. },
  19705. set: function (newValue) {
  19706. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  19707. this._onlefttriggerchanged(newValue);
  19708. }
  19709. this._leftTrigger = newValue;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  19715. get: function () {
  19716. return this._rightTrigger;
  19717. },
  19718. set: function (newValue) {
  19719. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  19720. this._onrighttriggerchanged(newValue);
  19721. }
  19722. this._rightTrigger = newValue;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Xbox360Pad.prototype.onbuttondown = function (callback) {
  19728. this._onbuttondown = callback;
  19729. };
  19730. Xbox360Pad.prototype.onbuttonup = function (callback) {
  19731. this._onbuttonup = callback;
  19732. };
  19733. Xbox360Pad.prototype.ondpaddown = function (callback) {
  19734. this._ondpaddown = callback;
  19735. };
  19736. Xbox360Pad.prototype.ondpadup = function (callback) {
  19737. this._ondpadup = callback;
  19738. };
  19739. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  19740. if (newValue !== currentValue) {
  19741. if (this._onbuttondown && newValue === 1) {
  19742. this._onbuttondown(buttonType);
  19743. }
  19744. if (this._onbuttonup && newValue === 0) {
  19745. this._onbuttonup(buttonType);
  19746. }
  19747. }
  19748. return newValue;
  19749. };
  19750. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  19751. if (newValue !== currentValue) {
  19752. if (this._ondpaddown && newValue === 1) {
  19753. this._ondpaddown(buttonType);
  19754. }
  19755. if (this._ondpadup && newValue === 0) {
  19756. this._ondpadup(buttonType);
  19757. }
  19758. }
  19759. return newValue;
  19760. };
  19761. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  19762. get: function () {
  19763. return this._buttonA;
  19764. },
  19765. set: function (value) {
  19766. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  19772. get: function () {
  19773. return this._buttonB;
  19774. },
  19775. set: function (value) {
  19776. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  19782. get: function () {
  19783. return this._buttonX;
  19784. },
  19785. set: function (value) {
  19786. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  19792. get: function () {
  19793. return this._buttonY;
  19794. },
  19795. set: function (value) {
  19796. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  19802. get: function () {
  19803. return this._buttonStart;
  19804. },
  19805. set: function (value) {
  19806. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  19812. get: function () {
  19813. return this._buttonBack;
  19814. },
  19815. set: function (value) {
  19816. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  19822. get: function () {
  19823. return this._buttonLB;
  19824. },
  19825. set: function (value) {
  19826. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  19832. get: function () {
  19833. return this._buttonRB;
  19834. },
  19835. set: function (value) {
  19836. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  19837. },
  19838. enumerable: true,
  19839. configurable: true
  19840. });
  19841. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  19842. get: function () {
  19843. return this._buttonLeftStick;
  19844. },
  19845. set: function (value) {
  19846. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  19852. get: function () {
  19853. return this._buttonRightStick;
  19854. },
  19855. set: function (value) {
  19856. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  19862. get: function () {
  19863. return this._dPadUp;
  19864. },
  19865. set: function (value) {
  19866. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  19872. get: function () {
  19873. return this._dPadDown;
  19874. },
  19875. set: function (value) {
  19876. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  19882. get: function () {
  19883. return this._dPadLeft;
  19884. },
  19885. set: function (value) {
  19886. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  19892. get: function () {
  19893. return this._dPadRight;
  19894. },
  19895. set: function (value) {
  19896. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. Xbox360Pad.prototype.update = function () {
  19902. _super.prototype.update.call(this);
  19903. this.buttonA = this.browserGamepad.buttons[0].value;
  19904. this.buttonB = this.browserGamepad.buttons[1].value;
  19905. this.buttonX = this.browserGamepad.buttons[2].value;
  19906. this.buttonY = this.browserGamepad.buttons[3].value;
  19907. this.buttonLB = this.browserGamepad.buttons[4].value;
  19908. this.buttonRB = this.browserGamepad.buttons[5].value;
  19909. this.leftTrigger = this.browserGamepad.buttons[6].value;
  19910. this.rightTrigger = this.browserGamepad.buttons[7].value;
  19911. this.buttonBack = this.browserGamepad.buttons[8].value;
  19912. this.buttonStart = this.browserGamepad.buttons[9].value;
  19913. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  19914. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  19915. this.dPadUp = this.browserGamepad.buttons[12].value;
  19916. this.dPadDown = this.browserGamepad.buttons[13].value;
  19917. this.dPadLeft = this.browserGamepad.buttons[14].value;
  19918. this.dPadRight = this.browserGamepad.buttons[15].value;
  19919. };
  19920. return Xbox360Pad;
  19921. })(Gamepad);
  19922. BABYLON.Xbox360Pad = Xbox360Pad;
  19923. })(BABYLON || (BABYLON = {}));
  19924. var __extends = this.__extends || function (d, b) {
  19925. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19926. function __() { this.constructor = d; }
  19927. __.prototype = b.prototype;
  19928. d.prototype = new __();
  19929. };
  19930. var BABYLON;
  19931. (function (BABYLON) {
  19932. var GamepadCamera = (function (_super) {
  19933. __extends(GamepadCamera, _super);
  19934. function GamepadCamera(name, position, scene) {
  19935. var _this = this;
  19936. _super.call(this, name, position, scene);
  19937. this.angularSensibility = 200;
  19938. this.moveSensibility = 75;
  19939. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19940. _this._onNewGameConnected(gamepad);
  19941. });
  19942. }
  19943. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19944. if (gamepad.index === 0) {
  19945. this._gamepad = gamepad;
  19946. }
  19947. };
  19948. GamepadCamera.prototype._checkInputs = function () {
  19949. if (!this._gamepad) {
  19950. return;
  19951. }
  19952. var LSValues = this._gamepad.leftStick;
  19953. var normalizedLX = LSValues.x / this.moveSensibility;
  19954. var normalizedLY = LSValues.y / this.moveSensibility;
  19955. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19956. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19957. var RSValues = this._gamepad.rightStick;
  19958. var normalizedRX = RSValues.x / this.angularSensibility;
  19959. var normalizedRY = RSValues.y / this.angularSensibility;
  19960. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  19961. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  19962. ;
  19963. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19964. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19965. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19966. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  19967. };
  19968. GamepadCamera.prototype.dispose = function () {
  19969. this._gamepads.dispose();
  19970. _super.prototype.dispose.call(this);
  19971. };
  19972. return GamepadCamera;
  19973. })(BABYLON.FreeCamera);
  19974. BABYLON.GamepadCamera = GamepadCamera;
  19975. })(BABYLON || (BABYLON = {}));
  19976. var __extends = this.__extends || function (d, b) {
  19977. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19978. function __() { this.constructor = d; }
  19979. __.prototype = b.prototype;
  19980. d.prototype = new __();
  19981. };
  19982. var BABYLON;
  19983. (function (BABYLON) {
  19984. var LinesMesh = (function (_super) {
  19985. __extends(LinesMesh, _super);
  19986. function LinesMesh(name, scene, updatable) {
  19987. if (typeof updatable === "undefined") { updatable = false; }
  19988. _super.call(this, name, scene);
  19989. this.color = new BABYLON.Color3(1, 1, 1);
  19990. this.alpha = 1;
  19991. this._indices = new Array();
  19992. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19993. attributes: ["position"],
  19994. uniforms: ["worldViewProjection", "color"],
  19995. needAlphaBlending: true
  19996. });
  19997. }
  19998. Object.defineProperty(LinesMesh.prototype, "material", {
  19999. get: function () {
  20000. return this._colorShader;
  20001. },
  20002. enumerable: true,
  20003. configurable: true
  20004. });
  20005. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20006. get: function () {
  20007. return false;
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20013. get: function () {
  20014. return false;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20020. var engine = this.getScene().getEngine();
  20021. var indexToBind = this._geometry.getIndexBuffer();
  20022. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20023. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20024. };
  20025. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20026. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20027. return;
  20028. }
  20029. var engine = this.getScene().getEngine();
  20030. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20031. };
  20032. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20033. return null;
  20034. };
  20035. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20036. this._colorShader.dispose();
  20037. _super.prototype.dispose.call(this, doNotRecurse);
  20038. };
  20039. return LinesMesh;
  20040. })(BABYLON.Mesh);
  20041. BABYLON.LinesMesh = LinesMesh;
  20042. })(BABYLON || (BABYLON = {}));
  20043. var BABYLON;
  20044. (function (BABYLON) {
  20045. var OutlineRenderer = (function () {
  20046. function OutlineRenderer(scene) {
  20047. this._scene = scene;
  20048. }
  20049. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20050. var scene = this._scene;
  20051. var engine = this._scene.getEngine();
  20052. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20053. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20054. return;
  20055. }
  20056. var mesh = subMesh.getRenderingMesh();
  20057. var material = subMesh.getMaterial();
  20058. engine.enableEffect(this._effect);
  20059. this._effect.setFloat("offset", mesh.outlineWidth);
  20060. this._effect.setColor3("color", mesh.outlineColor);
  20061. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20062. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20063. if (useBones) {
  20064. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20065. }
  20066. mesh._bind(subMesh, this._effect, false);
  20067. if (material && material.needAlphaTesting()) {
  20068. var alphaTexture = material.getAlphaTestTexture();
  20069. this._effect.setTexture("diffuseSampler", alphaTexture);
  20070. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20071. }
  20072. if (hardwareInstancedRendering) {
  20073. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20074. } else {
  20075. if (batch.renderSelf[subMesh._id]) {
  20076. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20077. mesh._draw(subMesh, true);
  20078. }
  20079. if (batch.visibleInstances[subMesh._id]) {
  20080. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20081. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20082. this._effect.setMatrix("world", instance.getWorldMatrix());
  20083. mesh._draw(subMesh, true);
  20084. }
  20085. }
  20086. }
  20087. };
  20088. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20089. var defines = [];
  20090. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20091. var mesh = subMesh.getMesh();
  20092. var material = subMesh.getMaterial();
  20093. if (material && material.needAlphaTesting()) {
  20094. defines.push("#define ALPHATEST");
  20095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20096. attribs.push(BABYLON.VertexBuffer.UVKind);
  20097. defines.push("#define UV1");
  20098. }
  20099. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20100. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20101. defines.push("#define UV2");
  20102. }
  20103. }
  20104. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20107. defines.push("#define BONES");
  20108. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20109. }
  20110. if (useInstances) {
  20111. defines.push("#define INSTANCES");
  20112. attribs.push("world0");
  20113. attribs.push("world1");
  20114. attribs.push("world2");
  20115. attribs.push("world3");
  20116. }
  20117. var join = defines.join("\n");
  20118. if (this._cachedDefines != join) {
  20119. this._cachedDefines = join;
  20120. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20121. }
  20122. return this._effect.isReady();
  20123. };
  20124. return OutlineRenderer;
  20125. })();
  20126. BABYLON.OutlineRenderer = OutlineRenderer;
  20127. })(BABYLON || (BABYLON = {}));
  20128. var BABYLON;
  20129. (function (BABYLON) {
  20130. var MeshAssetTask = (function () {
  20131. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20132. this.name = name;
  20133. this.meshesNames = meshesNames;
  20134. this.rootUrl = rootUrl;
  20135. this.sceneFilename = sceneFilename;
  20136. this.isCompleted = false;
  20137. }
  20138. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20139. var _this = this;
  20140. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20141. _this.loadedMeshes = meshes;
  20142. _this.loadedParticleSystems = particleSystems;
  20143. _this.loadedSkeletons = skeletons;
  20144. _this.isCompleted = true;
  20145. if (_this.onSuccess) {
  20146. _this.onSuccess(_this);
  20147. }
  20148. onSuccess();
  20149. }, null, function () {
  20150. if (_this.onError) {
  20151. _this.onError(_this);
  20152. }
  20153. onError();
  20154. });
  20155. };
  20156. return MeshAssetTask;
  20157. })();
  20158. BABYLON.MeshAssetTask = MeshAssetTask;
  20159. var TextFileAssetTask = (function () {
  20160. function TextFileAssetTask(name, url) {
  20161. this.name = name;
  20162. this.url = url;
  20163. this.isCompleted = false;
  20164. }
  20165. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20166. var _this = this;
  20167. BABYLON.Tools.LoadFile(this.url, function (data) {
  20168. _this.text = data;
  20169. _this.isCompleted = true;
  20170. if (_this.onSuccess) {
  20171. _this.onSuccess(_this);
  20172. }
  20173. onSuccess();
  20174. }, null, scene.database, false, function () {
  20175. if (_this.onError) {
  20176. _this.onError(_this);
  20177. }
  20178. onError();
  20179. });
  20180. };
  20181. return TextFileAssetTask;
  20182. })();
  20183. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20184. var BinaryFileAssetTask = (function () {
  20185. function BinaryFileAssetTask(name, url) {
  20186. this.name = name;
  20187. this.url = url;
  20188. this.isCompleted = false;
  20189. }
  20190. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20191. var _this = this;
  20192. BABYLON.Tools.LoadFile(this.url, function (data) {
  20193. _this.data = data;
  20194. _this.isCompleted = true;
  20195. if (_this.onSuccess) {
  20196. _this.onSuccess(_this);
  20197. }
  20198. onSuccess();
  20199. }, null, scene.database, true, function () {
  20200. if (_this.onError) {
  20201. _this.onError(_this);
  20202. }
  20203. onError();
  20204. });
  20205. };
  20206. return BinaryFileAssetTask;
  20207. })();
  20208. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20209. var ImageAssetTask = (function () {
  20210. function ImageAssetTask(name, url) {
  20211. this.name = name;
  20212. this.url = url;
  20213. this.isCompleted = false;
  20214. }
  20215. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20216. var _this = this;
  20217. var img = new Image();
  20218. img.onload = function () {
  20219. _this.image = img;
  20220. _this.isCompleted = true;
  20221. if (_this.onSuccess) {
  20222. _this.onSuccess(_this);
  20223. }
  20224. onSuccess();
  20225. };
  20226. img.onerror = function () {
  20227. if (_this.onError) {
  20228. _this.onError(_this);
  20229. }
  20230. onError();
  20231. };
  20232. img.src = this.url;
  20233. };
  20234. return ImageAssetTask;
  20235. })();
  20236. BABYLON.ImageAssetTask = ImageAssetTask;
  20237. var TextureAssetTask = (function () {
  20238. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  20239. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20240. this.name = name;
  20241. this.url = url;
  20242. this.noMipmap = noMipmap;
  20243. this.invertY = invertY;
  20244. this.samplingMode = samplingMode;
  20245. this.isCompleted = false;
  20246. }
  20247. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20248. var _this = this;
  20249. var onload = function () {
  20250. _this.isCompleted = true;
  20251. if (_this.onSuccess) {
  20252. _this.onSuccess(_this);
  20253. }
  20254. onSuccess();
  20255. };
  20256. var onerror = function () {
  20257. if (_this.onError) {
  20258. _this.onError(_this);
  20259. }
  20260. onError();
  20261. };
  20262. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  20263. };
  20264. return TextureAssetTask;
  20265. })();
  20266. BABYLON.TextureAssetTask = TextureAssetTask;
  20267. var AssetsManager = (function () {
  20268. function AssetsManager(scene) {
  20269. this._tasks = new Array();
  20270. this._waitingTasksCount = 0;
  20271. this.useDefaultLoadingScreen = true;
  20272. this._scene = scene;
  20273. }
  20274. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20275. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20276. this._tasks.push(task);
  20277. return task;
  20278. };
  20279. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20280. var task = new TextFileAssetTask(taskName, url);
  20281. this._tasks.push(task);
  20282. return task;
  20283. };
  20284. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20285. var task = new BinaryFileAssetTask(taskName, url);
  20286. this._tasks.push(task);
  20287. return task;
  20288. };
  20289. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20290. var task = new ImageAssetTask(taskName, url);
  20291. this._tasks.push(task);
  20292. return task;
  20293. };
  20294. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  20295. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20296. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  20297. this._tasks.push(task);
  20298. return task;
  20299. };
  20300. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20301. this._waitingTasksCount--;
  20302. if (this._waitingTasksCount === 0) {
  20303. if (this.onFinish) {
  20304. this.onFinish(this._tasks);
  20305. }
  20306. this._scene.getEngine().hideLoadingUI();
  20307. }
  20308. };
  20309. AssetsManager.prototype._runTask = function (task) {
  20310. var _this = this;
  20311. task.run(this._scene, function () {
  20312. if (_this.onTaskSuccess) {
  20313. _this.onTaskSuccess(task);
  20314. }
  20315. _this._decreaseWaitingTasksCount();
  20316. }, function () {
  20317. if (_this.onTaskError) {
  20318. _this.onTaskError(task);
  20319. }
  20320. _this._decreaseWaitingTasksCount();
  20321. });
  20322. };
  20323. AssetsManager.prototype.reset = function () {
  20324. this._tasks = new Array();
  20325. return this;
  20326. };
  20327. AssetsManager.prototype.load = function () {
  20328. this._waitingTasksCount = this._tasks.length;
  20329. if (this._waitingTasksCount === 0) {
  20330. if (this.onFinish) {
  20331. this.onFinish(this._tasks);
  20332. }
  20333. return this;
  20334. }
  20335. if (this.useDefaultLoadingScreen) {
  20336. this._scene.getEngine().displayLoadingUI();
  20337. }
  20338. for (var index = 0; index < this._tasks.length; index++) {
  20339. var task = this._tasks[index];
  20340. this._runTask(task);
  20341. }
  20342. return this;
  20343. };
  20344. return AssetsManager;
  20345. })();
  20346. BABYLON.AssetsManager = AssetsManager;
  20347. })(BABYLON || (BABYLON = {}));
  20348. var __extends = this.__extends || function (d, b) {
  20349. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20350. function __() { this.constructor = d; }
  20351. __.prototype = b.prototype;
  20352. d.prototype = new __();
  20353. };
  20354. var BABYLON;
  20355. (function (BABYLON) {
  20356. var VRDeviceOrientationCamera = (function (_super) {
  20357. __extends(VRDeviceOrientationCamera, _super);
  20358. function VRDeviceOrientationCamera(name, position, scene) {
  20359. _super.call(this, name, position, scene);
  20360. this._alpha = 0;
  20361. this._beta = 0;
  20362. this._gamma = 0;
  20363. }
  20364. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20365. this._alpha = +evt.alpha | 0;
  20366. this._beta = +evt.beta | 0;
  20367. this._gamma = +evt.gamma | 0;
  20368. if (this._gamma < 0) {
  20369. this._gamma = 90 + this._gamma;
  20370. } else {
  20371. this._gamma = 270 - this._gamma;
  20372. }
  20373. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20374. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20375. this.rotation.z = this._beta / 180.0 * Math.PI;
  20376. };
  20377. return VRDeviceOrientationCamera;
  20378. })(BABYLON.OculusCamera);
  20379. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20380. })(BABYLON || (BABYLON = {}));
  20381. var __extends = this.__extends || function (d, b) {
  20382. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20383. function __() { this.constructor = d; }
  20384. __.prototype = b.prototype;
  20385. d.prototype = new __();
  20386. };
  20387. var BABYLON;
  20388. (function (BABYLON) {
  20389. var WebVRCamera = (function (_super) {
  20390. __extends(WebVRCamera, _super);
  20391. function WebVRCamera(name, position, scene) {
  20392. _super.call(this, name, position, scene);
  20393. this._hmdDevice = null;
  20394. this._sensorDevice = null;
  20395. this._cacheState = null;
  20396. this._cacheQuaternion = new BABYLON.Quaternion();
  20397. this._cacheRotation = BABYLON.Vector3.Zero();
  20398. this._vrEnabled = false;
  20399. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  20400. }
  20401. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  20402. var size = devices.length;
  20403. var i = 0;
  20404. this._sensorDevice = null;
  20405. this._hmdDevice = null;
  20406. while (i < size && this._hmdDevice === null) {
  20407. if (devices[i] instanceof HMDVRDevice) {
  20408. this._hmdDevice = devices[i];
  20409. }
  20410. i++;
  20411. }
  20412. i = 0;
  20413. while (i < size && this._sensorDevice === null) {
  20414. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  20415. this._sensorDevice = devices[i];
  20416. }
  20417. i++;
  20418. }
  20419. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  20420. };
  20421. WebVRCamera.prototype._update = function () {
  20422. if (this._vrEnabled) {
  20423. this._cacheState = this._sensorDevice.getState();
  20424. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  20425. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  20426. this.rotation.x = -this._cacheRotation.z;
  20427. this.rotation.y = -this._cacheRotation.y;
  20428. this.rotation.z = this._cacheRotation.x;
  20429. }
  20430. _super.prototype._update.call(this);
  20431. };
  20432. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  20433. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20434. if (navigator.getVRDevices) {
  20435. navigator.getVRDevices().then(this._getWebVRDevices);
  20436. } else if (navigator.mozGetVRDevices) {
  20437. navigator.mozGetVRDevices(this._getWebVRDevices);
  20438. }
  20439. };
  20440. WebVRCamera.prototype.detachControl = function (element) {
  20441. _super.prototype.detachControl.call(this, element);
  20442. this._vrEnabled = false;
  20443. };
  20444. return WebVRCamera;
  20445. })(BABYLON.OculusCamera);
  20446. BABYLON.WebVRCamera = WebVRCamera;
  20447. })(BABYLON || (BABYLON = {}));